import { api, type Health, 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', '显示']]; export function ManagePanel({ state, open, onClose, onSave, fail, theme, setTheme, real = false }: { real?: boolean; state: DemoState; open: boolean; onClose: () => void; onSave: (s: DemoState) => void; fail: boolean; theme: Theme; setTheme: (t: Theme) => void; }) { 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(''); }; return