chat-crawler.test.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. import test from 'node:test';
  2. import assert from 'node:assert/strict';
  3. import { JSDOM } from 'jsdom';
  4. import { createChatCrawler } from '../extension/chat-crawler.js';
  5. const enabled = { enabled: true, assigned: true, accountId: 'work', dwellSeconds: 4, intervalSeconds: 30, maxChats: 50, listScrollPasses: 8, historyScrollPasses: 0 };
  6. function fixture({ chats = ['a', 'b'], onClick, deliver, wait: injectedWait, html } = {}) {
  7. const dom = new JSDOM(html || '<div data-tid="chat-list"></div><h1 data-tid="chat-header-title">Home</h1><div role="log"><article data-message-id="old"><div data-tid="message-body">Original message</div></article></div>', { url: 'https://teams.cloud.microsoft/' });
  8. const { document } = dom.window;
  9. const list = document.querySelector('[data-tid="chat-list"]'), pane = document.querySelector('[role="log"]'), title = document.querySelector('[data-tid="chat-header-title"]');
  10. const captures = [], clicks = [], reports = [], events = [], interaction = new Map();
  11. let clock = Date.parse('2026-09-08T00:00:00Z'), crawler;
  12. const originalAdd = document.addEventListener.bind(document), originalRemove = document.removeEventListener.bind(document);
  13. document.addEventListener = (type, listener, ...rest) => { if (type === 'pointerdown' || type === 'keydown') interaction.set(type, listener); originalAdd(type, listener, ...rest); };
  14. document.removeEventListener = (type, listener, ...rest) => { if (interaction.get(type) === listener) interaction.delete(type); originalRemove(type, listener, ...rest); };
  15. const schedule = (ms, callback) => events.push({ at: clock + ms, callback });
  16. function advance(ms) {
  17. clock += ms;
  18. for (const event of [...events]) if (event.at <= clock) { events.splice(events.indexOf(event), 1); event.callback(); }
  19. }
  20. function messages(chat, ids = [`${chat}-message`]) {
  21. pane.replaceChildren(...ids.map(id => {
  22. const article = document.createElement('article');
  23. article.setAttribute('data-message-id', id);
  24. const body = document.createElement('div'); body.setAttribute('data-tid', 'message-body'); body.textContent = `Message ${id}`;
  25. article.append(body); return article;
  26. }));
  27. }
  28. function render(ids = chats, label = id => `Chat ${id}`) {
  29. list.replaceChildren(...ids.map(id => {
  30. const row = document.createElement('div'); row.setAttribute('data-tid', 'chat-list-item'); row.setAttribute('data-chat-id', id); row.setAttribute('role', 'treeitem');
  31. const name = document.createElement('span'); name.setAttribute('data-tid', 'chat-list-item-title'); name.textContent = label(id); row.append(name);
  32. row.addEventListener('click', () => {
  33. assert.equal(row.isConnected, true, 'must activate the current live row');
  34. for (const other of list.querySelectorAll('[aria-selected]')) other.removeAttribute('aria-selected');
  35. row.setAttribute('aria-selected', 'true');
  36. title.textContent = label(id);
  37. clicks.push({ id, at: clock, row });
  38. assert.equal(crawler.isNavigating(), true);
  39. assert.equal(crawler.captureContext(), null);
  40. if (onClick) onClick(id, { row, schedule, messages, pane, title, document, crawler });
  41. else schedule(500, () => messages(id));
  42. });
  43. return row;
  44. }));
  45. }
  46. if (list && pane && title) render();
  47. crawler = createChatCrawler({ window: dom.window, document, now: () => clock,
  48. wait: injectedWait || (async ms => { advance(ms); }),
  49. report: status => reports.push(status),
  50. capture: async () => {
  51. assert.equal(crawler.isNavigating(), false, 'never deliver while switching or scrolling');
  52. const context = crawler.captureContext();
  53. 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 };
  54. captures.push(record);
  55. return deliver ? deliver(record, captures.length) : { ok: true, pending: 0, records: record.ids.length };
  56. }
  57. });
  58. crawler.configure(enabled);
  59. 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(); } };
  60. }
  61. function scrollable(node, { height = 600, viewport = 200, initial = 0, onScroll = () => {} } = {}) {
  62. let top = initial;
  63. Object.defineProperties(node, {
  64. scrollHeight: { configurable: true, get: () => height }, clientHeight: { configurable: true, get: () => viewport },
  65. scrollTop: { configurable: true, get: () => top, set: value => { top = value; onScroll(value); } }
  66. });
  67. }
  68. test('automatically visits chats only after replacement messages settle for the dwell interval', async () => {
  69. const f = fixture();
  70. try {
  71. await f.crawler.tick();
  72. assert.deepEqual(f.clicks.map(click => click.id), ['a', 'b']);
  73. assert.equal(f.crawler.status().visited, 2);
  74. assert.equal(f.crawler.status().phase, 'waiting');
  75. for (const click of f.clicks) {
  76. const capture = f.captures.find(item => item.title === `Chat ${click.id}`);
  77. assert.deepEqual(capture.ids, [`${click.id}-message`]);
  78. assert.ok(capture.at - click.at >= 4500, 'replacement delay plus full stable dwell');
  79. assert.deepEqual(capture.context, { id: click.id, title: `Chat ${click.id}` });
  80. }
  81. assert.match(f.crawler.status().coverage, /不保证完整历史/);
  82. const count = f.clicks.length;
  83. await f.crawler.tick(); assert.equal(f.clicks.length, count, 'must respect completion-based interval');
  84. f.advance(30000); await f.crawler.tick(); assert.equal(f.crawler.status().pass, 2);
  85. } finally { f.close(); }
  86. });
  87. test('selected row and pane scope changes cannot cause old messages to be captured under a new title', async () => {
  88. const f = fixture({ onClick: (id, { pane }) => { pane.setAttribute('data-chat-id', id); } });
  89. try {
  90. await f.crawler.tick();
  91. assert.deepEqual(f.clicks.map(click => click.id), ['a']);
  92. assert.ok(f.captures.every(item => item.title === 'Home'));
  93. assert.equal(f.crawler.status().phase, 'error');
  94. assert.match(f.crawler.status().error, /上一聊天内容/);
  95. f.advance(60000); f.crawler.configure(enabled); await f.crawler.tick();
  96. assert.equal(f.clicks.length, 1, 'unchanged heartbeat configuration must not resume an error');
  97. } finally { f.close(); }
  98. });
  99. test('a mixture of new and stale message nodes is not accepted as a completed transition', async () => {
  100. const f = fixture({ chats: ['a'], onClick: (id, { pane, document, schedule, messages }) => {
  101. const newMessage = document.createElement('article'); newMessage.setAttribute('data-message-id', 'a-message'); newMessage.textContent = 'New message'; pane.append(newMessage);
  102. schedule(5000, () => messages(id));
  103. } });
  104. try {
  105. await f.crawler.tick();
  106. const current = f.captures.find(item => item.title === 'Chat a');
  107. assert.ok(current.at - f.clicks[0].at >= 9000);
  108. assert.deepEqual(current.ids, ['a-message']);
  109. } finally { f.close(); }
  110. });
  111. test('changes to stale message text with the same message ID do not satisfy transition evidence', async () => {
  112. const f = fixture({ chats: ['a'], onClick: (id, { pane }) => { pane.querySelector('[data-tid="message-body"]').textContent = 'Edited old message'; } });
  113. try {
  114. await f.crawler.tick();
  115. assert.equal(f.crawler.status().phase, 'error');
  116. assert.ok(f.captures.every(item => item.title === 'Home'));
  117. } finally { f.close(); }
  118. });
  119. test('failed delivery after capture prevents the next chat and requires explicit resume', async () => {
  120. let failing = true;
  121. const f = fixture({ deliver: record => ({ ok: !(failing && record.title === 'Chat a'), pending: failing && record.title === 'Chat a' ? 1 : 0, records: 1 }) });
  122. try {
  123. await f.crawler.tick();
  124. assert.deepEqual(f.clicks.map(click => click.id), ['a']);
  125. assert.match(f.crawler.status().error, /本地数据交付失败/);
  126. f.advance(60000); await f.crawler.tick(); assert.equal(f.clicks.length, 1);
  127. failing = false;
  128. f.crawler.resume(); await f.crawler.tick();
  129. assert.equal(f.crawler.status().pass, 2, 'explicit reconnect starts a new pass');
  130. assert.equal(f.crawler.status().phase, 'waiting');
  131. assert.deepEqual(f.clicks.map(click => click.id), ['a', 'b', 'a']);
  132. } finally { f.close(); }
  133. });
  134. test('bounded queue draining completes before clicking and pauses when pending never decreases', async () => {
  135. const f = fixture({ deliver: () => ({ ok: true, pending: 3, records: 1 }) });
  136. try {
  137. await f.crawler.tick();
  138. assert.equal(f.captures.length, 5);
  139. assert.equal(f.clicks.length, 0);
  140. assert.match(f.crawler.status().error, /队列未能排空/);
  141. } finally { f.close(); }
  142. let pending = 2;
  143. const g = fixture({ chats: ['a'], deliver: () => ({ ok: true, pending: Math.max(0, pending--), records: 1 }) });
  144. try {
  145. await g.crawler.tick();
  146. assert.equal(g.captures.filter(item => item.title === 'Home').length, 3);
  147. assert.equal(g.clicks.length, 1);
  148. } finally { g.close(); }
  149. });
  150. test('virtualized chat rows are rediscovered by identity and never clicked through stale DOM references', async () => {
  151. const f = fixture({ chats: ['a', 'b', 'c', 'd'] });
  152. const detached = [...f.list.children];
  153. try {
  154. const pages = [['a', 'b'], ['c', 'd']];
  155. f.render(pages[0]);
  156. scrollable(f.list, { height: 400, onScroll: top => f.render(pages[top >= 200 ? 1 : 0]) });
  157. f.crawler.configure({ ...enabled, listScrollPasses: 1 });
  158. await f.crawler.tick();
  159. assert.deepEqual(f.clicks.map(click => click.id), ['a', 'b', 'c', 'd']);
  160. assert.ok(f.clicks.every(click => !detached.includes(click.row)));
  161. assert.equal(f.crawler.status().visited, 4);
  162. } finally { f.close(); }
  163. });
  164. test('chat cap and identified history scrolling are bounded and do not scroll the document', async () => {
  165. const f = fixture({ chats: ['a', 'b', 'c'] });
  166. let historyScrolls = 0;
  167. try {
  168. scrollable(f.pane, { height: 1200, viewport: 200, initial: 1000, onScroll: () => { historyScrolls++; f.messages('a', [`history-${historyScrolls}`]); } });
  169. f.window.scrollTo = () => { throw new Error('must never scroll entire page'); };
  170. f.crawler.configure({ ...enabled, maxChats: 1, historyScrollPasses: 2 });
  171. await f.crawler.tick();
  172. assert.deepEqual(f.clicks.map(click => click.id), ['a']);
  173. assert.equal(historyScrolls, 2);
  174. assert.equal(f.crawler.status().visited, 1);
  175. assert.match(f.crawler.status().coverage, /最多 1 个聊天/);
  176. assert.ok(f.captures.some(item => item.ids.includes('history-1')));
  177. assert.ok(f.captures.some(item => item.ids.includes('history-2')));
  178. assert.ok(f.captures.filter(item => item.ids[0]?.startsWith('history-')).every(item => item.context.id === 'a'));
  179. } finally { f.close(); }
  180. });
  181. test('unchanged configure and concurrent ticks do not duplicate a pass; stop cancels a suspended wait immediately', async () => {
  182. let waitingResolve;
  183. const f = fixture({ wait: () => new Promise(resolve => { waitingResolve = resolve; }) });
  184. try {
  185. const pass = f.crawler.tick();
  186. while (!waitingResolve) await new Promise(resolve => setImmediate(resolve));
  187. f.crawler.configure(enabled);
  188. await f.crawler.tick();
  189. assert.equal(f.crawler.status().pass, 1);
  190. assert.equal(f.crawler.isNavigating(), true);
  191. f.crawler.stop('用户暂停');
  192. await pass;
  193. assert.equal(f.crawler.status().phase, 'paused');
  194. assert.equal(f.crawler.isNavigating(), false);
  195. assert.equal(f.crawler.captureContext(), null);
  196. assert.deepEqual(f.clicks.map(click => click.id), ['a']);
  197. waitingResolve(); await f.crawler.tick(); assert.equal(f.clicks.length, 1);
  198. } finally { f.close(); }
  199. });
  200. test('identity/config changes cancel old work without starting overlapping captures', async () => {
  201. let release;
  202. const f = fixture({ deliver: () => new Promise(resolve => { release = resolve; }) });
  203. try {
  204. const pass = f.crawler.tick();
  205. while (!release) await new Promise(resolve => setImmediate(resolve));
  206. f.crawler.configure({ ...enabled, accountId: 'another' });
  207. await f.crawler.tick(); await pass;
  208. assert.equal(f.clicks.length, 0);
  209. assert.equal(f.captures.length, 1);
  210. assert.equal(f.crawler.status().phase, 'idle');
  211. release({ ok: true, pending: 0, records: 0 });
  212. } finally { f.close(); }
  213. });
  214. test('trusted input pauses the collector; synthetic clicks and events do not, and disposal removes listeners', async () => {
  215. const f = fixture({ chats: ['a'] });
  216. try {
  217. f.document.dispatchEvent(new f.window.Event('pointerdown', { bubbles: true }));
  218. await f.crawler.tick(); assert.equal(f.crawler.status().visited, 1);
  219. f.interaction.get('keydown')({ isTrusted: true });
  220. assert.equal(f.crawler.status().phase, 'paused');
  221. f.advance(60000); f.crawler.configure(enabled); await f.crawler.tick();
  222. assert.equal(f.crawler.status().pass, 1);
  223. f.crawler.dispose(); assert.equal(f.interaction.size, 0);
  224. } finally { f.close(); }
  225. });
  226. test('crawler requires assignment and main enablement; preview is read-only and unsafe selectors never click', async () => {
  227. const f = fixture();
  228. try {
  229. const original = f.document.body.innerHTML;
  230. assert.deepEqual(f.crawler.preview(), { count: 2, labels: ['Chat a', 'Chat b'], errors: [] });
  231. const state = f.crawler.status();
  232. assert.equal(f.crawler.preview({ chatItemSelector: '[data-chat-id="b"]' }).count, 1);
  233. assert.deepEqual(f.crawler.status(), state, 'unsaved selector preview must not configure or schedule the crawler');
  234. assert.equal(f.crawler.preview().count, 2, 'unsaved selectors must not persist');
  235. assert.equal(f.document.body.innerHTML, original); assert.equal(f.clicks.length, 0); assert.equal(f.captures.length, 0);
  236. for (const config of [{ ...enabled, assigned: false }, { ...enabled, enabled: false }]) {
  237. f.crawler.configure(config); await f.crawler.tick(); assert.equal(f.clicks.length, 0);
  238. }
  239. f.crawler.configure({ ...enabled, chatListSelector: 'body', chatItemSelector: '*' });
  240. await f.crawler.tick(); assert.equal(f.clicks.length, 0); assert.equal(f.captures.length, 0);
  241. assert.match(f.crawler.status().error, /整页/);
  242. f.crawler.configure({ ...enabled, chatItemSelector: '[' });
  243. assert.match(f.crawler.preview().errors.join(' '), /CSS 选择器无效/);
  244. await f.crawler.tick(); assert.match(f.crawler.status().error, /CSS 选择器无效/);
  245. } finally { f.close(); }
  246. });
  247. test('same-name chats remain distinct by row identity; rows with names only and action buttons are skipped', async () => {
  248. const f = fixture();
  249. try {
  250. f.render(['a', 'b'], () => 'Same name');
  251. const namelessIdentity = f.document.createElement('div'); namelessIdentity.setAttribute('data-tid', 'chat-list-item'); namelessIdentity.textContent = 'Same name';
  252. 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'));
  253. f.list.append(namelessIdentity, action);
  254. f.crawler.configure({ ...enabled, chatItemSelector: '[data-tid="chat-list-item"],button' });
  255. const preview = f.crawler.preview();
  256. assert.equal(preview.count, 2); assert.match(preview.errors.join(' '), /稳定聊天标识/);
  257. await f.crawler.tick();
  258. const contexts = f.captures.filter(item => item.title === 'Same name').map(item => item.context?.id);
  259. assert.ok(contexts.includes('a')); assert.ok(contexts.includes('b'));
  260. assert.deepEqual(f.clicks.map(click => click.id), ['a', 'b']);
  261. } finally { f.close(); }
  262. });
  263. test('custom message and list selectors are used for transition evidence and capture context', async () => {
  264. const f = fixture({ chats: ['a'], onClick: (id, { document, pane, schedule }) => {
  265. schedule(500, () => {
  266. const message = document.createElement('div'); message.className = 'custom-message'; message.id = `message-${id}`; message.textContent = 'A custom Teams message';
  267. pane.replaceChildren(message);
  268. });
  269. } });
  270. try {
  271. f.pane.removeAttribute('role'); f.pane.className = 'custom-message-list';
  272. f.crawler.configure({ ...enabled, messageListSelector: '.custom-message-list', messageSelector: '.custom-message' });
  273. await f.crawler.tick();
  274. assert.equal(f.crawler.status().visited, 1);
  275. assert.equal(f.crawler.status().phase, 'waiting');
  276. assert.deepEqual(f.captures.find(record => record.title === 'Chat a').context, { id: 'a', title: 'Chat a' });
  277. f.crawler.configure({ ...enabled, messageListSelector: '.custom-message-list', messageSelector: '[' });
  278. await f.crawler.tick();
  279. assert.match(f.crawler.status().error, /消息 CSS 选择器无效/);
  280. } finally { f.close(); }
  281. });
  282. test('an unverified selected first chat is visited after another chat, so old content cannot be trusted on startup', async () => {
  283. const f = fixture();
  284. try {
  285. f.list.firstElementChild.setAttribute('aria-selected', 'true');
  286. f.title.textContent = 'Chat a'; // Header and selection changed, but old message DOM remains.
  287. await f.crawler.tick();
  288. assert.deepEqual(f.clicks.map(click => click.id), ['b', 'a']);
  289. assert.equal(f.crawler.status().visited, 2);
  290. assert.ok(f.captures.filter(record => record.context).every(record => !record.ids.includes('old')));
  291. } finally { f.close(); }
  292. });
  293. test('resuming a selected single chat after a failed transition cannot bypass freshness checks', async () => {
  294. for (const relabelledPane of [false, true]) {
  295. const f = fixture({ chats: ['a'], onClick: (id, { pane }) => { if (relabelledPane) pane.setAttribute('data-chat-id', id); } });
  296. try {
  297. await f.crawler.tick();
  298. assert.equal(f.crawler.status().phase, 'error');
  299. f.crawler.resume(); await f.crawler.tick();
  300. assert.equal(f.crawler.status().phase, 'error');
  301. assert.ok(f.captures.every(record => record.context === null));
  302. assert.equal(f.crawler.status().visited, 0);
  303. } finally { f.close(); }
  304. }
  305. });
  306. test('selected row cannot override conflicting or mixed explicit message conversation IDs', async () => {
  307. for (const mixed of [false, true]) {
  308. const f = fixture({ chats: ['a'], onClick: (id, { messages, pane, schedule }) => {
  309. schedule(500, () => {
  310. messages(id, mixed ? ['new-a', 'new-b'] : ['new-b']);
  311. pane.setAttribute('data-chat-id', mixed ? 'a' : 'b');
  312. if (mixed) {
  313. pane.children[0].setAttribute('data-chat-id', 'a');
  314. pane.children[1].setAttribute('data-chat-id', 'b');
  315. }
  316. });
  317. } });
  318. try {
  319. await f.crawler.tick();
  320. assert.equal(f.crawler.status().phase, 'error');
  321. assert.ok(f.captures.every(record => record.context === null));
  322. } finally { f.close(); }
  323. }
  324. });
  325. test('capture context exposes only the verified message root and expires when that pane is replaced', async () => {
  326. const f = fixture({ chats: ['a'] });
  327. try {
  328. await f.crawler.tick();
  329. assert.equal(f.crawler.captureContext().root, f.pane);
  330. assert.ok(f.captures.filter(record => record.context).every(record => record.captureRoot === f.pane));
  331. f.pane.replaceWith(f.pane.cloneNode(true));
  332. assert.equal(f.crawler.captureContext(), null, 'same-looking replacement DOM must be reverified');
  333. } finally { f.close(); }
  334. });
  335. test('each pass returns a selected chat to its newest viewport before bounded history collection', async () => {
  336. const f = fixture({ chats: ['a'] });
  337. let round = 1, historyScrolls = 0, bottomScrolls = 0;
  338. try {
  339. scrollable(f.pane, { height: 1200, viewport: 200, initial: 1000, onScroll: top => {
  340. if (top === 1000) { bottomScrolls++; f.messages('a', [`a-latest-${round}`]); }
  341. else { historyScrolls++; f.messages('a', [`a-history-${round}`]); }
  342. } });
  343. f.crawler.configure({ ...enabled, historyScrollPasses: 1 });
  344. await f.crawler.tick();
  345. assert.equal(historyScrolls, 1); assert.equal(f.pane.scrollTop, 800);
  346. round = 2; f.advance(30000);
  347. await f.crawler.tick();
  348. assert.equal(f.crawler.status().pass, 2); assert.equal(f.crawler.status().phase, 'waiting');
  349. assert.equal(bottomScrolls, 1); assert.equal(historyScrolls, 2);
  350. assert.ok(f.captures.some(record => record.ids.includes('a-latest-2') && record.context?.id === 'a'));
  351. assert.ok(f.captures.some(record => record.ids.includes('a-history-2') && record.context?.id === 'a'));
  352. } finally { f.close(); }
  353. });