import test from 'node:test'; import assert from 'node:assert/strict'; import { createStore } from '../src/store.js'; import { createAiService, projectAiRecord } from '../src/ai-service.js'; function setup(t) { const store = createStore(':memory:'); t.after(() => store.close()); return { store, query: createAiService({ store }) }; } const message = (externalId, extra = {}) => ({ source: 'web-api', accountId: 'account-a', kind: 'message', externalId, parentId: 'chat-a', title: '项目讨论', text: '部署计划', occurredAt: '2026-09-08T08:00:00Z', raw: { author: '测试用户', token: 'credential-never-return', headers: { Authorization: 'never' } }, ...extra }); test('AI search handles Chinese and literal SQL wildcard characters with account and time filters', t => { const { store, query } = setup(t); store.upsertRecord(message('1', { text: '部署完成率 50%_x\\y' })); store.upsertRecord(message('2', { text: '部署完成率 50AAxAy' })); store.upsertRecord(message('3', { accountId: 'other', text: '部署完成率 50%_x\\y' })); const found = query.searchMessages({ q: '50%_x\\y', accountId: 'account-a', from: '2026-09-08T16:00:00+08:00', to: '2026-09-08T17:00:00+08:00' }); assert.equal(found.items.length, 1); assert.equal(found.items[0].externalId, '1'); assert.equal(query.searchMessages({ q: "' OR 1=1 --" }).items.length, 0); assert.equal(query.searchMessages({ q: '部署' }).items.length, 3); assert.throws(() => query.searchMessages({ q: '部署', from: '2026-09-09T00:00:00Z', to: '2026-09-08T00:00:00Z' })); }); test('AI cursor pages tied timestamps without duplicates and binds to the query filters', t => { const { store, query } = setup(t); for (let i = 0; i < 5; i++) store.upsertRecord(message(`m${i}`)); const first = query.searchMessages({ q: '部署', limit: 2 }); const second = query.searchMessages({ q: '部署', limit: 2, cursor: first.nextCursor }); const third = query.searchMessages({ q: '部署', limit: 2, cursor: second.nextCursor }); assert.equal(new Set([...first.items, ...second.items, ...third.items].map(row => row.id)).size, 5); assert.equal(third.hasMore, false); assert.equal(third.nextCursor, null); assert.throws(() => query.searchMessages({ q: 'different', cursor: first.nextCursor })); assert.throws(() => query.searchMessages({ q: '部署', cursor: 'bad!cursor' })); }); test('AI chat inventory includes conversations discovered only through message history', t => { const { store, query } = setup(t); store.upsertRecord({ source: 'web-api', accountId: 'account-a', kind: 'chat', externalId: 'chat-a', title: '项目讨论', raw: { isOneOnOne: true } }); store.upsertRecord(message('1')); store.upsertRecord(message('2', { parentId: 'history-only', title: '历史会话' })); store.upsertRecord(message('3', { parentId: 'history-only', title: '历史会话' })); const chats = query.listChats({ limit: 10 }).items; assert.equal(chats.length, 2); const fallback = chats.find(row => row.chatId === 'history-only'); assert.equal(fallback.messageCount, 2); assert.equal(fallback.discoveredFromMessages, true); assert.equal(fallback.title, '未命名会话'); assert.equal(fallback.chatTitle, null); assert.equal(chats.find(row => row.chatId === 'chat-a').isDirect, true); assert.equal(query.listChats({ q: '历史' }).items.length, 0); }); test('AI context is chronologically ordered and cannot use an anchor from another chat', t => { const { store, query } = setup(t); const ids = []; for (let i = 0; i < 5; i++) ids.push(store.upsertRecord(message(`m${i}`, { occurredAt: `2026-09-08T08:0${i}:00Z` })).id); const result = query.getChatContext({ chatId: 'chat-a', aroundMessageId: ids[2], before: 1, after: 1 }); assert.deepEqual(result.items.map(row => row.id), ids.slice(1, 4)); assert.equal(result.hasMoreBefore, true); assert.equal(result.hasMoreAfter, true); assert.deepEqual(query.getChatContext({ chatId: 'other-chat', aroundMessageId: ids[2] }).items, []); assert.deepEqual(query.getChatContext({ chatId: 'chat-a', before: 2, after: 0 }).items.map(row => row.id), ids.slice(-2)); }); test('AI detail bounds history and redacts raw credentials and non-navigation URL queries', t => { const { store, query } = setup(t); const id = store.upsertRecord(message('m', { webUrl: 'https://teams.microsoft.com/l/message/chat/id?access_token=credential-never-return&messageId=4', text: 'a'.repeat(21000) })).id; store.upsertRecord(message('m', { text: 'changed' })); const result = query.getMessage({ id, includeVersions: true, versionLimit: 1 }); assert.equal(result.versions.length, 1); assert.equal(result.hasMoreVersions, true); assert.equal(result.message.author, '测试用户'); assert.equal(JSON.stringify(result).includes('credential-never-return'), false); assert.equal('raw' in result.message, false); const old = query.getMessage({ id, includeVersions: true, versionLimit: 2 }).versions[1].message; assert.equal(old.text.length, 20000); assert.equal(old.textTruncated, true); assert.equal(old.webUrl.includes('access_token'), false); assert.equal(query.getMessage({ id: 999 }).found, false); }); test('AI calendar time range filters resolved event starts and projects end time only', t => { const { store, query } = setup(t); store.upsertRecord({ ...message('meeting'), kind: 'event', title: '会议', occurredAt: '2026-09-08T10:00:00+08:00', raw: { start: { dateTime: '2026-09-08T10:00:00+08:00' }, end: { dateTime: '2026-09-08T11:00:00+08:00' }, secret: 'hidden' } }); assert.equal(query.listCalendarEvents({ from: '2026-09-08T02:00:00Z', to: '2026-09-08T03:00:00Z' }).items.length, 1); assert.equal(query.listCalendarEvents({ from: '2026-09-08T03:00:00Z' }).items.length, 0); assert.equal(JSON.stringify(query.listCalendarEvents()).includes('hidden'), false); }); test('AI changes initialize at latest, retain immutable snapshots and distinguish history backfill', t => { const { store, query } = setup(t); store.upsertRecord(message('old'), { ingestion: 'history' }); const baseline = query.pollChanges(); assert.equal(baseline.items.length, 0); assert.equal(baseline.initializedAtLatest, true); store.upsertRecord(message('new'), { ingestion: 'live' }); store.upsertRecord(message('new', { text: '修订后的部署计划' }), { ingestion: 'live' }); const first = query.pollChanges({ cursor: baseline.nextCursor, limit: 1 }); assert.equal(first.items.length, 1); assert.equal(first.items[0].action, 'created'); assert.equal(first.items[0].record.text, '部署计划'); const second = query.pollChanges({ cursor: first.nextCursor, limit: 1 }); assert.equal(second.items[0].action, 'updated'); assert.equal(second.hasMore, false); const all = query.pollChanges({ cursor: 0 }); assert.equal(all.items.length, 3); assert.equal(all.items[0].ingestion, 'history'); assert.equal(JSON.stringify(all).includes('credential-never-return'), false); }); test('AI persisted status does not claim a running worker or expose stored session URLs', t => { const { store, query } = setup(t); store.setState('web-api:service', { enabled: true, secret: 'never-return' }); store.setState('web-api:status', { at: '2026-09-08T00:00:00Z', ok: true, requests: 5, secret: 'never-return', coverage: { messages: 2, cursor: 'never-return' } }); const result = query.getCollectorStatus(); assert.equal(result.running, null); assert.equal(result.liveServiceAvailable, false); assert.equal(result.lastSync.requests, 5); assert.equal(JSON.stringify(result).includes('never-return'), false); const live = createAiService({ store, network: { status: () => ({ running: true, history: { pacing: { minDelayMs: 2000, maxDelayMs: 5000, waiting: false, coolingDownOrigins: 1, nextAllowedAt: '2026-09-08T01:00:00Z', origin: 'never-return', rawHeaders: 'never-return', } } }) } }).getCollectorStatus(); assert.equal(live.history.pacing.coolingDownOrigins, 1); assert.equal(live.history.pacing.maxDelayMs, 5000); assert.equal(JSON.stringify(live).includes('never-return'), false); }); test('AI message evidence uses structured identities and only a chat in the same account', t => { const { store, query } = setup(t); const self = '11111111-1111-1111-1111-111111111111'; const author = '22222222-2222-2222-2222-222222222222'; store.upsertRecord({ source: 'web-api', accountId: 'other', kind: 'chat', externalId: 'chat-a', title: '私聊', raw: { isOneOnOne: true } }); const id = store.upsertRecord(message('signals', { raw: { selfUserId: self, senderId: author, mentions: [{ type: 'user', id: self }] } })).id; const missingChat = query.getMessage({ id }).message; assert.equal(missingChat.mentionsSelf, true); assert.equal(missingChat.isFromSelf, false); assert.equal(missingChat.isDirect, null); store.upsertRecord({ source: 'web-api', accountId: 'account-a', kind: 'chat', externalId: 'chat-a', title: '私聊', raw: { isOneOnOne: true } }); assert.equal(query.getMessage({ id }).message.isDirect, true); }); test('AI context disambiguates shared chat IDs and binds anchored neighbors to the exact account/source', t => { const { store, query } = setup(t); const first = store.upsertRecord(message('a1', { occurredAt: '2026-09-08T08:01:00Z' })).id; const anchor = store.upsertRecord(message('a2', { occurredAt: '2026-09-08T08:02:00Z' })).id; const last = store.upsertRecord(message('a3', { occurredAt: '2026-09-08T08:03:00Z' })).id; store.upsertRecord(message('b1', { accountId: 'account-b', occurredAt: '2026-09-08T08:01:30Z' })); store.upsertRecord(message('b2', { accountId: 'account-b', occurredAt: '2026-09-08T08:02:30Z' })); store.upsertRecord(message('browser', { source: 'browser', occurredAt: '2026-09-08T08:02:40Z' })); const ambiguous = query.getChatContext({ chatId: 'chat-a' }); assert.equal(ambiguous.ambiguous, true); assert.deepEqual(ambiguous.items, []); assert.equal(query.getChatContext({ chatId: 'chat-a', accountId: 'account-a' }).ambiguous, true); const anchored = query.getChatContext({ chatId: 'chat-a', aroundMessageId: anchor, before: 10, after: 10 }); assert.deepEqual(anchored.items.map(row => row.id), [first, anchor, last]); assert.equal(anchored.hasMoreBefore, false); assert.equal(anchored.hasMoreAfter, false); const scoped = query.getChatContext({ chatId: 'chat-a', source: 'web-api', accountId: 'account-a' }); assert.deepEqual(scoped.items.map(row => row.id), [first, anchor, last]); assert.equal(query.getChatContext({ chatId: 'chat-a', aroundMessageId: anchor, accountId: 'account-b' }).found, false); }); test('AI citation URLs drop fragments and non-navigation parameters and reject API/auth routes', () => { const good = projectAiRecord(message('url', { webUrl: 'https://teams.microsoft.com/l/message/chat/42?messageId=42&tenantId=11111111-1111-1111-1111-111111111111&context=hidden&access_token=hidden#id_token=hidden' })); const url = new URL(good.webUrl); assert.equal(url.hash, ''); assert.equal(url.searchParams.get('messageId'), '42'); assert.equal(url.searchParams.get('tenantId'), '11111111-1111-1111-1111-111111111111'); assert.equal(good.webUrl.includes('hidden'), false); assert.equal(projectAiRecord(message('url', { webUrl: 'https://teams.microsoft.com/l/message/chat/42?messageId=not-a-message-id&tenantId=not-a-tenant' })).webUrl, 'https://teams.microsoft.com/l/message/chat/42'); for (const webUrl of [ 'https://teams.microsoft.com/api/auth/credential', 'https://teams.cloud.microsoft/oauth/callback#token=hidden', 'https://outlook.office.com/owa/service.svc?secret=hidden', 'https://teams.microsoft.com:8443/l/message/chat/42', 'https://user:password@teams.microsoft.com/l/message/chat/42' ]) assert.equal(projectAiRecord(message('url', { webUrl })).webUrl, null); }); test('AI current display uses the real same-scope chat name while saved version and change snapshots keep their original titles', t => { const { store, query } = setup(t); const saved = message('legacy', { title: '聊天', raw: { author: '示例作者' } }); const id = store.upsertRecord(saved).id; store.upsertRecord({ source: saved.source, accountId: saved.accountId, kind: 'chat', externalId: saved.parentId, title: '修复后的会话名', raw: { titleSource: 'members' } }); const before = store.getRecordByIdentity(saved), versionCount = store.stats().versions; const detail = query.getMessage({ id, includeVersions: true }); assert.equal(detail.message.title, '修复后的会话名'); assert.equal(detail.message.chatTitle, '修复后的会话名'); assert.equal(detail.message.author, '示例作者'); assert.equal(detail.versions[0].message.title, '聊天'); assert.equal(detail.versions[0].message.chatTitle, null); const change = query.pollChanges({ cursor: 0, kinds: ['message'] }).items[0]; assert.equal(change.record.title, '聊天'); assert.equal(change.record.chatTitle, null); assert.equal(store.getRecordByIdentity(saved).hash, before.hash); assert.equal(store.stats().versions, versionCount); }); test('AI searches allowlisted authors and real chat names with stable pagination and no cross-scope leakage', t => { const { store, query } = setup(t); store.upsertRecord(message('other', { title: '聊天', raw: { author: '作者%_\\昵称', privateValue: '不可见检索值' } })); store.upsertRecord(message('self', { title: '聊天', raw: { author: '本人' } })); store.upsertRecord(message('different-account', { title: '聊天', accountId: 'another', raw: { author: '另一个作者' } })); store.upsertRecord(message('different-source', { title: '聊天', source: 'browser', raw: { author: '另一个作者' } })); store.upsertRecord({ source: 'web-api', accountId: 'account-a', kind: 'chat', externalId: 'chat-a', title: '对方的聊天名称' }); assert.equal(query.searchMessages({ q: '作者%_\\昵称' }).items.length, 1); const first = query.searchMessages({ q: '对方的聊天名称', limit: 1 }); const second = query.searchMessages({ q: '对方的聊天名称', limit: 1, cursor: first.nextCursor }); assert.equal(first.items.length, 1); assert.equal(second.items.length, 1); assert.equal(second.hasMore, false); assert.deepEqual(new Set([...first.items, ...second.items].map(row => row.externalId)), new Set(['other', 'self'])); assert.equal(query.searchMessages({ q: '不可见检索值' }).items.length, 0); assert.throws(() => query.searchMessages({ q: 'another query', cursor: first.nextCursor })); }); test('AI preserves an explicit generic-looking chat name and keeps unknown senders separate from chat identity', t => { const { store, query } = setup(t); const id = store.upsertRecord(message('author-only', { title: '作者名字', raw: { author: '作者名字' } })).id; const unknown = query.getMessage({ id }).message; assert.equal(unknown.title, '聊天消息'); assert.equal(unknown.author, '作者名字'); assert.equal(unknown.chatTitle, null); store.upsertRecord({ source: 'web-api', accountId: 'account-a', kind: 'chat', externalId: 'chat-a', title: '聊天', raw: { titleSource: 'explicit' } }); const known = query.getMessage({ id }).message; assert.equal(known.title, '聊天'); assert.equal(known.chatTitle, '聊天'); assert.equal(known.author, '作者名字'); assert.equal(query.listChats().items[0].title, '聊天'); }); test('AI supports Graph sender display names without searching arbitrary raw payloads', t => { const { store, query } = setup(t); store.upsertRecord(message('graph-user', { source: 'graph', title: '聊天消息', raw: { from: { user: { displayName: '示例Graph用户' } } } })); store.upsertRecord(message('graph-app', { source: 'graph', title: '聊天消息', raw: { from: { application: { displayName: '示例Graph应用' } } } })); assert.equal(query.searchMessages({ q: '示例Graph用户' }).items[0].author, '示例Graph用户'); assert.equal(query.searchMessages({ q: '示例Graph应用' }).items[0].author, '示例Graph应用'); }); test('AI instance searches bind both source and account and keep pagination filters fixed', t => { const { store, query } = setup(t); store.createInstance({ id: 'default', name: '工作实例' }); const other = store.createInstance({ name: '第二实例' }); const empty = store.createInstance({ name: '尚未登录' }); store.bindInstanceAccounts('default', [{ source: 'web-api', accountId: 'account-a' }]); store.bindInstanceAccounts(other.id, [{ source: 'browser', accountId: 'account-a' }, { source: 'web-api', accountId: 'account-b' }]); const firstId = store.upsertRecord(message('one')).id; const secondId = store.upsertRecord(message('two')).id; store.upsertRecord(message('other-source', { source: 'browser' })); store.upsertRecord(message('other-account', { accountId: 'account-b' })); store.upsertRecord(message('unbound', { accountId: 'unbound' })); const filters = { instanceId: 'default', from: '2026-09-08T08:00:00Z', to: '2026-09-08T09:00:00Z', limit: 1 }; const first = query.searchMessages(filters); const second = query.searchMessages({ ...filters, cursor: first.nextCursor }); assert.deepEqual(new Set([...first.items, ...second.items].map(row => row.id)), new Set([firstId, secondId])); assert.equal(first.items[0].instanceId, 'default'); assert.equal(first.items[0].instanceName, '工作实例'); assert.equal(second.hasMore, false); assert.throws(() => query.searchMessages({ ...filters, instanceId: other.id, cursor: first.nextCursor }), /Cursor/); assert.throws(() => query.searchMessages({ ...filters, from: '2026-09-08T07:00:00Z', cursor: first.nextCursor }), /Cursor/); assert.deepEqual(query.searchMessages({ instanceId: empty.id }).items, []); assert.deepEqual(query.searchMessages({ instanceId: 'default', accountId: 'account-b' }).items, []); assert.equal(query.searchMessages({ instanceId: other.id }).items.length, 2); assert.throws(() => query.searchMessages({ instanceId: '99999999-9999-4999-8999-999999999999' }), /Unknown instance/); assert.equal(query.searchMessages({ accountId: 'unbound' }).items[0].instanceId, null); }); test('AI keyword-free time ranges resolve timezones with an inclusive start and exclusive end', t => { const { store, query } = setup(t); store.upsertRecord(message('before', { occurredAt: '2026-09-08T07:59:59Z' })); store.upsertRecord(message('start', { occurredAt: '2026-09-08T16:00:00+08:00' })); store.upsertRecord(message('middle', { occurredAt: '2026-09-08T08:30:00Z' })); store.upsertRecord(message('end', { occurredAt: '2026-09-08T09:00:00Z' })); store.upsertRecord(message('unknown-time', { occurredAt: null })); const found = query.searchMessages({ from: '2026-09-08T08:00:00Z', to: '2026-09-08T17:00:00+08:00' }); assert.deepEqual(found.items.map(row => row.externalId), ['middle', 'start']); assert.equal(query.searchMessages({ q: ' ', from: '2026-09-08T08:00:00Z' }).items.length, 3); for (const options of [{}, { q: ' ' }, { limit: 1 }]) assert.throws(() => query.searchMessages(options), /filter/); for (const from of ['2026-02-30T08:00:00Z', '2026-09-08T24:00:00Z', '2026-09-08T08:00:00', '2026-09-08T08:00:00+08:90', 'not a timestamp']) { assert.throws(() => query.searchMessages({ from }), /date/i); } assert.throws(() => query.searchMessages({ from: '2026-09-08T08:00:00Z', to: '2026-09-08T16:00:00+08:00' }), /range/); }); test('AI instance scope isolates real and discovered chats, anchored context and calendar events', t => { const { store, query } = setup(t); store.createInstance({ id: 'default', name: '实例一' }); const other = store.createInstance({ name: '实例二' }); store.bindInstanceAccounts('default', [{ source: 'web-api', accountId: 'account-a' }]); store.bindInstanceAccounts(other.id, [{ source: 'browser', accountId: 'account-a' }]); const scoped = store.upsertRecord(message('same-message')).id; const outside = store.upsertRecord(message('same-message', { source: 'browser' })).id; store.upsertRecord({ ...message('chat-a'), kind: 'chat', title: '本实例的会话' }); store.upsertRecord({ ...message('meeting'), kind: 'event' }); store.upsertRecord({ ...message('meeting'), source: 'browser', kind: 'event' }); const chats = query.listChats({ instanceId: 'default' }); assert.equal(chats.items.length, 1); assert.equal(chats.items[0].title, '本实例的会话'); const discovered = query.listChats({ instanceId: other.id }).items; assert.equal(discovered.length, 1); assert.equal(discovered[0].discoveredFromMessages, true); assert.equal(discovered[0].instanceId, other.id); assert.deepEqual(query.getChatContext({ chatId: 'chat-a', instanceId: 'default' }).items.map(row => row.id), [scoped]); assert.equal(query.getChatContext({ chatId: 'chat-a', instanceId: 'default', aroundMessageId: outside }).found, false); assert.equal(query.listCalendarEvents({ instanceId: 'default' }).items.length, 1); assert.equal(query.listCalendarEvents({ instanceId: other.id }).items[0].source, 'browser'); for (const method of ['listChats', 'getChatContext', 'listCalendarEvents']) { assert.throws(() => query[method]({ chatId: 'chat-a', instanceId: '99999999-9999-4999-8999-999999999999' }), /Unknown instance/); } }); test('AI lists persisted instance bindings and projects only safe per-instance runtime and presence fields', t => { const { store, query } = setup(t); store.createInstance({ id: 'default', name: '默认实例' }); const second = store.createInstance({ name: '第二实例', keepOnline: true }); store.bindInstanceAccounts(second.id, [{ source: 'web-api', accountId: 'account-b' }]); const persisted = query.listInstances().items; assert.equal(persisted.length, 2); assert.ok(persisted.every(row => row.running === null && row.sessionAvailable === null && row.presence === null && !row.liveServiceAvailable)); assert.deepEqual(persisted.find(row => row.id === second.id).accounts, [{ source: 'web-api', accountId: 'account-b' }]); const inspected = []; const live = createAiService({ store, network: { listInstances: () => [], status(id) { inspected.push(id); return { running: id === second.id, sessionAvailable: true, raw: 'never-return', login: { token: 'never-return' }, renewal: { state: 'renewed', available: true, interactionRequired: false, expiresAt: '2026-09-11T08:00:00Z', lastSuccessAt: 'never-return', refreshToken: 'never-return', message: 'never-return' }, presence: { state: 'running', enabled: true, running: true, configured: true, secret: 'never-return', lastCheckedAt: '2026-09-08T08:00:00Z', lastRenewedAt: 'never-return', nextRunAt: '2026-09-08T08:01:00Z', currentPresence: { availability: 'Available', activity: 'never-return', token: 'never-return' } } }; }, } }).listInstances(); assert.deepEqual(new Set(inspected), new Set(['default', second.id])); assert.equal(live.items.find(row => row.id === second.id).running, true); assert.equal(live.items.find(row => row.id === 'default').running, false); assert.equal(live.items[0].presence.currentPresence.availability, 'Available'); assert.equal(live.items[0].presence.currentPresence.activity, 'unknown'); assert.equal(live.items[0].presence.lastRenewedAt, null); assert.equal(live.items[0].renewal.state, 'renewed'); assert.equal(live.items[0].renewal.lastSuccessAt, null); assert.equal(live.items[0].renewal.expiresAt, '2026-09-11T08:00:00.000Z'); assert.equal(JSON.stringify(live).includes('never-return'), false); });