HEL-828: wire life/persona/receipt confirmation onto 4575b275 (original author delivery, 12 files per MANIFEST in HEL-828-source-4575b275.zip)
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
co-authored by
multica-agent
parent
4575b27515
commit
58d65aea05
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"baseline_version": "1.10",
|
||||
"read_commit": "4575b27515f391d7a8b91324dfd3b464a9b090e2",
|
||||
"requirement_ids": [
|
||||
"CG-007",
|
||||
"CG-008",
|
||||
"CG-012",
|
||||
"CG-013",
|
||||
"CG-014",
|
||||
"CG-015",
|
||||
"CG-016",
|
||||
"CG-018",
|
||||
"CG-020",
|
||||
"CG-031",
|
||||
"AM-001",
|
||||
"AM-002",
|
||||
"AM-003",
|
||||
"UX-001",
|
||||
"UX-002",
|
||||
"UX-003",
|
||||
"UX-004",
|
||||
"UX-005",
|
||||
"UX-006",
|
||||
"VIS-004",
|
||||
"VIS-007",
|
||||
"VIS-013",
|
||||
"GOV-001",
|
||||
"GOV-002",
|
||||
"GOV-003",
|
||||
"GOV-004",
|
||||
"GOV-005",
|
||||
"DEL-001"
|
||||
],
|
||||
"deliverable": "HEL-828 视觉总监在已审页面上接线:日子页读 GET /api/life 分页与 /api/life/{id} 详情(同形404、加载/空/失败沿用原状态,不用演示填充,完整历史不截200条),消息 lifeIds 与“在交谈里看这段”关联;设置·她 读 GET /api/persona 的 interpretation/seeds/growth 五状态与显式 retry,backfilled-R2 标“后来补上的初始印象”,出生事实仍只读;真实对话在 TurnGate 接受的完整 final 上用纯JS UTF-8 SHA-256 核对 receipt.text_hash 后 POST /api/chat/received 五字段(有界重试、幂等、replay 用 receipt 内原 epoch);生活状态文案按 health.backend 与 life_runtime.state 如实显示;后端只改 health.backend.web_connected=true。未改布局/动效,未部署。",
|
||||
"acceptance": [
|
||||
"日子:已公开事件分页(next_before)、详情、关联聊天跳转;隐藏/未知/非法ID统一“这一条现在打不开”;真实模式不出现演示资料",
|
||||
"人格:ready/loading(有界轮询12×5s)/failed(可重新形成)/disabled/not_initialized(旧档案不自动补建);空成长不伪造",
|
||||
"确认:仅 gate 接受、未 abort、完整 final 且全文已写入后计算哈希并确认;delta/error/取消/断流/哈希不符不确认;404/422不重试,网络/5xx最多3次",
|
||||
"普通HTTP非localhost(isSecureContext=false、无crypto.subtle)下中文/emoji/ZWJ/块边界哈希与.NET SHA256一致",
|
||||
"accepted 后不乐观置told:日子页打开时重读,已开着时在15s/45s各安静重读一次;离开再回来总是重读",
|
||||
"health 无 backend 显示“生活尚未接通”;backend.life=false 显示“后台未启用”;仅 life_runtime.state=running 才说后台运行中"
|
||||
],
|
||||
"deferred": [
|
||||
"总工 HEL-829:机械入库、npm build/lint/vitest、pytest、check_requirements 与 git diff --check;本环境无 git/node/python 未能运行",
|
||||
"两主题电脑/手机真实页面截图与浏览器接线流程(含重启replay、409、取消即重问)需构建后由总工补验;本卡未能出图",
|
||||
"后端真实样例第三人称“它”/办公楼茶水间的内容质量风险交总工审核;本卡未改提示词/温度、未追加真实调用",
|
||||
"隔离部署与真实连续3天每天1–4条长跑;本卡未部署",
|
||||
"R3长期记忆/FTS、R4主动联系、R5语音、R6城市天气素材备份、R7授权观察、真实视频/口型仍由主卡承接"
|
||||
],
|
||||
"requirement_changes": [],
|
||||
"verification": [
|
||||
"Edge headless 经 http://192.168.200.18(非localhost,secureContext=false, subtle=false)运行 harness:10个哈希向量+abc向量、五字段、receipt epoch、部分文本/他轮不确认、404不重试、网络失败3次即止、并发幂等、503后重试成功、存储无token,共21项PASS;harness 为 sha256.ts/receipt.ts 去类型手工转写,不是构建产物",
|
||||
"参考哈希由 .NET SHA256 独立计算核对一致",
|
||||
"web/tests/r2wiring.test.ts 新增 vitest(含 replay 当前epoch过闸+原epoch确认、取消轮不过闸),未运行:本机无node",
|
||||
"TS 未经 tsc/vite 编译;页面、手机、两主题未出图;pytest/check_requirements 未运行",
|
||||
"未访问8300/8310/8320,未复制用户档案或聊天;无部署、无PR合并"
|
||||
],
|
||||
"product_target": "origin/agent/agent/de8874a3803b",
|
||||
"branch": "未提交(无git);基于 agent/agent/2aea213ca76f @ 4575b27515f391d7a8b91324dfd3b464a9b090e2 的源码包",
|
||||
"frontend_connected": true,
|
||||
"deployed": false,
|
||||
"three_day_run": false
|
||||
}
|
||||
@@ -278,8 +278,11 @@ def create_app(
|
||||
"ok": True,
|
||||
"version": "R2-backend",
|
||||
"life_runtime": app.state.life.status(),
|
||||
# web_connected: this release's web build reads /api/life, /api/persona and confirms receipts (HEL-828).
|
||||
# It says nothing about the loop running (life_runtime.state) and capabilities.life stays false until
|
||||
# the isolated multi-day run is accepted.
|
||||
"backend": {"life": life_config.enabled, "persona": life_config.enabled,
|
||||
"receipt": True, "web_connected": False},
|
||||
"receipt": True, "web_connected": True},
|
||||
"epoch": app.state.epoch,
|
||||
"companion_created": bool(app.state.store.query_one("SELECT id FROM companion")),
|
||||
"llm": {"ok": ok, "model": models.tiers["high"].model},
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ChatAdapter } from './demo';
|
||||
import type { DemoState, Identity, Message, ServerEvent } from '../domain/model';
|
||||
import type { DemoState, Identity, LifeEvent, Message, ServerEvent } from '../domain/model';
|
||||
import { defaultSettings } from '../domain/model';
|
||||
|
||||
export interface Color {
|
||||
@@ -9,7 +9,80 @@ export interface Color {
|
||||
interpretation?: string;
|
||||
}
|
||||
export interface RealIdentity extends Identity { color: Color }
|
||||
export interface Health { epoch: number; llm: { ok: boolean; model: string } }
|
||||
export interface LifeRuntime { state: string; timezone: string; budget_warning: boolean; budget_stopped: boolean; last: { status: string; reason: string | null; finished_at: number | null } | null }
|
||||
export interface Health {
|
||||
epoch: number; llm: { ok: boolean; model: string };
|
||||
// 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;
|
||||
}
|
||||
// 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 }
|
||||
export function lifeStatus(health?: Health): LifeStatus {
|
||||
if (!health?.backend) return { wired: false, on: false, now: '生活尚未接通', label: '后台待接入', note: '生活后台尚未接通,不用示例经历填充。' };
|
||||
if (!health.backend.life) return { wired: true, on: false, now: '生活后台未启用', label: '后台未启用', note: '这台服务没有启用生活后台,不会生成新的日子,也不用示例经历填充。' };
|
||||
const state = health.life_runtime?.state || '';
|
||||
if (state === 'running') return { wired: true, on: true, now: '日子在后台继续', label: '后台运行中', note: '她的日子由服务器记录,关上网页也会继续。只有她在交谈里讲给你听过的,才会出现在这里。' };
|
||||
if (state === 'starting' || state === 'waiting_for_companion') return { wired: true, on: false, now: '生活后台正在启动', label: '后台启动中', note: '生活后台正在启动,还没有开始记录她的日子。' };
|
||||
if (state === 'paused_failures') return { wired: true, on: false, now: '生活后台已暂停', label: '后台已暂停', note: '连续几次没有生成成功,后台已暂停,等待检查;不会补造经历。' };
|
||||
if (state === 'budget_stopped') return { wired: true, on: false, now: '今天的生活暂停了', label: '今日已暂停', note: '今天的后台用量到了上限,新的日子暂停生成;不会补造经历。' };
|
||||
return { wired: true, on: false, now: '生活后台没有在运行', label: '后台未运行', note: '生活后台现在没有在运行,不会生成新的日子。' };
|
||||
}
|
||||
// ── Real life records (GET /api/life). The server returns only what she has already told you (AM-001). ──
|
||||
export interface ServerLife { id: number; ts: number; kind: string; content: string; place: string | null; salience: number; source: string; day_key: string; tz: string | null; told: true; told_at: number | null; messageIds: number[] }
|
||||
const NATURE: Record<string, string> = { scene: '那时的情景', thought: '一个念头', encounter: '遇到的事', mood_shift: '心情的变化' };
|
||||
const ints = (v: unknown): v is number[] => Array.isArray(v) && v.every(n => Number.isSafeInteger(n) && n > 0);
|
||||
function serverLife(v: unknown): v is ServerLife {
|
||||
const e = v as Record<string, unknown>;
|
||||
return !!e && typeof e === 'object' && Number.isSafeInteger(e.id) && (e.id as number) > 0 && Number.isFinite(e.ts) && typeof e.content === 'string' && typeof e.day_key === 'string' && /^\d{4}-\d{2}-\d{2}$/u.test(e.day_key) && e.told === true && ints(e.messageIds);
|
||||
}
|
||||
// Wall clock of a unix-ms instant in the zone the event was recorded in (its day_key was computed there too).
|
||||
export function clockOf(ms: number, tz?: string | null) {
|
||||
const options: Intl.DateTimeFormatOptions = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' };
|
||||
let parts: Intl.DateTimeFormatPart[];
|
||||
try { parts = new Intl.DateTimeFormat('en-CA', { ...options, timeZone: tz || undefined }).formatToParts(ms); }
|
||||
catch { parts = new Intl.DateTimeFormat('en-CA', options).formatToParts(ms); }
|
||||
const p = (type: string) => parts.find(x => x.type === type)?.value || '';
|
||||
return { date: `${p('year')}-${p('month')}-${p('day')}`, time: `${p('hour')}:${p('minute')}` };
|
||||
}
|
||||
export function toLifeEvent(e: ServerLife): LifeEvent {
|
||||
const at = clockOf(e.ts, e.tz), told = e.told_at ? clockOf(e.told_at, e.tz) : null;
|
||||
return { id: String(e.id), title: NATURE[e.kind] || '她的一件事', text: e.content, time: `${e.day_key} ${at.time}`, place: e.place || '', kind: 'done', shared: true,
|
||||
...(told ? { told: `${told.date === e.day_key ? '' : told.date.slice(5) + ' '}${told.time} 讲给你听` } : {}), memoryIds: [], messageIds: e.messageIds.map(String) };
|
||||
}
|
||||
export async function lifePage(before: string | null, signal: AbortSignal): Promise<{ events: LifeEvent[]; next: string | null }> {
|
||||
const page = await api<{ events: unknown[]; next_before: number | null }>(`life?limit=50${before ? `&before=${encodeURIComponent(before)}` : ''}`, { signal: within(signal, 10000) });
|
||||
// Malformed rows are dropped, never patched up into something that looks real.
|
||||
return { events: (Array.isArray(page.events) ? page.events : []).filter(serverLife).map(toLifeEvent), next: Number.isSafeInteger(page.next_before) ? String(page.next_before) : null };
|
||||
}
|
||||
export class NotFound extends Error {}
|
||||
export async function lifeDetail(id: string, signal: AbortSignal): Promise<LifeEvent> {
|
||||
if (!/^\d{1,19}$/u.test(id)) throw new NotFound();
|
||||
let response: Response;
|
||||
try { response = await fetch(`/api/life/${id}`, { signal: within(signal, 10000) }); }
|
||||
catch (e) { if (signal.aborted) throw e; throw new Error('暂时连不上真实服务,请检查连接后重试。'); }
|
||||
// Unknown, hidden, 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 (!serverLife(data?.event)) throw new NotFound();
|
||||
return toLifeEvent(data.event);
|
||||
}
|
||||
// ── 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';
|
||||
interpretation: { id: number; text: string; model: string; created_at: number; provenance: string } | null;
|
||||
seeds: { id: number; text: string; created_at: number; provenance: string }[];
|
||||
growth: { id: number; ts: number; source: string; ref_id: number; text: string; created_at: number }[];
|
||||
}
|
||||
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) {
|
||||
const c = new AbortController(), stop = () => c.abort(), timer = setTimeout(stop, ms);
|
||||
signal.addEventListener('abort', () => { clearTimeout(timer); stop(); }, { once: true });
|
||||
return c.signal;
|
||||
}
|
||||
export async function api<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
let response: Response;
|
||||
try { response = await fetch(`/api/${path}`, { ...init, headers: { 'Content-Type': 'application/json', ...init?.headers }, signal: init?.signal ?? AbortSignal.timeout(10000) }); }
|
||||
@@ -33,8 +106,9 @@ export async function loadMessages(): Promise<Message[]> {
|
||||
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'] }[]; next_before: number | null } = await api(`messages?limit=200${before ? `&before=${before}` : ''}`);
|
||||
messages.unshift(...page.messages.map(m => ({ id: String(m.id), role: m.role, text: m.text, lifeIds: [], turnId: m.turn_id, status: m.status })));
|
||||
const page: { messages: { id: number; role: Message['role']; text: string; turn_id: string; status: Message['status']; lifeIds?: number[] }[]; 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.
|
||||
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 })));
|
||||
before = page.next_before;
|
||||
} while (before);
|
||||
return messages;
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { Receipt } from '../domain/model';
|
||||
import { sha256Hex } from './sha256';
|
||||
// Complete-receipt confirmation (HEL-827 contract). The caller has already passed the TurnGate for this turn, the
|
||||
// final parsed and its full text is kept. Here the hash is recomputed from the text actually received and the five
|
||||
// contract fields are posted. Nothing else ever goes to /api/chat/received; the client never names life events.
|
||||
// The token lives only in this call's closure and the in-memory de-duplication set: never storage, history, logs or UI.
|
||||
export type ReceiptOutcome = 'accepted' | 'mismatch' | 'rejected' | 'gave-up';
|
||||
const RETRY_MS = [1500, 5000];
|
||||
const confirmed = new Set<string>(), inFlight = new Map<string, Promise<ReceiptOutcome>>();
|
||||
const keyOf = (r: Receipt) => `${r.message_id}:${r.token}`;
|
||||
const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
|
||||
export function receiptMatches(receipt: unknown, turnId: string, text: string): receipt is Receipt {
|
||||
if (!receipt || typeof receipt !== 'object') return false;
|
||||
const r = receipt as Record<string, unknown>;
|
||||
return Number.isSafeInteger(r.message_id) && (r.message_id as number) > 0 && r.turn_id === turnId && Number.isSafeInteger(r.epoch) && (r.epoch as number) > 0
|
||||
&& typeof r.token === 'string' && r.token.length >= 40 && r.token.length <= 100 && typeof r.text_hash === 'string' && /^[0-9a-f]{64}$/u.test(r.text_hash)
|
||||
&& sha256Hex(text) === r.text_hash;
|
||||
}
|
||||
// Bounded and idempotent: one request at a time per receipt, two delayed retries on transport/server failure, none on
|
||||
// 404/422 (forged, expired, mismatched or malformed — the server answers those the same way). A failure only means the
|
||||
// life stays unpublished; nothing is ever shown early.
|
||||
export function confirmReceipt(receipt: Receipt, turnId: string, text: string, post: typeof fetch = fetch): Promise<ReceiptOutcome> {
|
||||
if (!receiptMatches(receipt, turnId, text)) return Promise.resolve('mismatch');
|
||||
const key = keyOf(receipt);
|
||||
if (confirmed.has(key)) return Promise.resolve('accepted');
|
||||
const running = inFlight.get(key);
|
||||
if (running) return running;
|
||||
const body = JSON.stringify({ message_id: receipt.message_id, turn_id: receipt.turn_id, epoch: receipt.epoch, token: receipt.token, text_hash: sha256Hex(text) });
|
||||
const attempt = async (): Promise<ReceiptOutcome> => {
|
||||
for (let i = 0; ; i++) {
|
||||
let status = 0;
|
||||
try {
|
||||
const response = await post('/api/chat/received', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body, signal: AbortSignal.timeout(10000) });
|
||||
status = response.status;
|
||||
if (response.ok && (await response.json().catch(() => null))?.accepted === true) { confirmed.add(key); return 'accepted'; }
|
||||
} catch { /* Network failure: retried within the bound below. */ }
|
||||
if (status >= 400 && status < 500) return 'rejected';
|
||||
if (i >= RETRY_MS.length) return 'gave-up';
|
||||
await wait(RETRY_MS[i]);
|
||||
}
|
||||
};
|
||||
const task = attempt().finally(() => inFlight.delete(key));
|
||||
inFlight.set(key, task);
|
||||
return task;
|
||||
}
|
||||
// Tests only: start from a clean in-memory state.
|
||||
export function forgetReceipts() { confirmed.clear(); inFlight.clear(); }
|
||||
@@ -0,0 +1,36 @@
|
||||
// SHA-256 over the UTF-8 bytes of a string, in plain JS. crypto.subtle only exists in secure contexts, and the
|
||||
// first release is reached over plain LAN HTTP (CG-020), so one path is used everywhere: localhost, LAN HTTP, HTTPS.
|
||||
const K = new Uint32Array([
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
||||
]);
|
||||
export function sha256Hex(text: string): string {
|
||||
const data = new TextEncoder().encode(text), bits = data.length * 8;
|
||||
const padded = new Uint8Array(((data.length + 9 + 63) >> 6) << 6);
|
||||
padded.set(data); padded[data.length] = 0x80;
|
||||
const view = new DataView(padded.buffer);
|
||||
view.setUint32(padded.length - 8, Math.floor(bits / 0x100000000)); view.setUint32(padded.length - 4, bits >>> 0);
|
||||
const h = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]), w = new Uint32Array(64);
|
||||
const rotr = (x: number, n: number) => (x >>> n) | (x << (32 - n));
|
||||
for (let offset = 0; offset < padded.length; offset += 64) {
|
||||
for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4);
|
||||
for (let i = 16; i < 64; i++) {
|
||||
const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3), s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
|
||||
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
|
||||
}
|
||||
let [a, b, c, d, e, f, g, k] = h;
|
||||
for (let i = 0; i < 64; i++) {
|
||||
const t1 = (k + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]) >>> 0;
|
||||
const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0;
|
||||
k = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0;
|
||||
}
|
||||
h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += k;
|
||||
}
|
||||
return Array.from(h, x => x.toString(16).padStart(8, '0')).join('');
|
||||
}
|
||||
+19
-7
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { api, loadReal, type Health } from '../adapters/real';
|
||||
import { api, lifeStatus, loadReal, type Health } from '../adapters/real';
|
||||
import type { DemoState, Message, Theme } from '../domain/model';
|
||||
import { Presenter } from '../stage/Presenter';
|
||||
import { CreationWizard } from '../manage/CreationWizard';
|
||||
@@ -29,20 +29,32 @@ export function RealApp() {
|
||||
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); } }, []);
|
||||
const ignoreVoice = useCallback(() => {}, []);
|
||||
const navigate = useCallback((next: string) => { leaveSettingsThen(() => { setArea(next); setLog(false); }); }, []);
|
||||
// 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 acknowledged = useCallback(() => setAckAt(Date.now()), []);
|
||||
const navigate = useCallback((next: string) => { leaveSettingsThen(() => { setArea(next); setLog(false); setFocusLife(''); }); 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); });
|
||||
}, [changeMessages]);
|
||||
// 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;
|
||||
const talking = area === 'talk' && !!state && !creating;
|
||||
return <><Presenter real scene={{ mode: area === 'talk' ? 'talk' : 'daily', activity: '文字已接通', time_band: '', weather: '', outfit: '' }} space={space} theme={theme} instant={instant} observation="" now={state && !creating ? '生活尚未接通' : ''} onApproach={() => navigate('talk')}/>
|
||||
return <><Presenter real scene={{ mode: area === 'talk' ? 'talk' : 'daily', activity: '文字已接通', time_band: '', weather: '', outfit: '' }} space={space} theme={theme} instant={instant} observation="" now={state && !creating ? life.now : ''} lifeLabel={life.wired ? life.label : undefined} onApproach={() => navigate('talk')}/>
|
||||
<header className="topbar"><div className="who"><i className="dot"/><span className="name" title={state?.identity.name}>{state?.identity.name || 'CyberGril'}</span>{talking && <span className="presence">{presence}</span>}<span className="state">{ready ? '真实档案 · 文字对话' : '连接真实服务'}</span></div><div className="env"><span className="chip glass weather">天气尚未接通</span><span className="theme-switch glass">{(['moon', 'fog'] as Theme[]).map(t => <button key={t} data-t={t} aria-label={t === 'moon' ? '靛蓝月光' : '蓝紫雾光'} aria-pressed={theme === t} onClick={() => setTheme(t)}><i/><span>{t === 'moon' ? '月光' : '雾光'}</span></button>)}</span>{talking && <button className="end-talk" onClick={() => navigate('now')}><Icon name="x"/><span>结束交谈</span></button>}</div></header>
|
||||
{!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')}>日子与回忆 · 后台待接入 <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">资料与聊天已保存在服务器。生活、长期记忆与语音尚未接通。</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=""/>}
|
||||
<LifePanel real state={state} open={area === 'days'} now="生活尚未接通" onClose={() => navigate('now')} onChat={() => { navigate('talk'); setLog(true); }} onSettings={() => { navigate('settings'); setHerFocus(n => n + 1); }}/>
|
||||
<ManagePanel real state={state} open={area === 'settings'} now="生活尚未接通" focus={herFocus} onClose={() => navigate('now')} onSave={setState} fail={false} theme={theme} setTheme={setTheme}/>
|
||||
{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); }}/>
|
||||
<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></>}
|
||||
</>}</>;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { newId } from '../domain/id';
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { DemoState, Message } from '../domain/model';
|
||||
import { RealChatAdapter } from '../adapters/real';
|
||||
import { confirmReceipt, receiptMatches } from '../adapters/receipt';
|
||||
import { DemoAdapter, TurnGate } from '../adapters/demo';
|
||||
import { publicView } from '../domain/privacy';
|
||||
import { Icon, Modal } from '../shared/ui';
|
||||
@@ -14,8 +15,10 @@ 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 }: {
|
||||
export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation, onRecord, offline, fail, log, setLog, focusLife, real = false, onReceipt }: {
|
||||
real?: boolean;
|
||||
// Real only: the server accepted a complete-receipt confirmation (the life it may unlock is decided later).
|
||||
onReceipt?: () => void;
|
||||
state: DemoState;
|
||||
onChange: (messages: Message[]) => void;
|
||||
onPresence: (p: string) => void;
|
||||
@@ -39,7 +42,9 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
|
||||
const change = (messages: Message[]) => { live.current = messages; onChange(messages); };
|
||||
|
||||
// ── What the stage shows: the newest turn of the (already privacy-filtered) record, plus the live reply. ──
|
||||
const view = useMemo(() => publicView(state), [state]);
|
||||
// Real messages are trimmed by the server before transmission; their lifeIds point at records this page has not
|
||||
// necessarily loaded, so the demo's local filter would wrongly hide them.
|
||||
const view = useMemo(() => real ? state : publicView(state), [state, real]);
|
||||
// The cut-off part of a stopped reply stays with its own turn (it is shown, never stored).
|
||||
const shown = useMemo<ShownMessage[]>(() => {
|
||||
const list: ShownMessage[] = [...view.messages];
|
||||
@@ -75,7 +80,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)}"]`) : null; if (el) el.scrollIntoView({ block: 'center' }); else if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight; } }, [log, focusLife, view.messages.length]);
|
||||
|
||||
// ── Stage ──
|
||||
useLayoutEffect(() => { if (stageRef.current) lines.current = new LineStage(stageRef.current); return () => { lines.current = null; }; }, []);
|
||||
@@ -178,7 +183,14 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
|
||||
if (!gate.current.accepts(event)) return;
|
||||
if (event.t === 'chat.delta') { replyLive.current += event.delta; setInterrupted(null); setReply(replyLive.current); onPresence('在说话'); }
|
||||
else if (event.t === 'chat.final') {
|
||||
change([...live.current.map(m => m.id === msg.id ? { ...m, status: 'sent' as const } : m), { id: newId(), role: 'companion', text: event.utterance.text, lifeIds: [], turnId }]);
|
||||
// Receipt only for this gated, un-aborted, fully parsed final whose own text hashes to receipt.text_hash.
|
||||
const said = event.utterance.text, receipt = real && !signal.aborted && receiptMatches(event.receipt, turnId, said) ? event.receipt : null;
|
||||
// With a receipt the reply carries its server id, so a replayed turn replaces rather than duplicates it
|
||||
// and life records can point back at it.
|
||||
const replyId = receipt ? String(receipt.message_id) : newId();
|
||||
change([...live.current.filter(m => m.id !== replyId).map(m => m.id === msg.id ? { ...m, status: 'sent' as const } : m), { id: replyId, role: 'companion', text: said, lifeIds: [], turnId }]);
|
||||
// The full text is kept above; only now is receipt confirmed. accepted means received, not published.
|
||||
if (receipt) void confirmReceipt(receipt, turnId, said).then(outcome => { if (outcome === 'accepted') onReceipt?.(); });
|
||||
replyLive.current = ''; setInterrupted(null); setReply('');
|
||||
if (real) setDraft(current => current === text ? '' : current);
|
||||
setBusy(false);
|
||||
@@ -233,7 +245,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[0]} 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-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>
|
||||
{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>}
|
||||
|
||||
@@ -26,6 +26,8 @@ export interface LifeEvent {
|
||||
// When and how she told you ("19:34 告诉你", "你们一起经历的"); only ever present on records she has shared.
|
||||
told?: string;
|
||||
memoryIds: string[];
|
||||
// Real records only: the (already server-trimmed) companion messages in which she told it.
|
||||
messageIds?: string[];
|
||||
}
|
||||
export interface Memory {
|
||||
id: string;
|
||||
@@ -75,7 +77,18 @@ export type ServerEvent = {
|
||||
text: string;
|
||||
speech_tags: string[];
|
||||
};
|
||||
// Only on a successful real final while the R2 backend is enabled; demo and older servers omit it.
|
||||
receipt?: Receipt | null;
|
||||
};
|
||||
export interface Receipt {
|
||||
message_id: number;
|
||||
turn_id: string;
|
||||
// The epoch of the turn that produced the message; on a replay it can differ from the frame's current epoch.
|
||||
epoch: number;
|
||||
token: string;
|
||||
text_hash: string;
|
||||
expires_at: number;
|
||||
}
|
||||
export const defaultSettings: Settings = { city: '杭州', appearance: 'reference-v1', reduced: false, services: { '对话模型': '', 'ASR': '', 'TTS': '', '视觉观察': '' } };
|
||||
export function validateCreation(name: string, birth: string, relation: string, now = new Date()): string {
|
||||
if (!name.trim() || name.trim().length > 20 || (/[<>]/u.test(name) || [...name].some(c => c.charCodeAt(0) < 32)))
|
||||
|
||||
+82
-18
@@ -1,8 +1,9 @@
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
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';
|
||||
// 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.
|
||||
@@ -10,18 +11,26 @@ const KIND = { plan: '打算', now: '正在', done: '已经发生' } as const;
|
||||
const MEMORY_GROUPS = ['我们一起的', '你们的小习惯', '她知道的你', '她的成长'];
|
||||
const phone = () => matchMedia('(max-width:720px)').matches;
|
||||
type Load = 'ok' | 'loading' | 'error';
|
||||
export function LifePanel({ state, open, onClose, onChat, onSettings, now = '', fail = false, real = false }: {
|
||||
// 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 };
|
||||
const RE_READ_MS = [15000, 45000];
|
||||
export function LifePanel({ state, open, onClose, onChat, onSettings, now = '', fail = false, real = false, life, ackAt = 0 }: {
|
||||
real?: boolean;
|
||||
state: DemoState;
|
||||
open: boolean;
|
||||
now?: string;
|
||||
fail?: boolean;
|
||||
onClose: () => void;
|
||||
onChat: (id: string) => void;
|
||||
onChat: (id: string, 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 view = publicView(state), [tab, setTab] = useState('life'), [selection, setSelection] = useState(''), [limit, setLimit] = useState(18), [load, setLoad] = useState<Load>('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);
|
||||
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);
|
||||
// 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 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');
|
||||
@@ -30,11 +39,60 @@ export function LifePanel({ state, open, onClose, onChat, onSettings, now = '',
|
||||
setSelection(id);
|
||||
}
|
||||
} }, [open]);
|
||||
// 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 () => {
|
||||
quiet.current?.abort(); request.current?.abort(); const c = new AbortController(); request.current = c;
|
||||
setLoad('loading');
|
||||
try { const page = await lifePage(null, c.signal); if (c.signal.aborted) return; setRealEvents(page.events); setNext(page.next); setLoad('ok'); }
|
||||
catch { if (!c.signal.aborted) setLoad('error'); }
|
||||
finally { if (!c.signal.aborted) setMore(false); }
|
||||
}, []);
|
||||
// A quiet look keeps what is on screen (including older pages you opened) and only adds newly told records on top;
|
||||
// ids grow with time, so newest-first is id order. A failed quiet look changes nothing.
|
||||
const quiet = useRef<AbortController | null>(null);
|
||||
const lookAgain = useCallback(async () => {
|
||||
if (loadRef.current !== 'ok') return;
|
||||
quiet.current?.abort(); const c = new AbortController(); quiet.current = c;
|
||||
try {
|
||||
const page = await lifePage(null, c.signal); if (c.signal.aborted) return;
|
||||
setRealEvents(old => { const known = new Set(old.map(e => e.id)), added = page.events.filter(e => !known.has(e.id)); return added.length ? [...added, ...old].sort((a, b) => Number(b.id) - Number(a.id)) : old; });
|
||||
} 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 && !real) setLoad(fail ? 'error' : 'ok'); wasOpen.current = open; if (!open) { request.current?.abort(); setMore(false); } }, [open, fail, real]);
|
||||
useEffect(() => () => request.current?.abort(), []);
|
||||
async function retry() { 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); try { await delay(real ? 0 : 450, c.signal); setLimit(x => x + 12); } catch { /* Closed. */ } finally { if (!c.signal.aborted) setMore(false); } }
|
||||
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]);
|
||||
// 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));
|
||||
return () => timers.forEach(clearTimeout);
|
||||
}, [real, open, ackAt, lookAgain]);
|
||||
useEffect(() => () => { request.current?.abort(); quiet.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);
|
||||
try {
|
||||
if (real) {
|
||||
if (!nextRef.current) return;
|
||||
const page = await lifePage(nextRef.current, c.signal);
|
||||
if (c.signal.aborted) return;
|
||||
setRealEvents(old => [...old, ...page.events.filter(e => !old.some(o => o.id === e.id))]); setNext(page.next);
|
||||
return;
|
||||
}
|
||||
await delay(450, c.signal); setLimit(x => x + 12);
|
||||
} catch { if (real && !c.signal.aborted) setMoreError(true); } finally { if (!c.signal.aborted) setMore(false); }
|
||||
}
|
||||
useEffect(() => { if (more) setMoreError(false); }, [more]);
|
||||
// Real deep link (#event=…) or a record outside the loaded pages: fetch that one record by id.
|
||||
const loaded = view.events.some(e => e.id === selection);
|
||||
useEffect(() => {
|
||||
if (!real || !open || tab !== 'life' || !selection || loaded || load === 'loading') return;
|
||||
const c = new AbortController();
|
||||
setLookup({ id: selection, state: 'loading' });
|
||||
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]);
|
||||
// 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]);
|
||||
@@ -43,11 +101,17 @@ export function LifePanel({ state, open, onClose, onChat, onSettings, now = '',
|
||||
const select = (id: string, t = tab) => { if (t !== tab) switchTab(t); setSelection(id); };
|
||||
// Esc on a phone closes the pushed detail first; the app then closes the panel on the next press.
|
||||
useEffect(() => { if (!open || !selection) return; const key = (e: KeyboardEvent) => { if (e.key !== 'Escape' || !phone() || document.querySelector('.modal.open')) return; e.stopImmediatePropagation(); setSelection(''); }; window.addEventListener('keydown', key, true); return () => window.removeEventListener('keydown', key, true); }, [open, selection]);
|
||||
const ordered = [...view.events.filter(e => e.kind === 'plan'), ...view.events.filter(e => e.kind !== 'plan')], shown = ordered.slice(0, limit);
|
||||
// Real pages are the server's newest-first order, kept in full as you page back (no client-side cap).
|
||||
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 event = tab === 'life' ? view.events.find(e => e.id === selection) : undefined, memory = tab === 'memory' ? view.memories.find(m => m.id === selection) : undefined;
|
||||
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 name = view.identity.name, demoTag = !real && <span className="tag-demo">演示数据</span>;
|
||||
const lines = (e: LifeEvent) => view.messages.filter(m => m.lifeIds.includes(e.id));
|
||||
// Real: the messages the server says told it, plus what you said in those same turns.
|
||||
const lines = (e: LifeEvent) => {
|
||||
const told = new Set(e.messageIds || []), turns = new Set(view.messages.filter(m => told.has(m.id)).map(m => m.turnId).filter(Boolean));
|
||||
return view.messages.filter(m => m.lifeIds.includes(e.id) || told.has(m.id) || (m.role === 'user' && turns.has(m.turnId)));
|
||||
};
|
||||
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) {
|
||||
@@ -60,8 +124,8 @@ export function LifePanel({ state, open, onClose, onChat, onSettings, now = '',
|
||||
{mems.length > 0 && <><div className="d-sec">和这件事有关的回忆</div><div className="link-list">{mems.map(m => linkCard(m.id, m.title, m.source, () => select(m.id, 'memory')))}</div></>}
|
||||
<div className="d-sec">那时候的聊天</div>
|
||||
{chat.length ? <div className="said-then">{chat.map(m => <p key={m.id} data-role={m.role}><span className="who"><i/>{m.role === 'user' ? '你' : name}</span>{m.text}</p>)}</div> : <p className="d-dim">那时候没有留下聊天记录。</p>}
|
||||
<Button onClick={() => onChat(e.id)}>在交谈里看这段<Icon name="next"/></Button>
|
||||
<div className="d-foot">{demoTag}这是模拟生活里的一条记录,不是真实发生的事。画面只按记录选片,不会反过来改写她的生活。</div>
|
||||
<Button onClick={() => onChat(e.id, e.messageIds)}>在交谈里看这段<Icon name="next"/></Button>
|
||||
<div className="d-foot">{real ? '这是服务器记下的她的日子,她在交谈里讲给你听过才会显示。它不是你们的长期记忆,也不会反过来改写她最初的底色。' : <>{demoTag}这是模拟生活里的一条记录,不是真实发生的事。画面只按记录选片,不会反过来改写她的生活。</>}</div>
|
||||
</>;
|
||||
}
|
||||
function memoryView(m: Memory) {
|
||||
@@ -82,9 +146,9 @@ export function LifePanel({ state, open, onClose, onChat, onSettings, now = '',
|
||||
function lifeList() {
|
||||
if (load === 'loading') return <><p className="grp" role="status">正在翻她的日子…</p>{skeleton(6)}</>;
|
||||
if (load === 'error') return failed;
|
||||
if (!view.events.length) return <div className="empty">{real ? '还没有可展示的生活记录' : '她今晚刚住进来,还没有发生什么。'}<small>{real ? '生活后台尚未接通,不用示例经历填充。你们说过的话可在交谈的完整记录中查看。' : '等她跟你讲起,日子会一条条留在这里。演示资料可以从「演示场景」载入。'}</small></div>;
|
||||
if (!view.events.length) return <div className="empty">{real ? (life?.wired ? '她还没有讲给你听过自己的日子' : '还没有可展示的生活记录') : '她今晚刚住进来,还没有发生什么。'}<small>{real ? `${life?.note || '生活后台尚未接通,不用示例经历填充。'}你们说过的话可在交谈的完整记录中查看。` : '等她跟你讲起,日子会一条条留在这里。演示资料可以从「演示场景」载入。'}</small></div>;
|
||||
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> : limit < ordered.length ? <div className="more"><Button onClick={() => void earlier()}>看更早的日子</Button></div> : <p className="list-end">再往前,就是她刚住进来的那天了。</p>}</>;
|
||||
{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>}</>;
|
||||
}
|
||||
function memoryList() {
|
||||
if (load === 'loading') return skeleton(5);
|
||||
@@ -93,10 +157,10 @@ export function LifePanel({ state, open, onClose, onChat, onSettings, now = '',
|
||||
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);
|
||||
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 ? '后台待接入' : '演示数据'}</span><span className="k-near"><i/>她此刻 · {now || '安静待着'}</span></small><h2>{tab === 'life' ? '她的日子' : '我们的回忆'}</h2></div><span className="grow"/>{real ? <span className="tag-demo">后台待接入</span> : demoTag}<button className="btn-round sm" aria-label="关闭日子" onClick={onClose}><Icon name="x"/></button></header>
|
||||
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> : 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 ? '后台接通后,她讲给你听过的事会出现在左侧;这里保留日子详情、回忆与聊天的关联。' : 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> : 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>}
|
||||
</article></div></section>;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { api, type Health, type RealIdentity } from '../adapters/real';
|
||||
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';
|
||||
@@ -13,8 +13,10 @@ const NOTE: Record<string, string> = { her: '只读资料', relation: '可以调
|
||||
function CapTag({ cap }: { cap: Cap }) { const [text, tone] = CAP[cap]; return <span className={`tag cap ${tone}`}>{text}</span>; }
|
||||
// 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 <div className="off-card"><p className="off-t">{title}</p><p>{will}</p><p className="d-dim">{now}</p></div>; }
|
||||
export function ManagePanel({ state, open, onClose, onSave, fail, theme, setTheme, real = false, now = '', focus = 0 }: {
|
||||
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;
|
||||
@@ -124,12 +126,53 @@ export function ManagePanel({ state, open, onClose, onSave, fail, theme, setThem
|
||||
// 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<PersonaView>(), [personaLoad, setPersonaLoad] = useState<'loading' | 'ok' | 'error'>('loading'), [personaNote, setPersonaNote] = useState(''), [personaBusy, setPersonaBusy] = useState(false), [personaRead, setPersonaRead] = useState(0);
|
||||
const personaRequest = useRef<AbortController | null>(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]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
// 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]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
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 <div className="skel" aria-hidden="true">{[78, 62, 70, 54].map(w => <i key={w} style={{ width: `${w}%` }}/>)}</div>;
|
||||
if (personaLoad === 'error' || !persona) return <div className="off-card" role="alert"><p className="off-t">她的这部分资料一时没读出来。</p><p>不是你的问题,资料仍在服务器保存。</p><Button onClick={() => setPersonaRead(n => n + 1)}>再试一次</Button></div>;
|
||||
const p = persona, interp = p.interpretation;
|
||||
if (p.state === 'ready' && interp) return <><blockquote className="quote">{interp.text}</blockquote><p className="d-dim">{backfilled(interp.provenance) ? `后来补上的初始印象 · ${day(interp.created_at)} 生成,不是她出生时就有的。` : `创建时形成 · ${day(interp.created_at)}`} 由模型从出生资料自主形成,会延续;不是固定模板,也不能直接改写。</p></>;
|
||||
if (p.state === 'loading') return <><div className="skel" aria-hidden="true">{[78, 62, 70].map(w => <i key={w} style={{ width: `${w}%` }}/>)}</div><p className="d-dim" role="status">{polls.current >= 12 ? '还在形成中。稍后回到这里会再看一次。' : '她正在形成对自己的理解…'}</p></>;
|
||||
if (p.state === 'failed') return <div className="off-card" role="alert"><p className="off-t">她对自己的理解这次没有形成。</p><p>档案、名字和底色都保留;这里不会用模板顶替。</p>{personaNote && <p className="d-dim">{personaNote}</p>}<Button disabled={personaBusy} onClick={() => void retryGeneration()}>{personaBusy ? '正在重新形成…' : '重新形成'}</Button></div>;
|
||||
if (p.state === 'not_initialized') return <Off title="这份档案创建时还没有这一层。" will="她对自己的理解和最初的小习惯,是这个版本以后新建档案时才会形成的。已有的档案不会被自动补建。" now="补建需要单独授权,这里不会自动生成,也不会用模板顶替。"/>;
|
||||
return <Off title="这台服务没有启用她的自我理解。" will="启用以后,新建档案时她会从出生资料自主形成一段可延续的自我理解和几条小习惯。" now="现在这里不显示任何固定段落,避免把模板当成她的个性。"/>;
|
||||
}
|
||||
function personaLayers() {
|
||||
const p = personaLoad === 'ok' ? persona : undefined, ready = p?.state === 'ready';
|
||||
const SOURCE: Record<string, string> = { life: '来自她讲给你听过的一天', chat: '来自你们的一次聊天' };
|
||||
return <div className="growth"><div><h4>最初就有的<small>{ready && backfilled(p?.interpretation?.provenance) ? '后来补上的初始印象' : '创建时形成'}</small></h4>{ready && p?.seeds.length ? <ul>{p.seeds.map(s => <li key={s.id}>{s.text}<small>{backfilled(s.provenance) ? `后来补上 · ${day(s.created_at)}` : day(s.created_at)}</small></li>)}</ul> : <p className="d-dim">{!p ? '读取中…' : ready ? '没有记下最初的小习惯。' : '和她对自己的理解一起形成;现在还没有。'}</p>}</div>
|
||||
<div><h4>后来慢慢有的<small>成长 · 单独记录</small></h4>{p?.growth.length ? <ul>{p.growth.map(g => <li key={g.id}>{g.text}<small>{SOURCE[g.source] || '有来处的成长'} · {day(g.ts)}</small></li>)}</ul> : <p className="d-dim">{!p ? '读取中…' : '还没有记下的成长。长期记忆尚未接通,聊天记录已独立保存。'}</p>}</div></div>;
|
||||
}
|
||||
const sectionLabel = (id: string) => real && id === 'backup' ? '备份' : sections.find(s => s[0] === id)?.[2] || '';
|
||||
return <section hidden={!open} className={`pane pane-manage glass read ${open ? 'open' : ''} ${detail ? 'has-detail' : ''}`} aria-label="设置"><header><div className="ttl"><small className="kicker"><span className="k-wide">慢慢安排你们的世界 · {real ? '服务器档案' : '仅本机演示'}</span><span className="k-near"><i/>她此刻 · {now || '安静待着'}</span></small><h2>设置</h2></div><span className="grow"/><span className="tag-demo">{real ? '服务器档案' : '仅本机演示'}</span><button className="btn-round sm" aria-label="关闭设置" onClick={() => requestLeave(onClose)}><Icon name="x"/></button></header><div className="cols"><nav className="snav" aria-label="设置分区">{sections.map(([id, icon]) => { const cap = capOf(id, real); return <button key={id} className={dirtySections[id] ? 'is-dirty' : ''} aria-current={section === id} onClick={() => switchSection(id)}><Icon name={icon}/><span className="sl">{sectionLabel(id)}<small aria-hidden="true">{NOTE[id] || CAP[cap][0]}</small></span><i className="dirty"/><span className="chev" aria-hidden="true"><Icon name="next"/></span></button>; })}<p className="snav-foot">首版只有一位她 · 没有重建或清空</p></nav><div className="detail"><button className="btn-text back" onClick={() => setDetail(false)}><Icon name="back"/>设置</button><div className="sec-body on"><div className="sec-h"><h3>{section === 'her' ? state.identity.name : sectionLabel(section)}</h3><CapTag cap={capOf(section, real)}/></div><p className="lead">{section === 'her' ? '她还是她。外观和关系的变化,都不会改写最初的底色。' : real ? '资料保存在服务器。尚未接通的功能写明接上以后能做什么,现在不会发生任何事。' : '所有修改仅用于本机演示。未接通的服务会明确说明。'}</p>
|
||||
{section === 'her' && <><dl className="kv"><dt>名字</dt><dd>{state.identity.name}<small>由你在初次创建时起的名字;首版不另设改名流程。</small></dd><dt>生辰</dt><dd>{state.identity.birth} · {state.identity.hour}<small><Icon name="lock"/>只读</small></dd></dl>
|
||||
<h4 className="sub-h">她的底色<small>系统资料 · 每轮对话都会重新带上 · 关系设定不能改写</small></h4><BaseColor color={real ? (state.identity as RealIdentity).color : undefined}/>
|
||||
<h4 className="sub-h">她怎么理解自己<small>模型诠释 · 会延续,也会变化</small></h4><Off title={real ? '她对自己的诠释还没有接上。' : '演示不生成她对自己的诠释。'} will="接上以后,这里是她在相处和生活里慢慢形成的自我理解,带版本和时间;不是固定模板,也不能直接改写。" now="现在这里不显示任何固定段落,避免把模板当成她的个性。"/>
|
||||
<div className="growth"><div><h4>最初就有的<small>创建时形成</small></h4><p className="d-dim">{real ? '最初的小习惯尚未接通,不用示例填充。' : '演示没有生成最初的小习惯。'}</p></div><div><h4>后来慢慢有的<small>成长 · 单独记录</small></h4>{growth.length ? <ul>{growth.map(m => <li key={m.id}>{m.title}<small>{m.source}</small></li>)}</ul> : <p className="d-dim">{real ? '长期记忆尚未接通。聊天记录已独立保存。' : '还在慢慢认识彼此。'}</p>}</div></div><p className="d-foot">首版只有一位她。这里没有新建、切换、清空或重建。底色只读。</p></>}
|
||||
<h4 className="sub-h">她怎么理解自己<small>模型诠释 · 会延续,也会变化</small></h4>{real ? personaView() : <Off title="演示不生成她对自己的诠释。" will="接上以后,这里是她在相处和生活里慢慢形成的自我理解,带版本和时间;不是固定模板,也不能直接改写。" now="现在这里不显示任何固定段落,避免把模板当成她的个性。"/>}
|
||||
{real ? personaLayers() : <div className="growth"><div><h4>最初就有的<small>创建时形成</small></h4><p className="d-dim">演示没有生成最初的小习惯。</p></div><div><h4>后来慢慢有的<small>成长 · 单独记录</small></h4>{growth.length ? <ul>{growth.map(m => <li key={m.id}>{m.title}<small>{m.source}</small></li>)}</ul> : <p className="d-dim">还在慢慢认识彼此。</p>}</div></div>}<p className="d-foot">首版只有一位她。这里没有新建、切换、清空或重建。底色只读。</p></>}
|
||||
{section === 'relation' && <><div className="field"><span id="rel-label">你们的关系</span><div className="seg" role="group" aria-labelledby="rel-label">{(['朋友', '恋人'] as const).map(r => <button key={r} aria-pressed={draft.identity.relation === r} onClick={() => setDraft(d => ({ ...d, identity: { ...d.identity, relation: r } }))}>{r}</button>)}</div></div><Field label="她怎么称呼你"><input className="input" value={draft.identity.nickname} maxLength={40} onChange={e => setDraft(d => ({ ...d, identity: { ...d.identity, nickname: e.target.value } }))}/></Field><Field label="相处边界"><textarea className="textarea" maxLength={2000} value={draft.identity.boundary} onChange={e => setDraft(d => ({ ...d, identity: { ...d.identity, boundary: e.target.value } }))}/></Field><p className="d-foot">改关系需要再次确认,已有记忆与信任都保留,底色不变。</p></>}
|
||||
{!real && section === 'city' && <><Field label="搜索城市"><input className="input" value={search} placeholder="输入城市名称" onChange={e => setSearch(e.target.value)}/></Field><ul className="city-list">{['杭州', '上海', '北京', '成都', '广州', '深圳'].filter(c => c.includes(search.trim())).map(c => <li key={c}><button aria-pressed={draft.settings.city === c} onClick={() => settings({ city: c })}>{c}<small>中国 · 演示城市</small></button></li>)}</ul>{!['杭州', '上海', '北京', '成都', '广州', '深圳'].some(c => c.includes(search.trim())) && <p>暂时没找到这个城市,演示清单只包含上面的六座。</p>}<p className="d-foot">城市保存后顶栏同步;天气与作息为固定演示,不请求天气服务。</p></>}
|
||||
{!real && section === 'appearance' && <><div className="card">当前素材:{state.settings.appearance}<small className="d-foot">参考静帧,不代表最终人物素材。</small></div><Field label="选择本地素材清单(演示 JSON)" hint="真实素材包格式尚待定稿。只读 JSON,不加载清单中的 URL 或脚本。"><input type="file" accept=".json,application/json" onChange={e => void importMaterial(e.target.files?.[0])}/></Field>{check && <Status text={check} error={!material}/>} {material && <><div className="compare"><figure><img src="/assets/her-room.jpg" alt="当前参考"/><figcaption>当前参考</figcaption></figure><figure className="new"><img src="/assets/her-room.jpg" alt="新外观模拟效果"/><figcaption>模拟效果 · 未加载素材</figcaption></figure></div><Button primary onClick={() => setConfirm('appearance')}>应用演示外观标识</Button></>}<p className="d-foot">只演示检查、预览与确认。媒体真实性未校验,不声称完成素材导入。</p></>}
|
||||
@@ -139,7 +182,7 @@ export function ManagePanel({ state, open, onClose, onSave, fail, theme, setThem
|
||||
{real && section === 'city' && <><Off title="城市与天气还没有接上。" will="接上以后,你选一个真实城市,她房间里的天气、白天黑夜和作息都跟着那里走;换城市不需要每次重新定位。" now="现在窗外的雨是界面氛围,不是真实天气。尚未设置可核实的城市,天气来源尚未确定。"/><Field label="搜索城市" hint="可浏览候选目录;当前无法保存,不会更改她的城市。"><input className="input" value={search} placeholder="输入城市名称" onChange={e => setSearch(e.target.value)}/></Field><ul className="city-list">{['杭州', '上海', '北京', '成都', '广州', '深圳'].filter(c => c.includes(search.trim())).map(c => <li key={c}><button disabled>{c}<small>候选城市 · 保存待接入</small></button></li>)}</ul>{!['杭州', '上海', '北京', '成都', '广州', '深圳'].some(c => c.includes(search.trim())) && <div className="empty">当前目录没有匹配的城市。</div>}<div className="actions"><Button disabled>保存城市 · 待接入</Button></div></>}
|
||||
{real && section === 'appearance' && <><dl className="kv"><dt>现在的样子</dt><dd>工程外观 v2<small>参考静帧 · 尚无成套日常与交谈视频</small></dd></dl><Off title="换外观还没有接上。" will="接上以后:选择素材包 → 检查素材 → 看新旧对比 → 确认「她还是她」。只换样子,名字、底色、记忆和关系都不变。" now="素材包规范与导入检查尚未定稿。这里不会导入、预览或替换任何素材。"/><Field label="选择外观素材包" hint="素材包格式与媒体检查将在后续接入。当前不上传、不读取文件。"><input type="file" disabled/></Field><ul className="phases">{['清单结构与版本', '媒体格式与时长', '人物一致性', '必要场景覆盖', '可用性与兼容性'].map(label => <li key={label}>待检查 · {label}</li>)}</ul><div className="compare"><figure><img src="/assets/her-room.jpg" alt="当前内置参考静帧"/><figcaption>当前参考</figcaption></figure><figure><div className="empty">导入并通过检查后显示新外观</div><figcaption>新旧对比 · 待接入</figcaption></figure></div><Button disabled>确认应用外观 · 待接入</Button></>}
|
||||
{real && section === 'backup' && <><Off title="备份还没有接上。" will="接上以后:服务器每天自动备份;你可以随时把她完整导出到自己的电脑(含底色、性格资料、对话、记忆、关系、生活进度和所用素材),也能从备份恢复同一个她。" now="现在没有任何备份在运行,这里也不会假装导出或恢复。"/><div className="card"><h4>每日自动备份</h4><p>暂无可核实的备份记录。自动备份、保留份数与运行结果将在接入后显示。</p><div className="empty">尚未接通备份服务</div></div><div className="card"><h4>完整导出</h4><p>将包含服务器档案、聊天及届时接通的记录与素材。当前不生成伪备份文件。</p><Button disabled>导出完整备份 · 待接入</Button></div><Field label="恢复同一位她的备份" hint="恢复前会检查完整性、版本和同一档案,要求输入“恢复”,并先备份当前资料。当前不接收文件或执行覆盖。"><input type="file" disabled/></Field><ul className="phases">{['检查完整性与版本', '核对是否同一位她', '先备份当前资料', '输入确认并恢复'].map(label => <li key={label}>待接入 · {label}</li>)}</ul><button className="btn-danger" disabled>检查备份并继续 · 待接入</button></>}
|
||||
{real && section === 'services' && <>{[['文字对话', serviceHealth ? serviceHealth.llm.ok ? '连接可达' : '暂时不可达' : '已接通 · 可重新检查'], ['语音识别', '尚未接通'], ['语音合成', '尚未接通'], ['视觉观察', '尚未接通']].map(([label, status], index) => <div className="svc" key={label}><div className="nm">{label}<small>{status}</small></div><Button disabled={index !== 0 || busy} onClick={() => void checkService()}>{index === 0 ? busy ? '检查中…' : '重新检查连接' : '测试连接 · 待接入'}</Button><input className="input" aria-label={`${label}配置`} value={index === 0 ? '由服务器管理' : '服务尚未配置'} readOnly/></div>)}<Off title="语音与视觉观察还没有接上。" will="接上以后:语音由你主动开启,结束后停止收音,文字聊天一直保留;视觉观察只看人在不在、明显物品和房间变化,过期的画面不再当作眼前。" now="这里不申请麦克风或摄像头,不采集声音与影像。"/><div className="card"><h4>其余能力</h4><p>生活、长期记忆、主动消息和天气尚未接通。文字模型暂时不可达时,已保存的档案和聊天记录仍可查看。</p></div></>}
|
||||
{real && section === 'services' && <>{[['文字对话', serviceHealth ? serviceHealth.llm.ok ? '连接可达' : '暂时不可达' : '已接通 · 可重新检查'], ['语音识别', '尚未接通'], ['语音合成', '尚未接通'], ['视觉观察', '尚未接通']].map(([label, status], index) => <div className="svc" key={label}><div className="nm">{label}<small>{status}</small></div><Button disabled={index !== 0 || busy} onClick={() => void checkService()}>{index === 0 ? busy ? '检查中…' : '重新检查连接' : '测试连接 · 待接入'}</Button><input className="input" aria-label={`${label}配置`} value={index === 0 ? '由服务器管理' : '服务尚未配置'} readOnly/></div>)}<Off title="语音与视觉观察还没有接上。" will="接上以后:语音由你主动开启,结束后停止收音,文字聊天一直保留;视觉观察只看人在不在、明显物品和房间变化,过期的画面不再当作眼前。" now="这里不申请麦克风或摄像头,不采集声音与影像。"/><div className="card"><h4>其余能力</h4><p>{life?.wired ? `生活:${life.label}。${life.note}长期记忆、主动消息和天气尚未接通。` : '生活、长期记忆、主动消息和天气尚未接通。'}文字模型暂时不可达时,已保存的档案和聊天记录仍可查看。</p></div></>}
|
||||
<div ref={feedback}><Status text={message} error={error}/></div>{(real ? ['relation', 'display'] : ['relation', 'city', 'services', 'display']).includes(section) && <div className="actions"><span className={`grow ${dirty ? 'dirty' : ''}`}>{dirty ? '有未保存的修改' : '尚未修改'}</span><Button disabled={!dirty || busy} onClick={reset}>取消修改</Button><Button primary disabled={!dirty || busy} onClick={() => void save()}>{busy ? '正在保存…' : error ? '重试保存' : '保存'}</Button></div>}</div></div></div>
|
||||
{confirm && <Modal title={confirm === 'leave' ? '有未保存的修改' : confirm === 'relation' ? `把关系从「${state.identity.relation}」改成「${draft.identity.relation}」?` : confirm === 'restore' ? '恢复本地演示资料?' : '她还是她'} danger={confirm === 'restore'} onClose={() => setConfirm('')} disabled={confirm === 'restore' && confirmText !== '恢复'} onConfirm={() => { const which = confirm; setConfirm(''); if (which === 'leave') { request.current?.abort(); setBusy(false); setDraft({ identity: structuredClone(state.identity), settings: structuredClone(state.settings) }); const action = pendingNavigation.current; pendingNavigation.current = null; approvedNavigation.current = true; try { action?.(); } finally { approvedNavigation.current = false; } } if (which === 'relation')
|
||||
void save(true); if (which === 'appearance') {
|
||||
|
||||
@@ -13,13 +13,16 @@ export interface PresenterProps {
|
||||
observation: string;
|
||||
// "她此刻": what she is doing, read from the same life state as the home page (never from the playing clip).
|
||||
now?: string;
|
||||
// Real only: the life backend's honest status word (HEL-828); absent means not wired.
|
||||
lifeLabel?: string;
|
||||
onApproach: () => void;
|
||||
}
|
||||
// One shared room (HEL-799, approved 01a16810): far = her room and the rainy city, middle = her, near = your table.
|
||||
// Only consumes scene. No life writes, no synthesis, no microphone/camera APIs. The two stills are reference frames,
|
||||
// not her real daily video; the camera move is the approved push-in, not body motion.
|
||||
export function Presenter({ scene, space, theme, instant, real = false, observation, now = '', onApproach }: PresenterProps) {
|
||||
export function Presenter({ scene, space, theme, instant, real = false, observation, now = '', lifeLabel, onApproach }: PresenterProps) {
|
||||
const [failed, setFailed] = useState(false);
|
||||
const lifeWord = lifeLabel ? `生活 · ${lifeLabel}` : '生活尚未接通';
|
||||
const cam = useRef<HTMLDivElement>(null), room = useRef<HTMLDivElement>(null), talk = useRef<HTMLDivElement>(null), moon = useRef<HTMLElement>(null), near = useRef<HTMLDivElement>(null), hit = useRef<HTMLButtonElement>(null), rainRoom = useRef<HTMLCanvasElement>(null), rainTalk = useRef<HTMLCanvasElement>(null);
|
||||
const chip = useRef<HTMLDivElement>(null);
|
||||
// While a page is open on your side of the table, "她此刻" sits just under her in the room. It follows the hit area
|
||||
@@ -84,11 +87,11 @@ export function Presenter({ scene, space, theme, instant, real = false, observat
|
||||
<div className="r-vignette"/><div className="r-veil"/>
|
||||
</div>
|
||||
<button className="her-hit" ref={hit} aria-label="走近她,开始交谈" tabIndex={space === 'home' ? 0 : -1} disabled={space !== 'home'} onClick={onApproach}><span>和她说话</span></button>
|
||||
{now && <div className="now-chip glass" ref={chip} aria-hidden={space !== 'pane'}><i/><span><b>她此刻 · {now}</b><small>{real ? '生活尚未接通 · 画面为参考静帧' : '来自演示生活状态 · 画面为参考静帧'}</small></span></div>}
|
||||
{now && <div className="now-chip glass" ref={chip} aria-hidden={space !== 'pane'}><i/><span><b>她此刻 · {now}</b><small>{real ? `${lifeWord} · 画面为参考静帧` : '来自演示生活状态 · 画面为参考静帧'}</small></span></div>}
|
||||
<div className="room-labels">
|
||||
{failed && <span className="chip glass">画面暂时没打开,文字仍可使用。</span>}
|
||||
{observation && <span className="chip glass observe show">{observation}</span>}
|
||||
</div>
|
||||
<p className="ref-note" data-activity={scene.activity}>{real ? '生活尚未接通' : '演示状态'} · 人物为旧参考静帧 · 不代表新日常 · 未接入真实动态</p>
|
||||
<p className="ref-note" data-activity={scene.activity}>{real ? lifeWord : '演示状态'} · 人物为旧参考静帧 · 不代表新日常 · 未接入真实动态</p>
|
||||
</>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { sha256Hex } from '../src/adapters/sha256';
|
||||
import { confirmReceipt, forgetReceipts, receiptMatches } from '../src/adapters/receipt';
|
||||
import { clockOf, lifeStatus, RealChatAdapter, toLifeEvent, type Health } from '../src/adapters/real';
|
||||
import { TurnGate } from '../src/adapters/demo';
|
||||
import type { Receipt, ServerEvent } from '../src/domain/model';
|
||||
|
||||
const TEXT = '今晚的雨很轻,我把窗开了一条缝🌧️。\n"引号" 和 emoji 👩💻 也要完整。';
|
||||
const hash = (s: string) => createHash('sha256').update(Buffer.from(s, 'utf8')).digest('hex');
|
||||
const receipt = (over: Partial<Receipt> = {}): Receipt => ({ message_id: 42, turn_id: '6f1c2a8e-0000-4000-8000-000000000001', epoch: 7, token: 'x'.repeat(43), text_hash: hash(TEXT), expires_at: Date.now() + 86400000, ...over });
|
||||
const ok = () => new Response(JSON.stringify({ accepted: true }), { status: 200 });
|
||||
|
||||
describe('UTF-8 SHA-256 without crypto.subtle (plain LAN HTTP)', () => {
|
||||
it('matches node crypto for empty, ASCII, Chinese, emoji/ZWJ and block-boundary lengths', () => {
|
||||
for (const s of ['', 'abc', TEXT, '你'.repeat(21), 'a'.repeat(55), 'a'.repeat(56), 'a'.repeat(64), '🌙'.repeat(300)]) expect(sha256Hex(s)).toBe(hash(s));
|
||||
expect(sha256Hex('abc')).toBe('ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad');
|
||||
});
|
||||
it('does not depend on crypto.subtle being present', () => {
|
||||
vi.stubGlobal('crypto', {});
|
||||
expect(sha256Hex(TEXT)).toBe(hash(TEXT));
|
||||
});
|
||||
});
|
||||
|
||||
describe('complete-receipt confirmation', () => {
|
||||
beforeEach(() => { forgetReceipts(); vi.useFakeTimers(); });
|
||||
afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });
|
||||
it('posts exactly the five contract fields, hashing the text actually received, with the receipt epoch', async () => {
|
||||
const post = vi.fn().mockResolvedValue(ok());
|
||||
await expect(confirmReceipt(receipt({ epoch: 3 }), receipt().turn_id, TEXT, post)).resolves.toBe('accepted');
|
||||
expect(post).toHaveBeenCalledTimes(1);
|
||||
const [url, init] = post.mock.calls[0];
|
||||
expect(url).toBe('/api/chat/received');
|
||||
const body = JSON.parse(init.body);
|
||||
expect(Object.keys(body).sort()).toEqual(['epoch', 'message_id', 'text_hash', 'token', 'turn_id']);
|
||||
expect(body).toMatchObject({ message_id: 42, epoch: 3, text_hash: hash(TEXT) });
|
||||
expect(body).not.toHaveProperty('event_ids');
|
||||
});
|
||||
it('never confirms a partial/other text, another turn, or a malformed receipt', async () => {
|
||||
const post = vi.fn().mockResolvedValue(ok());
|
||||
for (const [r, turn, text] of [[receipt(), receipt().turn_id, TEXT.slice(0, -1)], [receipt(), 'another-turn', TEXT], [receipt({ token: 'short' }), receipt().turn_id, TEXT], [receipt({ text_hash: 'A'.repeat(64) }), receipt().turn_id, TEXT], [null, receipt().turn_id, TEXT]] as const) {
|
||||
expect(receiptMatches(r, turn, text)).toBe(false);
|
||||
if (r) await expect(confirmReceipt(r, turn, text, post)).resolves.toBe('mismatch');
|
||||
}
|
||||
expect(post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('does not retry 404/422 and keeps retries bounded on transport failure', async () => {
|
||||
const rejected = vi.fn().mockResolvedValue(new Response('{"detail":"这一条现在打不开。"}', { status: 404 }));
|
||||
await expect(confirmReceipt(receipt(), receipt().turn_id, TEXT, rejected)).resolves.toBe('rejected');
|
||||
expect(rejected).toHaveBeenCalledTimes(1);
|
||||
forgetReceipts();
|
||||
const down = vi.fn().mockRejectedValue(new TypeError('offline'));
|
||||
const outcome = confirmReceipt(receipt(), receipt().turn_id, TEXT, down);
|
||||
await vi.runAllTimersAsync();
|
||||
await expect(outcome).resolves.toBe('gave-up');
|
||||
expect(down).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
it('is idempotent: concurrent and repeated confirmations of one receipt send once', async () => {
|
||||
const post = vi.fn().mockResolvedValue(ok());
|
||||
const [a, b] = [confirmReceipt(receipt(), receipt().turn_id, TEXT, post), confirmReceipt(receipt(), receipt().turn_id, TEXT, post)];
|
||||
await expect(Promise.all([a, b])).resolves.toEqual(['accepted', 'accepted']);
|
||||
await confirmReceipt(receipt(), receipt().turn_id, TEXT, post);
|
||||
expect(post).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it('a replayed final (same turn, original receipt) confirms with the receipt epoch after a restart', async () => {
|
||||
const post = vi.fn().mockResolvedValueOnce(new Response('', { status: 503 })).mockResolvedValueOnce(ok());
|
||||
const outcome = confirmReceipt(receipt({ epoch: 2 }), receipt().turn_id, TEXT, post);
|
||||
await vi.runAllTimersAsync();
|
||||
await expect(outcome).resolves.toBe('accepted');
|
||||
expect(post.mock.calls.map(c => JSON.parse(c[1].body).epoch)).toEqual([2, 2]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('receipt through the real stream and TurnGate', () => {
|
||||
afterEach(() => { vi.unstubAllGlobals(); });
|
||||
const sse = (e: object) => new Response(`data: ${JSON.stringify(e)}\n\n`);
|
||||
const final = (epoch: number, r: Receipt | null) => ({ t: 'chat.final', epoch, turn_id: receipt().turn_id, utterance: { text: TEXT, speech_tags: [] }, receipt: r });
|
||||
it('a replay after restart passes the gate on the current epoch while the receipt keeps the original one', async () => {
|
||||
const gate = new TurnGate(), signal = gate.begin(receipt().turn_id), seen: ServerEvent[] = [];
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce(new Response(JSON.stringify({ epoch: 5, llm: { ok: true } }))).mockResolvedValueOnce(sse(final(5, receipt({ epoch: 2 })))));
|
||||
await new RealChatAdapter(e => { gate.epoch = e; }).send('你好', receipt().turn_id, 1, signal, e => { if (gate.accepts(e)) seen.push(e); });
|
||||
expect(seen).toHaveLength(1);
|
||||
const e = seen[0] as Extract<ServerEvent, { t: 'chat.final' }>;
|
||||
expect(receiptMatches(e.receipt, receipt().turn_id, e.utterance.text)).toBe(true);
|
||||
expect(e.receipt?.epoch).toBe(2);
|
||||
});
|
||||
it('a cancelled turn never reaches the receipt step', async () => {
|
||||
const gate = new TurnGate(), signal = gate.begin(receipt().turn_id), seen: ServerEvent[] = [];
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce(new Response(JSON.stringify({ epoch: 7, llm: { ok: true } }))).mockImplementationOnce(async () => { gate.begin('next-turn'); return sse(final(7, receipt())); }));
|
||||
await new RealChatAdapter(e => { gate.epoch = e; }).send('你好', receipt().turn_id, 1, signal, e => { if (gate.accepts(e)) seen.push(e); });
|
||||
expect(signal.aborted).toBe(true);
|
||||
expect(seen).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('real life records and honest status', () => {
|
||||
const row = { id: 9007199254740, ts: Date.UTC(2026, 9, 23, 16, 30), kind: 'thought', content: '我试着给一段旋律换个结尾。', place: '房间', salience: .7, source: 'generated', day_key: '2026-10-24', tz: 'Asia/Shanghai', told: true as const, told_at: Date.UTC(2026, 9, 24, 3, 5), messageIds: [12, 15] };
|
||||
it('maps numeric ids, unix-ms in the event zone, day_key and message links without inventing a title', () => {
|
||||
const e = toLifeEvent(row);
|
||||
expect(e).toMatchObject({ id: '9007199254740', time: '2026-10-24 00:30', text: row.content, title: '一个念头', shared: true, kind: 'done', messageIds: ['12', '15'], memoryIds: [] });
|
||||
expect(e.told).toBe('11:05 讲给你听');
|
||||
expect(clockOf(row.ts, 'Not/AZone').date).toMatch(/^\d{4}-\d{2}-\d{2}$/);
|
||||
});
|
||||
it('never says the loop runs from the switch alone', () => {
|
||||
const base: Health = { epoch: 1, llm: { ok: true, model: 'm' } };
|
||||
expect(lifeStatus(base)).toMatchObject({ wired: false, now: '生活尚未接通' });
|
||||
expect(lifeStatus({ ...base, backend: { life: false, persona: false, receipt: true, web_connected: true } })).toMatchObject({ wired: true, on: false, label: '后台未启用' });
|
||||
expect(lifeStatus({ ...base, backend: { life: true, persona: true, receipt: true, web_connected: true } }).on).toBe(false);
|
||||
const running = { ...base, backend: { life: true, persona: true, receipt: true, web_connected: true }, life_runtime: { state: 'running', timezone: 'Asia/Shanghai', budget_warning: false, budget_stopped: false, last: null } };
|
||||
expect(lifeStatus(running).on).toBe(true);
|
||||
expect(lifeStatus({ ...running, life_runtime: { ...running.life_runtime, state: 'paused_failures' } })).toMatchObject({ on: false, label: '后台已暂停' });
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user