From 58d65aea056e6f17d711dfa4877591ee74a8bf41 Mon Sep 17 00:00:00 2001 From: Chief Engineer Date: Sat, 24 Oct 2026 11:08:53 +0800 Subject: [PATCH] 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 --- docs/requirements/handoff-HEL-828.json | 63 ++++++++++++++ src/cybergril/api/app.py | 5 +- web/src/adapters/real.ts | 82 +++++++++++++++++- web/src/adapters/receipt.ts | 47 ++++++++++ web/src/adapters/sha256.ts | 36 ++++++++ web/src/app/RealApp.tsx | 26 ++++-- web/src/chat/ChatPanel.tsx | 22 +++-- web/src/domain/model.ts | 13 +++ web/src/life/LifePanel.tsx | 100 ++++++++++++++++++---- web/src/manage/ManagePanel.tsx | 53 ++++++++++-- web/src/stage/Presenter.tsx | 9 +- web/tests/r2wiring.test.ts | 113 +++++++++++++++++++++++++ 12 files changed, 526 insertions(+), 43 deletions(-) create mode 100644 docs/requirements/handoff-HEL-828.json create mode 100644 web/src/adapters/receipt.ts create mode 100644 web/src/adapters/sha256.ts create mode 100644 web/tests/r2wiring.test.ts diff --git a/docs/requirements/handoff-HEL-828.json b/docs/requirements/handoff-HEL-828.json new file mode 100644 index 0000000..31d9fad --- /dev/null +++ b/docs/requirements/handoff-HEL-828.json @@ -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 +} diff --git a/src/cybergril/api/app.py b/src/cybergril/api/app.py index 4c5b04c..e71c6d7 100644 --- a/src/cybergril/api/app.py +++ b/src/cybergril/api/app.py @@ -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}, diff --git a/web/src/adapters/real.ts b/web/src/adapters/real.ts index b83025c..17f7777 100644 --- a/web/src/adapters/real.ts +++ b/web/src/adapters/real.ts @@ -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 = { 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; + 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 { + 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('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('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(path: string, init?: RequestInit): Promise { 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 { 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; diff --git a/web/src/adapters/receipt.ts b/web/src/adapters/receipt.ts new file mode 100644 index 0000000..7091056 --- /dev/null +++ b/web/src/adapters/receipt.ts @@ -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(), inFlight = new Map>(); +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; + 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 { + 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 => { + 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(); } diff --git a/web/src/adapters/sha256.ts b/web/src/adapters/sha256.ts new file mode 100644 index 0000000..cc927a0 --- /dev/null +++ b/web/src/adapters/sha256.ts @@ -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(''); +} diff --git a/web/src/app/RealApp.tsx b/web/src/app/RealApp.tsx index f94e88c..7a30e6a 100644 --- a/web/src/app/RealApp.tsx +++ b/web/src/app/RealApp.tsx @@ -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').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 <> navigate('talk')}/> + return <> navigate('talk')}/>
{state?.identity.name || 'CyberGril'}{talking && {presence}}{ready ? '真实档案 · 文字对话' : '连接真实服务'}
天气尚未接通{(['moon', 'fog'] as Theme[]).map(t => )}{talking && }
{!ready ?

一扇亮着的窗。

{error && <>

请检查真实服务是否可达。资料仍在服务器保存。

}
: <> {creating && setCreating(false)}/>} {!creating && state && <> - {area === 'now' &&
一扇亮着的窗

慢慢说,我在这里。

{state.identity.relation} · 慢慢熟悉
{lastReply && }

资料与聊天已保存在服务器。生活、长期记忆与语音尚未接通。

{health && !health.llm.ok && }
} - {area === 'talk' && } - navigate('now')} onChat={() => { navigate('talk'); setLog(true); }} onSettings={() => { navigate('settings'); setHerFocus(n => n + 1); }}/> - navigate('now')} onSave={setState} fail={false} theme={theme} setTheme={setTheme}/> + {area === 'now' &&
一扇亮着的窗

慢慢说,我在这里。

{state.identity.relation} · 慢慢熟悉
{lastReply && }

{life.wired ? `资料与聊天已保存在服务器。生活:${life.label}。长期记忆与语音尚未接通。` : '资料与聊天已保存在服务器。生活、长期记忆与语音尚未接通。'}

{health && !health.llm.ok && }
} + {area === 'talk' && } + navigate('now')} onChat={openTold} onSettings={() => { navigate('settings'); setHerFocus(n => n + 1); }}/> + navigate('now')} onSave={setState} fail={false} theme={theme} setTheme={setTheme}/> } }; } diff --git a/web/src/chat/ChatPanel.tsx b/web/src/chat/ChatPanel.tsx index 4e527a9..9c7f16c 100644 --- a/web/src/chat/ChatPanel.tsx +++ b/web/src/chat/ChatPanel.tsx @@ -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(() => { 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, +

内容完整保留;关闭后回到刚才那一句,自动呈现会接着走。

{record.map(m =>
{m.role === 'user' ? '你' : name}{m.proactive && 她主动说的}

{m.text}

{m.status === 'failed' && }{m.status === 'cancelled' && 已取消}{m.live === 'cancelled' && 已停止 · 这是未完成片段,未存入聊天记录}
)}{reply &&
{name}

{reply}

还在说…
}
{full && fullMessage && } {permission && { 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(''); }}>本次仅模拟界面状态,不申请麦克风或摄像头权限,不采集声音或影像,也不向外接服务发送请求。} diff --git a/web/src/domain/model.ts b/web/src/domain/model.ts index aec0668..2f0ae85 100644 --- a/web/src/domain/model.ts +++ b/web/src/domain/model.ts @@ -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))) diff --git a/web/src/life/LifePanel.tsx b/web/src/life/LifePanel.tsx index 3fe9b3a..841913c 100644 --- a/web/src/life/LifePanel.tsx +++ b/web/src/life/LifePanel.tsx @@ -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('ok'), [more, setMore] = useState(false); - const list = useRef(null), detail = useRef(null), scroll = useRef>({}), wasOpen = useRef(false), request = useRef(null); + const [realEvents, setRealEvents] = useState([]), [next, setNext] = useState(null), [lookup, setLookup] = useState(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(real ? 'loading' : 'ok'), [more, setMore] = useState(false); + const list = useRef(null), detail = useRef(null), scroll = useRef>({}), wasOpen = useRef(false), request = useRef(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(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 && 演示数据; - 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) =>
{who}{text}
; const linkCard = (key: string, title: string, sub: string, go: () => void) => ; function eventView(e: LifeEvent) { @@ -60,8 +124,8 @@ export function LifePanel({ state, open, onClose, onChat, onSettings, now = '', {mems.length > 0 && <>
和这件事有关的回忆
{mems.map(m => linkCard(m.id, m.title, m.source, () => select(m.id, 'memory')))}
}
那时候的聊天
{chat.length ?
{chat.map(m =>

{m.role === 'user' ? '你' : name}{m.text}

)}
:

那时候没有留下聊天记录。

} - -
{demoTag}这是模拟生活里的一条记录,不是真实发生的事。画面只按记录选片,不会反过来改写她的生活。
+ +
{real ? '这是服务器记下的她的日子,她在交谈里讲给你听过才会显示。它不是你们的长期记忆,也不会反过来改写她最初的底色。' : <>{demoTag}这是模拟生活里的一条记录,不是真实发生的事。画面只按记录选片,不会反过来改写她的生活。}
; } function memoryView(m: Memory) { @@ -82,9 +146,9 @@ export function LifePanel({ state, open, onClose, onChat, onSettings, now = '', function lifeList() { if (load === 'loading') return <>

正在翻她的日子…

{skeleton(6)}; if (load === 'error') return failed; - if (!view.events.length) return
{real ? '还没有可展示的生活记录' : '她今晚刚住进来,还没有发生什么。'}{real ? '生活后台尚未接通,不用示例经历填充。你们说过的话可在交谈的完整记录中查看。' : '等她跟你讲起,日子会一条条留在这里。演示资料可以从「演示场景」载入。'}
; + if (!view.events.length) return
{real ? (life?.wired ? '她还没有讲给你听过自己的日子' : '还没有可展示的生活记录') : '她今晚刚住进来,还没有发生什么。'}{real ? `${life?.note || '生活后台尚未接通,不用示例经历填充。'}你们说过的话可在交谈的完整记录中查看。` : '等她跟你讲起,日子会一条条留在这里。演示资料可以从「演示场景」载入。'}
; return <>{shown.map((e, i) =>
{(i === 0 || day(shown[i - 1]) !== day(e)) &&
{day(e)}
}
)} - {more ?

正在翻更早的日子…

: limit < ordered.length ?
:

再往前,就是她刚住进来的那天了。

}; + {more ?

正在翻更早的日子…

: (real ? next : limit < ordered.length) ?
{moreError &&

更早的日子一时没翻出来,记录没有丢。

}
:

再往前,就是她刚住进来的那天了。

}; } 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
{group}{!real && {items.length}}
{real &&
暂无可核实的回忆长期记忆尚未接通;文字聊天记录独立保留。
}{items.map(m => )}
; }); } const blank = load !== 'ok' || (tab === 'life' ? !view.events.length : !view.memories.length); - return