chat-crawler.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. // Bounded DOM navigation for the extension-owned collector tab. No network or Chrome API access.
  2. import { DEFAULT_SELECTORS, isVisible, stableHash, visibleText } from './parser.js';
  3. const LIST = '[data-tid="chat-list"],[data-tid="chat-list-container"],[data-tid="chat-list-viewport"],[data-tid="chat-list-scrollable-container"],[data-tid="chat-tree"],[data-tid="chat-list-tree"]';
  4. const KNOWN_ROW = '[data-tid="chat-list-item"],[data-tid="chat-list-item-container"],[data-tid="chat-list-item-wrapper"],[data-tid="chat-list-item-row"],[data-tid="chat-item"],[data-tid="chat-tree-item"]';
  5. const ROW = `${KNOWN_ROW},[role="treeitem"],[role="listitem"],[role="option"]`;
  6. const MESSAGE_LIST = '[data-tid="chat-pane-list"],[data-tid="message-pane-list-run"],[data-tid="message-pane-list"],[data-tid="chat-pane-message-list"],[role="log"]';
  7. const TITLE = '[data-tid="chat-header-title"],[data-tid="conversation-title"],[data-tid="chat-title"]';
  8. const ROW_TITLE = '[data-tid="chat-list-item-title"],[data-tid="chat-list-item-name"],[data-tid="chat-list-item-topic"],[data-tid="chat-title"]';
  9. const SCOPE = '[data-conversation-id],[data-chat-id],[data-thread-id]';
  10. const EXCLUDED = 'nav,form,[role="navigation"],[role="menu"],[role="menubar"],[role="toolbar"],[data-tid="app-bar"],[data-tid="message-editor"],[data-tid="message-compose"],input,textarea,select,[contenteditable]:not([contenteditable="false"]),[role="textbox"]';
  11. const STRUCTURAL = 'html,body,main,nav,form,header,footer,[role="main"],[role="navigation"]';
  12. const DEFAULTS = Object.freeze({ enabled: false, assigned: false, accountId: '', intervalSeconds: 120, dwellSeconds: 4, maxChats: 50, listScrollPasses: 8, historyScrollPasses: 2, chatItemSelector: '', chatListSelector: '', messageListSelector: '', messageSelector: '' });
  13. const CANCELLED = Symbol('crawler-cancelled');
  14. const compact = value => String(value || '').replace(/\s+/g, ' ').trim().slice(0, 300);
  15. const scopeId = node => node?.getAttribute('data-conversation-id') || node?.getAttribute('data-chat-id') || node?.getAttribute('data-thread-id') || '';
  16. function optionsFor(input = {}) {
  17. const result = { ...DEFAULTS, enabled: input.enabled === true, assigned: input.assigned === true, accountId: String(input.accountId || '').slice(0, 200) };
  18. for (const [key, min, max] of [['intervalSeconds', 30, 3600], ['dwellSeconds', 2, 30], ['maxChats', 1, 200], ['listScrollPasses', 0, 30], ['historyScrollPasses', 0, 20]]) {
  19. result[key] = Number.isInteger(input[key]) ? Math.min(max, Math.max(min, input[key])) : DEFAULTS[key];
  20. }
  21. for (const key of ['chatItemSelector', 'chatListSelector', 'messageListSelector', 'messageSelector']) result[key] = typeof input[key] === 'string' ? input[key].trim().slice(0, 2000) : '';
  22. return result;
  23. }
  24. export function createChatCrawler({ window, document, capture, report = () => {}, wait, now = () => Date.now() }) {
  25. if (typeof capture !== 'function') throw new TypeError('capture callback is required');
  26. let options = optionsFor(), fingerprint = JSON.stringify(options), active = null, paused = false, disposed = false, navigating = false;
  27. let verified = null, uncertainTransition = null;
  28. let state = { running: false, phase: 'disabled', visited: 0, discovered: 0, pass: 0, nextRunAt: null, error: '', coverage: '' };
  29. const enabled = () => options.enabled && options.assigned && !disposed;
  30. const status = () => ({ ...state });
  31. function publish(update = {}) {
  32. state = { ...state, ...update };
  33. try { Promise.resolve(report(status())).catch(() => {}); } catch { /* Diagnostics must not interfere with cancellation. */ }
  34. }
  35. function check(run) { if (disposed || run.controller.signal.aborted || active !== run) throw CANCELLED; }
  36. function abortable(promise, run, cleanup = () => {}) {
  37. check(run);
  38. return new Promise((resolve, reject) => {
  39. const signal = run.controller.signal;
  40. const abort = () => { cleanup(); signal.removeEventListener('abort', abort); reject(CANCELLED); };
  41. signal.addEventListener('abort', abort, { once: true });
  42. Promise.resolve(promise).then(value => { signal.removeEventListener('abort', abort); resolve(value); }, error => { signal.removeEventListener('abort', abort); reject(error); });
  43. if (signal.aborted) abort();
  44. });
  45. }
  46. async function delay(ms, run) {
  47. check(run);
  48. let timer;
  49. const pending = wait ? wait(ms, { signal: run.controller.signal }) : new Promise(resolve => { timer = window.setTimeout(resolve, ms); });
  50. await abortable(pending, run, () => { if (timer !== undefined) window.clearTimeout(timer); });
  51. check(run);
  52. }
  53. function select(root, selector, label, errors) {
  54. try {
  55. const nodes = [...root.querySelectorAll(selector)];
  56. if (nodes.length > 2000) { errors.push(`${label}匹配超过 2000 个元素,请缩小选择器范围`); return []; }
  57. return nodes;
  58. } catch { errors.push(`${label} CSS 选择器无效`); return []; }
  59. }
  60. const safeContainer = node => node && !node.matches(STRUCTURAL) && !node.closest(EXCLUDED) && isVisible(node);
  61. function findList(errors = [], settings = options) {
  62. const candidates = select(document, settings.chatListSelector || LIST, '聊天列表', errors);
  63. const safe = candidates.filter(safeContainer);
  64. if (candidates.length && !safe.length) errors.push('聊天列表选择器指向整页、导航或编辑区域,已忽略');
  65. const withRows = safe.filter(node => select(node, settings.chatItemSelector || ROW, '聊天行', errors).length);
  66. return withRows.find(node => scrollMax(node) > 0) || withRows[0] || safe[0] || null;
  67. }
  68. function routeIdentity(row) {
  69. const anchors = row.matches('a[href]') ? [row] : [...row.querySelectorAll('a[href]')];
  70. for (const anchor of anchors) {
  71. if (anchor.closest('[role="menu"],[role="toolbar"]')) continue;
  72. try {
  73. const url = new URL(anchor.getAttribute('href'), document.location.href);
  74. if (url.protocol !== 'https:' || !['teams.microsoft.com', 'teams.cloud.microsoft'].includes(url.hostname)) continue;
  75. // Inspect only chat route identifiers; never store arbitrary queries/fragments.
  76. const direct = url.pathname.match(/^\/(?:l\/)?chat\/([^/]+)(?:\/|$)/i);
  77. if (direct && direct[1] !== '0') return { key: `conversation:${decodeURIComponent(direct[1])}`, conversationId: decodeURIComponent(direct[1]) };
  78. if (!/^\/v2\/?$/i.test(url.pathname)) continue;
  79. for (const key of ['chatId', 'threadId', 'conversationId']) {
  80. const id = url.searchParams.get(key);
  81. if (id && id.length <= 500) return { key: `conversation:${id}`, conversationId: id };
  82. }
  83. } catch { /* A malformed link is not a navigation target. */ }
  84. }
  85. return null;
  86. }
  87. function identity(row) {
  88. const id = scopeId(row);
  89. if (id && id.length <= 500) return { key: `conversation:${id}`, conversationId: id };
  90. const itemId = row.getAttribute('data-item-id');
  91. if (itemId && itemId.length <= 500 && !/^\d+$/.test(itemId)) return { key: `item:${itemId}`, conversationId: '' };
  92. const route = routeIdentity(row);
  93. if (route) return route;
  94. const domId = row.id;
  95. if (/^(?:chat|thread|conversation)[-_:]/i.test(domId) && domId.length <= 500) return { key: `element:${domId}`, conversationId: '' };
  96. return null; // Display names and virtual-list indices are not stable identities.
  97. }
  98. function safeRow(row, list) {
  99. if (!list || !row.isConnected || row === list || !list.contains(row) || !isVisible(row) || row.matches(STRUCTURAL) || row.closest(EXCLUDED)) return false;
  100. if (row.matches('input,textarea,select,summary,[role="menuitem"],[role="tab"],[aria-haspopup]')) return false;
  101. if (row.matches('button,[role="button"]') && !row.matches(KNOWN_ROW)) return false;
  102. if (row.matches('button[type="submit"]') || row.querySelector('form,main,nav,[role="main"],[role="navigation"]')) return false;
  103. // A grouping tree node can expand/collapse many conversations; never activate it.
  104. if (row.querySelector('[role="treeitem"]')) return false;
  105. if (row.matches('a[href]') && !routeIdentity(row)) return false;
  106. return true;
  107. }
  108. function rows(list, errors = [], settings = options) {
  109. if (!list) return [];
  110. const nodes = select(list, settings.chatItemSelector || ROW, '聊天行', errors);
  111. const found = new Map();
  112. let unidentified = 0, unsafe = 0;
  113. for (const row of nodes) {
  114. if (!safeRow(row, list)) { unsafe++; continue; }
  115. const id = identity(row);
  116. if (!id) { unidentified++; continue; }
  117. const title = [...row.querySelectorAll(ROW_TITLE)].find(isVisible);
  118. const label = compact(visibleText(title, 300) || row.getAttribute('aria-label') || visibleText(row, 300));
  119. const item = { ...id, label, row };
  120. const previous = found.get(item.key);
  121. if (!previous || previous.row.contains(row)) found.set(item.key, item);
  122. }
  123. if (unidentified) errors.push(`${unidentified} 个聊天行缺少稳定聊天标识,已忽略(名称不能用于区分同名聊天)`);
  124. if (unsafe) errors.push(`${unsafe} 个匹配元素属于按钮、分组或不安全区域,已忽略`);
  125. return [...found.values()];
  126. }
  127. function preview(overrides) {
  128. const settings = optionsFor({ ...options, ...overrides });
  129. const errors = [], list = findList(errors, settings), found = rows(list, errors, settings);
  130. if (!list) errors.push('未识别聊天列表;请在采集页打开 Teams 聊天列表,或配置聊天列表选择器');
  131. else if (!found.length) errors.push('未识别带稳定标识的聊天行;请检查聊天行选择器');
  132. return { count: found.length, labels: found.slice(0, 20).map(item => item.label), errors: [...new Set(errors)] };
  133. }
  134. const scrollMax = node => Math.max(0, Number(node.scrollHeight) - Number(node.clientHeight));
  135. function findMessageList(errors = []) {
  136. const nodes = select(document, options.messageListSelector || MESSAGE_LIST, '消息列表', errors).filter(node => safeContainer(node) && !node.closest(LIST));
  137. const withMessages = nodes.filter(node => select(node, options.messageSelector || DEFAULT_SELECTORS.message, '消息', errors).length);
  138. return withMessages.find(node => scrollMax(node) > 0) || withMessages[0] || nodes[0] || null;
  139. }
  140. function snapshot() {
  141. const errors = [], pane = findMessageList(errors);
  142. const candidates = pane ? select(pane, options.messageSelector || DEFAULT_SELECTORS.message, '消息', errors).filter(isVisible) : [];
  143. const unique = candidates.filter(node => !candidates.some(other => other !== node && other.contains(node))).slice(0, 200);
  144. const messages = unique.map(node => {
  145. const id = node.getAttribute('data-message-id') || node.getAttribute('data-item-id') || node.id || '';
  146. const hash = stableHash(visibleText(node, 16000));
  147. return { key: id ? `id:${id}` : `text:${hash}`, hash };
  148. });
  149. const keys = messages.map(message => message.key);
  150. const titles = [...document.querySelectorAll(TITLE)].filter(isVisible).map(node => compact(visibleText(node, 300)));
  151. const scopes = [...new Set(unique.map(node => scopeId(node.closest(SCOPE))).filter(Boolean))];
  152. const paneScope = scopeId(pane?.closest(SCOPE));
  153. const conversationId = scopes.length === 1 ? scopes[0] : paneScope;
  154. const mixedScopes = scopes.length > 1 || Boolean(paneScope && scopes.some(id => id !== paneScope));
  155. return { pane, keys, titles, conversationId, mixedScopes, errors, signature: stableHash(JSON.stringify([messages, titles, conversationId, mixedScopes])) };
  156. }
  157. const rowSelected = row => Boolean(row && (row.matches('[aria-selected="true"],[aria-current="true"],[aria-current="page"],[data-is-selected="true"]') || row.querySelector('[aria-selected="true"],[data-is-selected="true"]')));
  158. function selected(target) {
  159. const list = findList();
  160. const row = rows(list).find(item => item.key === target.key)?.row;
  161. return rowSelected(row);
  162. }
  163. function pointsAt(target, view) {
  164. if (view.mixedScopes || (target.conversationId && view.conversationId && target.conversationId !== view.conversationId)) return false;
  165. return selected(target) || Boolean(target.conversationId && view.conversationId === target.conversationId) || Boolean(target.label && view.titles.includes(target.label));
  166. }
  167. function previouslyVerified(target, view) {
  168. return Boolean(verified && verified.target.key === target.key && verified.pane === view.pane && verified.signature === view.signature && pointsAt(target, view));
  169. }
  170. const explicitScope = (target, view) => Boolean(target.conversationId && !view.mixedScopes && view.conversationId === target.conversationId &&
  171. // Remember an interrupted transition even when resume clears the paused flag:
  172. // its pane metadata may have changed before the old message nodes disappear.
  173. (!uncertainTransition || uncertainTransition.key !== target.key || view.keys.every(key => !uncertainTransition.keys.has(key))));
  174. function captureContext() {
  175. if (!verified || navigating || disposed) return null;
  176. const view = snapshot();
  177. if (view.pane !== verified.pane || !view.keys.length || view.titles.join('\n') !== verified.titles.join('\n') || view.conversationId !== verified.paneId || !pointsAt(verified.target, view)) return null;
  178. return { ...verified.context, root: view.pane };
  179. }
  180. function remember(target, view, previousContext) {
  181. const context = previousContext ? { id: previousContext.id, title: previousContext.title } : { id: view.conversationId || target.conversationId || `auto-row:${stableHash(target.key)}`, title: view.titles[0] || target.label || '聊天消息' };
  182. verified = { target, titles: view.titles, pane: view.pane, paneId: view.conversationId, signature: view.signature, context };
  183. if (uncertainTransition?.key === target.key) uncertainTransition = null;
  184. }
  185. async function settle(target, before, run, { alreadySelected = false, history = false } = {}) {
  186. const start = now(), dwell = options.dwellSeconds * 1000, timeout = Math.max(15000, dwell * 3 + 4000);
  187. let lastSignature = '', stableSince = null;
  188. while (now() - start <= timeout) {
  189. check(run);
  190. const view = snapshot();
  191. if (view.errors.length) throw new Error(view.errors[0]);
  192. const old = new Set(before.keys);
  193. // A changed header/selected row or relabelled pane may coexist with old messages.
  194. // Require *all* old message fingerprints to disappear before capturing a new chat.
  195. const fresh = alreadySelected || history || (view.keys.length > 0 && view.keys.every(key => !old.has(key)));
  196. const sameHistory = !history || (view.titles.join('\n') === before.titles.join('\n') && view.conversationId === before.conversationId);
  197. const titleChangedToTarget = target.label && view.titles.includes(target.label) && view.titles.join('\n') !== before.titles.join('\n');
  198. const selectionEvidence = alreadySelected || history || selected(target) || Boolean(target.conversationId && view.conversationId === target.conversationId) || titleChangedToTarget;
  199. const ready = view.pane && view.keys.length > 0 && fresh && sameHistory && selectionEvidence && pointsAt(target, view);
  200. if (ready && view.signature === lastSignature) {
  201. if (stableSince !== null && now() - stableSince >= dwell) return view;
  202. } else {
  203. lastSignature = view.signature;
  204. stableSince = ready ? now() : null;
  205. }
  206. await delay(250, run);
  207. }
  208. throw new Error(history ? '消息列表滚动后未能确认同一聊天稳定显示,自动采集已暂停' : '聊天切换后未能确认新消息已加载(可能为空聊天或页面结构未识别),已暂停以避免保存上一聊天内容');
  209. }
  210. async function drain(run, requireVerified = false) {
  211. publish({ phase: 'capturing' });
  212. // Queue batches are smaller than a full DOM scan. Retry draining without changing chats.
  213. for (let attempts = 0; attempts < 5; attempts++) {
  214. check(run);
  215. if (requireVerified && !captureContext()) throw new Error('消息列表已离开当前聊天,自动采集已暂停');
  216. let result;
  217. try { result = await abortable(capture(), run); } catch (error) {
  218. if (error === CANCELLED) throw error;
  219. throw new Error('本地数据交付失败,已暂停;请检查本地服务后重新连接');
  220. }
  221. check(run);
  222. if (!result || result.ok !== true || !Number.isInteger(result.pending) || result.pending < 0) throw new Error('本地数据交付失败,已暂停;请检查本地服务后重新连接');
  223. if (result.pending === 0) return;
  224. await delay(250, run);
  225. }
  226. throw new Error('待保存队列未能排空,已暂停自动切换聊天;请检查本地服务后重新连接');
  227. }
  228. async function discover(run) {
  229. publish({ phase: 'discovering' });
  230. navigating = true;
  231. const found = new Map(), errors = [];
  232. let list = findList(errors);
  233. if (!list) throw new Error(errors[0] || '未识别聊天列表;请在采集页打开 Teams 聊天列表,或配置聊天列表选择器');
  234. if (list.scrollTop !== 0 && scrollMax(list) > 0) { list.scrollTop = 0; await delay(350, run); }
  235. let scrolls = 0, capped = false;
  236. for (;;) {
  237. check(run);
  238. list = findList(errors);
  239. if (!list) throw new Error('聊天列表在采集过程中消失,已暂停');
  240. for (const item of rows(list, errors)) {
  241. if (!found.has(item.key) && found.size >= options.maxChats) { capped = true; break; }
  242. // Retain identity and label only: a virtualized row is not a lasting DOM reference.
  243. found.set(item.key, { key: item.key, conversationId: item.conversationId, label: item.label, wasSelected: rowSelected(item.row) || found.get(item.key)?.wasSelected || false });
  244. }
  245. publish({ discovered: found.size });
  246. const max = scrollMax(list), next = Math.min(max, Number(list.scrollTop) + Math.max(Number(list.clientHeight) * 0.8, 200));
  247. if (found.size >= options.maxChats) { capped ||= next > list.scrollTop; break; }
  248. if (scrolls >= options.listScrollPasses || next <= list.scrollTop) break;
  249. list.scrollTop = next;
  250. scrolls++;
  251. await delay(350, run);
  252. }
  253. if (!found.size) throw new Error(errors[0] || '未识别带稳定标识的聊天行;请检查聊天行选择器');
  254. const limited = capped || scrollMax(list) > list.scrollTop;
  255. run.notes = [`本轮最多 ${options.maxChats} 个聊天;列表滚动最多 ${options.listScrollPasses} 次;每个聊天向上滚动最多 ${options.historyScrollPasses} 次`, '仅已发现且可加载的消息,不保证完整历史', ...(limited ? ['已达到聊天数或列表滚动范围限制'] : []), ...[...new Set(errors)].slice(0, 2)];
  256. navigating = false;
  257. return [...found.values()];
  258. }
  259. async function refind(target, run) {
  260. let list = findList();
  261. let match = rows(list).find(item => item.key === target.key);
  262. if (match) return match.row;
  263. if (!list) throw new Error('聊天列表在采集过程中消失,已暂停');
  264. if (list.scrollTop !== 0 && scrollMax(list) > 0) { list.scrollTop = 0; await delay(350, run); }
  265. for (let pass = 0; pass <= options.listScrollPasses; pass++) {
  266. check(run);
  267. list = findList();
  268. if (!list) throw new Error('聊天列表在采集过程中消失,已暂停');
  269. match = rows(list).find(item => item.key === target.key);
  270. if (match) return match.row;
  271. if (pass === options.listScrollPasses) break;
  272. const next = Math.min(scrollMax(list), Number(list.scrollTop) + Math.max(Number(list.clientHeight) * 0.8, 200));
  273. if (next <= list.scrollTop) break;
  274. list.scrollTop = next;
  275. await delay(350, run);
  276. }
  277. return null;
  278. }
  279. async function traverse(run) {
  280. const targets = await discover(run);
  281. const initial = snapshot();
  282. // The initial selected row might still contain the previous chat's DOM after a
  283. // cancelled transition. Visit another conversation first to get fresh evidence.
  284. const uncertain = target => (target.wasSelected || selected(target)) && !explicitScope(target, initial) && !previouslyVerified(target, initial);
  285. targets.sort((left, right) => Number(uncertain(left)) - Number(uncertain(right)));
  286. for (const target of targets) {
  287. check(run);
  288. // Flush the preceding, still verified view before any navigation.
  289. await drain(run);
  290. navigating = true;
  291. const row = await refind(target, run);
  292. check(run);
  293. if (!row || !row.isConnected || identity(row)?.key !== target.key || !safeRow(row, findList())) {
  294. run.notes.push('部分聊天行在虚拟列表中无法重新定位,已跳过');
  295. navigating = false;
  296. continue;
  297. }
  298. const before = snapshot(), alreadySelected = selected(target) && before.keys.length > 0 && (explicitScope(target, before) || previouslyVerified(target, before));
  299. verified = null;
  300. publish({ phase: 'opening' });
  301. if (!alreadySelected) {
  302. uncertainTransition = { key: target.key, keys: new Set(before.keys) };
  303. row.click();
  304. }
  305. check(run);
  306. publish({ phase: 'settling' });
  307. const loaded = await settle(target, before, run, { alreadySelected });
  308. remember(target, loaded);
  309. // A previous pass can leave this chat scrolled into history. Always load the
  310. // newest viewport first; this does not consume the bounded history budget.
  311. if (scrollMax(loaded.pane) > 0 && loaded.pane.scrollTop < scrollMax(loaded.pane)) {
  312. loaded.pane.scrollTop = scrollMax(loaded.pane);
  313. await delay(350, run);
  314. const latest = await settle(target, loaded, run, { history: true });
  315. remember(target, latest, verified.context);
  316. }
  317. navigating = false;
  318. await drain(run, true);
  319. for (let historyPass = 0; historyPass < options.historyScrollPasses; historyPass++) {
  320. check(run);
  321. const view = snapshot(), pane = view.pane;
  322. if (!pane || pane.scrollTop <= 0 || scrollMax(pane) <= 0) break;
  323. const context = captureContext();
  324. if (!context) throw new Error('消息列表已离开当前聊天,自动采集已暂停');
  325. navigating = true;
  326. verified = null;
  327. publish({ phase: 'history' });
  328. pane.scrollTop = Math.max(0, Number(pane.scrollTop) - Math.max(Number(pane.clientHeight) * 0.8, 200));
  329. // Give asynchronous scroll handlers a turn before beginning the stability window.
  330. await delay(350, run);
  331. const historical = await settle(target, view, run, { history: true });
  332. remember(target, historical, context);
  333. navigating = false;
  334. await drain(run, true);
  335. }
  336. publish({ visited: state.visited + 1, coverage: [...new Set(run.notes)].join(';').slice(0, 500) });
  337. }
  338. }
  339. async function tick() {
  340. if (!enabled() || paused || active || (state.nextRunAt && now() < Date.parse(state.nextRunAt))) return status();
  341. const run = { controller: new window.AbortController(), notes: [] };
  342. active = run;
  343. publish({ running: true, phase: 'discovering', visited: 0, discovered: 0, pass: state.pass + 1, nextRunAt: null, error: '', coverage: '' });
  344. try {
  345. await traverse(run);
  346. check(run);
  347. publish({ running: false, phase: 'waiting', nextRunAt: new Date(now() + options.intervalSeconds * 1000).toISOString(), coverage: [...new Set(run.notes)].join(';').slice(0, 500) });
  348. } catch (error) {
  349. if (error !== CANCELLED && active === run) {
  350. paused = true;
  351. verified = null;
  352. publish({ running: false, phase: 'error', nextRunAt: null, error: String(error.message || error).slice(0, 500), coverage: [...new Set(run.notes)].join(';').slice(0, 500) });
  353. }
  354. } finally {
  355. if (active === run) { active = null; navigating = false; }
  356. }
  357. return status();
  358. }
  359. function stop(reason = '自动采集已暂停') {
  360. paused = true;
  361. active?.controller.abort();
  362. navigating = false;
  363. verified = null;
  364. publish({ running: false, phase: enabled() ? 'paused' : 'disabled', nextRunAt: null, error: String(reason || '').slice(0, 500) });
  365. }
  366. function configure(input) {
  367. const next = optionsFor(input), nextFingerprint = JSON.stringify(next);
  368. if (nextFingerprint === fingerprint || disposed) return status();
  369. active?.controller.abort();
  370. verified = null;
  371. navigating = false;
  372. options = next;
  373. fingerprint = nextFingerprint;
  374. paused = false;
  375. publish({ running: false, phase: enabled() ? 'idle' : 'disabled', visited: 0, discovered: 0, nextRunAt: null, error: '', coverage: '' });
  376. return status();
  377. }
  378. // Called only for a user-requested reconnect/configuration action, never a heartbeat.
  379. function resume() {
  380. if (!disposed && (!active || active.controller.signal.aborted) && enabled()) {
  381. paused = false;
  382. publish({ phase: 'idle', running: false, nextRunAt: null, error: '' });
  383. }
  384. return status();
  385. }
  386. const onInteraction = event => { if (event.isTrusted && enabled()) stop('检测到你在采集页操作,自动采集已暂停;请重新连接后继续'); };
  387. document.addEventListener('pointerdown', onInteraction, true);
  388. document.addEventListener('keydown', onInteraction, true);
  389. function dispose() {
  390. if (disposed) return;
  391. disposed = true;
  392. stop('');
  393. document.removeEventListener('pointerdown', onInteraction, true);
  394. document.removeEventListener('keydown', onInteraction, true);
  395. }
  396. return { configure, tick, stop, resume, status, isNavigating: () => navigating, captureContext, dispose, preview };
  397. }