import { test } from 'node:test'; import assert from 'node:assert/strict'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, resolve, dirname } from 'node:path'; import { createStore } from '../src/store.js'; const record = { source: 'browser', accountId: 'browser:work', kind: 'message', externalId: 'm1', title: '讨论', text: '原文', raw: { capturedAt: 'first' } }; test('instance binding is atomic and scoped by source/account, and settings persist independently', () => { const s=createStore(':memory:'); try { s.createInstance({id:'default',name:'Fictional A'}); const b=s.createInstance({name:'Fictional B'}); s.bindInstanceAccounts('default',[{source:'web-api',accountId:'shared'}]); s.bindInstanceAccounts(b.id,[{source:'browser',accountId:'shared'}]); assert.throws(()=>s.bindInstanceAccounts(b.id,[{source:'web-api',accountId:'uncommitted'},{source:'web-api',accountId:'shared'}]),/bound/); assert.deepEqual(s.getInstance(b.id).accounts,[{source:'browser',accountId:'shared'}]); s.updateInstance(b.id,{name:'Renamed B',keepOnline:true}); assert.equal(s.getInstance('default').keepOnline,false);assert.equal(s.getInstance(b.id).keepOnline,true); for(const source of ['web-api','browser']) s.upsertRecord({...record,source,accountId:'shared'}); assert.equal(s.listRecords({instanceId:'default'}).total,1); assert.equal(s.listRecords({instanceId:b.id}).items[0].source,'browser'); assert.equal(s.listRecords({instanceId:'default',source:'browser'}).total,0); assert.throws(()=>s.listRecords({instanceId:'11111111-1111-1111-1111-111111111111'}),/Unknown/); } finally {s.close();} }); test('account purge removes version and notification payloads atomically while retaining other accounts and subscriptions', () => { const s=createStore(':memory:'); try { s.createInstance({id:'default',name:'Fictional A'});s.bindInstanceAccounts('default',[{source:'web-api',accountId:'a'}]); const a={...record,source:'web-api',accountId:'a',text:'DELETE-MARKER'},b={...record,source:'web-api',accountId:'b',text:'KEEP-MARKER'}; const first=s.upsertRecord(a,{ingestion:'live'});s.upsertRecord({...a,text:'DELETE-EDIT'},{ingestion:'live'}); const other=s.upsertRecord(b,{ingestion:'live'}); s.upsertRecord({...record,source:'browser',accountId:'a'}); const timestamp=new Date().toISOString(); s.execute('INSERT INTO webhook_subscriptions(id,name,url,secret,config,enabled,cursor,createdAt,updatedAt) VALUES(?,?,?,?,?,1,0,?,?)', ['fictional-sub','Fixture','https://example.invalid/','fictional-secret','{}',timestamp,timestamp]); for(const id of [first.id,other.id]){ const seq=s.readOne('SELECT seq FROM change_log WHERE recordId=? ORDER BY seq LIMIT 1',[id]).seq; s.execute("INSERT INTO webhook_deliveries(id,subscriptionId,seq,subscriptionRevision,payload,status,nextAttemptAt,createdAt,updatedAt) VALUES(?,?,?,1,?,'pending',?,?,?)", ['delivery-'+id,'fictional-sub',seq,JSON.stringify({fixture:id}),timestamp,timestamp,timestamp]); } const scope={source:'web-api',accountId:'a'}; assert.deepEqual(s.previewAccountDeletion(scope).counts,{records:1,versions:2,changes:2,liveObservations:1,webhookDeliveries:1,images:0}); const keep=s.getRecord(other.id); assert.equal(s.deleteAccountRecords(scope).deleted,true); assert.equal(s.getRecord(first.id),null);assert.deepEqual(s.getRecord(other.id),keep); assert.equal(s.listRecords({source:'browser',accountId:'a'}).total,1); assert.equal(s.readOne('SELECT COUNT(*) n FROM webhook_deliveries').n,1); for(const table of ['versions','change_log','message_live_observations']) assert.equal(s.readOne(`SELECT COUNT(*) n FROM ${table} WHERE recordId=?`,[first.id]).n,0); assert.equal(s.getInstance('default').accounts.length,1);assert.equal(s.readOne('SELECT COUNT(*) n FROM webhook_subscriptions').n,1); assert.equal(s.deleteAccountRecords(scope).counts.records,0); } finally {s.close();} }); test('state prefix deletion treats wildcard characters literally and preserves other instance state', () => { const s=createStore(':memory:'); try { s.setState('instance:test_%\\:cursor',1);s.setState('instance:test_X\\:cursor',2);s.setState('web-api:service',{enabled:true}); assert.equal(s.deleteStatesByPrefix('instance:test_%\\:'),1); assert.equal(s.getState('instance:test_X\\:cursor'),2);assert.equal(s.getState('web-api:service').enabled,true); assert.throws(()=>s.deleteStatesByPrefix(''),/prefix/); } finally {s.close();} }); test('deleted local record IDs remain unused after restart, including migration from a store without an allocator', () => { const directory=mkdtempSync(join(tmpdir(),'teams-id-sequence-')),path=join(directory,'records.sqlite'); let s; try { s=createStore(path);const original=s.upsertRecord(record); s.execute('DELETE FROM state WHERE key=?',['records:id-sequence']);s.close(); s=createStore(path);s.deleteAccountRecords({source:record.source,accountId:record.accountId});s.close(); s=createStore(path);const later=s.upsertRecord({...record,accountId:'other-account'}); assert.ok(later.id>original.id);assert.equal(s.getRecord(original.id),null); assert.equal(s.getRecord(later.id).accountId,'other-account'); } finally {s?.close();assert.equal(dirname(resolve(directory)),resolve(tmpdir()));rmSync(directory,{recursive:true,force:true});} }); test('重复心跳不产生新版本,内容编辑保留历史;按来源/账号隔离', () => { const s = createStore(':memory:'); try { const first = s.upsertRecord(record); assert.equal(s.upsertRecord({ ...record, raw: { capturedAt: 'later' } }).changed, false); assert.equal(s.stats().versions, 1); s.upsertRecord({ ...record, text: '编辑后' }); assert.deepEqual(s.getRecord(first.id).versions.map(v => v.text), ['编辑后', '原文']); s.upsertRecord({ ...record, accountId: 'browser:other' }); s.upsertRecord({ ...record, source: 'demo' }); assert.equal(s.stats().total, 3); assert.equal(s.listRecords({ accountId: 'browser:other' }).total, 1); } finally { s.close(); } }); test('Graph 删除保留原始正文、原始 tombstone 和派生记录', () => { const s = createStore(':memory:'); try { const base = { ...record, source: 'graph', accountId: 'graph:user', kind: 'event' }; const { id } = s.upsertRecord(base); s.upsertRecord({ source: 'graph', accountId: 'graph:user', kind: 'event', externalId: 'm1', deleted: true, raw: { id: 'm1', '@removed': { reason: 'deleted' } } }); const saved = s.getRecord(id); assert.equal(saved.text, '原文'); assert.equal(saved.deleted, 1); assert.equal(saved.raw['@removed'].reason, 'deleted'); assert.equal(s.listRecords({ kind: 'activity' }).total, 2); assert.equal(s.getRecord(id).versions.length, 2); } finally { s.close(); } }); test('批量失败回滚全部数据,搜索通配符按字面匹配', () => { const s = createStore(':memory:'); try { assert.throws(() => s.transaction(() => { s.upsertRecord(record); s.upsertRecord({}); })); assert.equal(s.stats().total, 0); s.upsertRecord({ ...record, text: '进度 100%_ready' }); s.upsertRecord({ ...record, externalId: 'm2', text: '进度 100abready' }); assert.equal(s.listRecords({ q: '%_' }).total, 1); assert.equal(s.listRecords({ q: "' OR 1=1--" }).total, 0); } finally { s.close(); } }); test('SQLite 重启后保留记录和同步游标', () => { const dir = mkdtempSync(join(tmpdir(), 'teams-store-')); const filename = join(dir, 'test.sqlite'); try { const s = createStore(filename); s.upsertRecord(record); s.setState('cursor', { next: 'opaque' }); s.close(); const reopened = createStore(filename); assert.equal(reopened.stats().total, 1); assert.deepEqual(reopened.getState('cursor'), { next: 'opaque' }); reopened.close(); } finally { rmSync(dir, { recursive: true, force: true }); } }); test('日历 delta 视图移除保留内容,不生成未知的空白删除记录', () => { const s = createStore(':memory:'); try { const base = { ...record, source: 'graph', accountId: 'graph:user', kind: 'event' }; const { id } = s.upsertRecord(base); const tombstone = { source: base.source, accountId: base.accountId, kind: 'event', externalId: 'm1', removedFromView: true, raw: { id: 'm1', '@removed': { reason: 'deleted' } } }; s.upsertRecord(tombstone); assert.equal(s.getRecord(id).text, '原文'); assert.equal(s.getRecord(id).removedFromView, 1); assert.equal(s.getRecord(id).deleted, 0); const total = s.stats().total; assert.equal(s.upsertRecord({ ...tombstone, externalId: 'unknown' }).changed, false); assert.equal(s.stats().total, total); s.upsertRecord(base); assert.equal(s.getRecord(id).removedFromView, 0); } finally { s.close(); } }); test('既有消息展示会话与发送者,读取不改保存标题、版本或hash', () => { const s = createStore(':memory:'); try { const original = { ...record, parentId: 'chat-one', title: '聊天', raw: { author: '示例发送者' } }; const { id } = s.upsertRecord(original); s.upsertRecord({ source: original.source, accountId: original.accountId, kind: 'chat', externalId: original.parentId, title: '示例对话名', raw: { titleSource: 'members' } }); const before = s.getRecordByIdentity(original), versions = s.stats().versions; for (const row of [s.listRecords({ kind: 'message' }).items[0], s.getRecord(id)]) { assert.equal(row.title, '聊天'); assert.equal(row.displayTitle, '示例对话名'); assert.equal(row.chatTitle, '示例对话名'); assert.equal(row.senderName, '示例发送者'); } assert.equal(s.getRecord(id).versions[0].title, '聊天'); assert.equal(s.getRecordByIdentity(original).hash, before.hash); assert.equal(s.stats().versions, versions); assert.equal('displayTitle' in s.getRecordByIdentity(original), false); } finally { s.close(); } }); test('消息读取不把发送者当会话名,不串账号,并保留明确命名为聊天的真实会话', () => { const s = createStore(':memory:'); try { const original = { ...record, parentId: 'same-chat', title: '示例作者', raw: { author: '示例作者' } }; const { id } = s.upsertRecord(original); s.upsertRecord({ source: original.source, accountId: 'other-account', kind: 'chat', externalId: original.parentId, title: '不应引用的名称' }); let saved = s.getRecord(id); assert.equal(saved.chatTitle, null); assert.equal(saved.displayTitle, '聊天消息'); assert.equal(saved.senderName, '示例作者'); s.upsertRecord({ source: original.source, accountId: original.accountId, kind: 'chat', externalId: original.parentId, title: '聊天', raw: { titleSource: 'explicit' } }); saved = s.getRecord(id); assert.equal(saved.chatTitle, '聊天'); assert.equal(saved.displayTitle, '聊天'); } finally { s.close(); } }); test('按发送者或同范围会话名搜索既有消息,自己的消息也能按对方会话名命中', () => { const s = createStore(':memory:'); try { s.upsertRecord({ ...record, parentId: 'chat-one', title: '聊天', raw: { author: '作者%_\\名称', privateField: '不可搜索字段' } }); s.upsertRecord({ ...record, externalId: 'own', parentId: 'chat-one', title: '聊天', raw: { author: '本人' } }); s.upsertRecord({ source: record.source, accountId: record.accountId, kind: 'chat', externalId: 'chat-one', title: '聊天对象名称' }); s.upsertRecord({ ...record, externalId: 'other-account', accountId: 'another', parentId: 'chat-one', title: '聊天' }); s.upsertRecord({ ...record, externalId: 'other-source', source: 'demo', parentId: 'chat-one', title: '聊天' }); const author = s.listRecords({ kind: 'message', q: '作者%_\\名称' }); assert.equal(author.total, 1); assert.equal(author.items[0].externalId, 'm1'); const conversation = s.listRecords({ kind: 'message', q: '聊天对象名称', limit: 1 }); assert.equal(conversation.total, 2); assert.equal(conversation.items.length, 1); assert.equal(s.listRecords({ kind: 'message', q: '聊天对象名称', offset: 1 }).items.length, 1); assert.equal(s.listRecords({ q: '不可搜索字段' }).total, 0); assert.equal(s.listRecords({ q: "' OR 1=1 --" }).total, 0); } finally { s.close(); } }); test('web-api聊天改名不制造既有消息版本,真实内容/raw/时间变化仍保留修订', () => { const s = createStore(':memory:'); try { const original = { ...record, source: 'web-api', accountId: 'api-account', parentId: 'chat-one', title: '首次采集的名称', updatedAt: '2026-09-08T00:00:00Z', raw: { author: '作者' } }; const { id } = s.upsertRecord(original, { ingestion: 'live' }); const before = s.getRecordByIdentity(original); const versions = () => Number(s.readOne('SELECT COUNT(*) AS n FROM versions WHERE recordId=?', [id]).n); const changes = () => Number(s.readOne('SELECT COUNT(*) AS n FROM change_log WHERE recordId=?', [id]).n); const renamed = { ...original, title: '现在的会话名称' }; assert.equal(s.upsertRecord(renamed, { ingestion: 'live' }).changed, false); assert.equal(s.getRecordByIdentity(original).hash, before.hash); assert.equal(versions(), 1); assert.equal(changes(), 1); s.upsertRecord({ source: original.source, accountId: original.accountId, kind: 'chat', externalId: original.parentId, title: renamed.title }); assert.equal(s.getRecord(id).displayTitle, renamed.title); assert.equal(s.getRecord(id).title, original.title); assert.equal(s.upsertRecord({ ...renamed, text: '真正编辑的正文' }, { ingestion: 'live' }).changed, true); assert.equal(s.upsertRecord({ ...renamed, text: '真正编辑的正文', raw: { author: '作者', edited: true } }, { ingestion: 'live' }).changed, true); assert.equal(s.upsertRecord({ ...renamed, text: '真正编辑的正文', raw: { author: '作者', edited: true }, updatedAt: '2026-09-08T00:01:00Z' }, { ingestion: 'live' }).changed, true); assert.equal(versions(), 4); assert.equal(changes(), 4); assert.ok(s.getRecord(id).versions.every(version => version.title === original.title)); const added = s.upsertRecord({ ...renamed, externalId: 'new-message' }); assert.equal(s.getRecord(added.id).title, renamed.title); } finally { s.close(); } }); test('标题保留规则不影响其他来源消息或聊天日历记录的正常标题变更', () => { const s = createStore(':memory:'); try { for (const [source, kind] of [['browser', 'message'], ['graph', 'message'], ['web-api', 'chat'], ['web-api', 'event']]) { const base = { ...record, source, kind, externalId: `${source}-${kind}`, title: '原名称' }; const { id } = s.upsertRecord(base); assert.equal(s.upsertRecord({ ...base, title: '新名称' }).changed, true); assert.equal(s.getRecord(id).title, '新名称'); assert.equal(s.getRecord(id).versions.length, 2); } } finally { s.close(); } });