import test from 'node:test'; import assert from 'node:assert/strict'; import { JSDOM } from 'jsdom'; import { createChatCrawler } from '../extension/chat-crawler.js'; const enabled = { enabled: true, assigned: true, accountId: 'work', dwellSeconds: 4, intervalSeconds: 30, maxChats: 50, listScrollPasses: 8, historyScrollPasses: 0 }; function fixture({ chats = ['a', 'b'], onClick, deliver, wait: injectedWait, html } = {}) { const dom = new JSDOM(html || '

Home

Original message
', { url: 'https://teams.cloud.microsoft/' }); const { document } = dom.window; const list = document.querySelector('[data-tid="chat-list"]'), pane = document.querySelector('[role="log"]'), title = document.querySelector('[data-tid="chat-header-title"]'); const captures = [], clicks = [], reports = [], events = [], interaction = new Map(); let clock = Date.parse('2026-09-08T00:00:00Z'), crawler; const originalAdd = document.addEventListener.bind(document), originalRemove = document.removeEventListener.bind(document); document.addEventListener = (type, listener, ...rest) => { if (type === 'pointerdown' || type === 'keydown') interaction.set(type, listener); originalAdd(type, listener, ...rest); }; document.removeEventListener = (type, listener, ...rest) => { if (interaction.get(type) === listener) interaction.delete(type); originalRemove(type, listener, ...rest); }; const schedule = (ms, callback) => events.push({ at: clock + ms, callback }); function advance(ms) { clock += ms; for (const event of [...events]) if (event.at <= clock) { events.splice(events.indexOf(event), 1); event.callback(); } } function messages(chat, ids = [`${chat}-message`]) { pane.replaceChildren(...ids.map(id => { const article = document.createElement('article'); article.setAttribute('data-message-id', id); const body = document.createElement('div'); body.setAttribute('data-tid', 'message-body'); body.textContent = `Message ${id}`; article.append(body); return article; })); } function render(ids = chats, label = id => `Chat ${id}`) { list.replaceChildren(...ids.map(id => { const row = document.createElement('div'); row.setAttribute('data-tid', 'chat-list-item'); row.setAttribute('data-chat-id', id); row.setAttribute('role', 'treeitem'); const name = document.createElement('span'); name.setAttribute('data-tid', 'chat-list-item-title'); name.textContent = label(id); row.append(name); row.addEventListener('click', () => { assert.equal(row.isConnected, true, 'must activate the current live row'); for (const other of list.querySelectorAll('[aria-selected]')) other.removeAttribute('aria-selected'); row.setAttribute('aria-selected', 'true'); title.textContent = label(id); clicks.push({ id, at: clock, row }); assert.equal(crawler.isNavigating(), true); assert.equal(crawler.captureContext(), null); if (onClick) onClick(id, { row, schedule, messages, pane, title, document, crawler }); else schedule(500, () => messages(id)); }); return row; })); } if (list && pane && title) render(); crawler = createChatCrawler({ window: dom.window, document, now: () => clock, wait: injectedWait || (async ms => { advance(ms); }), report: status => reports.push(status), capture: async () => { assert.equal(crawler.isNavigating(), false, 'never deliver while switching or scrolling'); const context = crawler.captureContext(); const record = { title: title?.textContent, ids: [...document.querySelectorAll('[data-message-id]')].map(node => node.getAttribute('data-message-id')), at: clock, context: context ? { id: context.id, title: context.title } : null, captureRoot: context?.root || null }; captures.push(record); return deliver ? deliver(record, captures.length) : { ok: true, pending: 0, records: record.ids.length }; } }); crawler.configure(enabled); return { crawler, window: dom.window, document, list, pane, title, captures, clicks, reports, interaction, render, messages, schedule, advance, now: () => clock, close: () => { crawler.dispose(); dom.window.close(); } }; } function scrollable(node, { height = 600, viewport = 200, initial = 0, onScroll = () => {} } = {}) { let top = initial; Object.defineProperties(node, { scrollHeight: { configurable: true, get: () => height }, clientHeight: { configurable: true, get: () => viewport }, scrollTop: { configurable: true, get: () => top, set: value => { top = value; onScroll(value); } } }); } test('automatically visits chats only after replacement messages settle for the dwell interval', async () => { const f = fixture(); try { await f.crawler.tick(); assert.deepEqual(f.clicks.map(click => click.id), ['a', 'b']); assert.equal(f.crawler.status().visited, 2); assert.equal(f.crawler.status().phase, 'waiting'); for (const click of f.clicks) { const capture = f.captures.find(item => item.title === `Chat ${click.id}`); assert.deepEqual(capture.ids, [`${click.id}-message`]); assert.ok(capture.at - click.at >= 4500, 'replacement delay plus full stable dwell'); assert.deepEqual(capture.context, { id: click.id, title: `Chat ${click.id}` }); } assert.match(f.crawler.status().coverage, /不保证完整历史/); const count = f.clicks.length; await f.crawler.tick(); assert.equal(f.clicks.length, count, 'must respect completion-based interval'); f.advance(30000); await f.crawler.tick(); assert.equal(f.crawler.status().pass, 2); } finally { f.close(); } }); test('selected row and pane scope changes cannot cause old messages to be captured under a new title', async () => { const f = fixture({ onClick: (id, { pane }) => { pane.setAttribute('data-chat-id', id); } }); try { await f.crawler.tick(); assert.deepEqual(f.clicks.map(click => click.id), ['a']); assert.ok(f.captures.every(item => item.title === 'Home')); assert.equal(f.crawler.status().phase, 'error'); assert.match(f.crawler.status().error, /上一聊天内容/); f.advance(60000); f.crawler.configure(enabled); await f.crawler.tick(); assert.equal(f.clicks.length, 1, 'unchanged heartbeat configuration must not resume an error'); } finally { f.close(); } }); test('a mixture of new and stale message nodes is not accepted as a completed transition', async () => { const f = fixture({ chats: ['a'], onClick: (id, { pane, document, schedule, messages }) => { const newMessage = document.createElement('article'); newMessage.setAttribute('data-message-id', 'a-message'); newMessage.textContent = 'New message'; pane.append(newMessage); schedule(5000, () => messages(id)); } }); try { await f.crawler.tick(); const current = f.captures.find(item => item.title === 'Chat a'); assert.ok(current.at - f.clicks[0].at >= 9000); assert.deepEqual(current.ids, ['a-message']); } finally { f.close(); } }); test('changes to stale message text with the same message ID do not satisfy transition evidence', async () => { const f = fixture({ chats: ['a'], onClick: (id, { pane }) => { pane.querySelector('[data-tid="message-body"]').textContent = 'Edited old message'; } }); try { await f.crawler.tick(); assert.equal(f.crawler.status().phase, 'error'); assert.ok(f.captures.every(item => item.title === 'Home')); } finally { f.close(); } }); test('failed delivery after capture prevents the next chat and requires explicit resume', async () => { let failing = true; const f = fixture({ deliver: record => ({ ok: !(failing && record.title === 'Chat a'), pending: failing && record.title === 'Chat a' ? 1 : 0, records: 1 }) }); try { await f.crawler.tick(); assert.deepEqual(f.clicks.map(click => click.id), ['a']); assert.match(f.crawler.status().error, /本地数据交付失败/); f.advance(60000); await f.crawler.tick(); assert.equal(f.clicks.length, 1); failing = false; f.crawler.resume(); await f.crawler.tick(); assert.equal(f.crawler.status().pass, 2, 'explicit reconnect starts a new pass'); assert.equal(f.crawler.status().phase, 'waiting'); assert.deepEqual(f.clicks.map(click => click.id), ['a', 'b', 'a']); } finally { f.close(); } }); test('bounded queue draining completes before clicking and pauses when pending never decreases', async () => { const f = fixture({ deliver: () => ({ ok: true, pending: 3, records: 1 }) }); try { await f.crawler.tick(); assert.equal(f.captures.length, 5); assert.equal(f.clicks.length, 0); assert.match(f.crawler.status().error, /队列未能排空/); } finally { f.close(); } let pending = 2; const g = fixture({ chats: ['a'], deliver: () => ({ ok: true, pending: Math.max(0, pending--), records: 1 }) }); try { await g.crawler.tick(); assert.equal(g.captures.filter(item => item.title === 'Home').length, 3); assert.equal(g.clicks.length, 1); } finally { g.close(); } }); test('virtualized chat rows are rediscovered by identity and never clicked through stale DOM references', async () => { const f = fixture({ chats: ['a', 'b', 'c', 'd'] }); const detached = [...f.list.children]; try { const pages = [['a', 'b'], ['c', 'd']]; f.render(pages[0]); scrollable(f.list, { height: 400, onScroll: top => f.render(pages[top >= 200 ? 1 : 0]) }); f.crawler.configure({ ...enabled, listScrollPasses: 1 }); await f.crawler.tick(); assert.deepEqual(f.clicks.map(click => click.id), ['a', 'b', 'c', 'd']); assert.ok(f.clicks.every(click => !detached.includes(click.row))); assert.equal(f.crawler.status().visited, 4); } finally { f.close(); } }); test('chat cap and identified history scrolling are bounded and do not scroll the document', async () => { const f = fixture({ chats: ['a', 'b', 'c'] }); let historyScrolls = 0; try { scrollable(f.pane, { height: 1200, viewport: 200, initial: 1000, onScroll: () => { historyScrolls++; f.messages('a', [`history-${historyScrolls}`]); } }); f.window.scrollTo = () => { throw new Error('must never scroll entire page'); }; f.crawler.configure({ ...enabled, maxChats: 1, historyScrollPasses: 2 }); await f.crawler.tick(); assert.deepEqual(f.clicks.map(click => click.id), ['a']); assert.equal(historyScrolls, 2); assert.equal(f.crawler.status().visited, 1); assert.match(f.crawler.status().coverage, /最多 1 个聊天/); assert.ok(f.captures.some(item => item.ids.includes('history-1'))); assert.ok(f.captures.some(item => item.ids.includes('history-2'))); assert.ok(f.captures.filter(item => item.ids[0]?.startsWith('history-')).every(item => item.context.id === 'a')); } finally { f.close(); } }); test('unchanged configure and concurrent ticks do not duplicate a pass; stop cancels a suspended wait immediately', async () => { let waitingResolve; const f = fixture({ wait: () => new Promise(resolve => { waitingResolve = resolve; }) }); try { const pass = f.crawler.tick(); while (!waitingResolve) await new Promise(resolve => setImmediate(resolve)); f.crawler.configure(enabled); await f.crawler.tick(); assert.equal(f.crawler.status().pass, 1); assert.equal(f.crawler.isNavigating(), true); f.crawler.stop('用户暂停'); await pass; assert.equal(f.crawler.status().phase, 'paused'); assert.equal(f.crawler.isNavigating(), false); assert.equal(f.crawler.captureContext(), null); assert.deepEqual(f.clicks.map(click => click.id), ['a']); waitingResolve(); await f.crawler.tick(); assert.equal(f.clicks.length, 1); } finally { f.close(); } }); test('identity/config changes cancel old work without starting overlapping captures', async () => { let release; const f = fixture({ deliver: () => new Promise(resolve => { release = resolve; }) }); try { const pass = f.crawler.tick(); while (!release) await new Promise(resolve => setImmediate(resolve)); f.crawler.configure({ ...enabled, accountId: 'another' }); await f.crawler.tick(); await pass; assert.equal(f.clicks.length, 0); assert.equal(f.captures.length, 1); assert.equal(f.crawler.status().phase, 'idle'); release({ ok: true, pending: 0, records: 0 }); } finally { f.close(); } }); test('trusted input pauses the collector; synthetic clicks and events do not, and disposal removes listeners', async () => { const f = fixture({ chats: ['a'] }); try { f.document.dispatchEvent(new f.window.Event('pointerdown', { bubbles: true })); await f.crawler.tick(); assert.equal(f.crawler.status().visited, 1); f.interaction.get('keydown')({ isTrusted: true }); assert.equal(f.crawler.status().phase, 'paused'); f.advance(60000); f.crawler.configure(enabled); await f.crawler.tick(); assert.equal(f.crawler.status().pass, 1); f.crawler.dispose(); assert.equal(f.interaction.size, 0); } finally { f.close(); } }); test('crawler requires assignment and main enablement; preview is read-only and unsafe selectors never click', async () => { const f = fixture(); try { const original = f.document.body.innerHTML; assert.deepEqual(f.crawler.preview(), { count: 2, labels: ['Chat a', 'Chat b'], errors: [] }); const state = f.crawler.status(); assert.equal(f.crawler.preview({ chatItemSelector: '[data-chat-id="b"]' }).count, 1); assert.deepEqual(f.crawler.status(), state, 'unsaved selector preview must not configure or schedule the crawler'); assert.equal(f.crawler.preview().count, 2, 'unsaved selectors must not persist'); assert.equal(f.document.body.innerHTML, original); assert.equal(f.clicks.length, 0); assert.equal(f.captures.length, 0); for (const config of [{ ...enabled, assigned: false }, { ...enabled, enabled: false }]) { f.crawler.configure(config); await f.crawler.tick(); assert.equal(f.clicks.length, 0); } f.crawler.configure({ ...enabled, chatListSelector: 'body', chatItemSelector: '*' }); await f.crawler.tick(); assert.equal(f.clicks.length, 0); assert.equal(f.captures.length, 0); assert.match(f.crawler.status().error, /整页/); f.crawler.configure({ ...enabled, chatItemSelector: '[' }); assert.match(f.crawler.preview().errors.join(' '), /CSS 选择器无效/); await f.crawler.tick(); assert.match(f.crawler.status().error, /CSS 选择器无效/); } finally { f.close(); } }); test('same-name chats remain distinct by row identity; rows with names only and action buttons are skipped', async () => { const f = fixture(); try { f.render(['a', 'b'], () => 'Same name'); const namelessIdentity = f.document.createElement('div'); namelessIdentity.setAttribute('data-tid', 'chat-list-item'); namelessIdentity.textContent = 'Same name'; const action = f.document.createElement('button'); action.setAttribute('data-chat-id', 'danger'); action.textContent = 'Delete'; action.addEventListener('click', () => assert.fail('must never activate action button')); f.list.append(namelessIdentity, action); f.crawler.configure({ ...enabled, chatItemSelector: '[data-tid="chat-list-item"],button' }); const preview = f.crawler.preview(); assert.equal(preview.count, 2); assert.match(preview.errors.join(' '), /稳定聊天标识/); await f.crawler.tick(); const contexts = f.captures.filter(item => item.title === 'Same name').map(item => item.context?.id); assert.ok(contexts.includes('a')); assert.ok(contexts.includes('b')); assert.deepEqual(f.clicks.map(click => click.id), ['a', 'b']); } finally { f.close(); } }); test('custom message and list selectors are used for transition evidence and capture context', async () => { const f = fixture({ chats: ['a'], onClick: (id, { document, pane, schedule }) => { schedule(500, () => { const message = document.createElement('div'); message.className = 'custom-message'; message.id = `message-${id}`; message.textContent = 'A custom Teams message'; pane.replaceChildren(message); }); } }); try { f.pane.removeAttribute('role'); f.pane.className = 'custom-message-list'; f.crawler.configure({ ...enabled, messageListSelector: '.custom-message-list', messageSelector: '.custom-message' }); await f.crawler.tick(); assert.equal(f.crawler.status().visited, 1); assert.equal(f.crawler.status().phase, 'waiting'); assert.deepEqual(f.captures.find(record => record.title === 'Chat a').context, { id: 'a', title: 'Chat a' }); f.crawler.configure({ ...enabled, messageListSelector: '.custom-message-list', messageSelector: '[' }); await f.crawler.tick(); assert.match(f.crawler.status().error, /消息 CSS 选择器无效/); } finally { f.close(); } }); test('an unverified selected first chat is visited after another chat, so old content cannot be trusted on startup', async () => { const f = fixture(); try { f.list.firstElementChild.setAttribute('aria-selected', 'true'); f.title.textContent = 'Chat a'; // Header and selection changed, but old message DOM remains. await f.crawler.tick(); assert.deepEqual(f.clicks.map(click => click.id), ['b', 'a']); assert.equal(f.crawler.status().visited, 2); assert.ok(f.captures.filter(record => record.context).every(record => !record.ids.includes('old'))); } finally { f.close(); } }); test('resuming a selected single chat after a failed transition cannot bypass freshness checks', async () => { for (const relabelledPane of [false, true]) { const f = fixture({ chats: ['a'], onClick: (id, { pane }) => { if (relabelledPane) pane.setAttribute('data-chat-id', id); } }); try { await f.crawler.tick(); assert.equal(f.crawler.status().phase, 'error'); f.crawler.resume(); await f.crawler.tick(); assert.equal(f.crawler.status().phase, 'error'); assert.ok(f.captures.every(record => record.context === null)); assert.equal(f.crawler.status().visited, 0); } finally { f.close(); } } }); test('selected row cannot override conflicting or mixed explicit message conversation IDs', async () => { for (const mixed of [false, true]) { const f = fixture({ chats: ['a'], onClick: (id, { messages, pane, schedule }) => { schedule(500, () => { messages(id, mixed ? ['new-a', 'new-b'] : ['new-b']); pane.setAttribute('data-chat-id', mixed ? 'a' : 'b'); if (mixed) { pane.children[0].setAttribute('data-chat-id', 'a'); pane.children[1].setAttribute('data-chat-id', 'b'); } }); } }); try { await f.crawler.tick(); assert.equal(f.crawler.status().phase, 'error'); assert.ok(f.captures.every(record => record.context === null)); } finally { f.close(); } } }); test('capture context exposes only the verified message root and expires when that pane is replaced', async () => { const f = fixture({ chats: ['a'] }); try { await f.crawler.tick(); assert.equal(f.crawler.captureContext().root, f.pane); assert.ok(f.captures.filter(record => record.context).every(record => record.captureRoot === f.pane)); f.pane.replaceWith(f.pane.cloneNode(true)); assert.equal(f.crawler.captureContext(), null, 'same-looking replacement DOM must be reverified'); } finally { f.close(); } }); test('each pass returns a selected chat to its newest viewport before bounded history collection', async () => { const f = fixture({ chats: ['a'] }); let round = 1, historyScrolls = 0, bottomScrolls = 0; try { scrollable(f.pane, { height: 1200, viewport: 200, initial: 1000, onScroll: top => { if (top === 1000) { bottomScrolls++; f.messages('a', [`a-latest-${round}`]); } else { historyScrolls++; f.messages('a', [`a-history-${round}`]); } } }); f.crawler.configure({ ...enabled, historyScrollPasses: 1 }); await f.crawler.tick(); assert.equal(historyScrolls, 1); assert.equal(f.pane.scrollTop, 800); round = 2; f.advance(30000); await f.crawler.tick(); assert.equal(f.crawler.status().pass, 2); assert.equal(f.crawler.status().phase, 'waiting'); assert.equal(bottomScrolls, 1); assert.equal(historyScrolls, 2); assert.ok(f.captures.some(record => record.ids.includes('a-latest-2') && record.context?.id === 'a')); assert.ok(f.captures.some(record => record.ids.includes('a-history-2') && record.context?.id === 'a')); } finally { f.close(); } });