import { api, clockOf, loadPersona, retryPersona, type Health, type LifeStatus, type PersonaView, type RealIdentity } from '../adapters/real'; import { useEffect, useRef, useState } from 'react'; import type { DemoState, Settings, Theme } from '../domain/model'; import { delay } from '../adapters/demo'; import { exportDemo, parseState } from '../adapters/storage'; import { BaseColor, Button, Field, Icon, Modal, Status } from '../shared/ui'; const sections = [['her', 'user', '她'], ['relation', 'heart', '关系'], ['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 = { ro: ['只读', ''], edit: ['可以调整', 'accent'], demo: ['演示数据', 'demo'], off: ['未接入', 'off'], live: ['文字已接通', 'ok'], local: ['本机生效', 'ok'] }; const capOf = (id: string, real: boolean): Cap => id === 'her' ? 'ro' : id === 'relation' ? 'edit' : id === 'display' ? 'local' : id === 'services' && real ? 'live' : real ? 'off' : 'demo'; const NOTE: Record = { her: '只读资料', relation: '可以调整', display: '本机生效' }; function CapTag({ cap }: { cap: Cap }) { const [text, tone] = CAP[cap]; return {text}; } // 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

{title}

{will}

{now}

; } export function ManagePanel({ state, open, onClose, onSave, fail, theme, setTheme, real = false, now = '', focus = 0, life }: { real?: boolean; // Real only: what the life backend is actually doing (never "running" from its switch alone). life?: LifeStatus; state: DemoState; open: boolean; onClose: () => void; onSave: (s: DemoState) => void; fail: boolean; theme: Theme; setTheme: (t: Theme) => void; now?: string; // Bumped when another page asks to show her base colour and growth ("在设置里看底色与成长"). focus?: number; }) { const [section, setSection] = useState('her'), [detail, setDetail] = useState(false), [draft, setDraft] = useState(() => ({ settings: structuredClone(state.settings), identity: structuredClone(state.identity) })), [message, setMessage] = useState(''), [error, setError] = useState(false), [busy, setBusy] = useState(false), [confirm, setConfirm] = useState(''), [confirmText, setConfirmText] = useState(''), [search, setSearch] = useState(''), [restore, setRestore] = useState(null), [material, setMaterial] = useState(''), [check, setCheck] = useState(''); const approvedNavigation = useRef(false); const pendingNavigation = useRef<(() => void) | null>(null); const [serviceHealth, setServiceHealth] = useState(); const request = useRef(null), generation = useRef(0), feedback = useRef(null); useEffect(()=>{if(message) feedback.current?.scrollIntoView({block:'center'});},[message]); const latestState = useRef(state); latestState.current = state; const dirtySections: Record = {relation: JSON.stringify(draft.identity)!==JSON.stringify(state.identity), city: !real && draft.settings.city!==state.settings.city, services: !real && JSON.stringify(draft.settings.services)!==JSON.stringify(state.settings.services), display: draft.settings.reduced!==state.settings.reduced}; const dirty = !!dirtySections[section], anyDirty = Object.values(dirtySections).some(Boolean); useEffect(() => { if (!open) { request.current?.abort(); setBusy(false); } }, [open]); useEffect(() => () => { request.current?.abort(); }, []); useEffect(() => { if (!anyDirty) return; const before = (e: BeforeUnloadEvent) => { e.preventDefault(); }; window.addEventListener('beforeunload', before); return () => window.removeEventListener('beforeunload', before); }, [anyDirty]); const requestLeave = (action: () => void) => { if (anyDirty) { pendingNavigation.current = action; setConfirm('leave'); } else action(); }; useEffect(() => { if (!open || !anyDirty) return; const guard = (event: Event) => { if (approvedNavigation.current) return; event.preventDefault(); pendingNavigation.current = (event as CustomEvent<() => void>).detail; setConfirm('leave'); }; window.addEventListener('cg:leave-settings', guard); return () => window.removeEventListener('cg:leave-settings', guard); }, [open, anyDirty]); async function checkService() { setBusy(true); setError(false); setMessage('正在检查文字服务…'); try { const status = await api('health'); setServiceHealth(status); setMessage(status.llm.ok ? '文字服务可达。语音、视觉和长期记忆仍未接通。' : '文字模型暂时不可达,档案和历史仍可查看。'); setError(!status.llm.ok); } catch (e) { setMessage((e as Error).message); setError(true); } finally { setBusy(false); } } const settings = (value: Partial) => setDraft(d => ({ ...d, settings: { ...d.settings, ...value } })); const reset = () => { request.current?.abort(); generation.current++; setBusy(false); setDraft(d => ({identity: section==='relation'?structuredClone(state.identity):d.identity, settings: {...d.settings, ...(section==='city'?{city:state.settings.city}:section==='services'?{services:structuredClone(state.settings.services)}:section==='display'?{reduced:state.settings.reduced}:{})}})); setMessage('已取消,恢复为上次保存的内容。'); setError(false); }; async function save(confirmed = false) { if (section==='relation' && draft.identity.relation !== state.identity.relation && !confirmed) { setConfirm('relation'); return; } request.current?.abort(); const ctrl = new AbortController(); request.current = ctrl; setBusy(true); setError(false); setMessage(real ? '正在保存…' : '正在保存到本机…'); try { if (real && section === 'relation') { const identity = await api('relation', { method: 'PATCH', signal: ctrl.signal, body: JSON.stringify({ relation: draft.identity.relation, nickname: draft.identity.nickname, boundary: draft.identity.boundary }) }); if (!ctrl.signal.aborted) { onSave({ ...latestState.current, identity }); setMessage('已保存在服务器,聊天与底色保留。'); } return; } if (real && section === 'display') { localStorage.setItem('cg.real.display', JSON.stringify({ reduced: draft.settings.reduced })); onSave({ ...latestState.current, settings: { ...latestState.current.settings, reduced: draft.settings.reduced } }); setMessage('显示偏好已保存在此浏览器。'); return; } await delay(450, ctrl.signal); if (fail) throw new Error('这次没存好,你的修改还在,可以再试一次。'); const current=latestState.current; const next = {...current, identity: section==='relation'?draft.identity:current.identity, settings:{...current.settings, ...(section==='city'?{city:draft.settings.city}:section==='services'?{services:draft.settings.services}:section==='display'?{reduced:draft.settings.reduced}:{})}}; onSave(next); setMessage(real ? '显示偏好已应用。' : '已保存在本机演示中。'); } catch (e) { if (ctrl.signal.aborted) return; setError(true); setMessage((e as Error).message); } finally { if (!ctrl.signal.aborted) setBusy(false); } } async function importBackup(file?: File) { const gen = ++generation.current; setRestore(null); if (!file) return; try { if (file.size > 5000000) throw new Error('请选 5MB 以内的演示 JSON。'); const next = parseState(await file.text(), state.identity); if (gen !== generation.current) return; setRestore(next); setMessage('完整性、版本和同一位档案检查通过。可以确认恢复。'); setError(false); } catch (e) { if (gen !== generation.current) return; setError(true); setMessage('无法恢复:' + (e as Error).message); } } async function importMaterial(file?: File) { const gen = ++generation.current; setMaterial(''); setCheck(''); if (!file) return; try { if (file.size > 100000) throw new Error('演示清单不能超过 100KB。'); const x: unknown = JSON.parse(await file.text()); if (!x || typeof x !== 'object' || !('manifest_version' in x) || x.manifest_version !== 1 || !('appearance_id' in x) || typeof x.appearance_id !== 'string' || !/^[\w-]{1,60}$/.test(x.appearance_id) || !('clips' in x) || !Array.isArray(x.clips) || !x.clips.length) throw new Error('需要 manifest_version:1、合法 appearance_id 和非空 clips。'); if (gen !== generation.current) return; setMaterial(x.appearance_id); setCheck('✓ JSON 结构通过 · ✓ 版本通过 · 媒体格式、时长、人脸一致性:未真实检测,不应用外部媒体。'); } catch (e) { if (gen !== generation.current) return; setCheck('检查没通过:' + (e instanceof SyntaxError?'清单不是有效的 JSON,请重新选择。':(e as Error).message)); } } const switchSection = (s: string) => { request.current?.abort(); generation.current++; setBusy(false); setSection(s); setDetail(true); setMessage(''); }; const lastFocus = useRef(focus); useEffect(() => { if (focus === lastFocus.current) return; lastFocus.current = focus; switchSection('her'); }, [focus]); // Esc on a phone steps back from a section to the section list first; confirmations handle their own Esc. useEffect(() => { if (!open || !detail) return; const key = (e: KeyboardEvent) => { if (e.key !== 'Escape' || confirm || !matchMedia('(max-width:720px)').matches) return; e.stopImmediatePropagation(); setDetail(false); }; window.addEventListener('keydown', key, true); return () => window.removeEventListener('keydown', key, true); }, [open, detail, confirm]); const growth = state.memories.filter(m => m.group === '她的成长' && m.lifeIds.every(id => state.events.some(e => e.id === id && e.shared === true))); // ── Real persona layers (HEL-827 GET /api/persona). Birth facts above stay read-only; these are separate model // layers and are never filled with the old six-section template. ── const [persona, setPersona] = useState(), [personaLoad, setPersonaLoad] = useState<'loading' | 'ok' | 'error'>('loading'), [personaNote, setPersonaNote] = useState(''), [personaBusy, setPersonaBusy] = useState(false), [personaRead, setPersonaRead] = useState(0); const personaRequest = useRef(null), polls = useRef(0); const readPersona = (quiet = false) => { personaRequest.current?.abort(); const c = new AbortController(); personaRequest.current = c; if (!quiet) setPersonaLoad('loading'); loadPersona(c.signal).then(view => { if (!c.signal.aborted) { setPersona(view); setPersonaLoad('ok'); } }, () => { if (!c.signal.aborted && !quiet) setPersonaLoad('error'); }); }; useEffect(() => { if (!real || !open || section !== 'her') return; polls.current = 0; readPersona(); return () => personaRequest.current?.abort(); }, [real, open, section, personaRead]); // A profile created moments ago may still be forming: look again a bounded number of times, never forever. useEffect(() => { if (!real || !open || section !== 'her' || persona?.state !== 'loading' || polls.current >= 12) return; const t = setTimeout(() => { polls.current++; readPersona(true); }, 5000); return () => clearTimeout(t); }, [real, open, section, persona]); async function retryGeneration() { personaRequest.current?.abort(); const c = new AbortController(); personaRequest.current = c; setPersonaBusy(true); setPersonaNote(''); try { const view = await retryPersona(c.signal); if (!c.signal.aborted) { setPersona(view); setPersonaLoad('ok'); if (view.state === 'failed') setPersonaNote('这次还是没有形成。档案和底色都保留,可以稍后再试。'); } } catch (e) { if (!c.signal.aborted) setPersonaNote(e instanceof DOMException ? '这次没有等到结果。档案和底色都保留,可以稍后再试。' : (e as Error).message); } finally { setPersonaBusy(false); } } const day = (ms: number) => clockOf(ms).date; const backfilled = (provenance?: string) => provenance === 'backfilled-R2'; function personaView() { if (personaLoad === 'loading' && !persona) return ; if (personaLoad === 'error' || !persona) return

她的这部分资料一时没读出来。

不是你的问题,资料仍在服务器保存。

; const p = persona, interp = p.interpretation; if (p.state === 'ready' && interp) return <>
{interp.text}

{backfilled(interp.provenance) ? `后来补上的初始印象 · ${day(interp.created_at)} 生成,不是她出生时就有的。` : `创建时形成 · ${day(interp.created_at)}`} 由模型从出生资料自主形成,会延续;不是固定模板,也不能直接改写。

; if (p.state === 'loading') return <>

{polls.current >= 12 ? '还在形成中。稍后回到这里会再看一次。' : '她正在形成对自己的理解…'}

; if (p.state === 'failed') return

她对自己的理解这次没有形成。

档案、名字和底色都保留;这里不会用模板顶替。

{personaNote &&

{personaNote}

}
; if (p.state === 'not_initialized') return ; return ; } function personaLayers() { const p = personaLoad === 'ok' ? persona : undefined, ready = p?.state === 'ready'; const SOURCE: Record = { life: '来自她讲给你听过的一天', chat: '来自你们的一次聊天' }; return

最初就有的{ready && backfilled(p?.interpretation?.provenance) ? '后来补上的初始印象' : '创建时形成'}

{ready && p?.seeds.length ?
    {p.seeds.map(s =>
  • {s.text}{backfilled(s.provenance) ? `后来补上 · ${day(s.created_at)}` : day(s.created_at)}
  • )}
:

{!p ? '读取中…' : ready ? '没有记下最初的小习惯。' : '和她对自己的理解一起形成;现在还没有。'}

}

后来慢慢有的成长 · 单独记录

{p?.growth.length ?
    {p.growth.map(g =>
  • {g.text}{SOURCE[g.source] || '有来处的成长'} · {day(g.ts)}
  • )}
:

{!p ? '读取中…' : '还没有记下的成长。长期记忆尚未接通,聊天记录已独立保存。'}

}
; } const sectionLabel = (id: string) => real && id === 'backup' ? '备份' : sections.find(s => s[0] === id)?.[2] || ''; return