Aichatbot12321 commited on
Commit
06aa2ed
·
verified ·
1 Parent(s): 03533c4

Upload 2 files

Browse files
Files changed (2) hide show
  1. search.html +1 -1
  2. server.js +123 -88
search.html CHANGED
@@ -16301,7 +16301,7 @@ body.ai-dark-thinking .fill-empty-fill {
16301
 
16302
  <div class="ws3-console">
16303
  <div class="ws3-console-head">
16304
- <span>⚡ Parallel 3-Tab Browser Telemetry (Google Search → Red Markers → Click 3 Distinct Sites → Auto-Close Popups → Full Snap → Gemini Vision)</span>
16305
  <span id="ws3StatusStateText">Idle</span>
16306
  </div>
16307
  <div class="ws3-console-logs" id="ws3ConsoleLogs">
 
16301
 
16302
  <div class="ws3-console">
16303
  <div class="ws3-console-head">
16304
+ <span>⚡ Parallel 3-Tab Telemetry (Open Website: <b>gemini-3.5-flash-lite</b> → Auto-Close Popups → Full Snap → Read &amp; Analyze: <b>gemini-3.6-flash</b>)</span>
16305
  <span id="ws3StatusStateText">Idle</span>
16306
  </div>
16307
  <div class="ws3-console-logs" id="ws3ConsoleLogs">
server.js CHANGED
@@ -893,7 +893,7 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
893
  for (const sel of selectorList) {
894
  const candidate = p.locator(sel).first();
895
  try {
896
- if (await candidate.isVisible({ timeout: 1200 })) {
897
  loc = candidate;
898
  break;
899
  }
@@ -928,19 +928,25 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
928
  await loc.type(s, { delay, timeout: tmo });
929
  }
930
  await wsSleep(80);
 
 
931
  await p.keyboard.press("Enter");
 
932
  return true;
933
  };
934
 
935
- // Check if current page is a Google/Bot CAPTCHA page
936
- const isCaptchaOrBlockedPage = async (p) => {
 
937
  try {
938
  const u = p.url().toLowerCase();
939
- if (u.includes("/sorry/") || u.includes("ipv4.google.com/sorry") || u.includes("captcha")) return true;
940
  return await p.evaluate(() => {
941
- const txt = ((document.title || "") + " " + (document.body ? document.body.innerText.slice(0, 1200) : "")).toLowerCase();
942
- if (txt.includes("unusual traffic from your computer") || txt.includes("not a robot") || txt.includes("verify you are human")) return true;
943
- if (document.querySelector('iframe[src*="recaptcha"], #captcha-form, #recaptcha')) return true;
 
 
944
  return false;
945
  });
946
  } catch (e) {
@@ -948,61 +954,72 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
948
  }
949
  };
950
 
951
- // Extract & tag organic search result WEBSITE TITLES on the current search engine page, drawing Red Boxes on each website title
952
  const markAndExtractSearchResultTitles = async (p) => {
953
  return await p.evaluate(() => {
954
  document.querySelectorAll(".ws-red-marker-box").forEach(el => el.remove());
955
  document.querySelectorAll("[data-ws-title-id]").forEach(el => el.removeAttribute("data-ws-title-id"));
 
956
 
957
  const results = [];
958
  const seenUrls = new Set();
959
 
960
- // Match Google result titles (a h3), Bing result titles (li.b_algo h2 a, h2 a), Yahoo/Brave result titles (h3 a, a h3)
961
  const candidateNodes = Array.from(document.querySelectorAll(
962
- '#search a[href^="http"] h3, #rso a[href^="http"] h3, a[href^="http"]:has(h3) h3, li.b_algo h2 a[href^="http"], #b_results h2 a[href^="http"], div.algo h3 a[href^="http"], a[href^="http"] h2, a[href^="http"] h3'
963
  ));
964
 
965
  let idx = 0;
966
  for (const node of candidateNodes) {
967
- if (results.length >= 12) break;
968
  const anchor = node.tagName.toLowerCase() === "a" ? node : node.closest("a[href]");
969
  if (!anchor) continue;
970
- let href = anchor.href || "";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971
  if (!href.startsWith("http")) continue;
972
- if (/google\.com\/search|google\.com\/url|google\.co\.in\/search|bing\.com\/search|bing\.com\/ck\/a.*bing\.com|yahoo\.com\/search|youtube\.com|youtu\.be|webcache|translate\.google|support\.google|accounts\.google/i.test(href)) {
973
- // Note: Bing sometimes wraps organic links with bing.com/ck/a?!&&p=...&u=a1aHR0cHM6...
974
- if (href.includes("bing.com/ck/a") && href.includes("u=a1")) {
975
- try {
976
- const uParam = new URL(href).searchParams.get("u") || "";
977
- if (uParam.startsWith("a1")) {
978
- const b64 = uParam.slice(2).replace(/-/g, "+").replace(/_/g, "/");
979
- const decoded = atob(b64);
980
- if (decoded.startsWith("http")) href = decoded;
981
- }
982
- } catch (e) {}
983
- }
984
- if (/google\.|bing\.com|yahoo\.com|youtube\.com|youtu\.be/i.test(href)) continue;
985
  }
986
  if (seenUrls.has(href)) continue;
987
 
988
  const rect = node.getBoundingClientRect();
989
- if (rect.width < 15 || rect.height < 8 || rect.top < 0 || rect.top > window.innerHeight + 250) continue;
 
990
 
991
  const titleText = (node.innerText || anchor.innerText || "").replace(/\s+/g, " ").trim();
992
  if (!titleText || titleText.length < 4) continue;
993
 
994
  seenUrls.add(href);
995
- // Ensure clicking the website title opens in the SAME tab
996
  anchor.removeAttribute("target");
997
  node.setAttribute("data-ws-title-id", String(idx));
998
  anchor.setAttribute("data-ws-title-anchor", String(idx));
999
 
1000
- // Draw Red Numbered Box (#ff7675) on the website title name
1001
- if (rect.top >= 0 && rect.top <= window.innerHeight) {
1002
  const badge = document.createElement("div");
1003
  badge.className = "ws-red-marker-box";
1004
- badge.textContent = String(idx + 1);
1005
- badge.style.cssText = `position:fixed;top:${Math.max(0, Math.round(rect.top - 5))}px;left:${Math.max(0, Math.round(rect.left - 6))}px;width:${Math.round(rect.width + 10)}px;height:${Math.round(rect.height + 8)}px;border:2px solid #ff7675;background:rgba(255,118,117,0.10);color:#fff;font-size:10px;font-weight:800;border-radius:5px;z-index:2147483646;pointer-events:none;box-sizing:border-box;`;
1006
  const tag = document.createElement("span");
1007
  tag.textContent = String(idx + 1);
1008
  tag.style.cssText = "position:absolute;top:-14px;left:-2px;background:#ff7675;color:#fff;font-size:10px;font-weight:800;padding:0px 5px;border-radius:4px;box-shadow:0 2px 4px rgba(0,0,0,0.25);";
@@ -1035,7 +1052,7 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
1035
  try {
1036
  // =========================================================================
1037
  // STEP 1: Open https://www.google.com, type the web search prompt with
1038
- // human-like anti-bot safety, and press Enter!
1039
  // =========================================================================
1040
  tabState.model = WS_OPEN_MODEL;
1041
  tabState.status = "running";
@@ -1049,33 +1066,42 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
1049
  await p.evaluate(WS_AUTO_CLOSE_POPUPS_FN).catch(() => {});
1050
  await snapTab(tabIdx, p);
1051
 
1052
- tabState.step = `1/5 Typing Search on Google (${WS_OPEN_MODEL})`;
1053
  wsTabLog(`⌨️ Tab ${tabIdx + 1} [${WS_OPEN_MODEL}]: Typing "${query}" on google.com...`);
1054
- const typedGoogle = await wsTypeSearchBox(
1055
  p,
1056
  ['textarea[name="q"]', 'input[name="q"]', 'textarea[title*="Search"]', 'input[title*="Search"]'],
1057
  query
1058
  );
1059
- if (typedGoogle) {
1060
- await p.waitForNavigation({ waitUntil: "domcontentloaded", timeout: 5500 }).catch(() => {});
1061
- await wsSleep(450);
1062
- }
1063
  await p.evaluate(WS_CURSOR_INIT).catch(() => {});
1064
  await p.evaluate(WS_AUTO_CLOSE_POPUPS_FN).catch(() => {});
1065
  tabState.url = p.url();
1066
 
1067
- let googleBlocked = await isCaptchaOrBlockedPage(p);
1068
- let candidates = [];
1069
- if (!googleBlocked) {
1070
- candidates = await markAndExtractSearchResultTitles(p);
 
 
 
 
 
 
 
1071
  }
1072
 
 
 
1073
  // =========================================================================
1074
- // CAPTCHA / 0-RESULT RECOVERY: Switch to Bing (https://www.bing.com)
1075
- // (or Yahoo Search https://search.yahoo.com) — NEVER DuckDuckGo!
1076
  // =========================================================================
1077
- if (googleBlocked || !candidates || candidates.length === 0) {
1078
- wsTabLog(`🛡️ Tab ${tabIdx + 1}: Google showed CAPTCHA or 0 results — switching to Bing Search (bing.com)...`);
1079
  tabState.step = `1/5 Searching on Bing (${WS_OPEN_MODEL})`;
1080
  tabState.domain = "bing.com";
1081
  tabState.url = "https://www.bing.com";
@@ -1093,33 +1119,23 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
1093
  );
1094
  if (!typedBing) {
1095
  await p.goto(`https://www.bing.com/search?q=${encodeURIComponent(query)}&setlang=en`, { waitUntil: "domcontentloaded", timeout: 6500 }).catch(() => {});
1096
- } else {
1097
- await p.waitForNavigation({ waitUntil: "domcontentloaded", timeout: 5000 }).catch(() => {});
1098
- await wsSleep(450);
1099
  }
 
 
1100
  tabState.url = p.url();
1101
  await p.evaluate(WS_CURSOR_INIT).catch(() => {});
1102
  await p.evaluate(WS_AUTO_CLOSE_POPUPS_FN).catch(() => {});
1103
  candidates = await markAndExtractSearchResultTitles(p);
1104
-
1105
- // Secondary non-Duck fallback if Bing also fails: Yahoo Search (search.yahoo.com)
1106
- if (!candidates || candidates.length === 0) {
1107
- wsTabLog(`🔄 Tab ${tabIdx + 1}: Trying Yahoo Search (search.yahoo.com)...`);
1108
- tabState.step = `1/5 Searching on Yahoo (${WS_OPEN_MODEL})`;
1109
- tabState.domain = "search.yahoo.com";
1110
- await p.goto(`https://search.yahoo.com/search?p=${encodeURIComponent(query)}`, { waitUntil: "domcontentloaded", timeout: 6500 }).catch(() => {});
1111
- tabState.url = p.url();
1112
- await p.evaluate(WS_CURSOR_INIT).catch(() => {});
1113
- candidates = await markAndExtractSearchResultTitles(p);
1114
- }
1115
  }
1116
 
1117
  // =========================================================================
1118
- // STEP 2: Show RED numbered markers on the Website Result Titles & call
1119
  // gemini-3.5-flash-lite (WS_OPEN_MODEL) to choose which Website Title to click!
1120
  // =========================================================================
1121
  tabState.model = WS_OPEN_MODEL;
1122
- tabState.step = `2/5 ${WS_OPEN_MODEL} Selecting Website Title`;
1123
  const searchShotBuf = await snapTab(tabIdx, p);
1124
 
1125
  // Stagger domain claiming slightly by tabIdx * 120ms so Tab 0, Tab 1, Tab 2 never claim the same domain
@@ -1147,7 +1163,7 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
1147
 
1148
  const shortlist = availableForThisTab.slice(0, 5);
1149
  if (shortlist.length > 1 && searchShotBuf) {
1150
- const openPrompt = `You are Browser Tab #${tabIdx + 1} (${WS_OPEN_MODEL}) selecting a search result website title to click and open for query: "${rawUserPrompt || query}".
1151
  Look at the search results screenshot with RED numbered boxes on the website titles and choose the best candidate index (0 to ${shortlist.length - 1}) from this list:
1152
  ${shortlist.map((c, idx) => `[${idx}] (Red Box #${c.markerNum}) Title: "${c.title}" (${c.domain})`).join("\n")}
1153
  Return ONLY JSON: {"pickIndex": 0}`;
@@ -1173,35 +1189,54 @@ Return ONLY JSON: {"pickIndex": 0}`;
1173
  }
1174
 
1175
  // =========================================================================
1176
- // STEP 3: Click the Website Result Title Name directly on the search page!
 
1177
  // =========================================================================
1178
  const clickWebsiteResultTitleOnPage = async (targetItem) => {
1179
  tabState.model = WS_OPEN_MODEL;
1180
- tabState.step = `3/5 Clicking Title (${WS_OPEN_MODEL})`;
1181
  tabState.domain = targetItem.domain;
1182
  tabState.title = targetItem.title;
1183
- wsTabLog(`🖱️ Tab ${tabIdx + 1} [${WS_OPEN_MODEL}]: Clicking website title "${targetItem.title.slice(0, 52)}" (${targetItem.domain})`);
1184
  if (onStatusUpdate) onStatusUpdate(`Tab ${tabIdx + 1} (${WS_OPEN_MODEL}): Clicking "${targetItem.title.slice(0, 35)}"...`);
1185
 
1186
  const beforeSearchUrl = p.url();
1187
- const titleLoc = p.locator(`[data-ws-title-id="${targetItem.titleId}"]`).first();
1188
- let clickedTitle = false;
1189
- try {
1190
- await titleLoc.scrollIntoViewIfNeeded({ timeout: 1800 });
1191
- const box = await titleLoc.boundingBox();
1192
- if (box && box.width > 0 && box.height > 0) {
1193
- const clickX = wsClamp(box.x + box.width * wsRnd(0.25, 0.65), 6, VIEW_W - 6);
1194
- const clickY = wsClamp(box.y + box.height * wsRnd(0.3, 0.7), 6, VIEW_H - 6);
1195
- await snapTab(tabIdx, p);
1196
- const navWait = p.waitForNavigation({ waitUntil: "domcontentloaded", timeout: 6500 }).catch(() => {});
1197
- await wsClickAt(p, clickX, clickY);
1198
- await navWait;
1199
- clickedTitle = true;
1200
- }
1201
- } catch (e) {}
1202
 
1203
- // If mouse click on h3 didn't trigger navigation yet, click the title's anchor directly in DOM
1204
- if (!clickedTitle || p.url() === beforeSearchUrl) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1205
  try {
1206
  const navWait2 = p.waitForNavigation({ waitUntil: "domcontentloaded", timeout: 5500 }).catch(() => {});
1207
  await p.evaluate((tid) => {
@@ -1216,11 +1251,11 @@ Return ONLY JSON: {"pickIndex": 0}`;
1216
  } catch (e) {}
1217
  }
1218
 
1219
- // Final safety fallback if search page JS intercepted the click
1220
- if (p.url() === beforeSearchUrl || /google\.com\/search|bing\.com\/search|yahoo\.com\/search/i.test(p.url())) {
1221
  await p.goto(targetItem.url, { waitUntil: "domcontentloaded", timeout: 6500 }).catch(() => {});
1222
  }
1223
- await wsSleep(500);
1224
  tabState.url = p.url();
1225
  };
1226
 
@@ -1254,10 +1289,10 @@ Return ONLY JSON: {"pickIndex": 0}`;
1254
  openedOk = true;
1255
  break;
1256
  } else {
1257
- wsTabLog(`🛡️ Tab ${tabIdx + 1}: Cloudflare/block on ${target.domain}, trying next result title...`);
1258
  }
1259
  } catch (navErr) {
1260
- wsTabLog(`⚠️ Tab ${tabIdx + 1}: Timeout on ${target.domain}, trying next result title...`);
1261
  }
1262
  }
1263
 
 
893
  for (const sel of selectorList) {
894
  const candidate = p.locator(sel).first();
895
  try {
896
+ if (await candidate.isVisible({ timeout: 1500 })) {
897
  loc = candidate;
898
  break;
899
  }
 
928
  await loc.type(s, { delay, timeout: tmo });
929
  }
930
  await wsSleep(80);
931
+ // Attach navigation/result wait BEFORE pressing Enter so we never miss fast navigation
932
+ const navPromise = p.waitForNavigation({ waitUntil: "domcontentloaded", timeout: 6500 }).catch(() => {});
933
  await p.keyboard.press("Enter");
934
+ await navPromise;
935
  return true;
936
  };
937
 
938
+ // ONLY return true if Google/Bing actually redirected to a hard CAPTCHA block page (e.g. /sorry/index)
939
+ // Never trigger false positives from background recaptcha badges when search results exist!
940
+ const isHardCaptchaBlockPage = async (p) => {
941
  try {
942
  const u = p.url().toLowerCase();
943
+ if (u.includes("/sorry/") || u.includes("ipv4.google.com/sorry")) return true;
944
  return await p.evaluate(() => {
945
+ const hasResults = document.querySelectorAll('#search a h3, #rso a h3, a[href^="http"] h3, li.b_algo h2 a').length > 0;
946
+ if (hasResults) return false;
947
+ const txt = ((document.title || "") + " " + (document.body ? document.body.innerText.slice(0, 1000) : "")).toLowerCase();
948
+ if (txt.includes("unusual traffic from your computer") || txt.includes("our systems have detected unusual traffic")) return true;
949
+ if (document.querySelector('#captcha-form, form[action*="sorry"]')) return true;
950
  return false;
951
  });
952
  } catch (e) {
 
954
  }
955
  };
956
 
957
+ // Extract & tag organic search result WEBSITE TITLES across the entire search results page, drawing Red Boxes on each website title
958
  const markAndExtractSearchResultTitles = async (p) => {
959
  return await p.evaluate(() => {
960
  document.querySelectorAll(".ws-red-marker-box").forEach(el => el.remove());
961
  document.querySelectorAll("[data-ws-title-id]").forEach(el => el.removeAttribute("data-ws-title-id"));
962
+ document.querySelectorAll("[data-ws-title-anchor]").forEach(el => el.removeAttribute("data-ws-title-anchor"));
963
 
964
  const results = [];
965
  const seenUrls = new Set();
966
 
967
+ // Match all Google organic result titles (h3 inside anchor), plus Bing/Yahoo result headings
968
  const candidateNodes = Array.from(document.querySelectorAll(
969
+ '#rso a[href] h3, #search a[href] h3, a[href]:has(h3) h3, #rso a[href] [role="heading"], #search a[href] [role="heading"], li.b_algo h2 a[href], #b_results h2 a[href], div.algo h3 a[href], a[href^="http"] h3, a[href^="http"] h2'
970
  ));
971
 
972
  let idx = 0;
973
  for (const node of candidateNodes) {
974
+ if (results.length >= 16) break;
975
  const anchor = node.tagName.toLowerCase() === "a" ? node : node.closest("a[href]");
976
  if (!anchor) continue;
977
+ let href = anchor.href || anchor.getAttribute("href") || "";
978
+
979
+ // Unwrap Google redirect links (/url?q=https://... or /url?url=https://...)
980
+ if (href.includes("google.") && (href.includes("/url?") || href.includes("?q=http") || href.includes("&q=http"))) {
981
+ try {
982
+ const uObj = new URL(href, window.location.origin);
983
+ const realTarget = uObj.searchParams.get("q") || uObj.searchParams.get("url");
984
+ if (realTarget && realTarget.startsWith("http")) href = realTarget;
985
+ } catch (e) {}
986
+ }
987
+
988
+ // Unwrap Bing redirect links (bing.com/ck/a?...&u=a1...)
989
+ if (href.includes("bing.com/ck/a") && href.includes("u=a1")) {
990
+ try {
991
+ const uParam = new URL(href).searchParams.get("u") || "";
992
+ if (uParam.startsWith("a1")) {
993
+ const b64 = uParam.slice(2).replace(/-/g, "+").replace(/_/g, "/");
994
+ const decoded = atob(b64);
995
+ if (decoded.startsWith("http")) href = decoded;
996
+ }
997
+ } catch (e) {}
998
+ }
999
+
1000
  if (!href.startsWith("http")) continue;
1001
+ if (/^https?:\/\/([a-z0-9-]+\.)?(google\.(com|co\.[a-z]{2}|[a-z]{2})|bing\.com|yahoo\.com|youtube\.com|youtu\.be|webcache\.googleusercontent\.com)\b/i.test(href)) {
1002
+ continue;
 
 
 
 
 
 
 
 
 
 
 
1003
  }
1004
  if (seenUrls.has(href)) continue;
1005
 
1006
  const rect = node.getBoundingClientRect();
1007
+ // Allow results anywhere down the page (even below initial fold) as long as they have real width/height
1008
+ if (rect.width < 12 || rect.height < 8) continue;
1009
 
1010
  const titleText = (node.innerText || anchor.innerText || "").replace(/\s+/g, " ").trim();
1011
  if (!titleText || titleText.length < 4) continue;
1012
 
1013
  seenUrls.add(href);
 
1014
  anchor.removeAttribute("target");
1015
  node.setAttribute("data-ws-title-id", String(idx));
1016
  anchor.setAttribute("data-ws-title-anchor", String(idx));
1017
 
1018
+ // Draw Red Numbered Box (#ff7675) on visible website titles
1019
+ if (rect.top >= -10 && rect.top <= window.innerHeight + 20) {
1020
  const badge = document.createElement("div");
1021
  badge.className = "ws-red-marker-box";
1022
+ badge.style.cssText = `position:fixed;top:${Math.max(0, Math.round(rect.top - 4))}px;left:${Math.max(0, Math.round(rect.left - 5))}px;width:${Math.round(rect.width + 10)}px;height:${Math.round(rect.height + 8)}px;border:2px solid #ff7675;background:rgba(255,118,117,0.12);color:#fff;font-size:10px;font-weight:800;border-radius:5px;z-index:2147483646;pointer-events:none;box-sizing:border-box;`;
 
1023
  const tag = document.createElement("span");
1024
  tag.textContent = String(idx + 1);
1025
  tag.style.cssText = "position:absolute;top:-14px;left:-2px;background:#ff7675;color:#fff;font-size:10px;font-weight:800;padding:0px 5px;border-radius:4px;box-shadow:0 2px 4px rgba(0,0,0,0.25);";
 
1052
  try {
1053
  // =========================================================================
1054
  // STEP 1: Open https://www.google.com, type the web search prompt with
1055
+ // human-like anti-bot safety, press Enter, and STAY on Google Search!
1056
  // =========================================================================
1057
  tabState.model = WS_OPEN_MODEL;
1058
  tabState.status = "running";
 
1066
  await p.evaluate(WS_AUTO_CLOSE_POPUPS_FN).catch(() => {});
1067
  await snapTab(tabIdx, p);
1068
 
1069
+ tabState.step = `1/5 Searching Google (${WS_OPEN_MODEL})`;
1070
  wsTabLog(`⌨️ Tab ${tabIdx + 1} [${WS_OPEN_MODEL}]: Typing "${query}" on google.com...`);
1071
+ await wsTypeSearchBox(
1072
  p,
1073
  ['textarea[name="q"]', 'input[name="q"]', 'textarea[title*="Search"]', 'input[title*="Search"]'],
1074
  query
1075
  );
1076
+
1077
+ // Wait for Google Search results (<h3> inside #search / #rso) to render on screen!
1078
+ await p.waitForSelector('#search h3, #rso h3, a[href^="http"] h3, #captcha-form, form[action*="sorry"]', { timeout: 5500 }).catch(() => {});
1079
+ await wsSleep(350);
1080
  await p.evaluate(WS_CURSOR_INIT).catch(() => {});
1081
  await p.evaluate(WS_AUTO_CLOSE_POPUPS_FN).catch(() => {});
1082
  tabState.url = p.url();
1083
 
1084
+ // First, extract Google Search result titles directly!
1085
+ let candidates = await markAndExtractSearchResultTitles(p);
1086
+
1087
+ // If Google showed an AI Overview / knowledge card at the very top, scroll slightly to ensure organic h3 results are loaded
1088
+ if (!candidates || candidates.length < 3) {
1089
+ const hardBlocked = await isHardCaptchaBlockPage(p);
1090
+ if (!hardBlocked) {
1091
+ await p.evaluate(() => window.scrollBy(0, 320)).catch(() => {});
1092
+ await wsSleep(450);
1093
+ candidates = await markAndExtractSearchResultTitles(p);
1094
+ }
1095
  }
1096
 
1097
+ const googleHardBlocked = (!candidates || candidates.length === 0) && (await isHardCaptchaBlockPage(p));
1098
+
1099
  // =========================================================================
1100
+ // ONLY IF GOOGLE FAILED / GAVE CAPTCHA ERROR (0 RESULTS) -> GO TO BING!
1101
+ // If Google returned search results (candidates.length > 0), NEVER go to Bing!
1102
  // =========================================================================
1103
+ if (googleHardBlocked || !candidates || candidates.length === 0) {
1104
+ wsTabLog(`🛡️ Tab ${tabIdx + 1}: Google Search gave error/CAPTCHA (0 results) — falling back to Bing Search...`);
1105
  tabState.step = `1/5 Searching on Bing (${WS_OPEN_MODEL})`;
1106
  tabState.domain = "bing.com";
1107
  tabState.url = "https://www.bing.com";
 
1119
  );
1120
  if (!typedBing) {
1121
  await p.goto(`https://www.bing.com/search?q=${encodeURIComponent(query)}&setlang=en`, { waitUntil: "domcontentloaded", timeout: 6500 }).catch(() => {});
 
 
 
1122
  }
1123
+ await p.waitForSelector('li.b_algo h2 a, #b_results h2 a', { timeout: 5000 }).catch(() => {});
1124
+ await wsSleep(350);
1125
  tabState.url = p.url();
1126
  await p.evaluate(WS_CURSOR_INIT).catch(() => {});
1127
  await p.evaluate(WS_AUTO_CLOSE_POPUPS_FN).catch(() => {});
1128
  candidates = await markAndExtractSearchResultTitles(p);
1129
+ } else {
1130
+ wsTabLog(`✅ Tab ${tabIdx + 1}: Google Search loaded ${candidates.length} website results.`);
 
 
 
 
 
 
 
 
 
1131
  }
1132
 
1133
  // =========================================================================
1134
+ // STEP 2: Show RED numbered markers on the Google Result Website Titles & call
1135
  // gemini-3.5-flash-lite (WS_OPEN_MODEL) to choose which Website Title to click!
1136
  // =========================================================================
1137
  tabState.model = WS_OPEN_MODEL;
1138
+ tabState.step = `2/5 ${WS_OPEN_MODEL} Selecting Google Result`;
1139
  const searchShotBuf = await snapTab(tabIdx, p);
1140
 
1141
  // Stagger domain claiming slightly by tabIdx * 120ms so Tab 0, Tab 1, Tab 2 never claim the same domain
 
1163
 
1164
  const shortlist = availableForThisTab.slice(0, 5);
1165
  if (shortlist.length > 1 && searchShotBuf) {
1166
+ const openPrompt = `You are Browser Tab #${tabIdx + 1} (${WS_OPEN_MODEL}) selecting a Google search result website title to click and open for query: "${rawUserPrompt || query}".
1167
  Look at the search results screenshot with RED numbered boxes on the website titles and choose the best candidate index (0 to ${shortlist.length - 1}) from this list:
1168
  ${shortlist.map((c, idx) => `[${idx}] (Red Box #${c.markerNum}) Title: "${c.title}" (${c.domain})`).join("\n")}
1169
  Return ONLY JSON: {"pickIndex": 0}`;
 
1189
  }
1190
 
1191
  // =========================================================================
1192
+ // STEP 3: Scroll the chosen Google Result Website Title into view, draw Red Box,
1193
+ // move AI cursor onto the Website Title Name, and CLICK IT to open!
1194
  // =========================================================================
1195
  const clickWebsiteResultTitleOnPage = async (targetItem) => {
1196
  tabState.model = WS_OPEN_MODEL;
1197
+ tabState.step = `3/5 Clicking "${targetItem.title.slice(0, 22)}..." (${WS_OPEN_MODEL})`;
1198
  tabState.domain = targetItem.domain;
1199
  tabState.title = targetItem.title;
1200
+ wsTabLog(`🖱️ Tab ${tabIdx + 1} [${WS_OPEN_MODEL}]: Clicking Google result title "${targetItem.title.slice(0, 52)}" (${targetItem.domain})`);
1201
  if (onStatusUpdate) onStatusUpdate(`Tab ${tabIdx + 1} (${WS_OPEN_MODEL}): Clicking "${targetItem.title.slice(0, 35)}"...`);
1202
 
1203
  const beforeSearchUrl = p.url();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1204
 
1205
+ // Scroll the target title smoothly into center viewport and highlight its Red Box
1206
+ const coords = await p.evaluate((tid) => {
1207
+ const el = document.querySelector(`[data-ws-title-id="${tid}"]`) || document.querySelector(`[data-ws-title-anchor="${tid}"]`);
1208
+ if (!el) return null;
1209
+ const a = el.tagName.toLowerCase() === "a" ? el : el.closest("a");
1210
+ if (a) a.removeAttribute("target");
1211
+ el.scrollIntoView({ behavior: "instant", block: "center" });
1212
+ const r = el.getBoundingClientRect();
1213
+ return {
1214
+ x: Math.round(r.left + Math.min(120, Math.max(16, r.width * 0.35))),
1215
+ y: Math.round(r.top + Math.max(8, r.height * 0.5))
1216
+ };
1217
+ }, targetItem.titleId).catch(() => null);
1218
+
1219
+ await markAndExtractSearchResultTitles(p);
1220
+ await snapTab(tabIdx, p);
1221
+
1222
+ if (coords && coords.x > 0 && coords.y > 0) {
1223
+ const navWait = p.waitForNavigation({ waitUntil: "domcontentloaded", timeout: 6500 }).catch(() => {});
1224
+ await wsClickAt(
1225
+ p,
1226
+ wsClamp(coords.x, 6, VIEW_W - 6),
1227
+ wsClamp(coords.y, 6, VIEW_H - 6)
1228
+ );
1229
+ await navWait;
1230
+ }
1231
+
1232
+ // Wait briefly to see if URL changed away from the search results page
1233
+ for (let w = 0; w < 8; w++) {
1234
+ if (p.url() !== beforeSearchUrl && !/google\.[^/]+\/search|bing\.com\/search/i.test(p.url())) break;
1235
+ await wsSleep(180);
1236
+ }
1237
+
1238
+ // If physical mouse click was intercepted by a search page wrapper, trigger DOM click on the title anchor
1239
+ if (p.url() === beforeSearchUrl || /google\.[^/]+\/search|bing\.com\/search/i.test(p.url())) {
1240
  try {
1241
  const navWait2 = p.waitForNavigation({ waitUntil: "domcontentloaded", timeout: 5500 }).catch(() => {});
1242
  await p.evaluate((tid) => {
 
1251
  } catch (e) {}
1252
  }
1253
 
1254
+ // Final guarantee if still on search page
1255
+ if (p.url() === beforeSearchUrl || /google\.[^/]+\/search|bing\.com\/search/i.test(p.url())) {
1256
  await p.goto(targetItem.url, { waitUntil: "domcontentloaded", timeout: 6500 }).catch(() => {});
1257
  }
1258
+ await wsSleep(450);
1259
  tabState.url = p.url();
1260
  };
1261
 
 
1289
  openedOk = true;
1290
  break;
1291
  } else {
1292
+ wsTabLog(`🛡️ Tab ${tabIdx + 1}: Cloudflare/block on ${target.domain}, trying next Google result...`);
1293
  }
1294
  } catch (navErr) {
1295
+ wsTabLog(`⚠️ Tab ${tabIdx + 1}: Timeout on ${target.domain}, trying next Google result...`);
1296
  }
1297
  }
1298