@reconcrap/boss-recommend-mcp 2.0.45 → 2.0.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/bin/boss-recommend-mcp.js +4 -4
  2. package/config/screening-config.example.json +27 -27
  3. package/package.json +1 -1
  4. package/scripts/postinstall.cjs +44 -44
  5. package/skills/boss-chat/README.md +39 -39
  6. package/skills/boss-chat/SKILL.md +93 -93
  7. package/skills/boss-recommend-pipeline/README.md +12 -12
  8. package/skills/boss-recommend-pipeline/SKILL.md +180 -180
  9. package/skills/boss-recruit-pipeline/README.md +17 -17
  10. package/skills/boss-recruit-pipeline/SKILL.md +58 -58
  11. package/src/chat-mcp.js +1780 -1780
  12. package/src/chat-runtime-config.js +749 -749
  13. package/src/cli.js +3054 -3054
  14. package/src/core/boss-cards/index.js +199 -199
  15. package/src/core/browser/index.js +1453 -1446
  16. package/src/core/capture/index.js +1201 -1201
  17. package/src/core/cv-acquisition/index.js +238 -238
  18. package/src/core/cv-capture-target/index.js +299 -299
  19. package/src/core/greet-quota/index.js +54 -54
  20. package/src/core/infinite-list/index.js +1326 -1326
  21. package/src/core/reporting/legacy-csv.js +341 -341
  22. package/src/core/run/timing.js +33 -33
  23. package/src/core/screening/index.js +50 -3
  24. package/src/core/self-heal/index.js +973 -973
  25. package/src/core/self-heal/viewport.js +564 -564
  26. package/src/domains/chat/cards.js +137 -137
  27. package/src/domains/chat/constants.js +221 -221
  28. package/src/domains/chat/detail.js +1668 -1661
  29. package/src/domains/chat/index.js +7 -7
  30. package/src/domains/chat/jobs.js +592 -588
  31. package/src/domains/chat/page-guard.js +98 -98
  32. package/src/domains/chat/roots.js +56 -56
  33. package/src/domains/chat/run-service.js +1977 -1955
  34. package/src/domains/recommend/actions.js +457 -457
  35. package/src/domains/recommend/cards.js +243 -243
  36. package/src/domains/recommend/constants.js +165 -165
  37. package/src/domains/recommend/detail.js +36 -28
  38. package/src/domains/recommend/filters.js +610 -581
  39. package/src/domains/recommend/index.js +10 -10
  40. package/src/domains/recommend/jobs.js +316 -263
  41. package/src/domains/recommend/refresh.js +472 -472
  42. package/src/domains/recommend/roots.js +80 -80
  43. package/src/domains/recommend/run-service.js +75 -35
  44. package/src/domains/recommend/scopes.js +246 -245
  45. package/src/domains/recruit/actions.js +277 -277
  46. package/src/domains/recruit/cards.js +74 -74
  47. package/src/domains/recruit/constants.js +167 -167
  48. package/src/domains/recruit/detail.js +461 -460
  49. package/src/domains/recruit/index.js +9 -9
  50. package/src/domains/recruit/instruction-parser.js +451 -451
  51. package/src/domains/recruit/refresh.js +44 -44
  52. package/src/domains/recruit/roots.js +68 -68
  53. package/src/domains/recruit/run-service.js +1207 -1161
  54. package/src/domains/recruit/search.js +1202 -1149
  55. package/src/recommend-mcp.js +22 -22
  56. package/src/recruit-mcp.js +1338 -1338
@@ -1,1661 +1,1668 @@
1
- import {
2
- clearFocusedInput,
3
- clickNodeCenter,
4
- clickPoint,
5
- getFrameDocumentNodeId,
6
- getAttributesMap,
7
- getNodeBox,
8
- getOuterHTML,
9
- insertText,
10
- pressKey,
11
- querySelectorAll,
12
- sleep
13
- } from "../../core/browser/index.js";
14
- import {
15
- buildScreeningCandidateFromDetail,
16
- htmlToText
17
- } from "../../core/screening/index.js";
18
- import {
19
- CHAT_ACTIVE_CANDIDATE_SELECTORS,
20
- CHAT_ASK_RESUME_BUTTON_SELECTORS,
21
- CHAT_ATTACHMENT_RESUME_BUTTON_SELECTORS,
22
- CHAT_CONFIRM_REQUEST_RESUME_SELECTORS,
23
- CHAT_EDITOR_SELECTORS,
24
- CHAT_MESSAGE_FILTER_SELECTORS,
25
- CHAT_MESSAGE_LIST_SELECTORS,
26
- CHAT_ONLINE_RESUME_BUTTON_SELECTORS,
27
- CHAT_PRIMARY_LABEL_SELECTORS,
28
- CHAT_PROFILE_NETWORK_PATTERNS,
29
- CHAT_RESUME_CLOSE_SELECTORS,
30
- CHAT_RESUME_CONTENT_SELECTORS,
31
- CHAT_RESUME_FAST_MODAL_SELECTORS,
32
- CHAT_RESUME_IFRAME_SELECTORS,
33
- CHAT_RESUME_MODAL_SELECTORS,
34
- CHAT_SEND_BUTTON_SELECTORS
35
- } from "./constants.js";
36
- import {
37
- getChatRoots,
38
- queryFirstAcrossChatRoots
39
- } from "./roots.js";
40
- import {
41
- assertChatShellNotResumeTopLevel,
42
- getChatTopLevelState,
43
- isForbiddenChatResumeTopLevelUrl,
44
- makeForbiddenChatResumeNavigationError
45
- } from "./page-guard.js";
46
-
47
- export const CHAT_UNSAFE_ONLINE_RESUME_LINK_CODE = "CHAT_UNSAFE_ONLINE_RESUME_LINK";
48
-
49
- const CHAT_CONVERSATION_CONTROL_SCOPE_SELECTORS = Object.freeze([
50
- ".conversation-main",
51
- ".conversation-editor",
52
- ".chat-message-list",
53
- ".toolbar-box-right",
54
- ".operate-exchange-left",
55
- ".operate-icon-item",
56
- ".exchange-tooltip",
57
- ".boss-popup__wrapper",
58
- ".boss-dialog",
59
- ".dialog-wrap.active",
60
- ".geek-detail-modal"
61
- ]);
62
-
63
- const CHAT_REQUESTED_RESUME_SCOPE_SELECTORS = Object.freeze([
64
- ".chat-message-list",
65
- ".conversation-editor",
66
- ".conversation-main",
67
- ".toolbar-box-right",
68
- ".operate-exchange-left",
69
- ".operate-icon-item",
70
- ".exchange-tooltip",
71
- ".boss-popup__wrapper",
72
- ".boss-dialog",
73
- ".dialog-wrap.active"
74
- ]);
75
-
76
- export function matchesChatProfileNetwork(url) {
77
- return CHAT_PROFILE_NETWORK_PATTERNS.some((pattern) => pattern.test(String(url || "")));
78
- }
79
-
80
- function looksLikeForbiddenChatResumePath(value = "") {
81
- const normalized = String(value || "");
82
- return isForbiddenChatResumeTopLevelUrl(normalized)
83
- || /(?:^|["'\s=])(?:https?:\/\/[^"'\s>]*zhipin\.com)?\/web\/frame\/c-resume(?:[/?#"' >]|$)/i
84
- .test(normalized);
85
- }
86
-
87
- function extractFirstHtmlAttribute(html = "", names = []) {
88
- const source = String(html || "");
89
- for (const name of names) {
90
- const escaped = String(name).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
91
- const regex = new RegExp(`${escaped}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`, "i");
92
- const match = source.match(regex);
93
- if (match) return match[1] ?? match[2] ?? match[3] ?? "";
94
- }
95
- return "";
96
- }
97
-
98
- export function isUnsafeChatOnlineResumeTarget(target = {}, buttonHTML = "") {
99
- const attributes = target?.attributes || {};
100
- const href = attributes.href
101
- || attributes["data-href"]
102
- || attributes["data-url"]
103
- || attributes.url
104
- || extractFirstHtmlAttribute(buttonHTML, ["href", "data-href", "data-url", "url"]);
105
- return looksLikeForbiddenChatResumePath(href)
106
- || looksLikeForbiddenChatResumePath(buttonHTML);
107
- }
108
-
109
- export function makeUnsafeChatOnlineResumeLinkError(target = {}, buttonHTML = "") {
110
- const href = target?.attributes?.href
111
- || target?.attributes?.["data-href"]
112
- || target?.attributes?.["data-url"]
113
- || extractFirstHtmlAttribute(buttonHTML, ["href", "data-href", "data-url", "url"])
114
- || null;
115
- const error = new Error("CHAT_UNSAFE_ONLINE_RESUME_LINK: refusing to click an online resume link that can navigate the chat tab to /web/frame/c-resume/");
116
- error.code = CHAT_UNSAFE_ONLINE_RESUME_LINK_CODE;
117
- error.href = href;
118
- error.button_selector = target?.selector || null;
119
- error.button_text = htmlToText(buttonHTML).slice(0, 120);
120
- error.button_html_length = String(buttonHTML || "").length;
121
- return error;
122
- }
123
-
124
- export function isUnsafeChatOnlineResumeLinkError(error) {
125
- return error?.code === CHAT_UNSAFE_ONLINE_RESUME_LINK_CODE
126
- || /CHAT_UNSAFE_ONLINE_RESUME_LINK/i.test(String(error?.message || error || ""));
127
- }
128
-
129
- export function createChatProfileNetworkRecorder(client) {
130
- const events = [];
131
- client.Network.responseReceived((event) => {
132
- const url = event?.response?.url || "";
133
- if (!matchesChatProfileNetwork(url)) return;
134
- events.push({
135
- requestId: event.requestId,
136
- url,
137
- status: event.response?.status,
138
- mimeType: event.response?.mimeType,
139
- type: event.type
140
- });
141
- });
142
- if (typeof client.Network.loadingFinished === "function") {
143
- client.Network.loadingFinished((event) => {
144
- const found = events.find((item) => item.requestId === event.requestId);
145
- if (!found) return;
146
- found.loading_finished = true;
147
- found.encodedDataLength = event.encodedDataLength;
148
- });
149
- }
150
- if (typeof client.Network.loadingFailed === "function") {
151
- client.Network.loadingFailed((event) => {
152
- const found = events.find((item) => item.requestId === event.requestId);
153
- if (!found) return;
154
- found.loading_failed = true;
155
- found.loading_error = event.errorText || event.blockedReason || "Network loading failed";
156
- });
157
- }
158
- return {
159
- events,
160
- clear() {
161
- events.length = 0;
162
- }
163
- };
164
- }
165
-
166
- export async function waitForChatProfileNetworkEvents(recorder, {
167
- minCount = 1,
168
- requireLoaded = true,
169
- timeoutMs = 8000,
170
- intervalMs = 120
171
- } = {}) {
172
- const started = Date.now();
173
- const events = Array.isArray(recorder) ? recorder : recorder?.events || [];
174
- let matching = [];
175
- while (Date.now() - started <= timeoutMs) {
176
- matching = events.filter((event) => (
177
- !requireLoaded
178
- || event.loading_finished === true
179
- || event.loading_failed === true
180
- ));
181
- if (matching.length >= minCount) {
182
- return {
183
- ok: true,
184
- elapsed_ms: Date.now() - started,
185
- count: matching.length,
186
- events: matching
187
- };
188
- }
189
- await sleep(intervalMs);
190
- }
191
- return {
192
- ok: false,
193
- elapsed_ms: Date.now() - started,
194
- count: matching.length,
195
- events: matching,
196
- total_event_count: events.length
197
- };
198
- }
199
-
200
- export async function readChatProfileNetworkBodies(client, events = [], {
201
- limit = 20
202
- } = {}) {
203
- const bodies = [];
204
- for (const event of events.slice(0, limit)) {
205
- try {
206
- const body = await client.Network.getResponseBody({ requestId: event.requestId });
207
- bodies.push({
208
- ...event,
209
- body,
210
- body_length: String(body?.body || "").length
211
- });
212
- } catch (error) {
213
- bodies.push({
214
- ...event,
215
- body_error: error?.message || String(error)
216
- });
217
- }
218
- }
219
- return bodies;
220
- }
221
-
222
- function normalizeDetailText(value = "") {
223
- return String(value || "").replace(/\s+/g, " ").trim();
224
- }
225
-
226
- function chatCandidateIdFromAttributes(attributes = {}) {
227
- return normalizeDetailText(
228
- attributes["data-id"]
229
- || attributes["data-geekid"]
230
- || attributes["data-geek"]
231
- || attributes["data-uid"]
232
- || attributes.key
233
- || attributes.id
234
- || ""
235
- );
236
- }
237
-
238
- async function hydrateActiveChatCandidate(client, activeCandidate = null) {
239
- if (!activeCandidate?.node_id) return activeCandidate;
240
- let attributes = {};
241
- let outerHTML = "";
242
- try {
243
- [attributes, outerHTML] = await Promise.all([
244
- getAttributesMap(client, activeCandidate.node_id),
245
- getOuterHTML(client, activeCandidate.node_id)
246
- ]);
247
- } catch {}
248
- return {
249
- ...activeCandidate,
250
- attributes,
251
- candidate_id: chatCandidateIdFromAttributes(attributes) || null,
252
- label: normalizeDetailText(htmlToText(outerHTML)),
253
- outer_html_length: outerHTML.length
254
- };
255
- }
256
-
257
- export async function waitForChatOnlineResumeButton(client, {
258
- timeoutMs = 12000,
259
- intervalMs = 250,
260
- expectedCandidateId = ""
261
- } = {}) {
262
- const started = Date.now();
263
- let lastState = null;
264
- const expectedId = chatCandidateIdFromAttributes({ "data-id": expectedCandidateId });
265
- while (Date.now() - started <= timeoutMs) {
266
- const topLevelState = await getChatTopLevelState(client);
267
- if (topLevelState.is_forbidden_resume_top_level) {
268
- return {
269
- forbidden_top_level_navigation: true,
270
- top_level_state: topLevelState
271
- };
272
- }
273
- const rootState = await getChatRoots(client);
274
- const target = await findVisibleTarget(client, rootState.roots, CHAT_ONLINE_RESUME_BUTTON_SELECTORS);
275
- const activeCandidate = await hydrateActiveChatCandidate(
276
- client,
277
- await queryFirstAcrossChatRoots(client, rootState.roots, CHAT_ACTIVE_CANDIDATE_SELECTORS)
278
- );
279
- const activeCandidateId = activeCandidate?.candidate_id || "";
280
- const candidateSelectionVerified = expectedId
281
- ? activeCandidateId === expectedId
282
- : undefined;
283
- lastState = {
284
- roots: rootState.roots,
285
- target,
286
- activeCandidate,
287
- expected_candidate_id: expectedId || null,
288
- active_candidate_id: activeCandidateId || null,
289
- candidate_selection_verified: candidateSelectionVerified
290
- };
291
- if (target && (!expectedId || candidateSelectionVerified)) {
292
- return {
293
- ok: true,
294
- elapsed_ms: Date.now() - started,
295
- ...lastState
296
- };
297
- }
298
- await sleep(intervalMs);
299
- }
300
- return {
301
- ok: false,
302
- reason: expectedId && lastState?.candidate_selection_verified === false
303
- ? "active_candidate_mismatch"
304
- : "online_resume_button_unavailable",
305
- elapsed_ms: Date.now() - started,
306
- ...lastState
307
- };
308
- }
309
-
310
- export async function selectChatCandidate(client, cardNodeId, {
311
- timeoutMs = 12000,
312
- settleMs = 1200
313
- } = {}) {
314
- const cardBox = await clickNodeCenter(client, cardNodeId, {
315
- scrollIntoView: true
316
- });
317
- if (settleMs > 0) await sleep(settleMs);
318
- const ready = await waitForChatOnlineResumeButton(client, { timeoutMs });
319
- return {
320
- card_box: cardBox,
321
- ready
322
- };
323
- }
324
-
325
- function hasActiveSignal(attributes = {}, outerHTML = "") {
326
- return /\b(active|selected|current|curr)\b/i.test(String(attributes.class || ""))
327
- || normalizeDetailText(attributes["aria-selected"]).toLowerCase() === "true"
328
- || normalizeDetailText(attributes["data-active"]).toLowerCase() === "true"
329
- || /\b(active|selected|current|curr)\b/i.test(String(outerHTML || "").slice(0, 500));
330
- }
331
-
332
- function isDisabledSignal(attributes = {}, outerHTML = "") {
333
- return attributes.disabled !== undefined
334
- || normalizeDetailText(attributes["aria-disabled"]).toLowerCase() === "true"
335
- || /\b(disabled|disable|is-disabled)\b/i.test([
336
- attributes.class,
337
- String(outerHTML || "").slice(0, 500)
338
- ].join(" "));
339
- }
340
-
341
- function isAskResumeText(text = "") {
342
- const normalized = normalizeDetailText(text);
343
- return Boolean(
344
- normalized === "求简历"
345
- || normalized === "索要简历"
346
- || normalized === "求附件简历"
347
- || normalized.includes("求简历")
348
- || normalized.includes("索要简历")
349
- || normalized.includes("求附件简历")
350
- );
351
- }
352
-
353
- function isRequestedResumeText(text = "") {
354
- const normalized = normalizeDetailText(text);
355
- return Boolean(
356
- normalized === "已求简历"
357
- || normalized === "已索要简历"
358
- || normalized.includes("已求简历")
359
- || normalized.includes("已索要简历")
360
- || normalized.includes("简历请求已发送")
361
- || normalized.includes("已发送简历")
362
- || (normalized.includes("已申请") && normalized.includes("简历"))
363
- );
364
- }
365
-
366
- function isResumeRequestSentMessageText(text = "") {
367
- const normalized = normalizeDetailText(text);
368
- return Boolean(
369
- normalized.includes("简历请求已发送")
370
- || normalized.includes("已发送简历")
371
- || normalized.includes("已求简历")
372
- || normalized.includes("已索要简历")
373
- || normalized.includes("已发送")
374
- );
375
- }
376
-
377
- function countTextOccurrences(text = "", needle = "") {
378
- if (!needle) return 0;
379
- let count = 0;
380
- let index = 0;
381
- while (index < text.length) {
382
- const found = text.indexOf(needle, index);
383
- if (found < 0) break;
384
- count += 1;
385
- index = found + needle.length;
386
- }
387
- return count;
388
- }
389
-
390
- function countResumeRequestSentMessageMarkers(lines = []) {
391
- const markers = ["简历请求已发送", "已发送简历", "已求简历", "已索要简历", "已发送"];
392
- return lines.reduce((total, line) => (
393
- total + markers.reduce((lineTotal, marker) => (
394
- lineTotal + countTextOccurrences(line, marker)
395
- ), 0)
396
- ), 0);
397
- }
398
-
399
- function isResumeAttachmentMessageText(text = "") {
400
- const normalized = normalizeDetailText(text);
401
- return Boolean(
402
- /点击.*附件简历/.test(normalized)
403
- || /预览附件简历/.test(normalized)
404
- || /查看附件简历/.test(normalized)
405
- || /(?:简历|resume)[^\s]*\.(?:pdf|docx?|jpg|jpeg|png)\b/i.test(normalized)
406
- );
407
- }
408
-
409
- function countResumeAttachmentMessageMarkers(lines = []) {
410
- return lines.reduce((total, line) => total + (isResumeAttachmentMessageText(line) ? 1 : 0), 0);
411
- }
412
-
413
- function isRequestedResumeControlTarget(target = {}) {
414
- const label = normalizeDetailText(target.label);
415
- const className = String(target.attributes?.class || "");
416
- const selector = String(target.selector || "");
417
- const controlLike = /\boperate-btn\b|operate|resume|button|btn/i.test(`${selector} ${className}`);
418
- if (isRequestedResumeText(label)) return true;
419
- return controlLike && Boolean(
420
- label === "已申请"
421
- || label === "已发送"
422
- || label.includes("已申请")
423
- || label.includes("已发送")
424
- );
425
- }
426
-
427
- function isAttachmentResumeText(text = "") {
428
- const normalized = normalizeDetailText(text);
429
- return Boolean(
430
- normalized === "附件简历"
431
- || (normalized.includes("附件简历") && !normalized.includes("求附件简历"))
432
- );
433
- }
434
-
435
- function isAttachmentResumeTarget(target = {}) {
436
- return isAttachmentResumeText(target.label)
437
- || /resume-btn-file/i.test(String(target.attributes?.class || target.selector || ""));
438
- }
439
-
440
- function isConfirmText(text = "") {
441
- const normalized = normalizeDetailText(text);
442
- return Boolean(
443
- normalized === "确定"
444
- || normalized === "确认"
445
- || normalized === "提交"
446
- || normalized === "继续"
447
- || normalized.includes("确定")
448
- || normalized.includes("确认")
449
- );
450
- }
451
-
452
- function isSendText(text = "") {
453
- const normalized = normalizeDetailText(text);
454
- return normalized === "发送" || normalized.includes("发送");
455
- }
456
-
457
- function isRecoverableNodeError(error) {
458
- return /(?:Could not find node|No node with given id|Cannot find node|Could not compute box model)/i
459
- .test(String(error?.message || error || ""));
460
- }
461
-
462
- async function readTarget(client, root, selector, nodeId) {
463
- let attributes = {};
464
- let outerHTML = "";
465
- let readError = "";
466
- try {
467
- [attributes, outerHTML] = await Promise.all([
468
- getAttributesMap(client, nodeId),
469
- getOuterHTML(client, nodeId)
470
- ]);
471
- } catch (error) {
472
- readError = error?.message || String(error);
473
- }
474
- const label = normalizeDetailText(htmlToText(outerHTML));
475
- let box = null;
476
- try {
477
- box = await getNodeBox(client, nodeId);
478
- } catch {}
479
- return {
480
- root: root.name,
481
- root_node_id: root.nodeId,
482
- selector,
483
- node_id: nodeId,
484
- label,
485
- attributes,
486
- disabled: isDisabledSignal(attributes, outerHTML),
487
- active: hasActiveSignal(attributes, outerHTML),
488
- visible: Boolean(box && box.rect.width > 2 && box.rect.height > 2),
489
- center: box?.center || null,
490
- rect: box?.rect || null,
491
- outer_html_length: outerHTML.length,
492
- read_error: readError || null
493
- };
494
- }
495
-
496
- async function findVisibleMatchingTarget(client, roots, selectors, predicate) {
497
- for (const root of roots) {
498
- if (!root?.nodeId) continue;
499
- for (const selector of selectors) {
500
- const nodeIds = await querySelectorAll(client, root.nodeId, selector);
501
- for (const nodeId of nodeIds) {
502
- const target = await readTarget(client, root, selector, nodeId);
503
- if (!target.visible) continue;
504
- if (predicate(target)) return target;
505
- }
506
- }
507
- }
508
- return null;
509
- }
510
-
511
- async function resolveScopedRoots(client, roots = [], selectors = [], {
512
- fallbackToRoots = true
513
- } = {}) {
514
- const scoped = [];
515
- const seen = new Set();
516
- for (const root of roots) {
517
- if (!root?.nodeId) continue;
518
- for (const selector of selectors) {
519
- let nodeIds = [];
520
- try {
521
- nodeIds = await querySelectorAll(client, root.nodeId, selector);
522
- } catch {
523
- nodeIds = [];
524
- }
525
- for (const nodeId of nodeIds) {
526
- const key = `${root.name}:${nodeId}`;
527
- if (seen.has(key)) continue;
528
- seen.add(key);
529
- scoped.push({
530
- name: `${root.name}:${selector}`,
531
- nodeId
532
- });
533
- }
534
- }
535
- }
536
- if (scoped.length || !fallbackToRoots) return scoped;
537
- return roots;
538
- }
539
-
540
- export async function selectChatPrimaryLabel(client, {
541
- label = "全部",
542
- timeoutMs = 8000,
543
- intervalMs = 300,
544
- settleMs = 700
545
- } = {}) {
546
- const started = Date.now();
547
- let lastCandidates = [];
548
- while (Date.now() - started <= timeoutMs) {
549
- const rootState = await getChatRoots(client);
550
- const candidates = [];
551
- for (const root of rootState.roots) {
552
- for (const selector of CHAT_PRIMARY_LABEL_SELECTORS) {
553
- const nodeIds = await querySelectorAll(client, root.nodeId, selector);
554
- for (const nodeId of nodeIds) {
555
- const target = await readTarget(client, root, selector, nodeId);
556
- if (target.visible) candidates.push(target);
557
- }
558
- }
559
- }
560
- lastCandidates = candidates;
561
- const matched = candidates.find((target) => (
562
- target.label === label || target.label.startsWith(`${label}(`)
563
- ));
564
- if (matched?.active) {
565
- return {
566
- ok: true,
567
- changed: false,
568
- verified: true,
569
- active_label: matched.label,
570
- control: matched
571
- };
572
- }
573
- if (matched) {
574
- if (matched.center) {
575
- await clickPoint(client, matched.center.x, matched.center.y);
576
- } else {
577
- await clickNodeCenter(client, matched.node_id, { scrollIntoView: true });
578
- }
579
- if (settleMs > 0) await sleep(settleMs);
580
- return {
581
- ok: true,
582
- changed: true,
583
- verified: true,
584
- active_label: label,
585
- control: matched
586
- };
587
- }
588
- await sleep(intervalMs);
589
- }
590
- return {
591
- ok: false,
592
- error: `CHAT_PRIMARY_LABEL_NOT_FOUND:${label}`,
593
- candidates: lastCandidates.map((item) => ({
594
- label: item.label,
595
- selector: item.selector,
596
- active: item.active
597
- }))
598
- };
599
- }
600
-
601
- export async function selectChatMessageFilter(client, {
602
- startFrom = "unread",
603
- timeoutMs = 8000,
604
- intervalMs = 300,
605
- settleMs = 900
606
- } = {}) {
607
- const label = startFrom === "all" ? "全部" : "未读";
608
- const started = Date.now();
609
- let lastCandidates = [];
610
- while (Date.now() - started <= timeoutMs) {
611
- const rootState = await getChatRoots(client);
612
- const candidates = [];
613
- for (const root of rootState.roots) {
614
- for (const selector of CHAT_MESSAGE_FILTER_SELECTORS) {
615
- const nodeIds = await querySelectorAll(client, root.nodeId, selector);
616
- for (const nodeId of nodeIds) {
617
- const target = await readTarget(client, root, selector, nodeId);
618
- if (target.visible && target.label === label) candidates.push(target);
619
- }
620
- }
621
- }
622
- lastCandidates = candidates;
623
- const active = candidates.find((target) => target.active);
624
- if (active) {
625
- return {
626
- ok: true,
627
- changed: false,
628
- verified: true,
629
- active_label: active.label,
630
- control: active
631
- };
632
- }
633
- const matched = candidates[0];
634
- if (matched) {
635
- if (matched.center) {
636
- await clickPoint(client, matched.center.x, matched.center.y);
637
- } else {
638
- await clickNodeCenter(client, matched.node_id, { scrollIntoView: true });
639
- }
640
- if (settleMs > 0) await sleep(settleMs);
641
- return {
642
- ok: true,
643
- changed: true,
644
- verified: true,
645
- active_label: label,
646
- control: matched
647
- };
648
- }
649
- await sleep(intervalMs);
650
- }
651
- return {
652
- ok: false,
653
- error: `CHAT_MESSAGE_FILTER_NOT_FOUND:${label}`,
654
- candidates: lastCandidates.map((item) => ({
655
- label: item.label,
656
- selector: item.selector,
657
- active: item.active
658
- }))
659
- };
660
- }
661
-
662
- export async function waitForChatResumeModal(client, {
663
- timeoutMs = 12000,
664
- intervalMs = 250
665
- } = {}) {
666
- const started = Date.now();
667
- let lastState = null;
668
- while (Date.now() - started <= timeoutMs) {
669
- const topLevelState = await getChatTopLevelState(client);
670
- if (topLevelState.is_forbidden_resume_top_level) {
671
- return {
672
- forbidden_top_level_navigation: true,
673
- top_level_state: topLevelState
674
- };
675
- }
676
- const rootState = await getChatRoots(client);
677
- const popup = await findVisibleTarget(client, rootState.roots, CHAT_RESUME_MODAL_SELECTORS);
678
- const content = await findVisibleTarget(client, rootState.roots, CHAT_RESUME_CONTENT_SELECTORS);
679
- const resumeIframe = await findVisibleTarget(client, rootState.roots, CHAT_RESUME_IFRAME_SELECTORS);
680
- lastState = {
681
- roots: rootState.roots,
682
- popup,
683
- content,
684
- resumeIframe
685
- };
686
- if (popup || content || resumeIframe) return lastState;
687
- await sleep(intervalMs);
688
- }
689
- return lastState;
690
- }
691
-
692
- export async function quickChatResumeModalOpenProbe(client, {
693
- selectors = CHAT_RESUME_FAST_MODAL_SELECTORS
694
- } = {}) {
695
- const rootState = await getChatRoots(client);
696
- for (const root of rootState.roots) {
697
- if (!root?.nodeId) continue;
698
- for (const selector of selectors) {
699
- let nodeIds = [];
700
- try {
701
- nodeIds = await querySelectorAll(client, root.nodeId, selector);
702
- } catch {
703
- nodeIds = [];
704
- }
705
- for (const nodeId of nodeIds.slice(0, 4)) {
706
- try {
707
- const box = await getNodeBox(client, nodeId);
708
- if (box?.rect?.width > 8 && box?.rect?.height > 8) {
709
- return {
710
- open: true,
711
- root: root.name,
712
- selector,
713
- node_id: nodeId,
714
- rect: box.rect,
715
- center: box.center
716
- };
717
- }
718
- } catch {
719
- // Hidden or stale modal probes are ignored.
720
- }
721
- }
722
- }
723
- }
724
- return {
725
- open: false
726
- };
727
- }
728
-
729
- export async function readChatResumeHtml(client, resumeState) {
730
- let popupHTML = "";
731
- let contentHTML = "";
732
- let resumeIframeHTML = "";
733
- let resumeIframeDocumentNodeId = null;
734
-
735
- if (resumeState?.popup?.node_id) {
736
- popupHTML = await getOuterHTML(client, resumeState.popup.node_id);
737
- }
738
-
739
- if (resumeState?.content?.node_id && resumeState.content.node_id !== resumeState?.popup?.node_id) {
740
- contentHTML = await getOuterHTML(client, resumeState.content.node_id);
741
- }
742
-
743
- if (resumeState?.resumeIframe?.node_id) {
744
- resumeIframeDocumentNodeId = await getFrameDocumentNodeId(client, resumeState.resumeIframe.node_id);
745
- resumeIframeHTML = await getOuterHTML(client, resumeIframeDocumentNodeId);
746
- }
747
-
748
- return {
749
- popupHTML,
750
- contentHTML,
751
- resumeIframeHTML,
752
- resumeIframeDocumentNodeId,
753
- popupText: htmlToText(popupHTML),
754
- contentText: htmlToText(contentHTML),
755
- resumeIframeText: htmlToText(resumeIframeHTML)
756
- };
757
- }
758
-
759
- function emptyChatResumeHtml(readError = null) {
760
- return {
761
- popupHTML: "",
762
- contentHTML: "",
763
- resumeIframeHTML: "",
764
- resumeIframeDocumentNodeId: null,
765
- popupText: "",
766
- contentText: "",
767
- resumeIframeText: "",
768
- readError: readError?.message || null
769
- };
770
- }
771
-
772
- export async function waitForChatResumeContent(client, {
773
- minTextLength = 120,
774
- timeoutMs = 15000,
775
- intervalMs = 250
776
- } = {}) {
777
- const started = Date.now();
778
- let lastState = null;
779
- let lastHtml = null;
780
- let lastError = null;
781
- while (Date.now() - started <= timeoutMs) {
782
- try {
783
- lastState = await waitForChatResumeModal(client, {
784
- timeoutMs: 700,
785
- intervalMs: 100
786
- });
787
- if (lastState?.popup || lastState?.content || lastState?.resumeIframe) {
788
- lastHtml = await readChatResumeHtml(client, lastState);
789
- const textLength = [
790
- lastHtml.popupText,
791
- lastHtml.contentText,
792
- lastHtml.resumeIframeText
793
- ].join("\n").length;
794
- if (textLength >= minTextLength) {
795
- return {
796
- ok: true,
797
- elapsed_ms: Date.now() - started,
798
- text_length: textLength,
799
- resume_state: lastState,
800
- resume_html: lastHtml
801
- };
802
- }
803
- }
804
- } catch (error) {
805
- lastError = error;
806
- }
807
- await sleep(intervalMs);
808
- }
809
-
810
- const textLength = [
811
- lastHtml?.popupText,
812
- lastHtml?.contentText,
813
- lastHtml?.resumeIframeText
814
- ].filter(Boolean).join("\n").length;
815
- return {
816
- ok: false,
817
- elapsed_ms: Date.now() - started,
818
- text_length: textLength,
819
- resume_state: lastState,
820
- resume_html: lastHtml,
821
- error: lastError?.message || null
822
- };
823
- }
824
-
825
- export async function openChatOnlineResume(client, {
826
- timeoutMs = 15000,
827
- attemptsLimit = 3,
828
- settleMs = 1200
829
- } = {}) {
830
- const attempts = [];
831
- for (let index = 0; index < attemptsLimit; index += 1) {
832
- if (settleMs > 0) await sleep(settleMs);
833
- await assertChatShellNotResumeTopLevel(client, {
834
- context: "openChatOnlineResume:before_existing_modal_check"
835
- });
836
- const existingResumeState = await waitForChatResumeModal(client, {
837
- timeoutMs: 500,
838
- intervalMs: 100
839
- });
840
- if (existingResumeState?.forbidden_top_level_navigation) {
841
- throw makeForbiddenChatResumeNavigationError(existingResumeState.top_level_state);
842
- }
843
- if (
844
- existingResumeState?.popup
845
- || existingResumeState?.content
846
- || existingResumeState?.resumeIframe
847
- ) {
848
- attempts.push({
849
- attempt: index + 1,
850
- ok: true,
851
- reused_existing_modal: true,
852
- resume_popup_selector: existingResumeState?.popup?.selector || null,
853
- resume_content_selector: existingResumeState?.content?.selector || null,
854
- resume_iframe_selector: existingResumeState?.resumeIframe?.selector || null
855
- });
856
- return {
857
- button: null,
858
- button_html: "",
859
- resume_state: existingResumeState,
860
- attempts
861
- };
862
- }
863
-
864
- const buttonState = await waitForChatOnlineResumeButton(client, {
865
- timeoutMs: Math.min(timeoutMs, 8000)
866
- });
867
- if (!buttonState?.target?.node_id) {
868
- attempts.push({
869
- attempt: index + 1,
870
- ok: false,
871
- error: "ONLINE_RESUME_BUTTON_NOT_FOUND"
872
- });
873
- continue;
874
- }
875
-
876
- let buttonHTML = "";
877
- try {
878
- buttonHTML = await getOuterHTML(client, buttonState.target.node_id);
879
- } catch {}
880
-
881
- if (isUnsafeChatOnlineResumeTarget(buttonState.target, buttonHTML)) {
882
- const error = makeUnsafeChatOnlineResumeLinkError(buttonState.target, buttonHTML);
883
- attempts.push({
884
- attempt: index + 1,
885
- ok: false,
886
- error: error.code,
887
- blocked_pre_click: true,
888
- button_selector: buttonState.target.selector,
889
- button_text: error.button_text,
890
- button_href: error.href,
891
- button_html_length: buttonHTML.length
892
- });
893
- error.attempts = attempts;
894
- throw error;
895
- }
896
-
897
- try {
898
- if (buttonState.target.center) {
899
- await clickPoint(client, buttonState.target.center.x, buttonState.target.center.y);
900
- } else {
901
- await clickNodeCenter(client, buttonState.target.node_id, {
902
- scrollIntoView: true
903
- });
904
- }
905
- } catch (error) {
906
- attempts.push({
907
- attempt: index + 1,
908
- ok: false,
909
- error: error?.message || String(error),
910
- recoverable_stale_node: isRecoverableNodeError(error),
911
- button_selector: buttonState.target.selector,
912
- button_text: htmlToText(buttonHTML).slice(0, 120),
913
- button_html_length: buttonHTML.length
914
- });
915
- if (isRecoverableNodeError(error)) {
916
- await sleep(350);
917
- continue;
918
- }
919
- throw error;
920
- }
921
- await assertChatShellNotResumeTopLevel(client, {
922
- context: "openChatOnlineResume:after_online_resume_click"
923
- });
924
- const resumeState = await waitForChatResumeModal(client, {
925
- timeoutMs: Math.max(2500, Math.floor(timeoutMs / attemptsLimit))
926
- });
927
- if (resumeState?.forbidden_top_level_navigation) {
928
- throw makeForbiddenChatResumeNavigationError(resumeState.top_level_state);
929
- }
930
- attempts.push({
931
- attempt: index + 1,
932
- ok: Boolean(resumeState?.popup || resumeState?.content || resumeState?.resumeIframe),
933
- button_selector: buttonState.target.selector,
934
- button_text: htmlToText(buttonHTML).slice(0, 120),
935
- button_html_length: buttonHTML.length,
936
- resume_popup_selector: resumeState?.popup?.selector || null,
937
- resume_content_selector: resumeState?.content?.selector || null,
938
- resume_iframe_selector: resumeState?.resumeIframe?.selector || null
939
- });
940
- if (resumeState?.popup || resumeState?.content || resumeState?.resumeIframe) {
941
- return {
942
- button: buttonState.target,
943
- button_html: buttonHTML,
944
- resume_state: resumeState,
945
- attempts
946
- };
947
- }
948
- }
949
-
950
- const error = new Error("Chat online resume modal did not open");
951
- error.attempts = attempts;
952
- throw error;
953
- }
954
-
955
- export async function readChatConversationReadyState(client) {
956
- const rootState = await getChatRoots(client);
957
- const scopedControlRoots = await resolveScopedRoots(
958
- client,
959
- rootState.roots,
960
- CHAT_CONVERSATION_CONTROL_SCOPE_SELECTORS,
961
- { fallbackToRoots: false }
962
- );
963
- const scopedRequestedRoots = await resolveScopedRoots(
964
- client,
965
- rootState.roots,
966
- CHAT_REQUESTED_RESUME_SCOPE_SELECTORS,
967
- { fallbackToRoots: false }
968
- );
969
- const controlRoots = scopedControlRoots.length ? scopedControlRoots : rootState.roots;
970
- const requestedRoots = scopedRequestedRoots.length ? scopedRequestedRoots : rootState.roots;
971
- const onlineResume = await findVisibleMatchingTarget(
972
- client,
973
- controlRoots,
974
- CHAT_ONLINE_RESUME_BUTTON_SELECTORS,
975
- (target) => target.label.includes("在线简历") && !target.disabled
976
- );
977
- const attachmentResume = await findVisibleMatchingTarget(
978
- client,
979
- controlRoots,
980
- CHAT_ATTACHMENT_RESUME_BUTTON_SELECTORS,
981
- (target) => isAttachmentResumeText(target.label)
982
- );
983
- const askResume = await findVisibleMatchingTarget(
984
- client,
985
- controlRoots,
986
- CHAT_ASK_RESUME_BUTTON_SELECTORS,
987
- (target) => isAskResumeText(target.label) && !isAttachmentResumeTarget(target)
988
- );
989
- const requestedResume = await findVisibleMatchingTarget(
990
- client,
991
- requestedRoots,
992
- CHAT_ASK_RESUME_BUTTON_SELECTORS,
993
- (target) => isRequestedResumeControlTarget(target)
994
- );
995
- const editor = await findVisibleMatchingTarget(
996
- client,
997
- controlRoots,
998
- CHAT_EDITOR_SELECTORS,
999
- () => true
1000
- );
1001
- const sendButton = await findVisibleMatchingTarget(
1002
- client,
1003
- controlRoots,
1004
- CHAT_SEND_BUTTON_SELECTORS,
1005
- (target) => isSendText(target.label) || /submit/i.test(String(target.attributes?.class || ""))
1006
- );
1007
- const resumeState = await waitForChatResumeModal(client, { timeoutMs: 300 });
1008
- return {
1009
- has_online_resume: Boolean(onlineResume),
1010
- online_resume: onlineResume,
1011
- has_ask_resume: Boolean(askResume),
1012
- ask_resume: askResume,
1013
- already_requested_resume: Boolean(requestedResume),
1014
- requested_resume: requestedResume,
1015
- has_attachment_resume: Boolean(attachmentResume),
1016
- attachment_resume_enabled: Boolean(attachmentResume && !attachmentResume.disabled),
1017
- attachment_resume: attachmentResume,
1018
- editor_visible: Boolean(editor),
1019
- editor,
1020
- send_button_visible: Boolean(sendButton),
1021
- send_button: sendButton,
1022
- resume_modal_open: Boolean(resumeState?.popup || resumeState?.content || resumeState?.resumeIframe),
1023
- panels_closed: !Boolean(resumeState?.popup || resumeState?.content || resumeState?.resumeIframe)
1024
- };
1025
- }
1026
-
1027
- export async function setChatEditorMessage(client, message, {
1028
- timeoutMs = 8000
1029
- } = {}) {
1030
- const started = Date.now();
1031
- let lastState = null;
1032
- while (Date.now() - started <= timeoutMs) {
1033
- const state = await readChatConversationReadyState(client);
1034
- lastState = state;
1035
- if (state.editor?.node_id) {
1036
- try {
1037
- if (state.editor.center) {
1038
- await clickPoint(client, state.editor.center.x, state.editor.center.y);
1039
- } else {
1040
- await clickNodeCenter(client, state.editor.node_id, { scrollIntoView: true });
1041
- }
1042
- await sleep(120);
1043
- await clearFocusedInput(client);
1044
- await sleep(80);
1045
- await insertText(client, message);
1046
- await sleep(250);
1047
- const afterState = await readChatConversationReadyState(client);
1048
- const editorText = normalizeDetailText(afterState.editor?.label || "");
1049
- if (editorText.includes(normalizeDetailText(message))) {
1050
- return {
1051
- ok: true,
1052
- value: editorText,
1053
- editor: afterState.editor || state.editor
1054
- };
1055
- }
1056
- lastState = {
1057
- ...afterState,
1058
- editor_message_mismatch: true,
1059
- editor_text: editorText
1060
- };
1061
- } catch (error) {
1062
- if (!isRecoverableNodeError(error)) throw error;
1063
- lastState = {
1064
- ...state,
1065
- recoverable_error: error?.message || String(error),
1066
- recoverable_phase: "set_editor_message"
1067
- };
1068
- }
1069
- }
1070
- await sleep(250);
1071
- }
1072
- return {
1073
- ok: false,
1074
- error: "CHAT_EDITOR_NOT_FOUND",
1075
- state: lastState
1076
- };
1077
- }
1078
-
1079
- export async function sendChatMessage(client, expectedText = "", {
1080
- timeoutMs = 8000,
1081
- settleMs = 800
1082
- } = {}) {
1083
- const started = Date.now();
1084
- let lastState = null;
1085
- while (Date.now() - started <= timeoutMs) {
1086
- const state = await readChatConversationReadyState(client);
1087
- lastState = state;
1088
- if (state.send_button?.node_id && !state.send_button.disabled) {
1089
- try {
1090
- if (state.send_button.center) {
1091
- await clickPoint(client, state.send_button.center.x, state.send_button.center.y);
1092
- } else {
1093
- await clickNodeCenter(client, state.send_button.node_id, { scrollIntoView: true });
1094
- }
1095
- if (settleMs > 0) await sleep(settleMs);
1096
- return {
1097
- sent: true,
1098
- method: "send-button",
1099
- control: state.send_button,
1100
- expected_text: expectedText
1101
- };
1102
- } catch (error) {
1103
- if (!isRecoverableNodeError(error)) throw error;
1104
- lastState = {
1105
- ...state,
1106
- recoverable_error: error?.message || String(error),
1107
- recoverable_phase: "send_button_click"
1108
- };
1109
- await sleep(250);
1110
- continue;
1111
- }
1112
- }
1113
- if (state.editor?.node_id) {
1114
- await pressKey(client, "Enter", {
1115
- code: "Enter",
1116
- windowsVirtualKeyCode: 13,
1117
- nativeVirtualKeyCode: 13
1118
- });
1119
- if (settleMs > 0) await sleep(settleMs);
1120
- return {
1121
- sent: true,
1122
- method: "enter",
1123
- expected_text: expectedText
1124
- };
1125
- }
1126
- await sleep(250);
1127
- }
1128
- return {
1129
- sent: false,
1130
- method: "none",
1131
- error: "CHAT_SEND_CONTROL_NOT_FOUND",
1132
- state: lastState
1133
- };
1134
- }
1135
-
1136
- export async function clickChatAskResume(client, {
1137
- timeoutMs = 8000,
1138
- settleMs = 700
1139
- } = {}) {
1140
- const started = Date.now();
1141
- let lastState = null;
1142
- let lastDisabledAskResume = null;
1143
- while (Date.now() - started <= timeoutMs) {
1144
- const state = await readChatConversationReadyState(client);
1145
- lastState = state;
1146
- if (state.attachment_resume_enabled) {
1147
- return {
1148
- ok: true,
1149
- already_requested: true,
1150
- attachment_resume_available: true,
1151
- control: state.attachment_resume
1152
- };
1153
- }
1154
- if (state.ask_resume?.node_id && !state.ask_resume.disabled) {
1155
- try {
1156
- if (state.ask_resume.center) {
1157
- await clickPoint(client, state.ask_resume.center.x, state.ask_resume.center.y);
1158
- } else {
1159
- await clickNodeCenter(client, state.ask_resume.node_id, { scrollIntoView: true });
1160
- }
1161
- if (settleMs > 0) await sleep(settleMs);
1162
- return {
1163
- ok: true,
1164
- already_requested: false,
1165
- control: state.ask_resume
1166
- };
1167
- } catch (error) {
1168
- if (!isRecoverableNodeError(error)) throw error;
1169
- lastState = {
1170
- ...state,
1171
- recoverable_error: error?.message || String(error),
1172
- recoverable_phase: "ask_resume_click"
1173
- };
1174
- }
1175
- }
1176
- if (state.ask_resume?.node_id && state.ask_resume.disabled) {
1177
- lastDisabledAskResume = state.ask_resume;
1178
- }
1179
- if (state.already_requested_resume) {
1180
- return {
1181
- ok: true,
1182
- already_requested: true,
1183
- control: state.requested_resume
1184
- };
1185
- }
1186
- await sleep(250);
1187
- }
1188
- if (lastDisabledAskResume) {
1189
- return {
1190
- ok: false,
1191
- already_requested: true,
1192
- request_pending: true,
1193
- error: "ASK_RESUME_BUTTON_DISABLED",
1194
- control: lastDisabledAskResume,
1195
- state: lastState
1196
- };
1197
- }
1198
- return {
1199
- ok: false,
1200
- error: "ASK_RESUME_BUTTON_NOT_FOUND",
1201
- state: lastState
1202
- };
1203
- }
1204
-
1205
- export async function clickChatConfirmRequestResume(client, {
1206
- timeoutMs = 8000,
1207
- settleMs = 900
1208
- } = {}) {
1209
- const started = Date.now();
1210
- let lastTarget = null;
1211
- let lastState = null;
1212
- while (Date.now() - started <= timeoutMs) {
1213
- lastState = await readChatConversationReadyState(client);
1214
- const rootState = await getChatRoots(client);
1215
- const confirmRoots = await resolveScopedRoots(
1216
- client,
1217
- rootState.roots,
1218
- CHAT_CONVERSATION_CONTROL_SCOPE_SELECTORS
1219
- );
1220
- const target = await findVisibleMatchingTarget(
1221
- client,
1222
- confirmRoots,
1223
- CHAT_CONFIRM_REQUEST_RESUME_SELECTORS,
1224
- (item) => isConfirmText(item.label) && !item.disabled
1225
- );
1226
- lastTarget = target;
1227
- if (target?.node_id) {
1228
- try {
1229
- if (target.center) {
1230
- await clickPoint(client, target.center.x, target.center.y);
1231
- } else {
1232
- await clickNodeCenter(client, target.node_id, { scrollIntoView: true });
1233
- }
1234
- if (settleMs > 0) await sleep(settleMs);
1235
- const afterState = await readChatConversationReadyState(client);
1236
- return {
1237
- confirmed: true,
1238
- assumed_requested: Boolean(afterState.already_requested_resume),
1239
- control: target,
1240
- state: afterState
1241
- };
1242
- } catch (error) {
1243
- if (!isRecoverableNodeError(error)) throw error;
1244
- lastTarget = {
1245
- ...target,
1246
- recoverable_error: error?.message || String(error),
1247
- recoverable_phase: "confirm_request_resume_click"
1248
- };
1249
- }
1250
- }
1251
- await sleep(250);
1252
- }
1253
- return {
1254
- confirmed: false,
1255
- error: "CONFIRM_BUTTON_NOT_FOUND",
1256
- control: lastTarget,
1257
- state: lastState
1258
- };
1259
- }
1260
-
1261
- export async function getChatResumeRequestMessageState(client) {
1262
- const rootState = await getChatRoots(client);
1263
- let messageRoot = null;
1264
- for (const root of rootState.roots) {
1265
- for (const selector of CHAT_MESSAGE_LIST_SELECTORS) {
1266
- const nodeIds = await querySelectorAll(client, root.nodeId, selector);
1267
- if (nodeIds.length) {
1268
- messageRoot = {
1269
- root,
1270
- selector,
1271
- node_id: nodeIds[0]
1272
- };
1273
- break;
1274
- }
1275
- }
1276
- if (messageRoot) break;
1277
- }
1278
- const nodeId = messageRoot?.node_id || rootState.rootNodes.top;
1279
- let text = "";
1280
- try {
1281
- text = htmlToText(await getOuterHTML(client, nodeId));
1282
- } catch {}
1283
- const lines = text.split(/\r?\n/).map(normalizeDetailText).filter(Boolean);
1284
- const matching = lines.filter((line) => isResumeRequestSentMessageText(line));
1285
- const attachmentMatching = lines.filter((line) => isResumeAttachmentMessageText(line));
1286
- const count = countResumeRequestSentMessageMarkers(lines);
1287
- const resumeAttachmentCount = countResumeAttachmentMessageMarkers(lines);
1288
- return {
1289
- ok: Boolean(text),
1290
- selector: messageRoot?.selector || "top",
1291
- count,
1292
- resume_attachment_count: resumeAttachmentCount,
1293
- success_count: count + resumeAttachmentCount,
1294
- last_text: matching[matching.length - 1] || lines[lines.length - 1] || "",
1295
- last_resume_attachment_text: attachmentMatching[attachmentMatching.length - 1] || "",
1296
- last_success_text: matching[matching.length - 1] || attachmentMatching[attachmentMatching.length - 1] || "",
1297
- recent: lines.slice(-12)
1298
- };
1299
- }
1300
-
1301
- export async function waitForChatResumeRequestMessage(client, {
1302
- baselineCount = 0,
1303
- baselineResumeAttachmentCount = 0,
1304
- timeoutMs = 6500,
1305
- intervalMs = 260
1306
- } = {}) {
1307
- const started = Date.now();
1308
- let state = null;
1309
- while (Date.now() - started <= timeoutMs) {
1310
- state = await getChatResumeRequestMessageState(client);
1311
- const observed = (
1312
- state.count > baselineCount
1313
- || state.resume_attachment_count > baselineResumeAttachmentCount
1314
- );
1315
- if (observed) {
1316
- return {
1317
- observed: true,
1318
- elapsed_ms: Date.now() - started,
1319
- state
1320
- };
1321
- }
1322
- await sleep(intervalMs);
1323
- }
1324
- return {
1325
- observed: false,
1326
- elapsed_ms: Date.now() - started,
1327
- state
1328
- };
1329
- }
1330
-
1331
- export async function requestChatResumeForPassedCandidate(client, {
1332
- greetingText = "Hi同学,能麻烦发下简历吗?",
1333
- maxAttempts = 3,
1334
- askResumeTimeoutMs = 8000,
1335
- dryRun = false
1336
- } = {}) {
1337
- const effectiveGreetingText = normalizeDetailText(greetingText) || "Hi同学,能麻烦发下简历吗?";
1338
- const initialState = await readChatConversationReadyState(client);
1339
- if (initialState.attachment_resume_enabled) {
1340
- return {
1341
- requested: false,
1342
- skipped: true,
1343
- reason: "attachment_resume_already_available",
1344
- initial_state: initialState
1345
- };
1346
- }
1347
- if (dryRun) {
1348
- return {
1349
- requested: false,
1350
- skipped: false,
1351
- reason: "dry_run",
1352
- initial_state: initialState,
1353
- would_send_greeting: true,
1354
- would_click_ask_resume: true
1355
- };
1356
- }
1357
-
1358
- const closeBeforeGreeting = await closeChatResumeModal(client, { attemptsLimit: 3 });
1359
- if (!closeBeforeGreeting.closed) {
1360
- return {
1361
- requested: false,
1362
- skipped: true,
1363
- reason: "resume_modal_close_failed_before_request",
1364
- initial_state: initialState,
1365
- close_before_greeting: closeBeforeGreeting
1366
- };
1367
- }
1368
- const editorState = await setChatEditorMessage(client, effectiveGreetingText);
1369
- if (!editorState.ok) {
1370
- throw new Error("CHAT_EDITOR_MESSAGE_MISMATCH");
1371
- }
1372
- const sendResult = await sendChatMessage(client, effectiveGreetingText);
1373
- if (!sendResult.sent) {
1374
- throw new Error(`CHAT_GREETING_SEND_FAILED:${sendResult.error || sendResult.method || "unknown"}`);
1375
- }
1376
-
1377
- const attempts = [];
1378
- for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
1379
- const before = await getChatResumeRequestMessageState(client);
1380
- const askResult = await clickChatAskResume(client, {
1381
- timeoutMs: askResumeTimeoutMs
1382
- });
1383
- let confirmResult = {
1384
- confirmed: false,
1385
- assumed_requested: Boolean(askResult.already_requested),
1386
- skipped: true,
1387
- reason: askResult.attachment_resume_available
1388
- ? "attachment_resume_already_available"
1389
- : askResult.request_pending
1390
- ? "resume_request_already_pending"
1391
- : askResult.ok
1392
- ? "already_requested"
1393
- : (askResult.error || "ask_resume_not_clicked")
1394
- };
1395
- if (askResult.attachment_resume_available) {
1396
- attempts.push({
1397
- attempt: attempt + 1,
1398
- ask_result: askResult,
1399
- confirm_result: confirmResult,
1400
- message_before_count: before.count,
1401
- message_after_count: before.count,
1402
- message_observed: false,
1403
- message_last_text: before.last_text || ""
1404
- });
1405
- return {
1406
- requested: false,
1407
- skipped: true,
1408
- reason: "attachment_resume_already_available",
1409
- initial_state: initialState,
1410
- close_before_greeting: closeBeforeGreeting,
1411
- greeting_sent: true,
1412
- greeting_send_result: sendResult,
1413
- attempts
1414
- };
1415
- }
1416
- if (askResult.request_pending || askResult.already_requested) {
1417
- attempts.push({
1418
- attempt: attempt + 1,
1419
- ask_result: askResult,
1420
- confirm_result: confirmResult,
1421
- message_before_count: before.count,
1422
- message_after_count: before.count,
1423
- resume_attachment_before_count: before.resume_attachment_count || 0,
1424
- resume_attachment_after_count: before.resume_attachment_count || 0,
1425
- message_observed: false,
1426
- message_last_text: before.last_success_text || before.last_text || ""
1427
- });
1428
- return {
1429
- requested: false,
1430
- skipped: true,
1431
- reason: "resume_request_already_pending",
1432
- initial_state: initialState,
1433
- close_before_greeting: closeBeforeGreeting,
1434
- greeting_sent: true,
1435
- greeting_send_result: sendResult,
1436
- attempts
1437
- };
1438
- }
1439
- if (askResult.ok && !askResult.already_requested) {
1440
- confirmResult = await clickChatConfirmRequestResume(client);
1441
- }
1442
- const messageCheck = await waitForChatResumeRequestMessage(client, {
1443
- baselineCount: before.count,
1444
- baselineResumeAttachmentCount: before.resume_attachment_count
1445
- });
1446
- const messageObserved = Boolean(messageCheck.observed);
1447
- attempts.push({
1448
- attempt: attempt + 1,
1449
- ask_result: askResult,
1450
- confirm_result: confirmResult,
1451
- message_before_count: before.count,
1452
- message_after_count: messageCheck.state?.count || 0,
1453
- resume_attachment_before_count: before.resume_attachment_count || 0,
1454
- resume_attachment_after_count: messageCheck.state?.resume_attachment_count || 0,
1455
- message_observed: messageObserved,
1456
- message_last_text: messageCheck.state?.last_success_text || messageCheck.state?.last_text || ""
1457
- });
1458
- if (messageObserved) {
1459
- return {
1460
- requested: true,
1461
- skipped: false,
1462
- reason: "requested",
1463
- initial_state: initialState,
1464
- close_before_greeting: closeBeforeGreeting,
1465
- greeting_sent: true,
1466
- greeting_send_result: sendResult,
1467
- attempts
1468
- };
1469
- }
1470
- await sleep(900);
1471
- }
1472
-
1473
- return {
1474
- requested: false,
1475
- skipped: false,
1476
- reason: "resume_request_message_not_observed",
1477
- initial_state: initialState,
1478
- close_before_greeting: closeBeforeGreeting,
1479
- greeting_sent: true,
1480
- greeting_send_result: sendResult,
1481
- attempts
1482
- };
1483
- }
1484
-
1485
- export async function closeChatResumeModal(client, {
1486
- attemptsLimit = 3
1487
- } = {}) {
1488
- const attempts = [];
1489
- for (let index = 0; index < attemptsLimit; index += 1) {
1490
- const existingState = await waitForChatResumeModal(client, { timeoutMs: 500 });
1491
- if (!existingState?.popup && !existingState?.content && !existingState?.resumeIframe) {
1492
- return {
1493
- closed: true,
1494
- attempts
1495
- };
1496
- }
1497
-
1498
- const rootState = await getChatRoots(client);
1499
- const closeTarget = await findVisibleTarget(client, rootState.roots, CHAT_RESUME_CLOSE_SELECTORS);
1500
- if (closeTarget) {
1501
- try {
1502
- await clickPoint(client, closeTarget.center.x, closeTarget.center.y);
1503
- attempts.push({
1504
- mode: "close-selector",
1505
- selector: closeTarget.selector,
1506
- root: closeTarget.root
1507
- });
1508
- } catch (error) {
1509
- attempts.push({
1510
- mode: "close-selector-error",
1511
- selector: closeTarget.selector,
1512
- root: closeTarget.root,
1513
- error: error?.message || String(error)
1514
- });
1515
- }
1516
- await sleep(700);
1517
- } else {
1518
- await pressEscape(client);
1519
- attempts.push({ mode: "Escape" });
1520
- await sleep(700);
1521
- }
1522
-
1523
- let state = await waitForChatResumeModal(client, { timeoutMs: 1000 });
1524
- if (!state?.popup && !state?.content && !state?.resumeIframe) {
1525
- return {
1526
- closed: true,
1527
- attempts
1528
- };
1529
- }
1530
-
1531
- await pressEscape(client);
1532
- attempts.push({ mode: "Escape-fallback" });
1533
- await sleep(700);
1534
-
1535
- state = await waitForChatResumeModal(client, { timeoutMs: 1000 });
1536
- if (!state?.popup && !state?.content && !state?.resumeIframe) {
1537
- return {
1538
- closed: true,
1539
- attempts
1540
- };
1541
- }
1542
- }
1543
-
1544
- return {
1545
- closed: false,
1546
- attempts
1547
- };
1548
- }
1549
-
1550
- export async function extractChatProfileCandidate(client, {
1551
- cardCandidate,
1552
- cardNodeId,
1553
- resumeState,
1554
- resumeHtml: providedResumeHtml = null,
1555
- networkEvents = [],
1556
- targetUrl = "",
1557
- closeResume = true,
1558
- networkParseRetryMs = 1800,
1559
- networkParseIntervalMs = 250
1560
- } = {}) {
1561
- let resumeHtml = providedResumeHtml || null;
1562
- if (!resumeHtml) {
1563
- try {
1564
- resumeHtml = await readChatResumeHtml(client, resumeState);
1565
- } catch (error) {
1566
- if (!networkEvents.length) throw error;
1567
- resumeHtml = emptyChatResumeHtml(error);
1568
- }
1569
- }
1570
- const detailText = [
1571
- resumeHtml.popupText,
1572
- resumeHtml.contentText,
1573
- resumeHtml.resumeIframeText
1574
- ].filter(Boolean).join("\n\n");
1575
-
1576
- const parseStarted = Date.now();
1577
- let networkBodies = [];
1578
- let detailCandidateResult = null;
1579
- do {
1580
- networkBodies = await readChatProfileNetworkBodies(client, networkEvents);
1581
- detailCandidateResult = buildScreeningCandidateFromDetail({
1582
- domain: "chat",
1583
- source: "chat-live-cdp-profile",
1584
- cardCandidate,
1585
- detailText,
1586
- networkBodies,
1587
- metadata: {
1588
- target_url: targetUrl,
1589
- card_node_id: cardNodeId,
1590
- resume_popup_selector: resumeState?.popup?.selector || null,
1591
- resume_content_selector: resumeState?.content?.selector || null,
1592
- resume_iframe_selector: resumeState?.resumeIframe?.selector || null,
1593
- resume_iframe_document_node_id: resumeHtml.resumeIframeDocumentNodeId
1594
- }
1595
- });
1596
- if (detailCandidateResult.parsed_network_profiles.some((item) => item.ok)) break;
1597
- if (Date.now() - parseStarted >= Math.max(0, Number(networkParseRetryMs) || 0)) break;
1598
- await sleep(Math.max(50, Number(networkParseIntervalMs) || 250));
1599
- } while (true);
1600
-
1601
- let closeResult = null;
1602
- if (closeResume) {
1603
- closeResult = await closeChatResumeModal(client);
1604
- }
1605
-
1606
- return {
1607
- candidate: detailCandidateResult.candidate,
1608
- parsed_network_profiles: detailCandidateResult.parsed_network_profiles,
1609
- network_bodies: networkBodies,
1610
- network_parse_retry_elapsed_ms: Date.now() - parseStarted,
1611
- network_event_count: networkEvents.length,
1612
- detail: {
1613
- popup_text: resumeHtml.popupText,
1614
- content_text: resumeHtml.contentText,
1615
- resume_iframe_text: resumeHtml.resumeIframeText,
1616
- popup_html_length: resumeHtml.popupHTML.length,
1617
- content_html_length: resumeHtml.contentHTML.length,
1618
- resume_iframe_html_length: resumeHtml.resumeIframeHTML.length
1619
- },
1620
- resume_html_read_error: resumeHtml.readError || null,
1621
- close_result: closeResult
1622
- };
1623
- }
1624
-
1625
- async function findVisibleTarget(client, roots, selectors) {
1626
- let fallback = null;
1627
- for (const root of roots) {
1628
- if (!root?.nodeId) continue;
1629
- for (const selector of selectors) {
1630
- const nodeIds = await querySelectorAll(client, root.nodeId, selector);
1631
- for (const nodeId of nodeIds) {
1632
- const target = {
1633
- root: root.name,
1634
- root_node_id: root.nodeId,
1635
- selector,
1636
- node_id: nodeId
1637
- };
1638
- if (!fallback) fallback = target;
1639
- try {
1640
- const box = await getNodeBox(client, nodeId);
1641
- if (box.rect.width > 2 && box.rect.height > 2) {
1642
- return {
1643
- ...target,
1644
- center: box.center,
1645
- rect: box.rect
1646
- };
1647
- }
1648
- } catch {}
1649
- }
1650
- }
1651
- }
1652
- return fallback;
1653
- }
1654
-
1655
- async function pressEscape(client) {
1656
- await pressKey(client, "Escape", {
1657
- code: "Escape",
1658
- windowsVirtualKeyCode: 27,
1659
- nativeVirtualKeyCode: 27
1660
- });
1661
- }
1
+ import {
2
+ clearFocusedInput,
3
+ clickNodeCenter,
4
+ clickPoint,
5
+ DETERMINISTIC_CLICK_OPTIONS,
6
+ getFrameDocumentNodeId,
7
+ getAttributesMap,
8
+ getNodeBox,
9
+ getOuterHTML,
10
+ insertText,
11
+ pressKey,
12
+ querySelectorAll,
13
+ sleep
14
+ } from "../../core/browser/index.js";
15
+ import {
16
+ buildScreeningCandidateFromDetail,
17
+ htmlToText
18
+ } from "../../core/screening/index.js";
19
+ import {
20
+ CHAT_ACTIVE_CANDIDATE_SELECTORS,
21
+ CHAT_ASK_RESUME_BUTTON_SELECTORS,
22
+ CHAT_ATTACHMENT_RESUME_BUTTON_SELECTORS,
23
+ CHAT_CONFIRM_REQUEST_RESUME_SELECTORS,
24
+ CHAT_EDITOR_SELECTORS,
25
+ CHAT_MESSAGE_FILTER_SELECTORS,
26
+ CHAT_MESSAGE_LIST_SELECTORS,
27
+ CHAT_ONLINE_RESUME_BUTTON_SELECTORS,
28
+ CHAT_PRIMARY_LABEL_SELECTORS,
29
+ CHAT_PROFILE_NETWORK_PATTERNS,
30
+ CHAT_RESUME_CLOSE_SELECTORS,
31
+ CHAT_RESUME_CONTENT_SELECTORS,
32
+ CHAT_RESUME_FAST_MODAL_SELECTORS,
33
+ CHAT_RESUME_IFRAME_SELECTORS,
34
+ CHAT_RESUME_MODAL_SELECTORS,
35
+ CHAT_SEND_BUTTON_SELECTORS
36
+ } from "./constants.js";
37
+ import {
38
+ getChatRoots,
39
+ queryFirstAcrossChatRoots
40
+ } from "./roots.js";
41
+ import {
42
+ assertChatShellNotResumeTopLevel,
43
+ getChatTopLevelState,
44
+ isForbiddenChatResumeTopLevelUrl,
45
+ makeForbiddenChatResumeNavigationError
46
+ } from "./page-guard.js";
47
+
48
+ export const CHAT_UNSAFE_ONLINE_RESUME_LINK_CODE = "CHAT_UNSAFE_ONLINE_RESUME_LINK";
49
+
50
+ const CHAT_CONVERSATION_CONTROL_SCOPE_SELECTORS = Object.freeze([
51
+ ".conversation-main",
52
+ ".conversation-editor",
53
+ ".chat-message-list",
54
+ ".toolbar-box-right",
55
+ ".operate-exchange-left",
56
+ ".operate-icon-item",
57
+ ".exchange-tooltip",
58
+ ".boss-popup__wrapper",
59
+ ".boss-dialog",
60
+ ".dialog-wrap.active",
61
+ ".geek-detail-modal"
62
+ ]);
63
+
64
+ const CHAT_REQUESTED_RESUME_SCOPE_SELECTORS = Object.freeze([
65
+ ".chat-message-list",
66
+ ".conversation-editor",
67
+ ".conversation-main",
68
+ ".toolbar-box-right",
69
+ ".operate-exchange-left",
70
+ ".operate-icon-item",
71
+ ".exchange-tooltip",
72
+ ".boss-popup__wrapper",
73
+ ".boss-dialog",
74
+ ".dialog-wrap.active"
75
+ ]);
76
+
77
+ export function matchesChatProfileNetwork(url) {
78
+ return CHAT_PROFILE_NETWORK_PATTERNS.some((pattern) => pattern.test(String(url || "")));
79
+ }
80
+
81
+ function looksLikeForbiddenChatResumePath(value = "") {
82
+ const normalized = String(value || "");
83
+ return isForbiddenChatResumeTopLevelUrl(normalized)
84
+ || /(?:^|["'\s=])(?:https?:\/\/[^"'\s>]*zhipin\.com)?\/web\/frame\/c-resume(?:[/?#"' >]|$)/i
85
+ .test(normalized);
86
+ }
87
+
88
+ function extractFirstHtmlAttribute(html = "", names = []) {
89
+ const source = String(html || "");
90
+ for (const name of names) {
91
+ const escaped = String(name).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
92
+ const regex = new RegExp(`${escaped}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`, "i");
93
+ const match = source.match(regex);
94
+ if (match) return match[1] ?? match[2] ?? match[3] ?? "";
95
+ }
96
+ return "";
97
+ }
98
+
99
+ export function isUnsafeChatOnlineResumeTarget(target = {}, buttonHTML = "") {
100
+ const attributes = target?.attributes || {};
101
+ const href = attributes.href
102
+ || attributes["data-href"]
103
+ || attributes["data-url"]
104
+ || attributes.url
105
+ || extractFirstHtmlAttribute(buttonHTML, ["href", "data-href", "data-url", "url"]);
106
+ return looksLikeForbiddenChatResumePath(href)
107
+ || looksLikeForbiddenChatResumePath(buttonHTML);
108
+ }
109
+
110
+ export function makeUnsafeChatOnlineResumeLinkError(target = {}, buttonHTML = "") {
111
+ const href = target?.attributes?.href
112
+ || target?.attributes?.["data-href"]
113
+ || target?.attributes?.["data-url"]
114
+ || extractFirstHtmlAttribute(buttonHTML, ["href", "data-href", "data-url", "url"])
115
+ || null;
116
+ const error = new Error("CHAT_UNSAFE_ONLINE_RESUME_LINK: refusing to click an online resume link that can navigate the chat tab to /web/frame/c-resume/");
117
+ error.code = CHAT_UNSAFE_ONLINE_RESUME_LINK_CODE;
118
+ error.href = href;
119
+ error.button_selector = target?.selector || null;
120
+ error.button_text = htmlToText(buttonHTML).slice(0, 120);
121
+ error.button_html_length = String(buttonHTML || "").length;
122
+ return error;
123
+ }
124
+
125
+ export function isUnsafeChatOnlineResumeLinkError(error) {
126
+ return error?.code === CHAT_UNSAFE_ONLINE_RESUME_LINK_CODE
127
+ || /CHAT_UNSAFE_ONLINE_RESUME_LINK/i.test(String(error?.message || error || ""));
128
+ }
129
+
130
+ export function createChatProfileNetworkRecorder(client) {
131
+ const events = [];
132
+ client.Network.responseReceived((event) => {
133
+ const url = event?.response?.url || "";
134
+ if (!matchesChatProfileNetwork(url)) return;
135
+ events.push({
136
+ requestId: event.requestId,
137
+ url,
138
+ status: event.response?.status,
139
+ mimeType: event.response?.mimeType,
140
+ type: event.type
141
+ });
142
+ });
143
+ if (typeof client.Network.loadingFinished === "function") {
144
+ client.Network.loadingFinished((event) => {
145
+ const found = events.find((item) => item.requestId === event.requestId);
146
+ if (!found) return;
147
+ found.loading_finished = true;
148
+ found.encodedDataLength = event.encodedDataLength;
149
+ });
150
+ }
151
+ if (typeof client.Network.loadingFailed === "function") {
152
+ client.Network.loadingFailed((event) => {
153
+ const found = events.find((item) => item.requestId === event.requestId);
154
+ if (!found) return;
155
+ found.loading_failed = true;
156
+ found.loading_error = event.errorText || event.blockedReason || "Network loading failed";
157
+ });
158
+ }
159
+ return {
160
+ events,
161
+ clear() {
162
+ events.length = 0;
163
+ }
164
+ };
165
+ }
166
+
167
+ export async function waitForChatProfileNetworkEvents(recorder, {
168
+ minCount = 1,
169
+ requireLoaded = true,
170
+ timeoutMs = 8000,
171
+ intervalMs = 120
172
+ } = {}) {
173
+ const started = Date.now();
174
+ const events = Array.isArray(recorder) ? recorder : recorder?.events || [];
175
+ let matching = [];
176
+ while (Date.now() - started <= timeoutMs) {
177
+ matching = events.filter((event) => (
178
+ !requireLoaded
179
+ || event.loading_finished === true
180
+ || event.loading_failed === true
181
+ ));
182
+ if (matching.length >= minCount) {
183
+ return {
184
+ ok: true,
185
+ elapsed_ms: Date.now() - started,
186
+ count: matching.length,
187
+ events: matching
188
+ };
189
+ }
190
+ await sleep(intervalMs);
191
+ }
192
+ return {
193
+ ok: false,
194
+ elapsed_ms: Date.now() - started,
195
+ count: matching.length,
196
+ events: matching,
197
+ total_event_count: events.length
198
+ };
199
+ }
200
+
201
+ export async function readChatProfileNetworkBodies(client, events = [], {
202
+ limit = 20
203
+ } = {}) {
204
+ const bodies = [];
205
+ for (const event of events.slice(0, limit)) {
206
+ try {
207
+ const body = await client.Network.getResponseBody({ requestId: event.requestId });
208
+ bodies.push({
209
+ ...event,
210
+ body,
211
+ body_length: String(body?.body || "").length
212
+ });
213
+ } catch (error) {
214
+ bodies.push({
215
+ ...event,
216
+ body_error: error?.message || String(error)
217
+ });
218
+ }
219
+ }
220
+ return bodies;
221
+ }
222
+
223
+ function normalizeDetailText(value = "") {
224
+ return String(value || "").replace(/\s+/g, " ").trim();
225
+ }
226
+
227
+ function chatCandidateIdFromAttributes(attributes = {}) {
228
+ return normalizeDetailText(
229
+ attributes["data-id"]
230
+ || attributes["data-geekid"]
231
+ || attributes["data-geek"]
232
+ || attributes["data-uid"]
233
+ || attributes.key
234
+ || attributes.id
235
+ || ""
236
+ );
237
+ }
238
+
239
+ async function hydrateActiveChatCandidate(client, activeCandidate = null) {
240
+ if (!activeCandidate?.node_id) return activeCandidate;
241
+ let attributes = {};
242
+ let outerHTML = "";
243
+ try {
244
+ [attributes, outerHTML] = await Promise.all([
245
+ getAttributesMap(client, activeCandidate.node_id),
246
+ getOuterHTML(client, activeCandidate.node_id)
247
+ ]);
248
+ } catch {}
249
+ return {
250
+ ...activeCandidate,
251
+ attributes,
252
+ candidate_id: chatCandidateIdFromAttributes(attributes) || null,
253
+ label: normalizeDetailText(htmlToText(outerHTML)),
254
+ outer_html_length: outerHTML.length
255
+ };
256
+ }
257
+
258
+ export async function waitForChatOnlineResumeButton(client, {
259
+ timeoutMs = 12000,
260
+ intervalMs = 250,
261
+ expectedCandidateId = ""
262
+ } = {}) {
263
+ const started = Date.now();
264
+ let lastState = null;
265
+ const expectedId = chatCandidateIdFromAttributes({ "data-id": expectedCandidateId });
266
+ while (Date.now() - started <= timeoutMs) {
267
+ const topLevelState = await getChatTopLevelState(client);
268
+ if (topLevelState.is_forbidden_resume_top_level) {
269
+ return {
270
+ forbidden_top_level_navigation: true,
271
+ top_level_state: topLevelState
272
+ };
273
+ }
274
+ const rootState = await getChatRoots(client);
275
+ const target = await findVisibleTarget(client, rootState.roots, CHAT_ONLINE_RESUME_BUTTON_SELECTORS);
276
+ const activeCandidate = await hydrateActiveChatCandidate(
277
+ client,
278
+ await queryFirstAcrossChatRoots(client, rootState.roots, CHAT_ACTIVE_CANDIDATE_SELECTORS)
279
+ );
280
+ const activeCandidateId = activeCandidate?.candidate_id || "";
281
+ const candidateSelectionVerified = expectedId
282
+ ? activeCandidateId === expectedId
283
+ : undefined;
284
+ lastState = {
285
+ roots: rootState.roots,
286
+ target,
287
+ activeCandidate,
288
+ expected_candidate_id: expectedId || null,
289
+ active_candidate_id: activeCandidateId || null,
290
+ candidate_selection_verified: candidateSelectionVerified
291
+ };
292
+ if (target && (!expectedId || candidateSelectionVerified)) {
293
+ return {
294
+ ok: true,
295
+ elapsed_ms: Date.now() - started,
296
+ ...lastState
297
+ };
298
+ }
299
+ await sleep(intervalMs);
300
+ }
301
+ return {
302
+ ok: false,
303
+ reason: expectedId && lastState?.candidate_selection_verified === false
304
+ ? "active_candidate_mismatch"
305
+ : "online_resume_button_unavailable",
306
+ elapsed_ms: Date.now() - started,
307
+ ...lastState
308
+ };
309
+ }
310
+
311
+ export async function selectChatCandidate(client, cardNodeId, {
312
+ timeoutMs = 12000,
313
+ settleMs = 1200
314
+ } = {}) {
315
+ const cardBox = await clickNodeCenter(client, cardNodeId, {
316
+ scrollIntoView: true
317
+ });
318
+ if (settleMs > 0) await sleep(settleMs);
319
+ const ready = await waitForChatOnlineResumeButton(client, { timeoutMs });
320
+ return {
321
+ card_box: cardBox,
322
+ ready
323
+ };
324
+ }
325
+
326
+ function hasActiveSignal(attributes = {}, outerHTML = "") {
327
+ return /\b(active|selected|current|curr)\b/i.test(String(attributes.class || ""))
328
+ || normalizeDetailText(attributes["aria-selected"]).toLowerCase() === "true"
329
+ || normalizeDetailText(attributes["data-active"]).toLowerCase() === "true"
330
+ || /\b(active|selected|current|curr)\b/i.test(String(outerHTML || "").slice(0, 500));
331
+ }
332
+
333
+ function isDisabledSignal(attributes = {}, outerHTML = "") {
334
+ return attributes.disabled !== undefined
335
+ || normalizeDetailText(attributes["aria-disabled"]).toLowerCase() === "true"
336
+ || /\b(disabled|disable|is-disabled)\b/i.test([
337
+ attributes.class,
338
+ String(outerHTML || "").slice(0, 500)
339
+ ].join(" "));
340
+ }
341
+
342
+ function isAskResumeText(text = "") {
343
+ const normalized = normalizeDetailText(text);
344
+ return Boolean(
345
+ normalized === "求简历"
346
+ || normalized === "索要简历"
347
+ || normalized === "求附件简历"
348
+ || normalized.includes("求简历")
349
+ || normalized.includes("索要简历")
350
+ || normalized.includes("求附件简历")
351
+ );
352
+ }
353
+
354
+ function isRequestedResumeText(text = "") {
355
+ const normalized = normalizeDetailText(text);
356
+ return Boolean(
357
+ normalized === "已求简历"
358
+ || normalized === "已索要简历"
359
+ || normalized.includes("已求简历")
360
+ || normalized.includes("已索要简历")
361
+ || normalized.includes("简历请求已发送")
362
+ || normalized.includes("已发送简历")
363
+ || (normalized.includes("已申请") && normalized.includes("简历"))
364
+ );
365
+ }
366
+
367
+ function isResumeRequestSentMessageText(text = "") {
368
+ const normalized = normalizeDetailText(text);
369
+ return Boolean(
370
+ normalized.includes("简历请求已发送")
371
+ || normalized.includes("已发送简历")
372
+ || normalized.includes("已求简历")
373
+ || normalized.includes("已索要简历")
374
+ || normalized.includes("已发送")
375
+ );
376
+ }
377
+
378
+ function countTextOccurrences(text = "", needle = "") {
379
+ if (!needle) return 0;
380
+ let count = 0;
381
+ let index = 0;
382
+ while (index < text.length) {
383
+ const found = text.indexOf(needle, index);
384
+ if (found < 0) break;
385
+ count += 1;
386
+ index = found + needle.length;
387
+ }
388
+ return count;
389
+ }
390
+
391
+ function countResumeRequestSentMessageMarkers(lines = []) {
392
+ const markers = ["简历请求已发送", "已发送简历", "已求简历", "已索要简历", "已发送"];
393
+ return lines.reduce((total, line) => (
394
+ total + markers.reduce((lineTotal, marker) => (
395
+ lineTotal + countTextOccurrences(line, marker)
396
+ ), 0)
397
+ ), 0);
398
+ }
399
+
400
+ function isResumeAttachmentMessageText(text = "") {
401
+ const normalized = normalizeDetailText(text);
402
+ return Boolean(
403
+ /点击.*附件简历/.test(normalized)
404
+ || /预览附件简历/.test(normalized)
405
+ || /查看附件简历/.test(normalized)
406
+ || /(?:简历|resume)[^\s]*\.(?:pdf|docx?|jpg|jpeg|png)\b/i.test(normalized)
407
+ );
408
+ }
409
+
410
+ function countResumeAttachmentMessageMarkers(lines = []) {
411
+ return lines.reduce((total, line) => total + (isResumeAttachmentMessageText(line) ? 1 : 0), 0);
412
+ }
413
+
414
+ function isRequestedResumeControlTarget(target = {}) {
415
+ const label = normalizeDetailText(target.label);
416
+ const className = String(target.attributes?.class || "");
417
+ const selector = String(target.selector || "");
418
+ const controlLike = /\boperate-btn\b|operate|resume|button|btn/i.test(`${selector} ${className}`);
419
+ if (isRequestedResumeText(label)) return true;
420
+ return controlLike && Boolean(
421
+ label === "已申请"
422
+ || label === "已发送"
423
+ || label.includes("已申请")
424
+ || label.includes("已发送")
425
+ );
426
+ }
427
+
428
+ function isAttachmentResumeText(text = "") {
429
+ const normalized = normalizeDetailText(text);
430
+ return Boolean(
431
+ normalized === "附件简历"
432
+ || (normalized.includes("附件简历") && !normalized.includes("求附件简历"))
433
+ );
434
+ }
435
+
436
+ function isAttachmentResumeTarget(target = {}) {
437
+ return isAttachmentResumeText(target.label)
438
+ || /resume-btn-file/i.test(String(target.attributes?.class || target.selector || ""));
439
+ }
440
+
441
+ function isConfirmText(text = "") {
442
+ const normalized = normalizeDetailText(text);
443
+ return Boolean(
444
+ normalized === "确定"
445
+ || normalized === "确认"
446
+ || normalized === "提交"
447
+ || normalized === "继续"
448
+ || normalized.includes("确定")
449
+ || normalized.includes("确认")
450
+ );
451
+ }
452
+
453
+ function isSendText(text = "") {
454
+ const normalized = normalizeDetailText(text);
455
+ return normalized === "发送" || normalized.includes("发送");
456
+ }
457
+
458
+ function isRecoverableNodeError(error) {
459
+ return /(?:Could not find node|No node with given id|Cannot find node|Could not compute box model)/i
460
+ .test(String(error?.message || error || ""));
461
+ }
462
+
463
+ async function readTarget(client, root, selector, nodeId) {
464
+ let attributes = {};
465
+ let outerHTML = "";
466
+ let readError = "";
467
+ try {
468
+ [attributes, outerHTML] = await Promise.all([
469
+ getAttributesMap(client, nodeId),
470
+ getOuterHTML(client, nodeId)
471
+ ]);
472
+ } catch (error) {
473
+ readError = error?.message || String(error);
474
+ }
475
+ const label = normalizeDetailText(htmlToText(outerHTML));
476
+ let box = null;
477
+ try {
478
+ box = await getNodeBox(client, nodeId);
479
+ } catch {}
480
+ return {
481
+ root: root.name,
482
+ root_node_id: root.nodeId,
483
+ selector,
484
+ node_id: nodeId,
485
+ label,
486
+ attributes,
487
+ disabled: isDisabledSignal(attributes, outerHTML),
488
+ active: hasActiveSignal(attributes, outerHTML),
489
+ visible: Boolean(box && box.rect.width > 2 && box.rect.height > 2),
490
+ center: box?.center || null,
491
+ rect: box?.rect || null,
492
+ outer_html_length: outerHTML.length,
493
+ read_error: readError || null
494
+ };
495
+ }
496
+
497
+ async function findVisibleMatchingTarget(client, roots, selectors, predicate) {
498
+ for (const root of roots) {
499
+ if (!root?.nodeId) continue;
500
+ for (const selector of selectors) {
501
+ const nodeIds = await querySelectorAll(client, root.nodeId, selector);
502
+ for (const nodeId of nodeIds) {
503
+ const target = await readTarget(client, root, selector, nodeId);
504
+ if (!target.visible) continue;
505
+ if (predicate(target)) return target;
506
+ }
507
+ }
508
+ }
509
+ return null;
510
+ }
511
+
512
+ async function resolveScopedRoots(client, roots = [], selectors = [], {
513
+ fallbackToRoots = true
514
+ } = {}) {
515
+ const scoped = [];
516
+ const seen = new Set();
517
+ for (const root of roots) {
518
+ if (!root?.nodeId) continue;
519
+ for (const selector of selectors) {
520
+ let nodeIds = [];
521
+ try {
522
+ nodeIds = await querySelectorAll(client, root.nodeId, selector);
523
+ } catch {
524
+ nodeIds = [];
525
+ }
526
+ for (const nodeId of nodeIds) {
527
+ const key = `${root.name}:${nodeId}`;
528
+ if (seen.has(key)) continue;
529
+ seen.add(key);
530
+ scoped.push({
531
+ name: `${root.name}:${selector}`,
532
+ nodeId
533
+ });
534
+ }
535
+ }
536
+ }
537
+ if (scoped.length || !fallbackToRoots) return scoped;
538
+ return roots;
539
+ }
540
+
541
+ export async function selectChatPrimaryLabel(client, {
542
+ label = "全部",
543
+ timeoutMs = 8000,
544
+ intervalMs = 300,
545
+ settleMs = 700
546
+ } = {}) {
547
+ const started = Date.now();
548
+ let lastCandidates = [];
549
+ while (Date.now() - started <= timeoutMs) {
550
+ const rootState = await getChatRoots(client);
551
+ const candidates = [];
552
+ for (const root of rootState.roots) {
553
+ for (const selector of CHAT_PRIMARY_LABEL_SELECTORS) {
554
+ const nodeIds = await querySelectorAll(client, root.nodeId, selector);
555
+ for (const nodeId of nodeIds) {
556
+ const target = await readTarget(client, root, selector, nodeId);
557
+ if (target.visible) candidates.push(target);
558
+ }
559
+ }
560
+ }
561
+ lastCandidates = candidates;
562
+ const matched = candidates.find((target) => (
563
+ target.label === label || target.label.startsWith(`${label}(`)
564
+ ));
565
+ if (matched?.active) {
566
+ return {
567
+ ok: true,
568
+ changed: false,
569
+ verified: true,
570
+ active_label: matched.label,
571
+ control: matched
572
+ };
573
+ }
574
+ if (matched) {
575
+ if (matched.center) {
576
+ await clickPoint(client, matched.center.x, matched.center.y, DETERMINISTIC_CLICK_OPTIONS);
577
+ } else {
578
+ await clickNodeCenter(client, matched.node_id, {
579
+ ...DETERMINISTIC_CLICK_OPTIONS,
580
+ scrollIntoView: true
581
+ });
582
+ }
583
+ if (settleMs > 0) await sleep(settleMs);
584
+ return {
585
+ ok: true,
586
+ changed: true,
587
+ verified: true,
588
+ active_label: label,
589
+ control: matched
590
+ };
591
+ }
592
+ await sleep(intervalMs);
593
+ }
594
+ return {
595
+ ok: false,
596
+ error: `CHAT_PRIMARY_LABEL_NOT_FOUND:${label}`,
597
+ candidates: lastCandidates.map((item) => ({
598
+ label: item.label,
599
+ selector: item.selector,
600
+ active: item.active
601
+ }))
602
+ };
603
+ }
604
+
605
+ export async function selectChatMessageFilter(client, {
606
+ startFrom = "unread",
607
+ timeoutMs = 8000,
608
+ intervalMs = 300,
609
+ settleMs = 900
610
+ } = {}) {
611
+ const label = startFrom === "all" ? "全部" : "未读";
612
+ const started = Date.now();
613
+ let lastCandidates = [];
614
+ while (Date.now() - started <= timeoutMs) {
615
+ const rootState = await getChatRoots(client);
616
+ const candidates = [];
617
+ for (const root of rootState.roots) {
618
+ for (const selector of CHAT_MESSAGE_FILTER_SELECTORS) {
619
+ const nodeIds = await querySelectorAll(client, root.nodeId, selector);
620
+ for (const nodeId of nodeIds) {
621
+ const target = await readTarget(client, root, selector, nodeId);
622
+ if (target.visible && target.label === label) candidates.push(target);
623
+ }
624
+ }
625
+ }
626
+ lastCandidates = candidates;
627
+ const active = candidates.find((target) => target.active);
628
+ if (active) {
629
+ return {
630
+ ok: true,
631
+ changed: false,
632
+ verified: true,
633
+ active_label: active.label,
634
+ control: active
635
+ };
636
+ }
637
+ const matched = candidates[0];
638
+ if (matched) {
639
+ if (matched.center) {
640
+ await clickPoint(client, matched.center.x, matched.center.y, DETERMINISTIC_CLICK_OPTIONS);
641
+ } else {
642
+ await clickNodeCenter(client, matched.node_id, {
643
+ ...DETERMINISTIC_CLICK_OPTIONS,
644
+ scrollIntoView: true
645
+ });
646
+ }
647
+ if (settleMs > 0) await sleep(settleMs);
648
+ return {
649
+ ok: true,
650
+ changed: true,
651
+ verified: true,
652
+ active_label: label,
653
+ control: matched
654
+ };
655
+ }
656
+ await sleep(intervalMs);
657
+ }
658
+ return {
659
+ ok: false,
660
+ error: `CHAT_MESSAGE_FILTER_NOT_FOUND:${label}`,
661
+ candidates: lastCandidates.map((item) => ({
662
+ label: item.label,
663
+ selector: item.selector,
664
+ active: item.active
665
+ }))
666
+ };
667
+ }
668
+
669
+ export async function waitForChatResumeModal(client, {
670
+ timeoutMs = 12000,
671
+ intervalMs = 250
672
+ } = {}) {
673
+ const started = Date.now();
674
+ let lastState = null;
675
+ while (Date.now() - started <= timeoutMs) {
676
+ const topLevelState = await getChatTopLevelState(client);
677
+ if (topLevelState.is_forbidden_resume_top_level) {
678
+ return {
679
+ forbidden_top_level_navigation: true,
680
+ top_level_state: topLevelState
681
+ };
682
+ }
683
+ const rootState = await getChatRoots(client);
684
+ const popup = await findVisibleTarget(client, rootState.roots, CHAT_RESUME_MODAL_SELECTORS);
685
+ const content = await findVisibleTarget(client, rootState.roots, CHAT_RESUME_CONTENT_SELECTORS);
686
+ const resumeIframe = await findVisibleTarget(client, rootState.roots, CHAT_RESUME_IFRAME_SELECTORS);
687
+ lastState = {
688
+ roots: rootState.roots,
689
+ popup,
690
+ content,
691
+ resumeIframe
692
+ };
693
+ if (popup || content || resumeIframe) return lastState;
694
+ await sleep(intervalMs);
695
+ }
696
+ return lastState;
697
+ }
698
+
699
+ export async function quickChatResumeModalOpenProbe(client, {
700
+ selectors = CHAT_RESUME_FAST_MODAL_SELECTORS
701
+ } = {}) {
702
+ const rootState = await getChatRoots(client);
703
+ for (const root of rootState.roots) {
704
+ if (!root?.nodeId) continue;
705
+ for (const selector of selectors) {
706
+ let nodeIds = [];
707
+ try {
708
+ nodeIds = await querySelectorAll(client, root.nodeId, selector);
709
+ } catch {
710
+ nodeIds = [];
711
+ }
712
+ for (const nodeId of nodeIds.slice(0, 4)) {
713
+ try {
714
+ const box = await getNodeBox(client, nodeId);
715
+ if (box?.rect?.width > 8 && box?.rect?.height > 8) {
716
+ return {
717
+ open: true,
718
+ root: root.name,
719
+ selector,
720
+ node_id: nodeId,
721
+ rect: box.rect,
722
+ center: box.center
723
+ };
724
+ }
725
+ } catch {
726
+ // Hidden or stale modal probes are ignored.
727
+ }
728
+ }
729
+ }
730
+ }
731
+ return {
732
+ open: false
733
+ };
734
+ }
735
+
736
+ export async function readChatResumeHtml(client, resumeState) {
737
+ let popupHTML = "";
738
+ let contentHTML = "";
739
+ let resumeIframeHTML = "";
740
+ let resumeIframeDocumentNodeId = null;
741
+
742
+ if (resumeState?.popup?.node_id) {
743
+ popupHTML = await getOuterHTML(client, resumeState.popup.node_id);
744
+ }
745
+
746
+ if (resumeState?.content?.node_id && resumeState.content.node_id !== resumeState?.popup?.node_id) {
747
+ contentHTML = await getOuterHTML(client, resumeState.content.node_id);
748
+ }
749
+
750
+ if (resumeState?.resumeIframe?.node_id) {
751
+ resumeIframeDocumentNodeId = await getFrameDocumentNodeId(client, resumeState.resumeIframe.node_id);
752
+ resumeIframeHTML = await getOuterHTML(client, resumeIframeDocumentNodeId);
753
+ }
754
+
755
+ return {
756
+ popupHTML,
757
+ contentHTML,
758
+ resumeIframeHTML,
759
+ resumeIframeDocumentNodeId,
760
+ popupText: htmlToText(popupHTML),
761
+ contentText: htmlToText(contentHTML),
762
+ resumeIframeText: htmlToText(resumeIframeHTML)
763
+ };
764
+ }
765
+
766
+ function emptyChatResumeHtml(readError = null) {
767
+ return {
768
+ popupHTML: "",
769
+ contentHTML: "",
770
+ resumeIframeHTML: "",
771
+ resumeIframeDocumentNodeId: null,
772
+ popupText: "",
773
+ contentText: "",
774
+ resumeIframeText: "",
775
+ readError: readError?.message || null
776
+ };
777
+ }
778
+
779
+ export async function waitForChatResumeContent(client, {
780
+ minTextLength = 120,
781
+ timeoutMs = 15000,
782
+ intervalMs = 250
783
+ } = {}) {
784
+ const started = Date.now();
785
+ let lastState = null;
786
+ let lastHtml = null;
787
+ let lastError = null;
788
+ while (Date.now() - started <= timeoutMs) {
789
+ try {
790
+ lastState = await waitForChatResumeModal(client, {
791
+ timeoutMs: 700,
792
+ intervalMs: 100
793
+ });
794
+ if (lastState?.popup || lastState?.content || lastState?.resumeIframe) {
795
+ lastHtml = await readChatResumeHtml(client, lastState);
796
+ const textLength = [
797
+ lastHtml.popupText,
798
+ lastHtml.contentText,
799
+ lastHtml.resumeIframeText
800
+ ].join("\n").length;
801
+ if (textLength >= minTextLength) {
802
+ return {
803
+ ok: true,
804
+ elapsed_ms: Date.now() - started,
805
+ text_length: textLength,
806
+ resume_state: lastState,
807
+ resume_html: lastHtml
808
+ };
809
+ }
810
+ }
811
+ } catch (error) {
812
+ lastError = error;
813
+ }
814
+ await sleep(intervalMs);
815
+ }
816
+
817
+ const textLength = [
818
+ lastHtml?.popupText,
819
+ lastHtml?.contentText,
820
+ lastHtml?.resumeIframeText
821
+ ].filter(Boolean).join("\n").length;
822
+ return {
823
+ ok: false,
824
+ elapsed_ms: Date.now() - started,
825
+ text_length: textLength,
826
+ resume_state: lastState,
827
+ resume_html: lastHtml,
828
+ error: lastError?.message || null
829
+ };
830
+ }
831
+
832
+ export async function openChatOnlineResume(client, {
833
+ timeoutMs = 15000,
834
+ attemptsLimit = 3,
835
+ settleMs = 1200
836
+ } = {}) {
837
+ const attempts = [];
838
+ for (let index = 0; index < attemptsLimit; index += 1) {
839
+ if (settleMs > 0) await sleep(settleMs);
840
+ await assertChatShellNotResumeTopLevel(client, {
841
+ context: "openChatOnlineResume:before_existing_modal_check"
842
+ });
843
+ const existingResumeState = await waitForChatResumeModal(client, {
844
+ timeoutMs: 500,
845
+ intervalMs: 100
846
+ });
847
+ if (existingResumeState?.forbidden_top_level_navigation) {
848
+ throw makeForbiddenChatResumeNavigationError(existingResumeState.top_level_state);
849
+ }
850
+ if (
851
+ existingResumeState?.popup
852
+ || existingResumeState?.content
853
+ || existingResumeState?.resumeIframe
854
+ ) {
855
+ attempts.push({
856
+ attempt: index + 1,
857
+ ok: true,
858
+ reused_existing_modal: true,
859
+ resume_popup_selector: existingResumeState?.popup?.selector || null,
860
+ resume_content_selector: existingResumeState?.content?.selector || null,
861
+ resume_iframe_selector: existingResumeState?.resumeIframe?.selector || null
862
+ });
863
+ return {
864
+ button: null,
865
+ button_html: "",
866
+ resume_state: existingResumeState,
867
+ attempts
868
+ };
869
+ }
870
+
871
+ const buttonState = await waitForChatOnlineResumeButton(client, {
872
+ timeoutMs: Math.min(timeoutMs, 8000)
873
+ });
874
+ if (!buttonState?.target?.node_id) {
875
+ attempts.push({
876
+ attempt: index + 1,
877
+ ok: false,
878
+ error: "ONLINE_RESUME_BUTTON_NOT_FOUND"
879
+ });
880
+ continue;
881
+ }
882
+
883
+ let buttonHTML = "";
884
+ try {
885
+ buttonHTML = await getOuterHTML(client, buttonState.target.node_id);
886
+ } catch {}
887
+
888
+ if (isUnsafeChatOnlineResumeTarget(buttonState.target, buttonHTML)) {
889
+ const error = makeUnsafeChatOnlineResumeLinkError(buttonState.target, buttonHTML);
890
+ attempts.push({
891
+ attempt: index + 1,
892
+ ok: false,
893
+ error: error.code,
894
+ blocked_pre_click: true,
895
+ button_selector: buttonState.target.selector,
896
+ button_text: error.button_text,
897
+ button_href: error.href,
898
+ button_html_length: buttonHTML.length
899
+ });
900
+ error.attempts = attempts;
901
+ throw error;
902
+ }
903
+
904
+ try {
905
+ if (buttonState.target.center) {
906
+ await clickPoint(client, buttonState.target.center.x, buttonState.target.center.y);
907
+ } else {
908
+ await clickNodeCenter(client, buttonState.target.node_id, {
909
+ scrollIntoView: true
910
+ });
911
+ }
912
+ } catch (error) {
913
+ attempts.push({
914
+ attempt: index + 1,
915
+ ok: false,
916
+ error: error?.message || String(error),
917
+ recoverable_stale_node: isRecoverableNodeError(error),
918
+ button_selector: buttonState.target.selector,
919
+ button_text: htmlToText(buttonHTML).slice(0, 120),
920
+ button_html_length: buttonHTML.length
921
+ });
922
+ if (isRecoverableNodeError(error)) {
923
+ await sleep(350);
924
+ continue;
925
+ }
926
+ throw error;
927
+ }
928
+ await assertChatShellNotResumeTopLevel(client, {
929
+ context: "openChatOnlineResume:after_online_resume_click"
930
+ });
931
+ const resumeState = await waitForChatResumeModal(client, {
932
+ timeoutMs: Math.max(2500, Math.floor(timeoutMs / attemptsLimit))
933
+ });
934
+ if (resumeState?.forbidden_top_level_navigation) {
935
+ throw makeForbiddenChatResumeNavigationError(resumeState.top_level_state);
936
+ }
937
+ attempts.push({
938
+ attempt: index + 1,
939
+ ok: Boolean(resumeState?.popup || resumeState?.content || resumeState?.resumeIframe),
940
+ button_selector: buttonState.target.selector,
941
+ button_text: htmlToText(buttonHTML).slice(0, 120),
942
+ button_html_length: buttonHTML.length,
943
+ resume_popup_selector: resumeState?.popup?.selector || null,
944
+ resume_content_selector: resumeState?.content?.selector || null,
945
+ resume_iframe_selector: resumeState?.resumeIframe?.selector || null
946
+ });
947
+ if (resumeState?.popup || resumeState?.content || resumeState?.resumeIframe) {
948
+ return {
949
+ button: buttonState.target,
950
+ button_html: buttonHTML,
951
+ resume_state: resumeState,
952
+ attempts
953
+ };
954
+ }
955
+ }
956
+
957
+ const error = new Error("Chat online resume modal did not open");
958
+ error.attempts = attempts;
959
+ throw error;
960
+ }
961
+
962
+ export async function readChatConversationReadyState(client) {
963
+ const rootState = await getChatRoots(client);
964
+ const scopedControlRoots = await resolveScopedRoots(
965
+ client,
966
+ rootState.roots,
967
+ CHAT_CONVERSATION_CONTROL_SCOPE_SELECTORS,
968
+ { fallbackToRoots: false }
969
+ );
970
+ const scopedRequestedRoots = await resolveScopedRoots(
971
+ client,
972
+ rootState.roots,
973
+ CHAT_REQUESTED_RESUME_SCOPE_SELECTORS,
974
+ { fallbackToRoots: false }
975
+ );
976
+ const controlRoots = scopedControlRoots.length ? scopedControlRoots : rootState.roots;
977
+ const requestedRoots = scopedRequestedRoots.length ? scopedRequestedRoots : rootState.roots;
978
+ const onlineResume = await findVisibleMatchingTarget(
979
+ client,
980
+ controlRoots,
981
+ CHAT_ONLINE_RESUME_BUTTON_SELECTORS,
982
+ (target) => target.label.includes("在线简历") && !target.disabled
983
+ );
984
+ const attachmentResume = await findVisibleMatchingTarget(
985
+ client,
986
+ controlRoots,
987
+ CHAT_ATTACHMENT_RESUME_BUTTON_SELECTORS,
988
+ (target) => isAttachmentResumeText(target.label)
989
+ );
990
+ const askResume = await findVisibleMatchingTarget(
991
+ client,
992
+ controlRoots,
993
+ CHAT_ASK_RESUME_BUTTON_SELECTORS,
994
+ (target) => isAskResumeText(target.label) && !isAttachmentResumeTarget(target)
995
+ );
996
+ const requestedResume = await findVisibleMatchingTarget(
997
+ client,
998
+ requestedRoots,
999
+ CHAT_ASK_RESUME_BUTTON_SELECTORS,
1000
+ (target) => isRequestedResumeControlTarget(target)
1001
+ );
1002
+ const editor = await findVisibleMatchingTarget(
1003
+ client,
1004
+ controlRoots,
1005
+ CHAT_EDITOR_SELECTORS,
1006
+ () => true
1007
+ );
1008
+ const sendButton = await findVisibleMatchingTarget(
1009
+ client,
1010
+ controlRoots,
1011
+ CHAT_SEND_BUTTON_SELECTORS,
1012
+ (target) => isSendText(target.label) || /submit/i.test(String(target.attributes?.class || ""))
1013
+ );
1014
+ const resumeState = await waitForChatResumeModal(client, { timeoutMs: 300 });
1015
+ return {
1016
+ has_online_resume: Boolean(onlineResume),
1017
+ online_resume: onlineResume,
1018
+ has_ask_resume: Boolean(askResume),
1019
+ ask_resume: askResume,
1020
+ already_requested_resume: Boolean(requestedResume),
1021
+ requested_resume: requestedResume,
1022
+ has_attachment_resume: Boolean(attachmentResume),
1023
+ attachment_resume_enabled: Boolean(attachmentResume && !attachmentResume.disabled),
1024
+ attachment_resume: attachmentResume,
1025
+ editor_visible: Boolean(editor),
1026
+ editor,
1027
+ send_button_visible: Boolean(sendButton),
1028
+ send_button: sendButton,
1029
+ resume_modal_open: Boolean(resumeState?.popup || resumeState?.content || resumeState?.resumeIframe),
1030
+ panels_closed: !Boolean(resumeState?.popup || resumeState?.content || resumeState?.resumeIframe)
1031
+ };
1032
+ }
1033
+
1034
+ export async function setChatEditorMessage(client, message, {
1035
+ timeoutMs = 8000
1036
+ } = {}) {
1037
+ const started = Date.now();
1038
+ let lastState = null;
1039
+ while (Date.now() - started <= timeoutMs) {
1040
+ const state = await readChatConversationReadyState(client);
1041
+ lastState = state;
1042
+ if (state.editor?.node_id) {
1043
+ try {
1044
+ if (state.editor.center) {
1045
+ await clickPoint(client, state.editor.center.x, state.editor.center.y);
1046
+ } else {
1047
+ await clickNodeCenter(client, state.editor.node_id, { scrollIntoView: true });
1048
+ }
1049
+ await sleep(120);
1050
+ await clearFocusedInput(client);
1051
+ await sleep(80);
1052
+ await insertText(client, message);
1053
+ await sleep(250);
1054
+ const afterState = await readChatConversationReadyState(client);
1055
+ const editorText = normalizeDetailText(afterState.editor?.label || "");
1056
+ if (editorText.includes(normalizeDetailText(message))) {
1057
+ return {
1058
+ ok: true,
1059
+ value: editorText,
1060
+ editor: afterState.editor || state.editor
1061
+ };
1062
+ }
1063
+ lastState = {
1064
+ ...afterState,
1065
+ editor_message_mismatch: true,
1066
+ editor_text: editorText
1067
+ };
1068
+ } catch (error) {
1069
+ if (!isRecoverableNodeError(error)) throw error;
1070
+ lastState = {
1071
+ ...state,
1072
+ recoverable_error: error?.message || String(error),
1073
+ recoverable_phase: "set_editor_message"
1074
+ };
1075
+ }
1076
+ }
1077
+ await sleep(250);
1078
+ }
1079
+ return {
1080
+ ok: false,
1081
+ error: "CHAT_EDITOR_NOT_FOUND",
1082
+ state: lastState
1083
+ };
1084
+ }
1085
+
1086
+ export async function sendChatMessage(client, expectedText = "", {
1087
+ timeoutMs = 8000,
1088
+ settleMs = 800
1089
+ } = {}) {
1090
+ const started = Date.now();
1091
+ let lastState = null;
1092
+ while (Date.now() - started <= timeoutMs) {
1093
+ const state = await readChatConversationReadyState(client);
1094
+ lastState = state;
1095
+ if (state.send_button?.node_id && !state.send_button.disabled) {
1096
+ try {
1097
+ if (state.send_button.center) {
1098
+ await clickPoint(client, state.send_button.center.x, state.send_button.center.y);
1099
+ } else {
1100
+ await clickNodeCenter(client, state.send_button.node_id, { scrollIntoView: true });
1101
+ }
1102
+ if (settleMs > 0) await sleep(settleMs);
1103
+ return {
1104
+ sent: true,
1105
+ method: "send-button",
1106
+ control: state.send_button,
1107
+ expected_text: expectedText
1108
+ };
1109
+ } catch (error) {
1110
+ if (!isRecoverableNodeError(error)) throw error;
1111
+ lastState = {
1112
+ ...state,
1113
+ recoverable_error: error?.message || String(error),
1114
+ recoverable_phase: "send_button_click"
1115
+ };
1116
+ await sleep(250);
1117
+ continue;
1118
+ }
1119
+ }
1120
+ if (state.editor?.node_id) {
1121
+ await pressKey(client, "Enter", {
1122
+ code: "Enter",
1123
+ windowsVirtualKeyCode: 13,
1124
+ nativeVirtualKeyCode: 13
1125
+ });
1126
+ if (settleMs > 0) await sleep(settleMs);
1127
+ return {
1128
+ sent: true,
1129
+ method: "enter",
1130
+ expected_text: expectedText
1131
+ };
1132
+ }
1133
+ await sleep(250);
1134
+ }
1135
+ return {
1136
+ sent: false,
1137
+ method: "none",
1138
+ error: "CHAT_SEND_CONTROL_NOT_FOUND",
1139
+ state: lastState
1140
+ };
1141
+ }
1142
+
1143
+ export async function clickChatAskResume(client, {
1144
+ timeoutMs = 8000,
1145
+ settleMs = 700
1146
+ } = {}) {
1147
+ const started = Date.now();
1148
+ let lastState = null;
1149
+ let lastDisabledAskResume = null;
1150
+ while (Date.now() - started <= timeoutMs) {
1151
+ const state = await readChatConversationReadyState(client);
1152
+ lastState = state;
1153
+ if (state.attachment_resume_enabled) {
1154
+ return {
1155
+ ok: true,
1156
+ already_requested: true,
1157
+ attachment_resume_available: true,
1158
+ control: state.attachment_resume
1159
+ };
1160
+ }
1161
+ if (state.ask_resume?.node_id && !state.ask_resume.disabled) {
1162
+ try {
1163
+ if (state.ask_resume.center) {
1164
+ await clickPoint(client, state.ask_resume.center.x, state.ask_resume.center.y);
1165
+ } else {
1166
+ await clickNodeCenter(client, state.ask_resume.node_id, { scrollIntoView: true });
1167
+ }
1168
+ if (settleMs > 0) await sleep(settleMs);
1169
+ return {
1170
+ ok: true,
1171
+ already_requested: false,
1172
+ control: state.ask_resume
1173
+ };
1174
+ } catch (error) {
1175
+ if (!isRecoverableNodeError(error)) throw error;
1176
+ lastState = {
1177
+ ...state,
1178
+ recoverable_error: error?.message || String(error),
1179
+ recoverable_phase: "ask_resume_click"
1180
+ };
1181
+ }
1182
+ }
1183
+ if (state.ask_resume?.node_id && state.ask_resume.disabled) {
1184
+ lastDisabledAskResume = state.ask_resume;
1185
+ }
1186
+ if (state.already_requested_resume) {
1187
+ return {
1188
+ ok: true,
1189
+ already_requested: true,
1190
+ control: state.requested_resume
1191
+ };
1192
+ }
1193
+ await sleep(250);
1194
+ }
1195
+ if (lastDisabledAskResume) {
1196
+ return {
1197
+ ok: false,
1198
+ already_requested: true,
1199
+ request_pending: true,
1200
+ error: "ASK_RESUME_BUTTON_DISABLED",
1201
+ control: lastDisabledAskResume,
1202
+ state: lastState
1203
+ };
1204
+ }
1205
+ return {
1206
+ ok: false,
1207
+ error: "ASK_RESUME_BUTTON_NOT_FOUND",
1208
+ state: lastState
1209
+ };
1210
+ }
1211
+
1212
+ export async function clickChatConfirmRequestResume(client, {
1213
+ timeoutMs = 8000,
1214
+ settleMs = 900
1215
+ } = {}) {
1216
+ const started = Date.now();
1217
+ let lastTarget = null;
1218
+ let lastState = null;
1219
+ while (Date.now() - started <= timeoutMs) {
1220
+ lastState = await readChatConversationReadyState(client);
1221
+ const rootState = await getChatRoots(client);
1222
+ const confirmRoots = await resolveScopedRoots(
1223
+ client,
1224
+ rootState.roots,
1225
+ CHAT_CONVERSATION_CONTROL_SCOPE_SELECTORS
1226
+ );
1227
+ const target = await findVisibleMatchingTarget(
1228
+ client,
1229
+ confirmRoots,
1230
+ CHAT_CONFIRM_REQUEST_RESUME_SELECTORS,
1231
+ (item) => isConfirmText(item.label) && !item.disabled
1232
+ );
1233
+ lastTarget = target;
1234
+ if (target?.node_id) {
1235
+ try {
1236
+ if (target.center) {
1237
+ await clickPoint(client, target.center.x, target.center.y);
1238
+ } else {
1239
+ await clickNodeCenter(client, target.node_id, { scrollIntoView: true });
1240
+ }
1241
+ if (settleMs > 0) await sleep(settleMs);
1242
+ const afterState = await readChatConversationReadyState(client);
1243
+ return {
1244
+ confirmed: true,
1245
+ assumed_requested: Boolean(afterState.already_requested_resume),
1246
+ control: target,
1247
+ state: afterState
1248
+ };
1249
+ } catch (error) {
1250
+ if (!isRecoverableNodeError(error)) throw error;
1251
+ lastTarget = {
1252
+ ...target,
1253
+ recoverable_error: error?.message || String(error),
1254
+ recoverable_phase: "confirm_request_resume_click"
1255
+ };
1256
+ }
1257
+ }
1258
+ await sleep(250);
1259
+ }
1260
+ return {
1261
+ confirmed: false,
1262
+ error: "CONFIRM_BUTTON_NOT_FOUND",
1263
+ control: lastTarget,
1264
+ state: lastState
1265
+ };
1266
+ }
1267
+
1268
+ export async function getChatResumeRequestMessageState(client) {
1269
+ const rootState = await getChatRoots(client);
1270
+ let messageRoot = null;
1271
+ for (const root of rootState.roots) {
1272
+ for (const selector of CHAT_MESSAGE_LIST_SELECTORS) {
1273
+ const nodeIds = await querySelectorAll(client, root.nodeId, selector);
1274
+ if (nodeIds.length) {
1275
+ messageRoot = {
1276
+ root,
1277
+ selector,
1278
+ node_id: nodeIds[0]
1279
+ };
1280
+ break;
1281
+ }
1282
+ }
1283
+ if (messageRoot) break;
1284
+ }
1285
+ const nodeId = messageRoot?.node_id || rootState.rootNodes.top;
1286
+ let text = "";
1287
+ try {
1288
+ text = htmlToText(await getOuterHTML(client, nodeId));
1289
+ } catch {}
1290
+ const lines = text.split(/\r?\n/).map(normalizeDetailText).filter(Boolean);
1291
+ const matching = lines.filter((line) => isResumeRequestSentMessageText(line));
1292
+ const attachmentMatching = lines.filter((line) => isResumeAttachmentMessageText(line));
1293
+ const count = countResumeRequestSentMessageMarkers(lines);
1294
+ const resumeAttachmentCount = countResumeAttachmentMessageMarkers(lines);
1295
+ return {
1296
+ ok: Boolean(text),
1297
+ selector: messageRoot?.selector || "top",
1298
+ count,
1299
+ resume_attachment_count: resumeAttachmentCount,
1300
+ success_count: count + resumeAttachmentCount,
1301
+ last_text: matching[matching.length - 1] || lines[lines.length - 1] || "",
1302
+ last_resume_attachment_text: attachmentMatching[attachmentMatching.length - 1] || "",
1303
+ last_success_text: matching[matching.length - 1] || attachmentMatching[attachmentMatching.length - 1] || "",
1304
+ recent: lines.slice(-12)
1305
+ };
1306
+ }
1307
+
1308
+ export async function waitForChatResumeRequestMessage(client, {
1309
+ baselineCount = 0,
1310
+ baselineResumeAttachmentCount = 0,
1311
+ timeoutMs = 6500,
1312
+ intervalMs = 260
1313
+ } = {}) {
1314
+ const started = Date.now();
1315
+ let state = null;
1316
+ while (Date.now() - started <= timeoutMs) {
1317
+ state = await getChatResumeRequestMessageState(client);
1318
+ const observed = (
1319
+ state.count > baselineCount
1320
+ || state.resume_attachment_count > baselineResumeAttachmentCount
1321
+ );
1322
+ if (observed) {
1323
+ return {
1324
+ observed: true,
1325
+ elapsed_ms: Date.now() - started,
1326
+ state
1327
+ };
1328
+ }
1329
+ await sleep(intervalMs);
1330
+ }
1331
+ return {
1332
+ observed: false,
1333
+ elapsed_ms: Date.now() - started,
1334
+ state
1335
+ };
1336
+ }
1337
+
1338
+ export async function requestChatResumeForPassedCandidate(client, {
1339
+ greetingText = "Hi同学,能麻烦发下简历吗?",
1340
+ maxAttempts = 3,
1341
+ askResumeTimeoutMs = 8000,
1342
+ dryRun = false
1343
+ } = {}) {
1344
+ const effectiveGreetingText = normalizeDetailText(greetingText) || "Hi同学,能麻烦发下简历吗?";
1345
+ const initialState = await readChatConversationReadyState(client);
1346
+ if (initialState.attachment_resume_enabled) {
1347
+ return {
1348
+ requested: false,
1349
+ skipped: true,
1350
+ reason: "attachment_resume_already_available",
1351
+ initial_state: initialState
1352
+ };
1353
+ }
1354
+ if (dryRun) {
1355
+ return {
1356
+ requested: false,
1357
+ skipped: false,
1358
+ reason: "dry_run",
1359
+ initial_state: initialState,
1360
+ would_send_greeting: true,
1361
+ would_click_ask_resume: true
1362
+ };
1363
+ }
1364
+
1365
+ const closeBeforeGreeting = await closeChatResumeModal(client, { attemptsLimit: 3 });
1366
+ if (!closeBeforeGreeting.closed) {
1367
+ return {
1368
+ requested: false,
1369
+ skipped: true,
1370
+ reason: "resume_modal_close_failed_before_request",
1371
+ initial_state: initialState,
1372
+ close_before_greeting: closeBeforeGreeting
1373
+ };
1374
+ }
1375
+ const editorState = await setChatEditorMessage(client, effectiveGreetingText);
1376
+ if (!editorState.ok) {
1377
+ throw new Error("CHAT_EDITOR_MESSAGE_MISMATCH");
1378
+ }
1379
+ const sendResult = await sendChatMessage(client, effectiveGreetingText);
1380
+ if (!sendResult.sent) {
1381
+ throw new Error(`CHAT_GREETING_SEND_FAILED:${sendResult.error || sendResult.method || "unknown"}`);
1382
+ }
1383
+
1384
+ const attempts = [];
1385
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
1386
+ const before = await getChatResumeRequestMessageState(client);
1387
+ const askResult = await clickChatAskResume(client, {
1388
+ timeoutMs: askResumeTimeoutMs
1389
+ });
1390
+ let confirmResult = {
1391
+ confirmed: false,
1392
+ assumed_requested: Boolean(askResult.already_requested),
1393
+ skipped: true,
1394
+ reason: askResult.attachment_resume_available
1395
+ ? "attachment_resume_already_available"
1396
+ : askResult.request_pending
1397
+ ? "resume_request_already_pending"
1398
+ : askResult.ok
1399
+ ? "already_requested"
1400
+ : (askResult.error || "ask_resume_not_clicked")
1401
+ };
1402
+ if (askResult.attachment_resume_available) {
1403
+ attempts.push({
1404
+ attempt: attempt + 1,
1405
+ ask_result: askResult,
1406
+ confirm_result: confirmResult,
1407
+ message_before_count: before.count,
1408
+ message_after_count: before.count,
1409
+ message_observed: false,
1410
+ message_last_text: before.last_text || ""
1411
+ });
1412
+ return {
1413
+ requested: false,
1414
+ skipped: true,
1415
+ reason: "attachment_resume_already_available",
1416
+ initial_state: initialState,
1417
+ close_before_greeting: closeBeforeGreeting,
1418
+ greeting_sent: true,
1419
+ greeting_send_result: sendResult,
1420
+ attempts
1421
+ };
1422
+ }
1423
+ if (askResult.request_pending || askResult.already_requested) {
1424
+ attempts.push({
1425
+ attempt: attempt + 1,
1426
+ ask_result: askResult,
1427
+ confirm_result: confirmResult,
1428
+ message_before_count: before.count,
1429
+ message_after_count: before.count,
1430
+ resume_attachment_before_count: before.resume_attachment_count || 0,
1431
+ resume_attachment_after_count: before.resume_attachment_count || 0,
1432
+ message_observed: false,
1433
+ message_last_text: before.last_success_text || before.last_text || ""
1434
+ });
1435
+ return {
1436
+ requested: false,
1437
+ skipped: true,
1438
+ reason: "resume_request_already_pending",
1439
+ initial_state: initialState,
1440
+ close_before_greeting: closeBeforeGreeting,
1441
+ greeting_sent: true,
1442
+ greeting_send_result: sendResult,
1443
+ attempts
1444
+ };
1445
+ }
1446
+ if (askResult.ok && !askResult.already_requested) {
1447
+ confirmResult = await clickChatConfirmRequestResume(client);
1448
+ }
1449
+ const messageCheck = await waitForChatResumeRequestMessage(client, {
1450
+ baselineCount: before.count,
1451
+ baselineResumeAttachmentCount: before.resume_attachment_count
1452
+ });
1453
+ const messageObserved = Boolean(messageCheck.observed);
1454
+ attempts.push({
1455
+ attempt: attempt + 1,
1456
+ ask_result: askResult,
1457
+ confirm_result: confirmResult,
1458
+ message_before_count: before.count,
1459
+ message_after_count: messageCheck.state?.count || 0,
1460
+ resume_attachment_before_count: before.resume_attachment_count || 0,
1461
+ resume_attachment_after_count: messageCheck.state?.resume_attachment_count || 0,
1462
+ message_observed: messageObserved,
1463
+ message_last_text: messageCheck.state?.last_success_text || messageCheck.state?.last_text || ""
1464
+ });
1465
+ if (messageObserved) {
1466
+ return {
1467
+ requested: true,
1468
+ skipped: false,
1469
+ reason: "requested",
1470
+ initial_state: initialState,
1471
+ close_before_greeting: closeBeforeGreeting,
1472
+ greeting_sent: true,
1473
+ greeting_send_result: sendResult,
1474
+ attempts
1475
+ };
1476
+ }
1477
+ await sleep(900);
1478
+ }
1479
+
1480
+ return {
1481
+ requested: false,
1482
+ skipped: false,
1483
+ reason: "resume_request_message_not_observed",
1484
+ initial_state: initialState,
1485
+ close_before_greeting: closeBeforeGreeting,
1486
+ greeting_sent: true,
1487
+ greeting_send_result: sendResult,
1488
+ attempts
1489
+ };
1490
+ }
1491
+
1492
+ export async function closeChatResumeModal(client, {
1493
+ attemptsLimit = 3
1494
+ } = {}) {
1495
+ const attempts = [];
1496
+ for (let index = 0; index < attemptsLimit; index += 1) {
1497
+ const existingState = await waitForChatResumeModal(client, { timeoutMs: 500 });
1498
+ if (!existingState?.popup && !existingState?.content && !existingState?.resumeIframe) {
1499
+ return {
1500
+ closed: true,
1501
+ attempts
1502
+ };
1503
+ }
1504
+
1505
+ const rootState = await getChatRoots(client);
1506
+ const closeTarget = await findVisibleTarget(client, rootState.roots, CHAT_RESUME_CLOSE_SELECTORS);
1507
+ if (closeTarget) {
1508
+ try {
1509
+ await clickPoint(client, closeTarget.center.x, closeTarget.center.y, DETERMINISTIC_CLICK_OPTIONS);
1510
+ attempts.push({
1511
+ mode: "close-selector",
1512
+ selector: closeTarget.selector,
1513
+ root: closeTarget.root
1514
+ });
1515
+ } catch (error) {
1516
+ attempts.push({
1517
+ mode: "close-selector-error",
1518
+ selector: closeTarget.selector,
1519
+ root: closeTarget.root,
1520
+ error: error?.message || String(error)
1521
+ });
1522
+ }
1523
+ await sleep(700);
1524
+ } else {
1525
+ await pressEscape(client);
1526
+ attempts.push({ mode: "Escape" });
1527
+ await sleep(700);
1528
+ }
1529
+
1530
+ let state = await waitForChatResumeModal(client, { timeoutMs: 1000 });
1531
+ if (!state?.popup && !state?.content && !state?.resumeIframe) {
1532
+ return {
1533
+ closed: true,
1534
+ attempts
1535
+ };
1536
+ }
1537
+
1538
+ await pressEscape(client);
1539
+ attempts.push({ mode: "Escape-fallback" });
1540
+ await sleep(700);
1541
+
1542
+ state = await waitForChatResumeModal(client, { timeoutMs: 1000 });
1543
+ if (!state?.popup && !state?.content && !state?.resumeIframe) {
1544
+ return {
1545
+ closed: true,
1546
+ attempts
1547
+ };
1548
+ }
1549
+ }
1550
+
1551
+ return {
1552
+ closed: false,
1553
+ attempts
1554
+ };
1555
+ }
1556
+
1557
+ export async function extractChatProfileCandidate(client, {
1558
+ cardCandidate,
1559
+ cardNodeId,
1560
+ resumeState,
1561
+ resumeHtml: providedResumeHtml = null,
1562
+ networkEvents = [],
1563
+ targetUrl = "",
1564
+ closeResume = true,
1565
+ networkParseRetryMs = 1800,
1566
+ networkParseIntervalMs = 250
1567
+ } = {}) {
1568
+ let resumeHtml = providedResumeHtml || null;
1569
+ if (!resumeHtml) {
1570
+ try {
1571
+ resumeHtml = await readChatResumeHtml(client, resumeState);
1572
+ } catch (error) {
1573
+ if (!networkEvents.length) throw error;
1574
+ resumeHtml = emptyChatResumeHtml(error);
1575
+ }
1576
+ }
1577
+ const detailText = [
1578
+ resumeHtml.popupText,
1579
+ resumeHtml.contentText,
1580
+ resumeHtml.resumeIframeText
1581
+ ].filter(Boolean).join("\n\n");
1582
+
1583
+ const parseStarted = Date.now();
1584
+ let networkBodies = [];
1585
+ let detailCandidateResult = null;
1586
+ do {
1587
+ networkBodies = await readChatProfileNetworkBodies(client, networkEvents);
1588
+ detailCandidateResult = buildScreeningCandidateFromDetail({
1589
+ domain: "chat",
1590
+ source: "chat-live-cdp-profile",
1591
+ cardCandidate,
1592
+ detailText,
1593
+ networkBodies,
1594
+ metadata: {
1595
+ target_url: targetUrl,
1596
+ card_node_id: cardNodeId,
1597
+ resume_popup_selector: resumeState?.popup?.selector || null,
1598
+ resume_content_selector: resumeState?.content?.selector || null,
1599
+ resume_iframe_selector: resumeState?.resumeIframe?.selector || null,
1600
+ resume_iframe_document_node_id: resumeHtml.resumeIframeDocumentNodeId
1601
+ }
1602
+ });
1603
+ if (detailCandidateResult.parsed_network_profiles.some((item) => item.ok)) break;
1604
+ if (Date.now() - parseStarted >= Math.max(0, Number(networkParseRetryMs) || 0)) break;
1605
+ await sleep(Math.max(50, Number(networkParseIntervalMs) || 250));
1606
+ } while (true);
1607
+
1608
+ let closeResult = null;
1609
+ if (closeResume) {
1610
+ closeResult = await closeChatResumeModal(client);
1611
+ }
1612
+
1613
+ return {
1614
+ candidate: detailCandidateResult.candidate,
1615
+ parsed_network_profiles: detailCandidateResult.parsed_network_profiles,
1616
+ network_bodies: networkBodies,
1617
+ network_parse_retry_elapsed_ms: Date.now() - parseStarted,
1618
+ network_event_count: networkEvents.length,
1619
+ detail: {
1620
+ popup_text: resumeHtml.popupText,
1621
+ content_text: resumeHtml.contentText,
1622
+ resume_iframe_text: resumeHtml.resumeIframeText,
1623
+ popup_html_length: resumeHtml.popupHTML.length,
1624
+ content_html_length: resumeHtml.contentHTML.length,
1625
+ resume_iframe_html_length: resumeHtml.resumeIframeHTML.length
1626
+ },
1627
+ resume_html_read_error: resumeHtml.readError || null,
1628
+ close_result: closeResult
1629
+ };
1630
+ }
1631
+
1632
+ async function findVisibleTarget(client, roots, selectors) {
1633
+ let fallback = null;
1634
+ for (const root of roots) {
1635
+ if (!root?.nodeId) continue;
1636
+ for (const selector of selectors) {
1637
+ const nodeIds = await querySelectorAll(client, root.nodeId, selector);
1638
+ for (const nodeId of nodeIds) {
1639
+ const target = {
1640
+ root: root.name,
1641
+ root_node_id: root.nodeId,
1642
+ selector,
1643
+ node_id: nodeId
1644
+ };
1645
+ if (!fallback) fallback = target;
1646
+ try {
1647
+ const box = await getNodeBox(client, nodeId);
1648
+ if (box.rect.width > 2 && box.rect.height > 2) {
1649
+ return {
1650
+ ...target,
1651
+ center: box.center,
1652
+ rect: box.rect
1653
+ };
1654
+ }
1655
+ } catch {}
1656
+ }
1657
+ }
1658
+ }
1659
+ return fallback;
1660
+ }
1661
+
1662
+ async function pressEscape(client) {
1663
+ await pressKey(client, "Escape", {
1664
+ code: "Escape",
1665
+ windowsVirtualKeyCode: 27,
1666
+ nativeVirtualKeyCode: 27
1667
+ });
1668
+ }