| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185 |
- import test from 'node:test';
- import assert from 'node:assert/strict';
- import { createBackgroundRuntime } from '../extension/background-runtime.js';
- import { DEFAULT_CONFIG, DEFAULT_AUTOMATION, publicConfig, validateConfig } from '../extension/config.js';
- const id = 'automation-test';
- const trusted = { id, url: `chrome-extension://${id}/options.html` };
- const initial = { ...DEFAULT_CONFIG, enabled: true, accountId: 'work', token: 'local-secret' };
- const event = () => {
- const listeners = [];
- return { listeners, addListener: fn => listeners.push(fn), emit: (...args) => listeners.forEach(fn => fn(...args)) };
- };
- const settle = () => new Promise(resolve => setImmediate(resolve));
- function fixture({ saved = initial, sessionData = {}, tabs = [{ id: 8, url: 'https://teams.cloud.microsoft/', active: true }] } = {}) {
- const local = { config: structuredClone(saved) }, session = structuredClone(sessionData), created = [], sent = [], requests = [];
- const tabMap = new Map(tabs.map(tab => [tab.id, structuredClone(tab)]));
- let nextId = 100;
- const storage = data => ({ setAccessLevel: async () => {}, get: async key => ({ [key]: structuredClone(data[key]) }), set: async values => Object.assign(data, structuredClone(values)) });
- const chrome = {
- storage: { local: storage(local), session: storage(session) },
- runtime: { id, getURL: path => `chrome-extension://${id}/${path}`, getManifest: () => ({ version: '0.2.0' }), onMessage: event(), onInstalled: event(), onStartup: event() },
- tabs: {
- onRemoved: event(), onUpdated: event(),
- query: async () => [...tabMap.values()],
- get: async tabId => { if (!tabMap.has(tabId)) throw new Error('No such tab'); return structuredClone(tabMap.get(tabId)); },
- create: async args => { created.push(structuredClone(args)); const tab = { ...args, id: nextId++ }; tabMap.set(tab.id, tab); return tab; },
- update: async () => { throw new Error('Must never focus a tab'); },
- 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: [] }; }
- },
- scripting: { executeScript: async () => {} }
- };
- const runtime = () => createBackgroundRuntime({ chrome, sleep: async () => {}, fetch: async (url, options) => { requests.push({ url, body: JSON.parse(options.body) }); return { ok: true }; } });
- const background = runtime();
- const page = tabId => { const tab = tabMap.get(tabId); return { id, frameId: 0, url: tab.url, tab: structuredClone(tab) }; };
- return { background, runtime, chrome, local, session, created, sent, tabMap, requests, page, send: (type, extra = {}) => background.dispatch({ type, ...extra }, trusted) };
- }
- test('automatic traversal is opt-in, validated, and public config cannot claim ownership', () => {
- assert.equal(DEFAULT_AUTOMATION.enabled, false);
- const config = validateConfig({ ...initial, automation: { enabled: true, assigned: true } });
- assert.equal(config.automation.intervalSeconds, 120);
- assert.equal(config.automation.assigned, undefined);
- assert.equal(publicConfig(config).automation.assigned, false);
- assert.equal(publicConfig(config).automation.collectorTab, false);
- assert.equal(publicConfig(config).token, undefined);
- for (const [key, value] of [['intervalSeconds', 29], ['dwellSeconds', 31], ['maxChats', 201], ['listScrollPasses', -1], ['historyScrollPasses', 21]]) {
- assert.throws(() => validateConfig({ ...initial, automation: { [key]: value } }), /自动采集/);
- }
- assert.throws(() => validateConfig({ ...initial, automation: { chatItemSelector: 'a'.repeat(2001) } }), /选择器/);
- });
- test('concurrent starts create exactly one inactive collector; normal Teams tabs remain unassigned', async () => {
- const f = fixture();
- await Promise.all([f.send('START_AUTOMATION'), f.send('START_AUTOMATION'), f.send('START_AUTOMATION')]);
- assert.deepEqual(f.created, [{ url: 'https://teams.cloud.microsoft/', active: false }]);
- assert.deepEqual(f.session.automationOwner, { tabId: 100, accountId: 'work', assigned: true });
- const normal = await f.background.dispatch({ type: 'GET_CONFIG' }, f.page(8));
- const collector = await f.background.dispatch({ type: 'GET_CONFIG' }, f.page(100));
- assert.equal(normal.config.automation.assigned, false);
- assert.equal(normal.config.automation.collectorTab, false);
- assert.equal(collector.config.automation.assigned, true);
- assert.equal(collector.config.automation.collectorTab, true);
- await f.send('GET_STATE'); await f.send('GET_STATE');
- assert.equal(f.created.length, 1);
- });
- test('service worker restart restores session ownership instead of creating or reusing another tab', async () => {
- const f = fixture(); await f.send('START_AUTOMATION');
- const resumed = f.runtime(); resumed.start();
- await settle();
- const state = await resumed.dispatch({ type: 'GET_STATE' }, trusted);
- assert.equal(f.created.length, 1); assert.equal(state.automation.tabId, 100);
- assert.equal((await resumed.dispatch({ type: 'GET_CONFIG' }, f.page(100))).config.automation.assigned, true);
- });
- test('browser startup honors saved explicit opt-in and uses allowed Teams origin or fixed fallback', async () => {
- const f = fixture({ saved: { ...initial, automation: { ...DEFAULT_AUTOMATION, enabled: true } }, tabs: [] });
- f.background.start(); f.chrome.runtime.onStartup.emit(); f.chrome.runtime.onInstalled.emit();
- await settle(); await f.send('GET_STATE');
- assert.deepEqual(f.created, [{ url: 'https://teams.cloud.microsoft/', active: false }]);
- const microsoft = fixture({ tabs: [{ id: 8, url: 'https://teams.microsoft.com/v2/?private=query', active: true }] });
- await microsoft.send('START_AUTOMATION');
- assert.deepEqual(microsoft.created, [{ url: 'https://teams.microsoft.com/', active: false }]);
- });
- test('stop revokes assignment, preserves the created tab, and restart reuses only that owned tab', async () => {
- const f = fixture(); await f.send('START_AUTOMATION'); await f.send('STOP_AUTOMATION');
- assert.equal(f.local.config.automation.enabled, false);
- assert.equal(f.session.automationOwner.assigned, false);
- assert.equal(f.tabMap.has(100), true);
- const stopped = await f.background.dispatch({ type: 'GET_CONFIG' }, f.page(100));
- assert.equal(stopped.config.automation.assigned, false);
- assert.equal(stopped.config.automation.collectorTab, true);
- const resumed = f.runtime();
- assert.equal((await resumed.dispatch({ type: 'GET_CONFIG' }, f.page(100))).config.automation.collectorTab, true);
- await f.send('START_AUTOMATION'); assert.equal(f.created.length, 1);
- });
- test('closing collector disables mode and subsequent popup/startup checks do not recreate it', async () => {
- const f = fixture(); f.background.start(); await settle(); await f.send('START_AUTOMATION');
- f.tabMap.delete(100); f.chrome.tabs.onRemoved.emit(100); await settle();
- assert.equal(f.local.config.automation.enabled, false); assert.equal(f.session.automationOwner, null);
- f.chrome.runtime.onStartup.emit(); await settle(); await f.send('GET_STATE');
- assert.equal(f.created.length, 1);
- await f.send('START_AUTOMATION'); assert.equal(f.created.length, 2);
- });
- test('collector tab closed while service worker sleeps is detected on resume and not recreated', async () => {
- const f = fixture(); await f.send('START_AUTOMATION'); f.tabMap.delete(100);
- const resumed = f.runtime(); resumed.start(); await settle();
- await resumed.dispatch({ type: 'GET_STATE' }, trusted);
- assert.equal(f.local.config.automation.enabled, false); assert.equal(f.created.length, 1);
- });
- test('leaving Teams or disabling main capture revokes automatic navigation', async () => {
- const f = fixture(); f.background.start(); await settle(); await f.send('START_AUTOMATION');
- f.tabMap.get(100).url = 'https://login.microsoftonline.com/';
- f.chrome.tabs.onUpdated.emit(100, { url: 'https://login.microsoftonline.com/' }); await settle();
- assert.equal(f.local.config.automation.enabled, false); assert.equal(f.session.automationOwner, null);
- const g = fixture(); await g.send('START_AUTOMATION');
- await g.send('SAVE_CONFIG', { config: { ...g.local.config, enabled: false } });
- assert.equal(g.local.config.automation.enabled, false); assert.equal(g.session.automationOwner.assigned, false);
- await assert.rejects(g.send('START_AUTOMATION'), /开启页面采集/);
- });
- test('changing account cannot reassign the former collector; explicit restart creates a fresh collector', async () => {
- const f = fixture(); await f.send('START_AUTOMATION');
- await f.send('SAVE_CONFIG', { config: { ...f.local.config, accountId: 'another-account' } });
- assert.equal(f.local.config.automation.enabled, false); assert.equal(f.session.automationOwner, null);
- assert.equal((await f.background.dispatch({ type: 'GET_CONFIG' }, f.page(100))).config.automation.assigned, false);
- await f.send('START_AUTOMATION'); assert.equal(f.created.length, 2);
- assert.equal(f.session.automationOwner.tabId, 101); assert.equal(f.session.automationOwner.accountId, 'another-account');
- });
- test('only assigned top-frame same-account collector can report bounded metadata; message fields are discarded', async () => {
- const f = fixture(); await f.send('START_AUTOMATION');
- 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'] } };
- await assert.rejects(f.background.dispatch(message, f.page(8)), /指定采集标签/);
- await assert.rejects(f.background.dispatch({ ...message, accountId: 'wrong' }, f.page(100)), /指定采集标签/);
- await assert.rejects(f.background.dispatch(message, { ...f.page(100), frameId: 1 }), /来源不受信任/);
- await f.background.dispatch(message, f.page(100));
- const auto = f.local.status.automation;
- assert.equal(auto.visited, 0); assert.equal(auto.discovered, 1000000); assert.equal(auto.pass, 2);
- assert.equal(auto.error.length, 300); assert.equal(auto.coverage.length, 500);
- assert.equal(auto.nextRunAt, '2026-09-08T04:00:00.000Z');
- assert.doesNotMatch(JSON.stringify(auto), /Private|records|labels/);
- assert.deepEqual(f.requests.at(-1).body.automation, auto);
- await f.send('STOP_AUTOMATION');
- await assert.rejects(f.background.dispatch(message, f.page(100)), /指定采集标签/);
- await assert.rejects(f.background.dispatch({ type: 'START_AUTOMATION' }, f.page(8)), /设置页或弹窗/);
- });
- test('chat discovery preview goes to collector when present and cannot transfer ownership', async () => {
- const f = fixture(); await f.send('PREVIEW_CHATS');
- assert.equal(f.sent.at(-1).tabId, 8); assert.equal(f.created.length, 0);
- await f.send('START_AUTOMATION'); await f.send('PREVIEW_CHATS');
- assert.equal(f.sent.at(-1).tabId, 100);
- assert.equal(f.sent.at(-1).message.config.automation.assigned, false);
- });
- test('delayed tab lookup cannot grant an assignment revoked by a concurrent stop', async () => {
- const f = fixture(); await f.send('START_AUTOMATION');
- let release;
- const lookup = f.chrome.tabs.get;
- f.chrome.tabs.get = tabId => tabId === 100 ? new Promise(resolve => { release = () => resolve({ ...f.tabMap.get(tabId) }); }) : lookup(tabId);
- const pending = f.background.dispatch({ type: 'GET_CONFIG' }, f.page(100));
- await settle(); assert.equal(typeof release, 'function');
- await f.send('STOP_AUTOMATION');
- release();
- assert.equal((await pending).config.automation.assigned, false);
- });
- test('startup and load notifications preserve pauses; only explicit extension actions request resume', async () => {
- const f = fixture(); await f.send('START_AUTOMATION');
- assert.ok(f.sent.some(({ tabId, message }) => tabId === 100 && message.resumeAutomation === true));
- f.sent.length = 0;
- const resumed = f.runtime(); resumed.start(); await settle();
- assert.ok(f.sent.some(({ message }) => message.type === 'CONFIG_CHANGED'));
- assert.equal(f.sent.some(({ message }) => message.resumeAutomation === true), false);
- f.chrome.tabs.onUpdated.emit(100, { status: 'complete' }); await settle();
- assert.equal(f.sent.some(({ message }) => message.resumeAutomation === true), false);
- await resumed.dispatch({ type: 'RECONNECT' }, trusted);
- assert.ok(f.sent.some(({ tabId, message }) => tabId === 100 && message.resumeAutomation === true));
- });
|