import assert from 'node:assert/strict'; import test from 'node:test'; import { MAX_CATCHUP, mailToEvent, selectCatchup } from '../lib/catchup.js'; const mail = (over = {}) => ({ mail_id: 'm1', session_id: 's1', from_name: 'admin', subject: '主题', mail_type: 'normal', to_workspace: '/tmp/ws', ...over, }); test('mailToEvent 产出与 SSE new_mail 同形的对象', () => { const ev = mailToEvent(mail()); // 投递侧读的就是这几个键,形状不一致会让补拉那条路径静默地少带信息 for (const k of ['mail_id', 'session_id', 'from_name', 'subject', 'mail_type', 'to_workspace']) { assert.ok(k in ev, `缺少 ${k}`); } assert.equal(ev.role, 'to'); assert.equal(ev.catchup, true); }); test('mailToEvent 对缺字段的行给出空串而非 undefined', () => { const ev = mailToEvent({}); assert.equal(ev.mail_id, ''); assert.equal(ev.to_workspace, ''); assert.equal(ev.mail_type, 'normal'); }); test('已经通过 SSE 投过的不再补投', () => { const mails = [mail({ mail_id: 'a' }), mail({ mail_id: 'b' })]; const got = selectCatchup(mails, new Set(['a'])); assert.deepEqual(got.map(e => e.mail_id), ['b']); }); test('按时间正序补投(收件箱是倒序返回的)', () => { // 收件箱:新的在前 const mails = [mail({ mail_id: 'new' }), mail({ mail_id: 'mid' }), mail({ mail_id: 'old' })]; const got = selectCatchup(mails, new Set()); assert.deepEqual( got.map(e => e.mail_id), ['old', 'mid', 'new'], '先来的邮件必须先处理,否则同一会话里的上下文顺序是乱的', ); }); test('permission 类邮件不补投', () => { const mails = [mail({ mail_id: 'p', mail_type: 'permission' }), mail({ mail_id: 'n' })]; const got = selectCatchup(mails, new Set()); assert.deepEqual(got.map(e => e.mail_id), ['n']); }); test('超过上限的部分留在收件箱里', () => { const mails = Array.from({ length: MAX_CATCHUP + 4 }, (_, i) => mail({ mail_id: 'm' + i })); const got = selectCatchup(mails, new Set()); assert.equal(got.length, MAX_CATCHUP, '一次补拉不该把几十封邮件同时放出去'); }); test('上限可显式压到 0(用于禁用补拉)', () => { const got = selectCatchup([mail()], new Set(), 0); assert.deepEqual(got, []); }); test('空输入与非数组不炸', () => { assert.deepEqual(selectCatchup([], new Set()), []); assert.deepEqual(selectCatchup(undefined, new Set()), []); assert.deepEqual(selectCatchup(null, new Set()), []); }); test('没有 mail_id 的行跳过', () => { const got = selectCatchup([mail({ mail_id: '' }), mail({ mail_id: 'ok' })], new Set()); assert.deepEqual(got.map(e => e.mail_id), ['ok']); }); test('seen 传 undefined 时不去重也不报错', () => { const got = selectCatchup([mail({ mail_id: 'x' })], undefined); assert.deepEqual(got.map(e => e.mail_id), ['x']); }); test('★ 补投事件必须带权限档位(漏了就会把 full 档会话误拦)', () => { const ev = mailToEvent(mail({ permission_mode: 'full', permission_enforcement: 'strict' })); assert.equal(ev.permission_mode, 'full', '补投路径不许把档位丢掉'); assert.equal(ev.permission_enforcement, 'strict'); // 缺字段时给空串:**不猜档位**(猜宽了就是提权),由调用方 `|| 'workspace'` 兜底 const bare = mailToEvent(mail()); assert.equal(bare.permission_mode, ''); assert.equal(bare.permission_enforcement, ''); assert.ok(!('permissionMode' in bare), '键名要与 SSE 逐字一致(蛇形),别自造驼峰'); });