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 => ({ 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; 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: '后台已暂停' }); }); });