HEL-834: apply visual director memories page source package (6 modified + 9 new, verified against MANIFEST)
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
co-authored by
multica-agent
parent
89d53b6c53
commit
2288471445
@@ -0,0 +1,85 @@
|
||||
// HEL-834 isolated contract mock: serves web/dist and the real-mode API shapes from the HEL-833 backend
|
||||
// (HEL-832 §5 memories, /api/life, /api/messages, /api/persona, /api/health). Synthetic data only, no model, no network.
|
||||
// Usage: node tests/hel834_mock.mjs <port>; switch scenarios with GET /__mode/<full|full-new|empty|fail|unwired>.
|
||||
import { createServer } from 'node:http';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { extname, join, normalize } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const dist = fileURLToPath(new URL('../dist/', import.meta.url));
|
||||
const port = Number(process.argv[2] || 8834);
|
||||
let mode = 'full';
|
||||
const log = [];
|
||||
const T0 = Date.UTC(2026, 9, 23, 13, 0);
|
||||
const identity = { id: '1', name: '栖', birth: '2000-03-14', hour: '子', relation: '朋友', nickname: '', boundary: '', color: { pillars: { year: '庚辰', month: '己卯', day: '丙午', hour: '戊子' }, traits: '合成测试档案' } };
|
||||
// Sent turns, plus one cancelled and one failed message that must never be shown as a memory's chat.
|
||||
const turns = [
|
||||
['下雨天的时候,你会想听什么?', '会想把窗开一条缝,听雨落在铁皮檐上。你呢,今天累不累?'],
|
||||
['今天加班到九点,好累。', '那先别急着做别的,喝口热水,慢慢跟我说。'],
|
||||
['我下周想去杭州看看西湖。', '记得带伞,十月的湖边风有点凉。'],
|
||||
['你昨天说的那段旋律,后来怎么样了?', '我给它换了一个结尾,像是把门轻轻带上。'],
|
||||
];
|
||||
const messages = [];
|
||||
turns.forEach(([u, c], i) => {
|
||||
const turn = `00000000-0000-4000-8000-00000000000${i}`, ts = T0 + i * 3600e3;
|
||||
messages.push({ id: i * 2 + 1, ts, role: 'user', text: u, turn_id: turn, status: 'sent', lifeIds: [] });
|
||||
messages.push({ id: i * 2 + 2, ts: ts + 4000, role: 'companion', text: c, turn_id: turn, status: 'sent', lifeIds: i === 3 ? [101] : [] });
|
||||
});
|
||||
messages.push({ id: 9, ts: T0 + 5 * 3600e3, role: 'user', text: '这句被我取消了', turn_id: '00000000-0000-4000-8000-000000000009', status: 'cancelled', lifeIds: [] });
|
||||
const life = [
|
||||
{ id: 101, ts: T0 - 86400e3, kind: 'thought', content: '我试着给一段旋律换个结尾。', place: '房间', salience: .7, source: 'generated', day_key: '2026-10-22', tz: 'Asia/Shanghai', told: true, told_at: T0 + 3 * 3600e3, messageIds: [8] },
|
||||
{ id: 100, ts: T0 - 2 * 86400e3, kind: 'scene', content: '傍晚下了一阵雨,窗台上积了一小洼水。', place: '窗边', salience: .5, source: 'generated', day_key: '2026-10-21', tz: 'Asia/Shanghai', told: true, told_at: T0, messageIds: [2] },
|
||||
];
|
||||
// Told, but older than the loaded page: only reachable by id.
|
||||
const olderLife = { id: 90, ts: T0 - 9 * 86400e3, kind: 'encounter', content: '楼下新开了一家修钟表的小店。', place: '街角', salience: .4, source: 'generated', day_key: '2026-10-14', tz: 'Asia/Shanghai', told: true, told_at: T0 - 8 * 86400e3, messageIds: [] };
|
||||
const stamp = ts => { const d = new Date(ts + 8 * 3600e3); return `来自 ${d.getUTCMonth() + 1}月${d.getUTCDate()}日 ${String(d.getUTCHours()).padStart(2, '0')}:${String(d.getUTCMinutes()).padStart(2, '0')} 的聊天`; };
|
||||
const mem = (id, gist, messageId, lifeIds = []) => { const m = messages.find(x => x.id === messageId); return { id: String(id), title: gist.slice(0, 40), text: gist.slice(0, 200), group: '我们一起的', source: stamp(m.ts), lifeIds, messageIds: [messageId], ts: m.ts }; };
|
||||
const filler = Array.from({ length: 28 }, (_, i) => mem(10 + i, `第 ${i + 1} 条合成回忆:你们聊到窗外的天色和晚饭吃了什么。`, 1 + (i % 8)));
|
||||
const base = [
|
||||
mem(48, '他下周想去杭州看西湖,她提醒他带伞,十月的湖边风有点凉;她还记得他说过想在断桥边等一场日落,看完再慢慢走回去。', 5),
|
||||
mem(47, '他说今天加班到九点很累,她让他先喝口热水再慢慢说。', 3),
|
||||
mem(46, '她把那段旋律换了个结尾,像把门轻轻带上——他问起过。', 8, [101, 90]),
|
||||
mem(45, '他问她下雨天想听什么,她说想听雨落在铁皮檐上。', 1),
|
||||
...filler.reverse(),
|
||||
];
|
||||
const fresh = mem(50, '他提起下雨天,她记得他喜欢开一条窗缝听雨。', 2);
|
||||
const malformed = [{ ...mem(49, '坏行:没有来源消息', 1), messageIds: [] }, { ...mem(44, '坏行:数字id', 1), id: 44 }];
|
||||
const visible = () => (mode === 'full-new' ? [fresh, ...base] : base);
|
||||
const send = (res, status, body, type = 'application/json; charset=utf-8') => { res.writeHead(status, { 'Content-Type': type, 'Cache-Control': 'no-store' }); res.end(typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body)); };
|
||||
const page = (rows, url, limit) => { const before = Number(url.searchParams.get('before') || Infinity), list = rows.filter(r => Number(r.id) < before), out = list.slice(0, limit); return { out, next: list.length > limit ? Number(out[out.length - 1].id) : null }; };
|
||||
|
||||
createServer(async (req, res) => {
|
||||
const url = new URL(req.url, 'http://x');
|
||||
log.push(`${req.method} ${url.pathname}${url.search}`);
|
||||
const p = url.pathname;
|
||||
if (p.startsWith('/__mode/')) { mode = p.slice(8); return send(res, 200, { mode }); }
|
||||
if (p === '/__log') return send(res, 200, log.splice(0));
|
||||
if (p === '/api/health') return send(res, 200, { version: 'R3-backend', epoch: 3, llm: { ok: true, model: 'mock' }, 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 }, capabilities: { text: true, life: false, voice: false, vision: false, weather: false, materials: false, backup: false, memory: mode !== 'unwired' } });
|
||||
if (p === '/api/companion') return send(res, 200, identity);
|
||||
if (p === '/api/messages') return send(res, 200, { messages, next_before: null, epoch: 3 });
|
||||
if (p === '/api/persona') return send(res, 200, { state: 'ready', interpretation: null, seeds: [], growth: [] });
|
||||
if (p === '/api/life') return send(res, 200, { events: life, next_before: null, epoch: 3 });
|
||||
const lifeId = p.match(/^\/api\/life\/(\d+)$/u);
|
||||
if (lifeId) { const e = [...life, olderLife].find(x => String(x.id) === lifeId[1]); return e ? send(res, 200, { event: e, epoch: 3 }) : send(res, 404, { detail: '这一条现在打不开。' }); }
|
||||
if (p === '/api/memories') {
|
||||
if (mode === 'unwired') return send(res, 404, { detail: 'Not Found' });
|
||||
if (mode === 'fail') return send(res, 500, { detail: 'Internal Server Error' });
|
||||
if (mode === 'empty') return send(res, 200, { memories: [], next_before: null, epoch: 3 });
|
||||
const limit = Number(url.searchParams.get('limit') || 30), { out, next } = page(visible(), url, limit);
|
||||
return send(res, 200, { memories: [...out, ...(url.searchParams.get('before') ? [] : malformed)], next_before: next, epoch: 3 });
|
||||
}
|
||||
const memId = p.match(/^\/api\/memories\/(.+)$/u);
|
||||
if (memId) { const m = mode === 'unwired' ? null : visible().find(x => x.id === memId[1]); return m ? send(res, 200, { memory: m, epoch: 3 }) : send(res, 404, { detail: '这一条现在打不开。' }); }
|
||||
if (p === '/api/chat' && req.method === 'POST') {
|
||||
let body = ''; for await (const chunk of req) body += chunk;
|
||||
const { turn_id } = JSON.parse(body), text = '我在。今天的雨停了没有?';
|
||||
res.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
||||
res.end(`data: ${JSON.stringify({ t: 'chat.delta', epoch: 3, turn_id, delta: text })}\n\ndata: ${JSON.stringify({ t: 'chat.final', epoch: 3, turn_id, utterance: { text, speech_tags: [] }, receipt: null })}\n\n`);
|
||||
return;
|
||||
}
|
||||
if (p.startsWith('/api/')) return send(res, 404, { detail: 'Not Found' });
|
||||
const file = normalize(join(dist, p === '/' ? 'index.html' : p));
|
||||
if (!file.startsWith(normalize(dist))) return send(res, 404, '');
|
||||
try { send(res, 200, await readFile(file), { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp', '.svg': 'image/svg+xml' }[extname(file)] || 'application/octet-stream'); }
|
||||
catch { send(res, 404, ''); }
|
||||
}).listen(port, '127.0.0.1', () => console.log(`mock on ${port}`));
|
||||
@@ -0,0 +1,131 @@
|
||||
// HEL-834 browser check: drives headless Edge over CDP against tests/hel834_mock.mjs.
|
||||
// Usage: node tests/hel834_shots.mjs <edge.exe> <outDir> [port]. Prints one PASS/FAIL line per check, exits 1 on any FAIL.
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
|
||||
const [edge, out, portArg] = process.argv.slice(2);
|
||||
const port = Number(portArg || 8834), base = `http://127.0.0.1:${port}`, cdpPort = 9434;
|
||||
mkdirSync(out, { recursive: true });
|
||||
const profile = join(tmpdir(), `hel834-edge-${Date.now()}`);
|
||||
const browser = spawn(edge, ['--headless=new', `--remote-debugging-port=${cdpPort}`, `--user-data-dir=${profile}`, '--no-first-run', '--hide-scrollbars', '--force-color-profile=srgb', 'about:blank'], { stdio: 'ignore' });
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
let targets;
|
||||
for (let i = 0; i < 60 && !targets; i++) { try { targets = await (await fetch(`http://127.0.0.1:${cdpPort}/json`)).json(); } catch { await sleep(250); } }
|
||||
const ws = new WebSocket(targets.find(t => t.type === 'page').webSocketDebuggerUrl);
|
||||
await new Promise(r => ws.addEventListener('open', r, { once: true }));
|
||||
let seq = 0; const waiting = new Map(), requests = [];
|
||||
ws.addEventListener('message', ({ data }) => {
|
||||
const m = JSON.parse(data);
|
||||
if (m.id && waiting.has(m.id)) { const { ok, ko } = waiting.get(m.id); waiting.delete(m.id); m.error ? ko(new Error(m.error.message)) : ok(m.result); }
|
||||
else if (m.method === 'Network.requestWillBeSent') requests.push(m.params.request.url);
|
||||
});
|
||||
const cdp = (method, params = {}) => new Promise((ok, ko) => { const id = ++seq; waiting.set(id, { ok, ko }); ws.send(JSON.stringify({ id, method, params })); });
|
||||
const js = async expr => { const r = await cdp('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true }); if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || 'js error'); return r.result.value; };
|
||||
const results = [];
|
||||
const check = (name, ok, detail = '') => { results.push(ok); console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` — ${detail}` : ''}`); };
|
||||
const mode = m => fetch(`${base}/__mode/${m}`);
|
||||
const serverLog = async () => (await fetch(`${base}/__log`)).json();
|
||||
const shot = async name => { const { data } = await cdp('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(out, `${name}.png`), Buffer.from(data, 'base64')); };
|
||||
const click = async (selector, text = '') => js(`(() => { const el = [...document.querySelectorAll(${JSON.stringify(selector)})].find(e => e.offsetParent !== null && e.textContent.includes(${JSON.stringify(text)})); if (!el) return false; el.click(); return true; })()`);
|
||||
const text = sel => js(`[...document.querySelectorAll(${JSON.stringify(sel)})].filter(e => e.offsetParent !== null).map(e => e.innerText).join('\\n')`);
|
||||
const count = sel => js(`[...document.querySelectorAll(${JSON.stringify(sel)})].filter(e => e.offsetParent !== null).length`);
|
||||
const views = { desktop: { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false }, phone: { width: 390, height: 844, deviceScaleFactor: 2, mobile: true } };
|
||||
async function view(v) { await cdp('Emulation.setDeviceMetricsOverride', views[v]); await cdp('Emulation.setTouchEmulationEnabled', { enabled: views[v].mobile, maxTouchPoints: 5 }); }
|
||||
async function boot(theme, path = '/') {
|
||||
await cdp('Page.navigate', { url: `${base}/` }); await sleep(600);
|
||||
await js(`localStorage.setItem('cg.theme', ${JSON.stringify(theme)}); sessionStorage.clear(); true`);
|
||||
await cdp('Page.navigate', { url: `${base}${path}` }); await sleep(1800);
|
||||
}
|
||||
const openMemories = async () => { await click('.nav-item', '日子'); await sleep(1300); await click('[role=tab]', '我们的回忆'); await sleep(900); };
|
||||
await cdp('Page.enable'); await cdp('Runtime.enable'); await cdp('Network.enable');
|
||||
|
||||
// 1. Two themes × desktop/phone: list and detail.
|
||||
for (const theme of ['moon', 'fog']) for (const v of ['desktop', 'phone']) {
|
||||
await mode('full'); await view(v); await boot(theme);
|
||||
await openMemories(); await shot(`${theme}-${v}-memories`);
|
||||
await click('button.mem', '旋律'); await sleep(1000); await shot(`${theme}-${v}-detail`);
|
||||
}
|
||||
|
||||
// 2. Behaviour (desktop, moon).
|
||||
await view('desktop'); await mode('full'); await boot('moon'); await serverLog();
|
||||
await openMemories();
|
||||
let list = await text('.list');
|
||||
check('first page renders 30 valid memories, malformed rows dropped', await count('button.mem') === 30 && !list.includes('坏行'), `${await count('button.mem')} items`);
|
||||
check('unbuilt groups not drawn; 她的成长 points to settings', !list.includes('你们的小习惯') && !list.includes('她知道的你') && list.includes('她的成长') && list.includes('在设置里看底色与成长'));
|
||||
await click('.more button', '看更早的回忆'); await sleep(900);
|
||||
list = await text('.list');
|
||||
check('cursor paging appends the older page', await count('button.mem') === 32 && list.includes('再往前的聊天'), `${await count('button.mem')} items`);
|
||||
check('paging used next_before=12', (await serverLog()).includes('GET /api/memories?limit=30&before=12'));
|
||||
await click('button.mem', '旋律'); await sleep(900);
|
||||
let detail = await text('.detail');
|
||||
check('detail shows server fields and source', /我们一起的 · 来自 \d+月\d+日 \d\d:\d\d 的聊天/u.test(detail) && detail.includes('她是这样记得的'));
|
||||
check('那时候的聊天 is exactly messageIds under the real speaker', await count('.said-then p') === 1 && detail.includes('换了一个结尾'));
|
||||
check('linked days: loaded one by title, older one by id placeholder', detail.includes('一个念头') && detail.includes('她讲给你听过的一件事'));
|
||||
await click('.link-card', '她讲给你听过的一件事'); await sleep(1200);
|
||||
detail = await text('.detail');
|
||||
check('older day opens by id through /api/life/90', detail.includes('修钟表'));
|
||||
await click('[role=tab]', '我们的回忆'); await sleep(600);
|
||||
await click('button.mem', '加班'); await sleep(900);
|
||||
detail = await text('.detail');
|
||||
check('a memory from your words shows them as yours', /你\s*今天加班到九点/u.test(detail) && await count('.said-then p[data-role=user]') === 1 && await count('.said-then p[data-role=companion]') === 0);
|
||||
await click('.detail button', '在交谈里看这段'); await sleep(1500);
|
||||
check('在交谈里看这段 opens the record at that message', await js(`!!document.querySelector('article.message.hl[data-mid="3"]')`) && await count('article.message.hl') === 1);
|
||||
await click('.nav-item', '日子'); await sleep(1000); await click('[role=tab]', '她的日子'); await sleep(500);
|
||||
await click('button.ev', '旋律'); await sleep(900);
|
||||
detail = await text('.detail');
|
||||
check('life detail lists the memory linked by server lifeIds', detail.includes('和这件事有关的回忆') && detail.includes('她把那段旋律换了个结尾'));
|
||||
// Reopen re-reads.
|
||||
await click('.nav-item', '此刻'); await sleep(800); await mode('full-new'); await serverLog();
|
||||
await click('.nav-item', '日子'); await sleep(1200); await click('[role=tab]', '我们的回忆'); await sleep(800);
|
||||
check('reopening re-reads /api/memories and shows the new memory first', (await serverLog()).some(l => l.startsWith('GET /api/memories?limit=30')) && (await text('button.mem')).split('\n').some(l => l.includes('开一条窗缝')));
|
||||
// Old link to a memory the server will not show.
|
||||
await mode('full'); await boot('moon', '/#memory=77'); await click('.nav-item', '日子'); await sleep(1600);
|
||||
detail = await text('.detail');
|
||||
check('old/hidden memory link is one neutral can\'t-open', detail.includes('这一条现在打不开') && !detail.includes('77'));
|
||||
await shot('moon-desktop-hidden-link');
|
||||
await boot('moon', '/#memory=47'); await click('.nav-item', '日子'); await sleep(1600);
|
||||
check('deep link to a visible memory opens it', (await text('.detail')).includes('加班到九点'));
|
||||
|
||||
// 3. States.
|
||||
for (const [m, expect] of [['empty', '还没有可以展示的回忆'], ['fail', '回忆一时没翻出来'], ['unwired', '长期记忆尚未接通']]) {
|
||||
for (const v of ['desktop', 'phone']) {
|
||||
await mode(m); await view(v); await boot('moon'); await openMemories();
|
||||
const t = await text('.list');
|
||||
if (v === 'desktop') check(`${m} state is its own honest state`, t.includes(expect) && !(m !== 'empty' && t.includes('还没有可以展示的回忆')) && !(m !== 'fail' && t.includes('一时没翻出来')));
|
||||
await shot(`moon-${v}-${m}`);
|
||||
}
|
||||
}
|
||||
await view('desktop'); await mode('fail'); await boot('fog'); await openMemories(); await shot('fog-desktop-fail');
|
||||
await mode('full'); await click('.list button', '再试一次'); await sleep(900);
|
||||
check('retry after failure loads the list', await count('button.mem') === 30);
|
||||
await mode('empty'); await boot('fog'); await openMemories(); await shot('fog-desktop-empty');
|
||||
await mode('unwired'); await boot('fog'); await openMemories(); await shot('fog-desktop-unwired');
|
||||
const home = async () => { await click('.nav-item', '此刻'); await sleep(700); return js(`document.querySelector('.first-note')?.textContent || ''`); };
|
||||
check('home note stays conservative when memory is not on', (await home()).includes('长期记忆与语音尚未接通'));
|
||||
await mode('full'); await boot('moon');
|
||||
check('home note says memory is saved only when the server reports it', (await js(`document.querySelector('.first-note')?.textContent || ''`)).includes('资料、聊天与回忆保存在服务器'));
|
||||
|
||||
// 4. Real text chat still works.
|
||||
await click('.nav-item', '交谈'); await sleep(1200);
|
||||
await js(`document.querySelector('textarea').focus(); true`);
|
||||
await cdp('Input.insertText', { text: '雨停了吗' });
|
||||
await cdp('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, text: '\r' });
|
||||
await cdp('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 });
|
||||
await sleep(6000);
|
||||
check('real text chat sends and receives', (await serverLog()).includes('POST /api/chat') && (await js('document.body.innerText')).includes('今天的雨停了没有'));
|
||||
|
||||
// 5. Demo path: separate, zero API and zero off-host requests.
|
||||
requests.length = 0; await serverLog();
|
||||
await view('desktop'); await cdp('Page.navigate', { url: `${base}/?demo=1` }); await sleep(2000);
|
||||
await shot('moon-desktop-demo-entry');
|
||||
const offHost = requests.filter(u => !u.startsWith(base) && !u.startsWith('data:') && !u.startsWith('blob:'));
|
||||
const api = (await serverLog()).filter(l => l.includes('/api/'));
|
||||
check('demo path makes zero /api and zero off-host requests', offHost.length === 0 && api.length === 0, `${requests.length} requests, off-host ${offHost.length}, api ${api.length}`);
|
||||
check('demo stays its own local path (wizard, no real profile)', (await js('document.body.innerText')).includes('这是本机演示') && !(await js('document.body.innerText')).includes('栖'));
|
||||
|
||||
ws.close(); browser.kill(); await sleep(500); try { rmSync(profile, { recursive: true, force: true }); } catch { /* Edge may still hold the profile. */ }
|
||||
const failed = results.filter(r => !r).length;
|
||||
console.log(`${results.length - failed}/${results.length} checks passed`);
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -0,0 +1,54 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { memoryDetail, memoryNote, memoryPage, NotFound, NotWired, lifeStatus, type Health } from '../src/adapters/real';
|
||||
|
||||
// HEL-832 §5 MemoryDTO exactly as the HEL-833 backend serializes it (episodic.py dto()).
|
||||
const dto = (id: string, over: Record<string, unknown> = {}) => ({ id, title: '一起听的那场雨', text: '你说下雨天想听她弹琴,她记得你那天很累。', group: '我们一起的', source: '来自 10月23日 21:04 的聊天', lifeIds: [], messageIds: [Number(id) * 2], ts: 1761224640000, ...over });
|
||||
const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status });
|
||||
const signal = () => new AbortController().signal;
|
||||
|
||||
describe('real memories (GET /api/memories)', () => {
|
||||
afterEach(() => { vi.unstubAllGlobals(); });
|
||||
it('maps the contract fields, keeps the server cursor and asks for the next page with before', async () => {
|
||||
const fetch = vi.fn().mockResolvedValueOnce(json({ memories: [dto('12', { lifeIds: [7] }), dto('9')], next_before: 9, epoch: 3 })).mockResolvedValueOnce(json({ memories: [dto('4')], next_before: null, epoch: 3 }));
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
const first = await memoryPage(null, signal());
|
||||
expect(first.next).toBe('9');
|
||||
expect(first.memories[0]).toEqual({ id: '12', title: '一起听的那场雨', text: dto('12').text, group: '我们一起的', source: '来自 10月23日 21:04 的聊天', lifeIds: ['7'], messageIds: ['24'] });
|
||||
const second = await memoryPage(first.next, signal());
|
||||
expect(second).toMatchObject({ next: null, memories: [{ id: '4' }] });
|
||||
expect(fetch.mock.calls.map(c => c[0])).toEqual(['/api/memories?limit=30', '/api/memories?limit=30&before=9']);
|
||||
});
|
||||
it('drops malformed rows instead of patching them up', async () => {
|
||||
const bad = [dto('0'), dto('x1'), { ...dto('5'), id: 5 }, dto('6', { title: '' }), dto('7', { text: ' ' }), dto('8', { messageIds: [] }), dto('10', { messageIds: ['3'] }), dto('11', { lifeIds: [-1] }), dto('13', { ts: 'yesterday' }), dto('14', { group: undefined }), null, 'row'];
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json({ memories: [...bad, dto('20')], next_before: null, epoch: 1 })));
|
||||
const page = await memoryPage(null, signal());
|
||||
expect(page.memories.map(m => m.id)).toEqual(['20']);
|
||||
});
|
||||
it('an empty list is just empty, a missing route is "not wired", and a failure is a failure', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce(json({ memories: [], next_before: null, epoch: 1 })).mockResolvedValueOnce(json({ detail: 'Not Found' }, 404)).mockResolvedValueOnce(json({ detail: 'boom' }, 500)).mockRejectedValueOnce(new TypeError('offline')).mockResolvedValueOnce(json({ nope: 1 })));
|
||||
await expect(memoryPage(null, signal())).resolves.toEqual({ memories: [], next: null });
|
||||
await expect(memoryPage(null, signal())).rejects.toBeInstanceOf(NotWired);
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const e = await memoryPage(null, signal()).catch(x => x);
|
||||
expect(e).toBeInstanceOf(Error);
|
||||
expect(e).not.toBeInstanceOf(NotWired);
|
||||
}
|
||||
});
|
||||
it('detail: a hidden, uncompressed or forged id is one neutral 404, malformed ids never reach the server', async () => {
|
||||
const fetch = vi.fn().mockResolvedValueOnce(json({ memory: dto('12'), epoch: 2 })).mockResolvedValueOnce(json({ detail: '这一条现在打不开。' }, 404)).mockResolvedValueOnce(json({ memory: { ...dto('15'), messageIds: [] }, epoch: 2 })).mockResolvedValueOnce(json({ detail: 'x' }, 503));
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
await expect(memoryDetail('12', signal())).resolves.toMatchObject({ id: '12', messageIds: ['24'] });
|
||||
await expect(memoryDetail('13', signal())).rejects.toBeInstanceOf(NotFound);
|
||||
await expect(memoryDetail('15', signal())).rejects.toBeInstanceOf(NotFound);
|
||||
const e = await memoryDetail('16', signal()).catch(x => x);
|
||||
expect(e).not.toBeInstanceOf(NotFound);
|
||||
for (const id of ['', '0', '-1', '1e3', '../life/1', '12345678901234567890']) await expect(memoryDetail(id, signal())).rejects.toBeInstanceOf(NotFound);
|
||||
expect(fetch).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
it('the home note only calls memory connected when the server says so', () => {
|
||||
const base: Health = { epoch: 1, llm: { ok: true, model: 'm' } };
|
||||
expect(memoryNote(base, lifeStatus(base))).toContain('长期记忆与语音尚未接通');
|
||||
expect(memoryNote({ ...base, capabilities: { memory: false } }, lifeStatus(base))).toContain('长期记忆与语音尚未接通');
|
||||
expect(memoryNote({ ...base, capabilities: { memory: true } }, lifeStatus(base))).toBe('资料、聊天与回忆保存在服务器。生活与语音尚未接通。');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user