HEL-834: apply visual director memories page source package (6 modified + 9 new, verified against MANIFEST)

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
zonggong
2026-10-24 13:35:48 +08:00
co-authored by multica-agent
parent 89d53b6c53
commit 2288471445
16 changed files with 637 additions and 22 deletions
+44 -1
View File
@@ -1,5 +1,5 @@
import type { ChatAdapter } from './demo';
import type { DemoState, Identity, LifeEvent, Message, ServerEvent } from '../domain/model';
import type { DemoState, Identity, LifeEvent, Memory, Message, ServerEvent } from '../domain/model';
import { defaultSettings } from '../domain/model';
export interface Color {
@@ -15,6 +15,14 @@ export interface Health {
// R2 servers only. backend.life is the configured switch; life_runtime.state is what the loop is actually doing.
backend?: { life: boolean; persona: boolean; receipt: boolean; web_connected: boolean };
life_runtime?: LifeRuntime;
// capabilities.memory is true only on an R3 server with chat memory writing and recall both on.
capabilities?: Record<string, boolean>;
}
// The home line under the window. Memory is only called connected when the server says so; when it is off or unknown
// this keeps the older, more conservative words rather than guessing.
export function memoryNote(health: Health | undefined, life: LifeStatus) {
if (health?.capabilities?.memory === true) return life.wired ? `资料、聊天与回忆保存在服务器。生活:${life.label}。语音尚未接通。` : '资料、聊天与回忆保存在服务器。生活与语音尚未接通。';
return life.wired ? `资料与聊天已保存在服务器。生活:${life.label}。长期记忆与语音尚未接通。` : '资料与聊天已保存在服务器。生活、长期记忆与语音尚未接通。';
}
// What the pages may honestly say about her life right now. Never "running" from the switch alone (HEL-828 item 6).
export interface LifeStatus { wired: boolean; on: boolean; now: string; label: string; note: string }
@@ -68,6 +76,41 @@ export async function lifeDetail(id: string, signal: AbortSignal): Promise<LifeE
if (!serverLife(data?.event)) throw new NotFound();
return toLifeEvent(data.event);
}
// ── Real chat memories (GET /api/memories, R3). The server only returns compressed memories whose chat source passed
// its gate (AM-001); uncompressed or non-public ones are simply absent, so an empty list proves nothing either way. ──
export interface ServerMemory { id: string; title: string; text: string; group: string; source: string; lifeIds: number[]; messageIds: number[]; ts: number }
function serverMemory(v: unknown): v is ServerMemory {
const m = v as Record<string, unknown>;
return !!m && typeof m === 'object' && typeof m.id === 'string' && /^[1-9]\d{0,18}$/u.test(m.id) && typeof m.title === 'string' && !!m.title.trim() && typeof m.text === 'string' && !!m.text.trim()
&& typeof m.group === 'string' && !!m.group && typeof m.source === 'string' && ints(m.lifeIds) && ints(m.messageIds) && m.messageIds.length > 0 && Number.isFinite(m.ts);
}
export const toMemory = (m: ServerMemory): Memory => ({ id: m.id, title: m.title, text: m.text, group: m.group, source: m.source, lifeIds: m.lifeIds.map(String), messageIds: m.messageIds.map(String) });
// A server from before R3 has no such route: that is "not wired", not a failure and not "nothing to show".
export class NotWired extends Error {}
export async function memoryPage(before: string | null, signal: AbortSignal): Promise<{ memories: Memory[]; next: string | null }> {
const s = within(signal, 10000);
let response: Response;
try { response = await fetch(`/api/memories?limit=30${before ? `&before=${encodeURIComponent(before)}` : ''}`, { signal: s }); }
catch (e) { if (signal.aborted) throw e; throw new Error('暂时连不上真实服务,请检查连接后重试。'); }
if (response.status === 404 || response.status === 405) throw new NotWired();
if (!response.ok) throw new Error('回忆暂时读不出来,请稍后重试。');
const page = await response.json().catch(() => null) as { memories?: unknown; next_before?: unknown } | null;
if (!page || !Array.isArray(page.memories)) throw new Error('真实服务暂时没有正确响应,请稍后重试。');
// Malformed rows are dropped, never patched up into something that looks real.
return { memories: page.memories.filter(serverMemory).map(toMemory), next: Number.isSafeInteger(page.next_before) && (page.next_before as number) > 0 ? String(page.next_before) : null };
}
export async function memoryDetail(id: string, signal: AbortSignal): Promise<Memory> {
if (!/^[1-9]\d{0,18}$/u.test(id)) throw new NotFound();
let response: Response;
try { response = await fetch(`/api/memories/${id}`, { signal: within(signal, 10000) }); }
catch (e) { if (signal.aborted) throw e; throw new Error('暂时连不上真实服务,请检查连接后重试。'); }
// Unknown, hidden, uncompressed, forged and malformed ids all come back as the same 404.
if (response.status === 404) throw new NotFound();
if (!response.ok) throw new Error('这一条暂时读不出来,请稍后重试。');
const data = await response.json().catch(() => null);
if (!serverMemory(data?.memory)) throw new NotFound();
return toMemory(data.memory);
}
// ── Persona layers (GET /api/persona). Birth facts stay on the identity; these are the separate model layers. ──
export interface PersonaView {
state: 'ready' | 'loading' | 'failed' | 'disabled' | 'not_initialized';
+9 -7
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { api, lifeStatus, loadReal, type Health } from '../adapters/real';
import { api, lifeStatus, loadReal, memoryNote, type Health } from '../adapters/real';
import type { DemoState, Message, Theme } from '../domain/model';
import { Presenter } from '../stage/Presenter';
import { CreationWizard } from '../manage/CreationWizard';
@@ -32,16 +32,18 @@ export function RealApp() {
// 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);
const refreshHealth = useCallback(() => { api<Health>('health').then(setHealth, () => {}); }, []);
const [focusLife, setFocusLife] = useState(''), [ackAt, setAckAt] = useState(0);
const [focusLife, setFocusLife] = useState(''), [focusIds, setFocusIds] = useState<string[]>([]), [ackAt, setAckAt] = useState(0);
const acknowledged = useCallback(() => setAckAt(Date.now()), []);
const navigate = useCallback((next: string) => { leaveSettingsThen(() => { setArea(next); setLog(false); setFocusLife(''); }); if (next === 'days' || next === 'settings') refreshHealth(); }, [refreshHealth]);
const navigate = useCallback((next: string) => { leaveSettingsThen(() => { setArea(next); setLog(false); setFocusLife(''); setFocusIds([]); }); if (next === 'days' || next === 'settings') refreshHealth(); }, [refreshHealth]);
// "在交谈里看这段": open the record at the turn that told it. The record's server links are authoritative, so the
// local copy of those messages learns them even if they were told after this page loaded.
const openTold = useCallback((id: string, messageIds: string[] = []) => {
const told = new Set(messageIds);
if (latest.current && told.size) changeMessages(latest.current.messages.map(m => told.has(m.id) && !m.lifeIds.includes(id) ? { ...m, lifeIds: [...m.lifeIds, id] } : m));
leaveSettingsThen(() => { setArea('talk'); setLog(true); setFocusLife(id); });
leaveSettingsThen(() => { setArea('talk'); setLog(true); setFocusLife(id); setFocusIds([]); });
}, [changeMessages]);
// A memory opens the record at exactly the messages the server says it was made from; no life links are added.
const openSaid = useCallback((messageIds: string[]) => { leaveSettingsThen(() => { setArea('talk'); setLog(true); setFocusLife(''); setFocusIds(messageIds); }); }, []);
// Esc peels one layer at a time: the record first, then you are back across the room at once.
useEffect(() => { const key = (e: KeyboardEvent) => { if (e.key !== 'Escape' || creating) return; if (log) { setLog(false); return; } if (area === 'talk') { snap(); setInstant(i => i + 1); setArea('now'); return; } if (area !== 'now') navigate('now'); }; window.addEventListener('keydown', key); return () => window.removeEventListener('keydown', key); }, [creating, log, navigate, area]);
const lastReply = state ? [...state.messages].reverse().find(m => m.role === 'companion') : undefined;
@@ -51,9 +53,9 @@ 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">{life.wired ? `资料与聊天已保存在服务器。生活:${life.label}。长期记忆与语音尚未接通。` : '资料与聊天已保存在服务器。生活、长期记忆与语音尚未接通。'}</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} onReceipt={acknowledged}/>}
<LifePanel real state={state} open={area === 'days'} now={life.now} life={life} ackAt={ackAt} onClose={() => navigate('now')} onChat={openTold} onSettings={() => { navigate('settings'); setHerFocus(n => n + 1); }}/>
{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}/>}
<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></>}
</>}</>;
+6 -3
View File
@@ -15,7 +15,8 @@ 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"]'));
export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation, onRecord, offline, fail, log, setLog, focusLife, real = false, onReceipt }: {
const NO_IDS: string[] = [];
export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation, onRecord, offline, fail, log, setLog, focusLife, focusIds = NO_IDS, real = false, onReceipt }: {
real?: boolean;
// Real only: the server accepted a complete-receipt confirmation (the life it may unlock is decided later).
onReceipt?: () => void;
@@ -31,6 +32,8 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
log: boolean;
setLog: (b: boolean) => void;
focusLife: string;
// Real only: exact message ids to open the record at (a memory's server-given sources), apart from life ids.
focusIds?: string[];
}) {
const draftKey = real ? 'cg.real.draft' : 'cg.draft', readKey = real ? 'cg.real.reading' : 'cg.reading';
const [draft, setDraft] = useState(() => { try { return sessionStorage.getItem(draftKey) || ''; } catch { return ''; } }), [reply, setReply] = useState(''), [busy, setBusy] = useState(false), [voice, setVoice] = useState(false), [permission, setPermission] = useState<'' | 'mic' | 'vision'>(''), [notice, setNotice] = useState(''), [flash, setFlash] = useState(''), [denied, setDenied] = useState(false), [vision, setVision] = useState(false);
@@ -80,7 +83,7 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
useEffect(() => { if (!flash) return; const t = setTimeout(() => setFlash(''), 2600); return () => clearTimeout(t); }, [flash]);
useEffect(() => { onRecord(log || full); }, [log, full, onRecord]);
useEffect(() => () => onRecord(false), [onRecord]);
useEffect(() => { if (log) { const el = focusLife ? logRef.current?.querySelector(`[data-life~="${CSS.escape(focusLife)}"]`) : null; if (el) el.scrollIntoView({ block: 'center' }); else if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight; } }, [log, focusLife, view.messages.length]);
useEffect(() => { if (log) { const el = focusLife ? logRef.current?.querySelector(`[data-life~="${CSS.escape(focusLife)}"]`) : focusIds.length ? logRef.current?.querySelector(`[data-mid="${CSS.escape(focusIds[0])}"]`) : null; if (el) el.scrollIntoView({ block: 'center' }); else if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight; } }, [log, focusLife, focusIds, view.messages.length]);
// ── Stage ──
useLayoutEffect(() => { if (stageRef.current) lines.current = new LineStage(stageRef.current); return () => { lines.current = null; }; }, []);
@@ -245,7 +248,7 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
</div>
</section>
<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-role={m.role} className={`message ${m.status === 'failed' ? 'fail' : ''} ${focusLife && m.lifeIds.includes(focusLife) ? '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>}</div></aside>
<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>}</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>}
{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>}
+2
View File
@@ -36,6 +36,8 @@ export interface Memory {
group: string;
source: string;
lifeIds: string[];
// Real memories only: the (already server-trimmed) sent chat messages the memory was made from.
messageIds?: string[];
}
export interface Message {
id: string;
+104 -11
View File
@@ -3,7 +3,7 @@ import type { DemoState, LifeEvent, Memory } from '../domain/model';
import { publicView } from '../domain/privacy';
import { Button, Icon } from '../shared/ui';
import { delay } from '../adapters/demo';
import { lifeDetail, lifePage, NotFound, type LifeStatus } from '../adapters/real';
import { lifeDetail, lifePage, memoryDetail, memoryPage, NotFound, NotWired, type LifeStatus } from '../adapters/real';
// HEL-815 page design: a page lying on your side of the table while the room steps back. Only what she has already
// told you is ever rendered (AM-001), so there is no "not told yet" label, filter or switch anywhere; any link the
// client cannot resolve opens one neutral "can't open" state that reveals nothing about whether the record exists.
@@ -11,10 +11,17 @@ const KIND = { plan: '打算', now: '正在', done: '已经发生' } as const;
const MEMORY_GROUPS = ['我们一起的', '你们的小习惯', '她知道的你', '她的成长'];
const phone = () => matchMedia('(max-width:720px)').matches;
type Load = 'ok' | 'loading' | 'error';
// Real memories also distinguish a server that has no memory route at all (before R3) from one that failed.
type MemLoad = Load | 'unwired';
// A real detail that is not in the loaded pages is asked for by id; anything the server will not show is one 404.
type Lookup = { id: string; state: 'loading' | 'missing' | 'error'; event?: undefined } | { id: string; state: 'ok'; event: LifeEvent };
type MemLookup = { id: string; state: 'loading' | 'missing' | 'error'; memory?: undefined } | { id: string; state: 'ok'; memory: Memory };
const RE_READ_MS = [15000, 45000];
export function LifePanel({ state, open, onClose, onChat, onSettings, now = '', fail = false, real = false, life, ackAt = 0 }: {
const byId = <T extends { id: string }>(a: T, b: T) => Number(b.id) - Number(a.id);
// Real titles and texts are both cut from one server summary; a title the server shortened says so, and a second line
// or quote that would only repeat it is left out.
const heading = (m: Memory) => m.text.length > m.title.length && m.text.startsWith(m.title) ? `${m.title}…` : m.title;
export function LifePanel({ state, open, onClose, onChat, onSaid, onSettings, now = '', fail = false, real = false, life, ackAt = 0 }: {
real?: boolean;
state: DemoState;
open: boolean;
@@ -22,23 +29,55 @@ export function LifePanel({ state, open, onClose, onChat, onSettings, now = '',
fail?: boolean;
onClose: () => void;
onChat: (id: string, messageIds?: string[]) => void;
// Real only: open the conversation at the exact (server-given) messages a memory was made from.
onSaid?: (messageIds: string[]) => void;
onSettings?: () => void;
// Real only: what the life backend is actually doing, and when the server last accepted a complete receipt.
life?: LifeStatus;
ackAt?: number;
}) {
const [realEvents, setRealEvents] = useState<LifeEvent[]>([]), [next, setNext] = useState<string | null>(null), [lookup, setLookup] = useState<Lookup | null>(null), [attempt, setAttempt] = useState(0), [moreError, setMoreError] = useState(false);
const [realMemories, setRealMemories] = useState<Memory[]>([]), [memNext, setMemNext] = useState<string | null>(null), [memLoad, setMemLoad] = useState<MemLoad>(real ? 'loading' : 'ok'), [memMore, setMemMore] = useState(false), [memMoreError, setMemMoreError] = useState(false), [memLookup, setMemLookup] = useState<MemLookup | null>(null);
// Real records come from the server already trimmed (AM-001); the demo filters its local fixtures the same way.
const view: DemoState = real ? { ...state, events: realEvents, memories: [] } : publicView(state), [tab, setTab] = useState('life'), [selection, setSelection] = useState(''), [limit, setLimit] = useState(18), [load, setLoad] = useState<Load>(real ? 'loading' : 'ok'), [more, setMore] = useState(false);
const view: DemoState = real ? { ...state, events: realEvents, memories: realMemories } : publicView(state), [tab, setTab] = useState('life'), [selection, setSelection] = useState(''), [limit, setLimit] = useState(18), [load, setLoad] = useState<Load>(real ? 'loading' : 'ok'), [more, setMore] = useState(false);
const list = useRef<HTMLDivElement>(null), detail = useRef<HTMLElement>(null), scroll = useRef<Record<string, number>>({}), wasOpen = useRef(false), request = useRef<AbortController | null>(null), nextRef = useRef(next), loadRef = useRef(load); nextRef.current = next; loadRef.current = load;
useEffect(() => { if (open) {
const params = new URLSearchParams(location.hash.slice(1));
const id = params.get('event');
const id = params.get('event'), memoryId = params.get('memory');
if (id) {
setTab('life');
setSelection(id);
} else if (memoryId) {
setTab('memory');
setSelection(memoryId);
}
} }, [open]);
// Memories load on their own track, so a slow or missing memory route never holds up her days (and vice versa).
const memRequest = useRef<AbortController | null>(null), memQuiet = useRef<AbortController | null>(null), memNextRef = useRef(memNext), memLoadRef = useRef(memLoad); memNextRef.current = memNext; memLoadRef.current = memLoad;
const reloadMemories = useCallback(async () => {
memQuiet.current?.abort(); memRequest.current?.abort(); const c = new AbortController(); memRequest.current = c;
setMemLoad('loading');
try { const page = await memoryPage(null, c.signal); if (c.signal.aborted) return; setRealMemories(page.memories); setMemNext(page.next); setMemLoad('ok'); }
catch (e) { if (!c.signal.aborted) setMemLoad(e instanceof NotWired ? 'unwired' : 'error'); }
finally { if (!c.signal.aborted) setMemMore(false); }
}, []);
const lookAgainMemories = useCallback(async () => {
if (memLoadRef.current !== 'ok') return;
memQuiet.current?.abort(); const c = new AbortController(); memQuiet.current = c;
try {
const page = await memoryPage(null, c.signal); if (c.signal.aborted) return;
setRealMemories(old => { const known = new Set(old.map(m => m.id)), added = page.memories.filter(m => !known.has(m.id)); return added.length ? [...added, ...old].sort(byId) : old; });
} catch { /* Stays as it was; reopening the page reads again. */ }
}, []);
async function earlierMemories() {
memRequest.current?.abort(); const c = new AbortController(); memRequest.current = c; setMemMore(true); setMemMoreError(false);
try {
if (!memNextRef.current) return;
const page = await memoryPage(memNextRef.current, c.signal);
if (c.signal.aborted) return;
setRealMemories(old => [...old, ...page.memories.filter(m => !old.some(o => o.id === m.id))]); setMemNext(page.next);
} catch { if (!c.signal.aborted) setMemMoreError(true); } finally { if (!c.signal.aborted) setMemMore(false); }
}
// Real: every opening re-reads the newest page, so what she told you since (and only that) shows up. Nothing is
// marked told on this side.
const reload = useCallback(async () => {
@@ -60,15 +99,16 @@ export function LifePanel({ state, open, onClose, onChat, onSettings, now = '',
} catch { /* Stays as it was; reopening the page reads again. */ }
}, []);
// Demo only: the failure switch shows how a list that could not be read looks; nothing real is requested.
useEffect(() => { if (open && !wasOpen.current) { if (real) void reload(); else setLoad(fail ? 'error' : 'ok'); } wasOpen.current = open; if (!open) { request.current?.abort(); quiet.current?.abort(); setMore(false); } }, [open, fail, real, reload]);
useEffect(() => { if (open && !wasOpen.current) { if (real) { void reload(); void reloadMemories(); } else setLoad(fail ? 'error' : 'ok'); } wasOpen.current = open; if (!open) { request.current?.abort(); quiet.current?.abort(); memRequest.current?.abort(); memQuiet.current?.abort(); setMore(false); setMemMore(false); } }, [open, fail, real, reload, reloadMemories]);
// A receipt the server just accepted may unlock a record once her telling is judged, which can finish a little
// later. While the page is open, look again a bounded number of times; leaving and coming back always re-reads.
useEffect(() => {
if (!real || !open || !ackAt) return;
const timers = RE_READ_MS.map(ms => ackAt + ms - Date.now()).filter(ms => ms > 0).map(ms => setTimeout(() => void lookAgain(), ms));
// Her side of a chat memory also waits on that same judged receipt, so memories are looked at again too.
const timers = RE_READ_MS.map(ms => ackAt + ms - Date.now()).filter(ms => ms > 0).map(ms => setTimeout(() => { void lookAgain(); void lookAgainMemories(); }, ms));
return () => timers.forEach(clearTimeout);
}, [real, open, ackAt, lookAgain]);
useEffect(() => () => { request.current?.abort(); quiet.current?.abort(); }, []);
}, [real, open, ackAt, lookAgain, lookAgainMemories]);
useEffect(() => () => { request.current?.abort(); quiet.current?.abort(); memRequest.current?.abort(); memQuiet.current?.abort(); }, []);
async function retry() { if (real) { void reload(); return; } request.current?.abort(); const c = new AbortController(); request.current = c; setLoad('loading'); try { await delay(600, c.signal); setLoad(fail ? 'error' : 'ok'); } catch { /* Closed or replaced. */ } }
async function earlier() {
request.current?.abort(); const c = new AbortController(); request.current = c; setMore(true);
@@ -93,6 +133,15 @@ export function LifePanel({ state, open, onClose, onChat, onSettings, now = '',
lifeDetail(selection, c.signal).then(event => { if (!c.signal.aborted) setLookup({ id: selection, state: 'ok', event }); }, e => { if (!c.signal.aborted) setLookup({ id: selection, state: e instanceof NotFound ? 'missing' : 'error' }); });
return () => c.abort();
}, [real, open, tab, selection, loaded, load, attempt]);
// Same for a memory: an old link or a memory outside the loaded pages is asked for by id, and stays one neutral 404.
const memLoaded = view.memories.some(m => m.id === selection);
useEffect(() => {
if (!real || !open || tab !== 'memory' || !selection || memLoaded || memLoad === 'loading') return;
const c = new AbortController();
setMemLookup({ id: selection, state: 'loading' });
memoryDetail(selection, c.signal).then(memory => { if (!c.signal.aborted) setMemLookup({ id: selection, state: 'ok', memory }); }, e => { if (!c.signal.aborted) setMemLookup({ id: selection, state: e instanceof NotFound ? 'missing' : 'error' }); });
return () => c.abort();
}, [real, open, tab, selection, memLoaded, memLoad, attempt]);
// Each tab keeps its own reading position; switching back lands where you left it.
// A hidden panel is display:none, which drops its scroll offset; reopening (e.g. "结束交谈 · 回到日子") puts it back.
useLayoutEffect(() => { if (list.current && open) list.current.scrollTop = scroll.current[tab] || 0; }, [tab, open]);
@@ -105,7 +154,8 @@ export function LifePanel({ state, open, onClose, onChat, onSettings, now = '',
const ordered = [...view.events.filter(e => e.kind === 'plan'), ...view.events.filter(e => e.kind !== 'plan')], shown = real ? ordered : ordered.slice(0, limit);
const day = (e: LifeEvent) => e.kind === 'plan' ? '她说过的打算' : e.time.split(' ')[0];
const fetched = lookup?.id === selection && lookup.state === 'ok' ? lookup.event : undefined;
const event = tab === 'life' ? view.events.find(e => e.id === selection) || fetched : undefined, memory = tab === 'memory' ? view.memories.find(m => m.id === selection) : undefined;
const memFetched = memLookup?.id === selection && memLookup.state === 'ok' ? memLookup.memory : undefined;
const event = tab === 'life' ? view.events.find(e => e.id === selection) || fetched : undefined, memory = tab === 'memory' ? view.memories.find(m => m.id === selection) || memFetched : undefined;
const name = view.identity.name, demoTag = !real && <span className="tag-demo">演示数据</span>;
// Real: the messages the server says told it, plus what you said in those same turns.
const lines = (e: LifeEvent) => {
@@ -115,7 +165,8 @@ export function LifePanel({ state, open, onClose, onChat, onSettings, now = '',
const said = (who: string, text: string) => <blockquote className="quote"><span className="who"><i/>{who}</span>{text}</blockquote>;
const linkCard = (key: string, title: string, sub: string, go: () => void) => <button className="link-card" key={key} aria-describedby={`lc-${key}`} onClick={go}><span><b>{title}</b><small id={`lc-${key}`}>{sub}</small></span><Icon name="next"/></button>;
function eventView(e: LifeEvent) {
const mems = e.memoryIds.map(id => view.memories.find(m => m.id === id)).filter((m): m is Memory => !!m), chat = lines(e);
// Real: a memory points at a day only through the server-trimmed lifeIds; nothing is linked on this side.
const mems = real ? view.memories.filter(m => m.lifeIds.includes(e.id)) : e.memoryIds.map(id => view.memories.find(m => m.id === id)).filter((m): m is Memory => !!m), chat = lines(e);
return <>
<div className="d-kicker"><i className={`k ${e.kind}`}/>{KIND[e.kind]} · {e.time} · {e.place}</div>
<h3 className="d-title">{e.title}</h3>
@@ -129,6 +180,7 @@ export function LifePanel({ state, open, onClose, onChat, onSettings, now = '',
</>;
}
function memoryView(m: Memory) {
if (real) return realMemoryView(m);
const from = m.lifeIds.map(id => view.events.find(e => e.id === id)).filter((e): e is LifeEvent => !!e);
return <>
<div className="d-kicker"><i className={`k ${m.group === '她的成长' ? 'grow' : 'mem'}`}/>{m.group} · {m.source}</div>
@@ -141,6 +193,23 @@ export function LifePanel({ state, open, onClose, onChat, onSettings, now = '',
<div className="d-foot">{demoTag}回忆由她在相处中整理,只引用她讲过的日子。</div>
</>;
}
// Real memory: only what the server returned. "那时候的聊天" is exactly its messageIds from your own chat history,
// each under who actually said it, so your words are never shown as hers. A day it names but this page has not
// loaded is opened by id and can still only come back as the one neutral "can't open".
function realMemoryView(m: Memory) {
const ids = new Set(m.messageIds || []), chat = view.messages.filter(x => ids.has(x.id) && x.status !== 'failed' && x.status !== 'cancelled');
return <>
<div className="d-kicker"><i className="k mem"/>{m.group} · {m.source}</div>
<h3 className="d-title">{heading(m)}</h3>
<p className="d-told">她是这样记得的</p>
{m.text !== m.title && said(name, m.text)}
{m.lifeIds.length > 0 && <><div className="d-sec">来自这些日子</div><div className="link-list">{m.lifeIds.map(id => { const e = view.events.find(x => x.id === id); return linkCard(id, e ? e.title : '她讲给你听过的一件事', e ? e.time : '在她的日子里打开', () => select(id, 'life')); })}</div></>}
<div className="d-sec">那时候的聊天</div>
{chat.length ? <div className="said-then">{chat.map(x => <p key={x.id} data-role={x.role}><span className="who"><i/>{x.role === 'user' ? '你' : name}</span>{x.text}</p>)}</div> : <p className="d-dim">那时候的聊天现在打不开。</p>}
{chat.length > 0 && onSaid && <Button onClick={() => onSaid(chat.map(x => x.id))}>在交谈里看这段<Icon name="next"/></Button>}
<div className="d-foot">这是她从你们说出口的聊天里整理的回忆,由服务器保存;只有来源可以公开的才会显示。它和她的日子分开,也不会改写她最初的底色。</div>
</>;
}
const failed = <div className="state-card" role="alert"><i className="state-mark"><Icon name="warn"/></i><p className="state-t">这几天的事一时没翻出来。</p><p>不是你的问题,记录也没有丢。</p><Button onClick={() => void retry()}>再试一次</Button></div>;
const skeleton = (n: number) => <div className="skel" aria-hidden="true">{Array.from({ length: n }, (_, i) => <i key={i} style={{ width: `${[78, 62, 70, 54, 66][i % 5]}%` }}/>)}</div>;
function lifeList() {
@@ -150,17 +219,41 @@ export function LifePanel({ state, open, onClose, onChat, onSettings, now = '',
return <>{shown.map((e, i) => <div key={e.id}>{(i === 0 || day(shown[i - 1]) !== day(e)) && <div className="grp">{day(e)}</div>}<button className={`ev told ${e.kind}`} aria-current={selection === e.id} onClick={() => select(e.id)}><time>{e.kind === 'plan' ? e.time : e.time.split(' ')[1]}</time><i className={`k ${e.kind}`}/><span><span className="tt">{e.title}</span><span className="sn">{e.text}</span>{(e.kind !== 'done' || e.memoryIds.length > 0) && <span className="sub">{e.kind === 'plan' && <span className="tag">计划可能会变</span>}{e.kind === 'now' && <span className="tag accent">正在</span>}{e.memoryIds.length > 0 && <span className="tag">和你有关</span>}</span>}</span></button></div>)}
{more ? <p className="more-busy" role="status"><i className="spin"/>正在翻更早的日子…</p> : (real ? next : limit < ordered.length) ? <div className="more">{moreError && <p className="d-dim" role="alert">更早的日子一时没翻出来,记录没有丢。</p>}<Button onClick={() => void earlier()}>{moreError ? '再试一次' : '看更早的日子'}</Button></div> : <p className="list-end">再往前,就是她刚住进来的那天了。</p>}</>;
}
const memItem = (m: Memory) => <button className="mem" key={m.id} aria-current={selection === m.id} onClick={() => select(m.id)}><i className={`k ${m.group === '她的成长' ? 'grow' : 'mem'}`}/><span><small className="src">{m.source}</small><b>{heading(m)}</b>{!m.text.startsWith(m.title) && <span className="sn">{m.text}</span>}</span></button>;
// Real: the server only produces chat memories ("我们一起的"). Unbuilt groups are not drawn as if they could fill;
// "她的成长" stays in Settings (from /api/persona) and is only pointed to here, never counted as a memory.
function realMemoryList() {
if (memLoad === 'loading') return <><p className="grp" role="status">正在翻你们的回忆…</p>{skeleton(5)}</>;
if (memLoad === 'error') return <div className="state-card" role="alert"><i className="state-mark"><Icon name="warn"/></i><p className="state-t">回忆一时没翻出来。</p><p>不是你的问题,聊天和回忆都没有丢。</p><Button onClick={() => void reloadMemories()}>再试一次</Button></div>;
const groups = ['我们一起的', ...new Set(view.memories.map(m => m.group).filter(g => g !== '我们一起的' && g !== '她的成长'))];
return <>
{memLoad === 'unwired' ? <><div className="grp">我们一起的</div><div className="empty">暂无可核实的回忆<small>这台服务的长期记忆尚未接通;文字聊天记录独立保留。</small></div></> : <>
{groups.map(group => { const items = view.memories.filter(m => m.group === group); return <div key={group}><div className="grp">{group}</div>{items.length ? items.map(memItem) : <div className="empty">还没有可以展示的回忆<small>聊过的话,她要过一阵才会整理成回忆;还没整理好的、或来源不能公开的,都不会出现在这里。你们说过的话都在交谈的完整记录里。</small></div>}</div>; })}
{memMore ? <p className="more-busy" role="status"><i className="spin"/>正在翻更早的回忆…</p> : memNext ? <div className="more">{memMoreError && <p className="d-dim" role="alert">更早的回忆一时没翻出来,记录没有丢。</p>}<Button onClick={() => void earlierMemories()}>{memMoreError ? '再试一次' : '看更早的回忆'}</Button></div> : view.memories.length > 0 && <p className="list-end">再往前的聊天,还没有整理成可以展示的回忆。</p>}
</>}
<div className="grp">她的成长</div>
<div className="empty">她后来慢慢有的变化另外保存<small>成长记在「设置 · 她」里,和回忆分开,不改写她最初的底色。</small>{onSettings && <button className="btn-text" onClick={onSettings}>在设置里看底色与成长<Icon name="next"/></button>}</div>
</>;
}
function memoryList() {
if (real) return realMemoryList();
if (load === 'loading') return skeleton(5);
if (load === 'error') return failed;
if (!real && !view.memories.length) return <div className="empty">还没有共同的回忆。<small>聊着聊着就会有了。</small></div>;
return MEMORY_GROUPS.map(group => { const items = view.memories.filter(m => m.group === group); return <div key={group}><div className="grp">{group}{!real && <span>{items.length}</span>}</div>{real && <div className="empty">暂无可核实的回忆<small>长期记忆尚未接通;文字聊天记录独立保留。</small></div>}{items.map(m => <button className="mem" key={m.id} aria-current={selection === m.id} onClick={() => select(m.id)}><i className={`k ${group === '她的成长' ? 'grow' : 'mem'}`}/><span><small className="src">{m.source}</small><b>{m.title}</b><span className="sn">{m.text}</span></span></button>)}</div>; });
}
const blank = load !== 'ok' || (tab === 'life' ? !view.events.length : !view.memories.length);
// Real detail still being looked up by id, or that lookup failed (not a 404), for whichever tab is showing.
const tabLoad = tab === 'life' ? load : memLoad, found = tab === 'life' ? lookup : memLookup;
const pending = real && !!selection && (tabLoad === 'loading' || !found || found.id !== selection || found.state === 'loading');
const lookupFailed = real && !!selection && found?.id === selection && found.state === 'error';
const idle = real ? (tab === 'life' ? (view.events.length ? '选一件她讲给你听过的事,慢慢读。' : life?.wired ? '她讲给你听过的事会出现在左侧;这里是日子详情和那时候的聊天。' : '后台接通后,她讲给你听过的事会出现在左侧;这里保留日子详情、回忆与聊天的关联。')
: view.memories.length ? '选一条,看她怎么记得。' : '她整理好的回忆会出现在左侧;这里是回忆详情和那时候的聊天。')
: blank ? (tab === 'life' ? '选一天,看她那天跟你讲过的事。' : '选一条,看她怎么记得。') : tab === 'life' ? '选一件小事,慢慢读。' : '选一条,看她怎么记得。';
return <section className={`pane glass read ${open ? 'open' : ''} ${selection ? 'has-detail' : ''}`} hidden={!open} aria-label="日子"><header><div className="ttl"><small className="kicker"><span className="k-wide">日子 · {real ? (life?.wired ? '服务器记录' : '后台待接入') : '演示数据'}</span><span className="k-near"><i/>她此刻 · {now || '安静待着'}</span></small><h2>{tab === 'life' ? '她的日子' : '我们的回忆'}</h2></div><span className="grow"/>{real ? <span className="tag-demo">{life?.label || '后台待接入'}</span> : demoTag}<button className="btn-round sm" aria-label="关闭日子" onClick={onClose}><Icon name="x"/></button></header>
<div className="pane-tabs"><div className="tabs" role="tablist">{[['life', '她的日子'], ['memory', '我们的回忆']].map(([t, l]) => <button role="tab" key={t} aria-selected={tab === t} onClick={() => switchTab(t)}>{l}</button>)}</div><span className="tabnote">{tab === 'life' ? '只有她讲给你听过的事,才会出现在这里' : '她记得的你们,和她后来慢慢有的'}</span></div>
<div className="cols"><div className="list" ref={list} onScroll={e => { scroll.current[tab] = e.currentTarget.scrollTop; }}>{tab === 'life' ? lifeList() : memoryList()}</div>
<article className="detail" ref={detail}><button className="btn-text back" onClick={() => setSelection('')}><Icon name="back"/>返回{tab === 'life' ? '她的日子' : '我们的回忆'}</button>
{event ? <div className="d-in" key={`e-${event.id}`}>{eventView(event)}</div> : memory ? <div className="d-in" key={`m-${memory.id}`}>{memoryView(memory)}</div> : real && tab === 'life' && selection && (load === 'loading' || !lookup || lookup.id !== selection || lookup.state === 'loading') ? skeleton(5) : real && tab === 'life' && selection && lookup?.state === 'error' ? <div className="state-card" role="alert"><i className="state-mark"><Icon name="warn"/></i><p className="state-t">这一条一时没翻出来。</p><p>不是你的问题,记录也没有丢。</p><Button onClick={() => setAttempt(n => n + 1)}>再试一次</Button></div> : selection ? <div className="state-card"><i className="state-mark"><Icon name="warn"/></i><p className="state-t">这一条现在打不开。</p><p>可能是链接已经过期。</p><Button onClick={() => setSelection('')}>回到{tab === 'life' ? '她的日子' : '我们的回忆'}</Button></div> : load === 'loading' ? skeleton(5) : <div className="d-empty"><div><Icon name="book"/>{real ? (view.events.length ? '选一件她讲给你听过的事,慢慢读。' : life?.wired ? '她讲给你听过的事会出现在左侧;这里是日子详情和那时候的聊天。' : '后台接通后,她讲给你听过的事会出现在左侧;这里保留日子详情、回忆与聊天的关联。') : blank ? (tab === 'life' ? '选一天,看她那天跟你讲过的事。' : '选一条,看她怎么记得。') : tab === 'life' ? '选一件小事,慢慢读。' : '选一条,看她怎么记得。'}</div></div>}
{event ? <div className="d-in" key={`e-${event.id}`}>{eventView(event)}</div> : memory ? <div className="d-in" key={`m-${memory.id}`}>{memoryView(memory)}</div> : pending ? skeleton(5) : lookupFailed ?<div className="state-card" role="alert"><i className="state-mark"><Icon name="warn"/></i><p className="state-t">这一条一时没翻出来。</p><p>不是你的问题,记录也没有丢。</p><Button onClick={() => setAttempt(n => n + 1)}>再试一次</Button></div> : selection ? <div className="state-card"><i className="state-mark"><Icon name="warn"/></i><p className="state-t">这一条现在打不开。</p><p>可能是链接已经过期。</p><Button onClick={() => setSelection('')}>回到{tab === 'life' ? '她的日子' : '我们的回忆'}</Button></div> : load === 'loading' ? skeleton(5) : <div className="d-empty"><div><Icon name="book"/>{idle}</div></div>}
</article></div></section>;
}
+3
View File
@@ -845,6 +845,9 @@ body:has(textarea:focus) .space *{animation-play-state:paused!important}
.mem .src{display:block;margin:0;font-size:12px;color:var(--text-3)}
.mem b{display:block;font-weight:400;font-size:15px}
.mem[aria-current="true"]{border-color:transparent;box-shadow:inset 2px 0 0 var(--accent)}
/* The memory dot also carries .mem; keep the card rules above from turning it into a padded block. */
i.k.mem,i.k.mem:hover{display:inline-block;width:9px;height:9px;padding:0;margin:7px 0 0;border-radius:50%;background:transparent;border:1.5px solid var(--accent);box-shadow:none}
.d-kicker i.k.mem{margin:0}
.ev[aria-current="true"]{box-shadow:inset 2px 0 0 var(--accent)}
.more-busy{display:flex;align-items:center;justify-content:center;gap:10px;margin:18px 0 6px;font-size:13px;color:var(--text-3)}
.more-busy .spin{width:14px;height:14px}