automation-background.test.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. import test from 'node:test';
  2. import assert from 'node:assert/strict';
  3. import { createBackgroundRuntime } from '../extension/background-runtime.js';
  4. import { DEFAULT_CONFIG, DEFAULT_AUTOMATION, publicConfig, validateConfig } from '../extension/config.js';
  5. const id = 'automation-test';
  6. const trusted = { id, url: `chrome-extension://${id}/options.html` };
  7. const initial = { ...DEFAULT_CONFIG, enabled: true, accountId: 'work', token: 'local-secret' };
  8. const event = () => {
  9. const listeners = [];
  10. return { listeners, addListener: fn => listeners.push(fn), emit: (...args) => listeners.forEach(fn => fn(...args)) };
  11. };
  12. const settle = () => new Promise(resolve => setImmediate(resolve));
  13. function fixture({ saved = initial, sessionData = {}, tabs = [{ id: 8, url: 'https://teams.cloud.microsoft/', active: true }] } = {}) {
  14. const local = { config: structuredClone(saved) }, session = structuredClone(sessionData), created = [], sent = [], requests = [];
  15. const tabMap = new Map(tabs.map(tab => [tab.id, structuredClone(tab)]));
  16. let nextId = 100;
  17. const storage = data => ({ setAccessLevel: async () => {}, get: async key => ({ [key]: structuredClone(data[key]) }), set: async values => Object.assign(data, structuredClone(values)) });
  18. const chrome = {
  19. storage: { local: storage(local), session: storage(session) },
  20. runtime: { id, getURL: path => `chrome-extension://${id}/${path}`, getManifest: () => ({ version: '0.2.0' }), onMessage: event(), onInstalled: event(), onStartup: event() },
  21. tabs: {
  22. onRemoved: event(), onUpdated: event(),
  23. query: async () => [...tabMap.values()],
  24. get: async tabId => { if (!tabMap.has(tabId)) throw new Error('No such tab'); return structuredClone(tabMap.get(tabId)); },
  25. create: async args => { created.push(structuredClone(args)); const tab = { ...args, id: nextId++ }; tabMap.set(tab.id, tab); return tab; },
  26. update: async () => { throw new Error('Must never focus a tab'); },
  27. sendMessage: async (tabId, message) => { sent.push({ tabId, message }); return message.type === 'PROBE' ? { ok: true, ready: true, runtimeError: '' } : { ok: true, count: 2, labels: ['Chat A'], errors: [] }; }
  28. },
  29. scripting: { executeScript: async () => {} }
  30. };
  31. const runtime = () => createBackgroundRuntime({ chrome, sleep: async () => {}, fetch: async (url, options) => { requests.push({ url, body: JSON.parse(options.body) }); return { ok: true }; } });
  32. const background = runtime();
  33. const page = tabId => { const tab = tabMap.get(tabId); return { id, frameId: 0, url: tab.url, tab: structuredClone(tab) }; };
  34. return { background, runtime, chrome, local, session, created, sent, tabMap, requests, page, send: (type, extra = {}) => background.dispatch({ type, ...extra }, trusted) };
  35. }
  36. test('automatic traversal is opt-in, validated, and public config cannot claim ownership', () => {
  37. assert.equal(DEFAULT_AUTOMATION.enabled, false);
  38. const config = validateConfig({ ...initial, automation: { enabled: true, assigned: true } });
  39. assert.equal(config.automation.intervalSeconds, 120);
  40. assert.equal(config.automation.assigned, undefined);
  41. assert.equal(publicConfig(config).automation.assigned, false);
  42. assert.equal(publicConfig(config).automation.collectorTab, false);
  43. assert.equal(publicConfig(config).token, undefined);
  44. for (const [key, value] of [['intervalSeconds', 29], ['dwellSeconds', 31], ['maxChats', 201], ['listScrollPasses', -1], ['historyScrollPasses', 21]]) {
  45. assert.throws(() => validateConfig({ ...initial, automation: { [key]: value } }), /自动采集/);
  46. }
  47. assert.throws(() => validateConfig({ ...initial, automation: { chatItemSelector: 'a'.repeat(2001) } }), /选择器/);
  48. });
  49. test('concurrent starts create exactly one inactive collector; normal Teams tabs remain unassigned', async () => {
  50. const f = fixture();
  51. await Promise.all([f.send('START_AUTOMATION'), f.send('START_AUTOMATION'), f.send('START_AUTOMATION')]);
  52. assert.deepEqual(f.created, [{ url: 'https://teams.cloud.microsoft/', active: false }]);
  53. assert.deepEqual(f.session.automationOwner, { tabId: 100, accountId: 'work', assigned: true });
  54. const normal = await f.background.dispatch({ type: 'GET_CONFIG' }, f.page(8));
  55. const collector = await f.background.dispatch({ type: 'GET_CONFIG' }, f.page(100));
  56. assert.equal(normal.config.automation.assigned, false);
  57. assert.equal(normal.config.automation.collectorTab, false);
  58. assert.equal(collector.config.automation.assigned, true);
  59. assert.equal(collector.config.automation.collectorTab, true);
  60. await f.send('GET_STATE'); await f.send('GET_STATE');
  61. assert.equal(f.created.length, 1);
  62. });
  63. test('service worker restart restores session ownership instead of creating or reusing another tab', async () => {
  64. const f = fixture(); await f.send('START_AUTOMATION');
  65. const resumed = f.runtime(); resumed.start();
  66. await settle();
  67. const state = await resumed.dispatch({ type: 'GET_STATE' }, trusted);
  68. assert.equal(f.created.length, 1); assert.equal(state.automation.tabId, 100);
  69. assert.equal((await resumed.dispatch({ type: 'GET_CONFIG' }, f.page(100))).config.automation.assigned, true);
  70. });
  71. test('browser startup honors saved explicit opt-in and uses allowed Teams origin or fixed fallback', async () => {
  72. const f = fixture({ saved: { ...initial, automation: { ...DEFAULT_AUTOMATION, enabled: true } }, tabs: [] });
  73. f.background.start(); f.chrome.runtime.onStartup.emit(); f.chrome.runtime.onInstalled.emit();
  74. await settle(); await f.send('GET_STATE');
  75. assert.deepEqual(f.created, [{ url: 'https://teams.cloud.microsoft/', active: false }]);
  76. const microsoft = fixture({ tabs: [{ id: 8, url: 'https://teams.microsoft.com/v2/?private=query', active: true }] });
  77. await microsoft.send('START_AUTOMATION');
  78. assert.deepEqual(microsoft.created, [{ url: 'https://teams.microsoft.com/', active: false }]);
  79. });
  80. test('stop revokes assignment, preserves the created tab, and restart reuses only that owned tab', async () => {
  81. const f = fixture(); await f.send('START_AUTOMATION'); await f.send('STOP_AUTOMATION');
  82. assert.equal(f.local.config.automation.enabled, false);
  83. assert.equal(f.session.automationOwner.assigned, false);
  84. assert.equal(f.tabMap.has(100), true);
  85. const stopped = await f.background.dispatch({ type: 'GET_CONFIG' }, f.page(100));
  86. assert.equal(stopped.config.automation.assigned, false);
  87. assert.equal(stopped.config.automation.collectorTab, true);
  88. const resumed = f.runtime();
  89. assert.equal((await resumed.dispatch({ type: 'GET_CONFIG' }, f.page(100))).config.automation.collectorTab, true);
  90. await f.send('START_AUTOMATION'); assert.equal(f.created.length, 1);
  91. });
  92. test('closing collector disables mode and subsequent popup/startup checks do not recreate it', async () => {
  93. const f = fixture(); f.background.start(); await settle(); await f.send('START_AUTOMATION');
  94. f.tabMap.delete(100); f.chrome.tabs.onRemoved.emit(100); await settle();
  95. assert.equal(f.local.config.automation.enabled, false); assert.equal(f.session.automationOwner, null);
  96. f.chrome.runtime.onStartup.emit(); await settle(); await f.send('GET_STATE');
  97. assert.equal(f.created.length, 1);
  98. await f.send('START_AUTOMATION'); assert.equal(f.created.length, 2);
  99. });
  100. test('collector tab closed while service worker sleeps is detected on resume and not recreated', async () => {
  101. const f = fixture(); await f.send('START_AUTOMATION'); f.tabMap.delete(100);
  102. const resumed = f.runtime(); resumed.start(); await settle();
  103. await resumed.dispatch({ type: 'GET_STATE' }, trusted);
  104. assert.equal(f.local.config.automation.enabled, false); assert.equal(f.created.length, 1);
  105. });
  106. test('leaving Teams or disabling main capture revokes automatic navigation', async () => {
  107. const f = fixture(); f.background.start(); await settle(); await f.send('START_AUTOMATION');
  108. f.tabMap.get(100).url = 'https://login.microsoftonline.com/';
  109. f.chrome.tabs.onUpdated.emit(100, { url: 'https://login.microsoftonline.com/' }); await settle();
  110. assert.equal(f.local.config.automation.enabled, false); assert.equal(f.session.automationOwner, null);
  111. const g = fixture(); await g.send('START_AUTOMATION');
  112. await g.send('SAVE_CONFIG', { config: { ...g.local.config, enabled: false } });
  113. assert.equal(g.local.config.automation.enabled, false); assert.equal(g.session.automationOwner.assigned, false);
  114. await assert.rejects(g.send('START_AUTOMATION'), /开启页面采集/);
  115. });
  116. test('changing account cannot reassign the former collector; explicit restart creates a fresh collector', async () => {
  117. const f = fixture(); await f.send('START_AUTOMATION');
  118. await f.send('SAVE_CONFIG', { config: { ...f.local.config, accountId: 'another-account' } });
  119. assert.equal(f.local.config.automation.enabled, false); assert.equal(f.session.automationOwner, null);
  120. assert.equal((await f.background.dispatch({ type: 'GET_CONFIG' }, f.page(100))).config.automation.assigned, false);
  121. await f.send('START_AUTOMATION'); assert.equal(f.created.length, 2);
  122. assert.equal(f.session.automationOwner.tabId, 101); assert.equal(f.session.automationOwner.accountId, 'another-account');
  123. });
  124. test('only assigned top-frame same-account collector can report bounded metadata; message fields are discarded', async () => {
  125. const f = fixture(); await f.send('START_AUTOMATION');
  126. const message = { type: 'REPORT_AUTOMATION', accountId: 'work', status: { running: true, phase: 'capturing', visited: -3, discovered: 3000000, pass: 2.9, nextRunAt: '2026-09-08T04:00:00Z', error: 'e'.repeat(900), coverage: 'c'.repeat(900), records: ['Private message'], labels: ['Private chat'] } };
  127. await assert.rejects(f.background.dispatch(message, f.page(8)), /指定采集标签/);
  128. await assert.rejects(f.background.dispatch({ ...message, accountId: 'wrong' }, f.page(100)), /指定采集标签/);
  129. await assert.rejects(f.background.dispatch(message, { ...f.page(100), frameId: 1 }), /来源不受信任/);
  130. await f.background.dispatch(message, f.page(100));
  131. const auto = f.local.status.automation;
  132. assert.equal(auto.visited, 0); assert.equal(auto.discovered, 1000000); assert.equal(auto.pass, 2);
  133. assert.equal(auto.error.length, 300); assert.equal(auto.coverage.length, 500);
  134. assert.equal(auto.nextRunAt, '2026-09-08T04:00:00.000Z');
  135. assert.doesNotMatch(JSON.stringify(auto), /Private|records|labels/);
  136. assert.deepEqual(f.requests.at(-1).body.automation, auto);
  137. await f.send('STOP_AUTOMATION');
  138. await assert.rejects(f.background.dispatch(message, f.page(100)), /指定采集标签/);
  139. await assert.rejects(f.background.dispatch({ type: 'START_AUTOMATION' }, f.page(8)), /设置页或弹窗/);
  140. });
  141. test('chat discovery preview goes to collector when present and cannot transfer ownership', async () => {
  142. const f = fixture(); await f.send('PREVIEW_CHATS');
  143. assert.equal(f.sent.at(-1).tabId, 8); assert.equal(f.created.length, 0);
  144. await f.send('START_AUTOMATION'); await f.send('PREVIEW_CHATS');
  145. assert.equal(f.sent.at(-1).tabId, 100);
  146. assert.equal(f.sent.at(-1).message.config.automation.assigned, false);
  147. });
  148. test('delayed tab lookup cannot grant an assignment revoked by a concurrent stop', async () => {
  149. const f = fixture(); await f.send('START_AUTOMATION');
  150. let release;
  151. const lookup = f.chrome.tabs.get;
  152. f.chrome.tabs.get = tabId => tabId === 100 ? new Promise(resolve => { release = () => resolve({ ...f.tabMap.get(tabId) }); }) : lookup(tabId);
  153. const pending = f.background.dispatch({ type: 'GET_CONFIG' }, f.page(100));
  154. await settle(); assert.equal(typeof release, 'function');
  155. await f.send('STOP_AUTOMATION');
  156. release();
  157. assert.equal((await pending).config.automation.assigned, false);
  158. });
  159. test('startup and load notifications preserve pauses; only explicit extension actions request resume', async () => {
  160. const f = fixture(); await f.send('START_AUTOMATION');
  161. assert.ok(f.sent.some(({ tabId, message }) => tabId === 100 && message.resumeAutomation === true));
  162. f.sent.length = 0;
  163. const resumed = f.runtime(); resumed.start(); await settle();
  164. assert.ok(f.sent.some(({ message }) => message.type === 'CONFIG_CHANGED'));
  165. assert.equal(f.sent.some(({ message }) => message.resumeAutomation === true), false);
  166. f.chrome.tabs.onUpdated.emit(100, { status: 'complete' }); await settle();
  167. assert.equal(f.sent.some(({ message }) => message.resumeAutomation === true), false);
  168. await resumed.dispatch({ type: 'RECONNECT' }, trusted);
  169. assert.ok(f.sent.some(({ tabId, message }) => tabId === 100 && message.resumeAutomation === true));
  170. });