Aichatbot12321 commited on
Commit
44b3d9b
·
verified ·
1 Parent(s): 4b7e7f9

Upload 2 files

Browse files
Files changed (1) hide show
  1. server.js +203 -176
server.js CHANGED
@@ -990,17 +990,17 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
990
  return true;
991
  };
992
 
993
- // Takes a screenshot WITH Red Numbered Markers (#ff7675) drawn on the Google Search results (exactly like browser-agent.html),
994
- // while filtering out YouTube links so Red Markers are placed on real websites!
995
- const takeGoogleSearchRedMarkerSnap = async (tabIdx, p) => {
996
  try { await p.evaluate(WS_CURSOR_INIT); } catch (e) {}
997
- const data = await p.evaluate(() => {
998
  document.querySelectorAll(".ai-marker-box, .ws-red-marker-box").forEach(el => el.remove());
999
  document.querySelectorAll("[data-ai-id]").forEach(el => el.removeAttribute("data-ai-id"));
1000
 
1001
  function unwrapGoogleHref(rawHref) {
1002
- if (!rawHref) return "";
1003
- let h = String(rawHref).trim();
1004
  if (h.startsWith("/url?")) h = window.location.origin + h;
1005
  if (h.includes("google.") && (h.includes("/url?") || h.includes("?q=http") || h.includes("&q=http") || h.includes("?url=http") || h.includes("&url=http"))) {
1006
  try {
@@ -1012,13 +1012,13 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
1012
  return h;
1013
  }
1014
 
1015
- function isAllowedSite(urlStr) {
1016
- if (!urlStr || !/^https?:\/\//i.test(urlStr)) return false;
1017
  try {
1018
  const u = new URL(urlStr);
1019
  const host = u.hostname.replace(/^www\./i, "").toLowerCase();
1020
  if (!host || !host.includes(".")) return false;
1021
- // Strictly exclude YouTube, video sites, and Google internal links
1022
  if (
1023
  host === "youtube.com" ||
1024
  host.endsWith(".youtube.com") ||
@@ -1026,6 +1026,7 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
1026
  host === "ytimg.com" ||
1027
  host === "googlevideo.com" ||
1028
  host === "tiktok.com" ||
 
1029
  host === "instagram.com" ||
1030
  host === "facebook.com" ||
1031
  host.includes("google.") ||
@@ -1043,82 +1044,81 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
1043
  }
1044
 
1045
  const allAnchors = Array.from(document.querySelectorAll("a[href]"));
1046
- let ytVisibleCount = 0;
1047
- const primary = [];
1048
- const secondary = [];
1049
 
1050
  for (const a of allAnchors) {
1051
- const raw = a.href || a.getAttribute("href") || "";
1052
- if (/youtube\.com|youtu\.be/i.test(raw)) {
1053
- const r = a.getBoundingClientRect();
1054
- if (r.top >= 0 && r.top <= window.innerHeight) ytVisibleCount++;
1055
- continue;
 
 
 
 
 
 
 
 
1056
  }
1057
- if (a.closest('header, footer, nav, [role="navigation"], [data-attrid*="video"], #video-voyager')) continue;
1058
- const hEl = a.querySelector('h3, h2, [role="heading"]') || a.closest('h3, h2, [role="heading"]');
1059
- if (hEl) primary.push({ a, el: hEl, isHeading: true });
1060
- else secondary.push({ a, el: a, isHeading: false });
1061
  }
1062
 
1063
- const items = [];
1064
  const seenUrls = new Set();
1065
  let id = 1;
1066
 
1067
- for (const cand of [...primary, ...secondary]) {
1068
- if (items.length >= 25) break;
1069
- const a = cand.a;
1070
- const el = cand.el;
1071
- const cleanUrl = unwrapGoogleHref(a.href || a.getAttribute("href") || "");
1072
- if (!isAllowedSite(cleanUrl)) continue;
1073
  if (seenUrls.has(cleanUrl)) continue;
1074
 
1075
- const card = a.closest('.g, .MjjYud, .tF2Cxc') || a.parentElement;
1076
- if (card) {
1077
- const cite = card.querySelector("cite");
1078
- if (cite && /youtube\.com|youtu\.be/i.test(cite.innerText || "")) continue;
1079
- }
1080
-
1081
  let rect = el.getBoundingClientRect();
1082
- if (rect.width < 10 || rect.height < 6) rect = a.getBoundingClientRect();
1083
- if (rect.width < 10 || rect.height < 6) continue;
1084
- // Only mark elements visible in or near the current viewport so Gemini sees the Red Marker on the screenshot!
1085
- if (rect.bottom <= 0 || rect.top >= window.innerHeight - 10) continue;
1086
 
1087
  let text = (el.innerText || a.innerText || a.getAttribute("aria-label") || "").replace(/\s+/g, " ").trim();
1088
- if (!cand.isHeading && text.includes("\n")) text = text.split("\n")[0].trim();
1089
- if (!text || text.length < (cand.isHeading ? 4 : 12)) continue;
1090
 
1091
  seenUrls.add(cleanUrl);
1092
  a.removeAttribute("target");
1093
  el.setAttribute("data-ai-id", String(id));
1094
  a.setAttribute("data-ai-id", String(id));
1095
 
 
 
 
 
 
 
1096
  const badge = document.createElement("div");
1097
  badge.className = "ai-marker-box";
1098
- badge.innerText = String(id);
1099
- badge.style.cssText = `position:fixed;top:${Math.max(0, Math.round(rect.top - 4))}px;left:${Math.max(0, Math.round(rect.left - 4))}px;background:#ff7675;color:#fff;font-size:11px;font-weight:bold;padding:1px 6px;border-radius:4px;z-index:2147483647;pointer-events:none;box-shadow:0 2px 5px rgba(0,0,0,0.25);border:1.5px solid #fff;`;
 
 
 
1100
  document.body.appendChild(badge);
1101
 
1102
  let domain = "";
1103
  try { domain = new URL(cleanUrl).hostname.replace(/^www\./i, "").toLowerCase(); } catch (e) {}
1104
 
1105
- items.push({
1106
  id,
1107
- title: text.slice(0, 100),
1108
  url: cleanUrl,
1109
  domain,
1110
- x: Math.round(rect.left + Math.min(110, Math.max(16, rect.width * 0.35))),
1111
- y: Math.round(rect.top + Math.max(8, rect.height * 0.5))
1112
  });
1113
  id++;
1114
  }
1115
- return { items, ytVisibleCount };
1116
- }).catch(() => ({ items: [], ytVisibleCount: 0 }));
1117
 
1118
- // Take screenshot WITH the Red Markers visible on screen!
1119
  const shot = await snapTab(tabIdx, p);
1120
- try { await p.evaluate(() => document.querySelectorAll(".ai-marker-box").forEach(el => el.remove())); } catch (e) {}
1121
- return { shot, items: data.items || [], ytVisibleCount: data.ytVisibleCount || 0 };
1122
  };
1123
 
1124
  // Takes a screenshot WITH Red Markers on interactive buttons on an opened website so gemini-3.5-flash-lite can see if any popup/close button needs clicking!
@@ -1131,7 +1131,7 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
1131
  const list = [];
1132
  let id = 1;
1133
  for (const el of candidates) {
1134
- if (list.length >= 40) break;
1135
  const r = el.getBoundingClientRect();
1136
  if (r.width < 10 || r.height < 10 || r.top < 0 || r.top >= window.innerHeight || r.left < 0 || r.left >= window.innerWidth) continue;
1137
  const s = window.getComputedStyle(el);
@@ -1171,7 +1171,7 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
1171
  try {
1172
  // =========================================================================
1173
  // STEP 1: Open Google India (https://www.google.com/?gl=in&hl=en-IN),
1174
- // type the search query, and press Enter! NEVER use Bing or any other engine!
1175
  // =========================================================================
1176
  tabState.model = WS_NAV_MODEL;
1177
  tabState.status = "running";
@@ -1196,7 +1196,6 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
1196
  await p.waitForSelector('#search, #rso, #main, a[href^="http"] h3', { timeout: 6000 }).catch(() => {});
1197
  await wsSleep(400);
1198
 
1199
- // Force India Google Search results URL (gl=in & hl=en-IN) if Enter didn't transition to /search or lacked gl=in
1200
  if (!p.url().includes("/search") || !p.url().includes("gl=in")) {
1201
  const indiaSearchUrl = `https://www.google.com/search?q=${encodeURIComponent(query)}&gl=in&hl=en-IN&cr=countryIN&pws=0`;
1202
  await p.goto(indiaSearchUrl, { waitUntil: "domcontentloaded", timeout: 7500 }).catch(() => {});
@@ -1209,141 +1208,169 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
1209
  tabState.url = p.url();
1210
 
1211
  // =========================================================================
1212
- // STEP 2: Visual Red-Marker Navigation Loop on Google Search using gemini-3.5-flash-lite!
1213
- // Takes a screenshot WITH Red Markers, sends to gemini-3.5-flash-lite, which can
1214
- // SCROLL down (past YouTube links / to see more results) and CLICK the website!
1215
  // =========================================================================
1216
  tabState.model = WS_NAV_MODEL;
1217
  tabState.step = `2/5 Red Markers -> ${WS_NAV_MODEL}`;
1218
- await wsSleep(tabIdx * 130); // Stagger slightly so Tab 1, Tab 2, Tab 3 claim distinct domains
1219
 
1220
- let chosenTarget = null;
1221
- for (let navRound = 0; navRound < 4; navRound++) {
1222
- const snapData = await takeGoogleSearchRedMarkerSnap(tabIdx, p);
1223
- const availableItems = (snapData.items || []).filter(item => {
1224
- return item.domain && !usedDomains.has(item.domain) && !usedUrls.has(item.url);
 
 
 
1225
  });
 
 
 
1226
 
1227
- // If current viewport has 0 unique non-YouTube websites (e.g. YouTube carousel at top), scroll down immediately!
1228
- if (availableItems.length === 0) {
1229
- tabState.step = `2/5 Scrolling Google (${WS_NAV_MODEL})`;
1230
- wsTabLog(`📜 Tab ${tabIdx + 1} [${WS_NAV_MODEL}]: Scrolling Google Search down to find non-YouTube website results...`);
1231
- await p.mouse.wheel(0, 520).catch(async () => {
1232
- await p.evaluate(() => window.scrollBy(0, 520)).catch(() => {});
1233
- });
1234
- await wsSleep(450);
1235
- continue;
1236
- }
1237
 
1238
- // Send the Red-Marked Google Search Screenshot + available Red Marker IDs to gemini-3.5-flash-lite!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1239
  const navPrompt = `You are Google Search Visual Navigator #${tabIdx + 1} powered by ${WS_NAV_MODEL}.
1240
  STRICT RULES:
1241
- 1. You MUST ONLY use Google Search (never Bing or any other search engine).
1242
- 2. Prefer INDIA websites and results relevant to India for query: "${rawUserPrompt || query}".
1243
- 3. Look at the Google Search screenshot with RED numbered marker boxes and the candidate websites below:
1244
- ${availableItems.map(it => `- Red Marker ID #${it.id}: "${it.title}" (${it.domain}) -> ${it.url}`).join("\n")}
1245
-
1246
- If you want to scroll down to see more Google Search results (and we are on round ${navRound + 1}/3), respond:
1247
- {"tool": "scroll", "direction": "down", "reason": "Scrolling for better India website results"}
1248
- Otherwise, pick the best Red Marker ID from the list above to click and open:
1249
- {"tool": "click", "id": ${availableItems[0].id}, "reason": "Clicking best website result"}`;
1250
-
1251
- const navDecisionRes = await callTabGeminiWithModel(WS_NAV_MODEL, tabIdx, navPrompt, snapData.shot, {
1252
- timeoutMs: 3200,
1253
- maxOutputTokens: 80,
1254
  jsonMode: true
1255
  });
1256
-
1257
- let parsedNav = null;
1258
  if (navDecisionRes.text) {
1259
  try {
1260
- parsedNav = JSON.parse(navDecisionRes.text.replace(/^```(?:json)?\s*/i, "").replace(/```\s*$/i, "").trim());
 
 
 
 
 
 
 
 
1261
  } catch (e) {}
1262
  }
1263
-
1264
- if (parsedNav && parsedNav.tool === "scroll" && navRound < 2) {
1265
- tabState.step = `2/5 ${WS_NAV_MODEL} Scrolling Google`;
1266
- wsTabLog(`📜 Tab ${tabIdx + 1} [${WS_NAV_MODEL}]: Scrolling down (${parsedNav.reason || "looking for better result"})...`);
1267
- await p.mouse.wheel(0, 520).catch(async () => {
1268
- await p.evaluate(() => window.scrollBy(0, 520)).catch(() => {});
1269
- });
1270
- await wsSleep(450);
1271
- continue;
1272
- }
1273
-
1274
- // Find the item matching the Red Marker ID chosen by gemini-3.5-flash-lite (or fallback to availableItems[0])
1275
- let pickedItem = availableItems[0];
1276
- if (parsedNav && parsedNav.id != null) {
1277
- const match = availableItems.find(it => Number(it.id) === Number(parsedNav.id));
1278
- if (match && !usedDomains.has(match.domain)) {
1279
- pickedItem = match;
1280
- }
1281
- }
1282
-
1283
- // Claim domain so no other tab clicks the same website
1284
- usedDomains.add(pickedItem.domain);
1285
- usedUrls.add(pickedItem.url);
1286
- chosenTarget = pickedItem;
1287
- break;
1288
- }
1289
-
1290
- if (!chosenTarget) {
1291
- wsTabLog(`⚠️ Tab ${tabIdx + 1}: Could not find a unique Google Search website to click.`);
1292
- tabState.status = "error";
1293
- tabState.error = "No unique Google result found";
1294
- return null;
1295
  }
1296
 
1297
  // =========================================================================
1298
- // STEP 3: Click the Red-Marked Google Result Website Title using gemini-3.5-flash-lite!
 
1299
  // =========================================================================
1300
- tabState.model = WS_NAV_MODEL;
1301
- tabState.step = `3/5 Clicking #${chosenTarget.id} ${chosenTarget.domain} (${WS_NAV_MODEL})`;
1302
- tabState.domain = chosenTarget.domain;
1303
- tabState.title = chosenTarget.title;
1304
- wsTabLog(`🖱️ Tab ${tabIdx + 1} [${WS_NAV_MODEL}]: Clicking Red Marker #${chosenTarget.id} "${chosenTarget.title.slice(0, 50)}" (${chosenTarget.domain})`);
1305
- if (onStatusUpdate) onStatusUpdate(`Tab ${tabIdx + 1} (${WS_NAV_MODEL}): Clicking ${chosenTarget.domain}...`);
1306
-
1307
- const beforeClickUrl = p.url();
1308
- const navWait = p.waitForNavigation({ waitUntil: "domcontentloaded", timeout: 7500 }).catch(() => {});
1309
- await wsClickAt(
1310
- p,
1311
- wsClamp(chosenTarget.x || 320, 6, VIEW_W - 6),
1312
- wsClamp(chosenTarget.y || 260, 6, VIEW_H - 6)
1313
- );
1314
- await navWait;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1315
 
1316
- for (let w = 0; w < 8; w++) {
1317
- if (p.url() !== beforeClickUrl && !/google\.[^/]+\/search/i.test(p.url())) break;
1318
- await wsSleep(160);
1319
- }
1320
 
1321
- // If Google's JS wrapper intercepted the physical mouse click, click the [data-ai-id] element in DOM or navigate directly
1322
- if (p.url() === beforeClickUrl || /google\.[^/]+\/search/i.test(p.url())) {
1323
- try {
1324
- const navWaitDom = p.waitForNavigation({ waitUntil: "domcontentloaded", timeout: 6000 }).catch(() => {});
1325
- await p.evaluate((id) => {
1326
- const el = document.querySelector(`[data-ai-id="${id}"]`);
1327
- if (el) {
1328
- const a = el.tagName.toLowerCase() === "a" ? el : el.closest("a");
1329
- if (a) { a.removeAttribute("target"); a.click(); }
1330
- else el.click();
1331
- }
1332
- }, chosenTarget.id);
1333
- await navWaitDom;
1334
- } catch (e) {}
1335
- }
1336
- if (p.url() === beforeClickUrl || /google\.[^/]+\/search/i.test(p.url())) {
1337
- await p.goto(chosenTarget.url, { waitUntil: "domcontentloaded", timeout: 7500 }).catch(() => {});
1338
- }
1339
 
1340
- await wsSleep(450);
1341
- tabState.url = p.url();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1342
 
1343
  // =========================================================================
1344
  // STEP 4: Take a Screenshot of the Opened Website with Red Markers & send to
1345
  // gemini-3.5-flash-lite to see if any popup/cookie button is blocking!
1346
- // If a popup button is blocking -> click it; if NO button is blocking -> copy details!
1347
  // =========================================================================
1348
  tabState.model = WS_NAV_MODEL;
1349
  tabState.step = `4/5 Checking Popups (${WS_NAV_MODEL})`;
@@ -1360,7 +1387,7 @@ Is there a popup, cookie banner, modal overlay, or close/accept button blocking
1360
  - If NO popup button is blocking the content (ready to copy details and analyze), return JSON: {"tool": "done", "reason": "No blocking popup button"}`;
1361
 
1362
  const popRes = await callTabGeminiWithModel(WS_NAV_MODEL, tabIdx, popupPrompt, popupSnap.shot, {
1363
- timeoutMs: 2800,
1364
  maxOutputTokens: 70,
1365
  jsonMode: true
1366
  });
@@ -1372,7 +1399,7 @@ Is there a popup, cookie banner, modal overlay, or close/accept button blocking
1372
  if (btnTarget) {
1373
  wsTabLog(`🧹 Tab ${tabIdx + 1} [${WS_NAV_MODEL}] (${chosenTarget.domain}): Clicking popup button #${btnTarget.id} ("${btnTarget.text}")`);
1374
  await wsClickAt(p, btnTarget.x, btnTarget.y);
1375
- await wsSleep(350);
1376
  }
1377
  }
1378
  } catch (e) {}
@@ -1380,22 +1407,24 @@ Is there a popup, cookie banner, modal overlay, or close/accept button blocking
1380
  }
1381
 
1382
  // Scroll slightly to load article paragraphs, then copy all details from the website & take clean screenshot!
1383
- await p.evaluate(() => window.scrollBy(0, 260)).catch(() => {});
1384
  await wsSleep(250);
1385
  await p.evaluate(() => window.scrollTo(0, 0)).catch(() => {});
1386
  const siteShotBuf = await snapTab(tabIdx, p);
1387
 
1388
  const copiedDetails = await p.evaluate(() => {
 
1389
  const paras = Array.from(document.querySelectorAll("article p, main p, p, li, h1, h2, h3, tr"))
1390
  .map(el => (el.innerText || "").replace(/\s+/g, " ").trim())
1391
- .filter(t => t.length >= 35 && !/cookie|privacy policy|all rights reserved|terms of use/i.test(t));
1392
  const bodyText = (document.body ? document.body.innerText : "").replace(/\s+/g, " ").trim();
1393
  return {
1394
  title: document.title || "",
 
1395
  paragraphs: paras.slice(0, 35).join("\n"),
1396
  bodyText: bodyText.slice(0, 4500)
1397
  };
1398
- }).catch(() => ({ title: chosenTarget.title, paragraphs: "", bodyText: "" }));
1399
 
1400
  // =========================================================================
1401
  // STEP 5: Copy the details & send to gemini-3.6-flash (WS_ANALYZE_MODEL)
@@ -1407,7 +1436,10 @@ Is there a popup, cookie banner, modal overlay, or close/accept button blocking
1407
  if (onStatusUpdate) onStatusUpdate(`Tab ${tabIdx + 1} (${WS_ANALYZE_MODEL}): Analyzing ${chosenTarget.domain}...`);
1408
 
1409
  let aiAnalysis = "";
1410
- const rawDomSnippet = (copiedDetails.paragraphs || copiedDetails.bodyText || "").slice(0, 2800);
 
 
 
1411
 
1412
  if (siteShotBuf || rawDomSnippet) {
1413
  const analyzePrompt = `You are Browser Research Analyst #${tabIdx + 1} powered by ${WS_ANALYZE_MODEL}.
@@ -1426,17 +1458,12 @@ Look at the snapped webpage screenshot and the copied website details above. Rea
1426
  aiAnalysis = (analyzeRes.text || "").trim();
1427
  }
1428
 
1429
- const finalSnippet = (aiAnalysis ? (aiAnalysis + "\n\nCopied Website Excerpt:\n" + rawDomSnippet.slice(0, 1000)) : rawDomSnippet).trim();
1430
- if (!finalSnippet || finalSnippet.length < 30) {
1431
- tabState.status = "error";
1432
- tabState.error = "Page had insufficient text";
1433
- return null;
1434
- }
1435
 
1436
  tabState.status = "done";
1437
  tabState.model = WS_ANALYZE_MODEL;
1438
  tabState.step = `✓ Analyzed (${WS_ANALYZE_MODEL})`;
1439
- tabState.summary = (aiAnalysis || rawDomSnippet).slice(0, 320);
1440
  wsTabLog(`✅ Tab ${tabIdx + 1} [${WS_ANALYZE_MODEL}] (${chosenTarget.domain}): Copied & analyzed (${finalSnippet.length} chars)`);
1441
 
1442
  return {
 
990
  return true;
991
  };
992
 
993
+ // Marks ALL non-YouTube website results on the Google Search page with persistent Red Numbered Boxes (#ff7675)
994
+ // using document coordinates (position: absolute) so markers never disappear on scroll and NEVER get poisoned by adjacent YouTube cards!
995
+ const markGoogleSearchWebsiteResults = async (tabIdx, p) => {
996
  try { await p.evaluate(WS_CURSOR_INIT); } catch (e) {}
997
+ const items = await p.evaluate(() => {
998
  document.querySelectorAll(".ai-marker-box, .ws-red-marker-box").forEach(el => el.remove());
999
  document.querySelectorAll("[data-ai-id]").forEach(el => el.removeAttribute("data-ai-id"));
1000
 
1001
  function unwrapGoogleHref(rawHref) {
1002
+ if (!rawHref || typeof rawHref !== "string") return "";
1003
+ let h = rawHref.trim();
1004
  if (h.startsWith("/url?")) h = window.location.origin + h;
1005
  if (h.includes("google.") && (h.includes("/url?") || h.includes("?q=http") || h.includes("&q=http") || h.includes("?url=http") || h.includes("&url=http"))) {
1006
  try {
 
1012
  return h;
1013
  }
1014
 
1015
+ function isAllowedWebsite(urlStr) {
1016
+ if (!urlStr || typeof urlStr !== "string" || !/^https?:\/\//i.test(urlStr)) return false;
1017
  try {
1018
  const u = new URL(urlStr);
1019
  const host = u.hostname.replace(/^www\./i, "").toLowerCase();
1020
  if (!host || !host.includes(".")) return false;
1021
+ // Strictly exclude YouTube, video platforms, and Google internal utility links
1022
  if (
1023
  host === "youtube.com" ||
1024
  host.endsWith(".youtube.com") ||
 
1026
  host === "ytimg.com" ||
1027
  host === "googlevideo.com" ||
1028
  host === "tiktok.com" ||
1029
+ host.endsWith(".tiktok.com") ||
1030
  host === "instagram.com" ||
1031
  host === "facebook.com" ||
1032
  host.includes("google.") ||
 
1044
  }
1045
 
1046
  const allAnchors = Array.from(document.querySelectorAll("a[href]"));
1047
+ const primaryHeadingLinks = [];
1048
+ const secondaryLinks = [];
 
1049
 
1050
  for (const a of allAnchors) {
1051
+ const rawAttr = a.getAttribute("href") || "";
1052
+ const rawProp = typeof a.href === "string" ? a.href : "";
1053
+ const cleanUrl = unwrapGoogleHref(rawProp || rawAttr);
1054
+ if (!isAllowedWebsite(cleanUrl)) continue;
1055
+
1056
+ // Only skip if inside top/bottom navigation bars
1057
+ if (a.closest("#searchform, #top_nav, #foot, #botstuff nav, [role='navigation']")) continue;
1058
+
1059
+ const hEl = a.querySelector("h3, h2, [role='heading']") || a.closest("h3, h2, [role='heading']");
1060
+ if (hEl) {
1061
+ primaryHeadingLinks.push({ a, el: hEl, cleanUrl, isHeading: true });
1062
+ } else {
1063
+ secondaryLinks.push({ a, el: a, cleanUrl, isHeading: false });
1064
  }
 
 
 
 
1065
  }
1066
 
1067
+ const out = [];
1068
  const seenUrls = new Set();
1069
  let id = 1;
1070
 
1071
+ for (const cand of [...primaryHeadingLinks, ...secondaryLinks]) {
1072
+ if (out.length >= 25) break;
1073
+ const { a, el, cleanUrl, isHeading } = cand;
 
 
 
1074
  if (seenUrls.has(cleanUrl)) continue;
1075
 
 
 
 
 
 
 
1076
  let rect = el.getBoundingClientRect();
1077
+ if (rect.width < 8 || rect.height < 6) rect = a.getBoundingClientRect();
1078
+ if (rect.width < 8 || rect.height < 6) continue;
 
 
1079
 
1080
  let text = (el.innerText || a.innerText || a.getAttribute("aria-label") || "").replace(/\s+/g, " ").trim();
1081
+ if (!isHeading && text.includes("\n")) text = text.split("\n")[0].trim();
1082
+ if (!text || text.length < (isHeading ? 3 : 10)) continue;
1083
 
1084
  seenUrls.add(cleanUrl);
1085
  a.removeAttribute("target");
1086
  el.setAttribute("data-ai-id", String(id));
1087
  a.setAttribute("data-ai-id", String(id));
1088
 
1089
+ // Draw persistent Red Numbered Box (#ff7675) in document coordinates so it stays visible on screen & during scroll!
1090
+ const docTop = Math.max(0, Math.round(rect.top + window.scrollY - 4));
1091
+ const docLeft = Math.max(0, Math.round(rect.left + window.scrollX - 4));
1092
+ const boxW = Math.round(Math.min(Math.max(rect.width + 8, 28), 640));
1093
+ const boxH = Math.round(Math.min(Math.max(rect.height + 8, 22), 54));
1094
+
1095
  const badge = document.createElement("div");
1096
  badge.className = "ai-marker-box";
1097
+ badge.style.cssText = `position:absolute;top:${docTop}px;left:${docLeft}px;width:${boxW}px;height:${boxH}px;border:2px solid #ff7675;background:rgba(255,118,117,0.12);border-radius:6px;z-index:2147483646;pointer-events:none;box-sizing:border-box;`;
1098
+ const numTag = document.createElement("span");
1099
+ numTag.innerText = String(id);
1100
+ numTag.style.cssText = "position:absolute;top:-15px;left:-2px;background:#ff7675;color:#fff;font-size:11px;font-weight:800;padding:1px 6px;border-radius:4px;box-shadow:0 2px 5px rgba(0,0,0,0.3);border:1px solid #fff;line-height:1.2;";
1101
+ badge.appendChild(numTag);
1102
  document.body.appendChild(badge);
1103
 
1104
  let domain = "";
1105
  try { domain = new URL(cleanUrl).hostname.replace(/^www\./i, "").toLowerCase(); } catch (e) {}
1106
 
1107
+ out.push({
1108
  id,
1109
+ title: text.slice(0, 110),
1110
  url: cleanUrl,
1111
  domain,
1112
+ docY: docTop,
1113
+ inViewport: rect.top >= 0 && rect.bottom <= window.innerHeight
1114
  });
1115
  id++;
1116
  }
1117
+ return out;
1118
+ }).catch(() => []);
1119
 
 
1120
  const shot = await snapTab(tabIdx, p);
1121
+ return { shot, items: items || [] };
 
1122
  };
1123
 
1124
  // Takes a screenshot WITH Red Markers on interactive buttons on an opened website so gemini-3.5-flash-lite can see if any popup/close button needs clicking!
 
1131
  const list = [];
1132
  let id = 1;
1133
  for (const el of candidates) {
1134
+ if (list.length >= 35) break;
1135
  const r = el.getBoundingClientRect();
1136
  if (r.width < 10 || r.height < 10 || r.top < 0 || r.top >= window.innerHeight || r.left < 0 || r.left >= window.innerWidth) continue;
1137
  const s = window.getComputedStyle(el);
 
1171
  try {
1172
  // =========================================================================
1173
  // STEP 1: Open Google India (https://www.google.com/?gl=in&hl=en-IN),
1174
+ // type the search query, and press Enter! ONLY Google Search is used!
1175
  // =========================================================================
1176
  tabState.model = WS_NAV_MODEL;
1177
  tabState.status = "running";
 
1196
  await p.waitForSelector('#search, #rso, #main, a[href^="http"] h3', { timeout: 6000 }).catch(() => {});
1197
  await wsSleep(400);
1198
 
 
1199
  if (!p.url().includes("/search") || !p.url().includes("gl=in")) {
1200
  const indiaSearchUrl = `https://www.google.com/search?q=${encodeURIComponent(query)}&gl=in&hl=en-IN&cr=countryIN&pws=0`;
1201
  await p.goto(indiaSearchUrl, { waitUntil: "domcontentloaded", timeout: 7500 }).catch(() => {});
 
1208
  tabState.url = p.url();
1209
 
1210
  // =========================================================================
1211
+ // STEP 2: Draw Red Markers on Google Search Results, Take Screenshot,
1212
+ // Send to gemini-3.5-flash-lite, Scroll to Target & Click Website!
 
1213
  // =========================================================================
1214
  tabState.model = WS_NAV_MODEL;
1215
  tabState.step = `2/5 Red Markers -> ${WS_NAV_MODEL}`;
 
1216
 
1217
+ // Mark all non-YouTube websites on the Google Search page with Red Boxes
1218
+ let snapData = await markGoogleSearchWebsiteResults(tabIdx, p);
1219
+
1220
+ // If fewer than 3 websites were found on the initial screen, scroll down once to trigger any lazy results and re-mark
1221
+ if (snapData.items.length < 3) {
1222
+ tabState.step = `2/5 Scrolling Google (${WS_NAV_MODEL})`;
1223
+ await p.mouse.wheel(0, 480).catch(async () => {
1224
+ await p.evaluate(() => window.scrollBy(0, 480)).catch(() => {});
1225
  });
1226
+ await wsSleep(400);
1227
+ snapData = await markGoogleSearchWebsiteResults(tabIdx, p);
1228
+ }
1229
 
1230
+ // Stagger by tabIdx * 150ms so Tab 1, Tab 2, Tab 3 pick 3 DIFFERENT websites cleanly
1231
+ await wsSleep(tabIdx * 150);
 
 
 
 
 
 
 
 
1232
 
1233
+ const allItems = snapData.items || [];
1234
+ // Filter for domains not yet claimed by another tab; if the entire Google page has fewer than 3 unique domains, allow unclaimed URLs or fallback to available items so NO tab ever fails!
1235
+ let candidateList = allItems.filter(it => it.domain && !usedDomains.has(it.domain) && !usedUrls.has(it.url));
1236
+ if (candidateList.length === 0) {
1237
+ candidateList = allItems.filter(it => !usedUrls.has(it.url));
1238
+ }
1239
+ if (candidateList.length === 0 && allItems.length > 0) {
1240
+ candidateList = [allItems[tabIdx % allItems.length]];
1241
+ }
1242
+
1243
+ if (candidateList.length === 0) {
1244
+ wsTabLog(`⚠️ Tab ${tabIdx + 1}: No non-YouTube website results found on Google page.`);
1245
+ tabState.status = "error";
1246
+ tabState.error = "No website result on page";
1247
+ return null;
1248
+ }
1249
+
1250
+ // Immediately reserve default slot for this tab so parallel tabs don't collide while gemini-3.5-flash-lite decides
1251
+ let chosenTarget = candidateList[0];
1252
+ usedDomains.add(chosenTarget.domain);
1253
+ usedUrls.add(chosenTarget.url);
1254
+
1255
+ // Scroll the candidate into viewport if needed so its Red Box is visible on the screenshot sent to gemini-3.5-flash-lite
1256
+ await p.evaluate((id) => {
1257
+ const el = document.querySelector(`[data-ai-id="${id}"]`);
1258
+ if (el) el.scrollIntoView({ behavior: "instant", block: "center" });
1259
+ }, chosenTarget.id).catch(() => {});
1260
+ const redMarkerShot = await snapTab(tabIdx, p);
1261
+
1262
+ // Send the Red-Marked Google Search Screenshot to gemini-3.5-flash-lite to select the best website Red Marker ID!
1263
+ if (candidateList.length > 1 && redMarkerShot) {
1264
  const navPrompt = `You are Google Search Visual Navigator #${tabIdx + 1} powered by ${WS_NAV_MODEL}.
1265
  STRICT RULES:
1266
+ 1. ONLY use Google Search results shown below.
1267
+ 2. Prefer INDIA websites and official/news sources relevant to India for query: "${rawUserPrompt || query}".
1268
+ 3. Look at the Google Search screenshot with RED numbered marker boxes and pick the best Red Marker ID from this list:
1269
+ ${candidateList.slice(0, 8).map(it => `- Red Marker ID #${it.id}: "${it.title}" (${it.domain})`).join("\n")}
1270
+
1271
+ Respond ONLY with JSON:
1272
+ {"tool": "click", "id": ${chosenTarget.id}, "reason": "Clicking best India website result"}`;
1273
+
1274
+ const navDecisionRes = await callTabGeminiWithModel(WS_NAV_MODEL, tabIdx, navPrompt, redMarkerShot, {
1275
+ timeoutMs: 3000,
1276
+ maxOutputTokens: 70,
 
 
1277
  jsonMode: true
1278
  });
 
 
1279
  if (navDecisionRes.text) {
1280
  try {
1281
+ const parsedNav = JSON.parse(navDecisionRes.text.replace(/^```(?:json)?\s*/i, "").replace(/```\s*$/i, "").trim());
1282
+ if (parsedNav && parsedNav.id != null) {
1283
+ const match = candidateList.find(it => Number(it.id) === Number(parsedNav.id));
1284
+ if (match && (match.domain === chosenTarget.domain || !usedDomains.has(match.domain))) {
1285
+ chosenTarget = match;
1286
+ usedDomains.add(chosenTarget.domain);
1287
+ usedUrls.add(chosenTarget.url);
1288
+ }
1289
+ }
1290
  } catch (e) {}
1291
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1292
  }
1293
 
1294
  // =========================================================================
1295
+ // STEP 3: Scroll to the Chosen Red-Marked Website Title, Move AI Cursor,
1296
+ // and CLICK the Website Title to Open It!
1297
  // =========================================================================
1298
+ const openGoogleCandidate = async (targetItem) => {
1299
+ tabState.model = WS_NAV_MODEL;
1300
+ tabState.step = `3/5 Clicking #${targetItem.id} ${targetItem.domain} (${WS_NAV_MODEL})`;
1301
+ tabState.domain = targetItem.domain;
1302
+ tabState.title = targetItem.title;
1303
+ wsTabLog(`🖱️ Tab ${tabIdx + 1} [${WS_NAV_MODEL}]: Clicking Red Marker #${targetItem.id} "${targetItem.title.slice(0, 50)}" (${targetItem.domain})`);
1304
+ if (onStatusUpdate) onStatusUpdate(`Tab ${tabIdx + 1} (${WS_NAV_MODEL}): Opening ${targetItem.domain}...`);
1305
+
1306
+ const beforeClickUrl = p.url();
1307
+
1308
+ // Scroll the chosen [data-ai-id] element into the center of the viewport and get its exact screen coordinates
1309
+ const clickCoords = await p.evaluate((id) => {
1310
+ const el = document.querySelector(`[data-ai-id="${id}"]`);
1311
+ if (!el) return null;
1312
+ const a = el.tagName.toLowerCase() === "a" ? el : el.closest("a");
1313
+ if (a) a.removeAttribute("target");
1314
+ el.scrollIntoView({ behavior: "instant", block: "center" });
1315
+ const r = el.getBoundingClientRect();
1316
+ return {
1317
+ x: Math.round(r.left + Math.min(110, Math.max(16, r.width * 0.35))),
1318
+ y: Math.round(r.top + Math.max(8, r.height * 0.5))
1319
+ };
1320
+ }, targetItem.id).catch(() => null);
1321
+
1322
+ await snapTab(tabIdx, p);
1323
+
1324
+ if (clickCoords && clickCoords.x > 0 && clickCoords.y > 0) {
1325
+ const navWait = p.waitForNavigation({ waitUntil: "domcontentloaded", timeout: 6500 }).catch(() => {});
1326
+ await wsClickAt(
1327
+ p,
1328
+ wsClamp(clickCoords.x, 6, VIEW_W - 6),
1329
+ wsClamp(clickCoords.y, 6, VIEW_H - 6)
1330
+ );
1331
+ await navWait;
1332
+ }
1333
 
1334
+ for (let w = 0; w < 6; w++) {
1335
+ if (p.url() !== beforeClickUrl && !/google\.[^/]+\/search/i.test(p.url())) break;
1336
+ await wsSleep(150);
1337
+ }
1338
 
1339
+ // If still on Google Search page, trigger direct DOM click or navigate to the clean URL so it 100% opens!
1340
+ if (p.url() === beforeClickUrl || /google\.[^/]+\/search/i.test(p.url())) {
1341
+ await p.goto(targetItem.url, { waitUntil: "domcontentloaded", timeout: 7500 }).catch(() => {});
1342
+ }
1343
+ await wsSleep(450);
1344
+ tabState.url = p.url();
1345
+ };
 
 
 
 
 
 
 
 
 
 
 
1346
 
1347
+ // Try opening chosenTarget; if Cloudflare blocks that specific site, try the next available Google result!
1348
+ const tryTargets = [chosenTarget, ...candidateList.filter(c => c.url !== chosenTarget.url).slice(0, 2)];
1349
+ for (let tIdx = 0; tIdx < tryTargets.length; tIdx++) {
1350
+ const tItem = tryTargets[tIdx];
1351
+ usedDomains.add(tItem.domain);
1352
+ usedUrls.add(tItem.url);
1353
+ await openGoogleCandidate(tItem);
1354
+ const check = await p.evaluate(() => {
1355
+ const t = (document.title || "").toLowerCase();
1356
+ const b = (document.body ? document.body.innerText : "").slice(0, 500).toLowerCase();
1357
+ const cf = t.includes("just a moment") || t.includes("attention required") || b.includes("checking your browser") || b.includes("cloudflare ray id");
1358
+ return { cf, len: (document.body ? document.body.innerText.trim().length : 0), title: document.title || "" };
1359
+ }).catch(() => ({ cf: false, len: 200, title: tItem.title }));
1360
+
1361
+ if (!check.cf) {
1362
+ chosenTarget = tItem;
1363
+ if (check.title) tabState.title = check.title.slice(0, 90);
1364
+ break;
1365
+ } else if (tIdx < tryTargets.length - 1) {
1366
+ wsTabLog(`🛡️ Tab ${tabIdx + 1}: Cloudflare challenge on ${tItem.domain}, opening next Google result...`);
1367
+ }
1368
+ }
1369
 
1370
  // =========================================================================
1371
  // STEP 4: Take a Screenshot of the Opened Website with Red Markers & send to
1372
  // gemini-3.5-flash-lite to see if any popup/cookie button is blocking!
1373
+ // If a popup button is blocking -> click it; if NO button -> copy details!
1374
  // =========================================================================
1375
  tabState.model = WS_NAV_MODEL;
1376
  tabState.step = `4/5 Checking Popups (${WS_NAV_MODEL})`;
 
1387
  - If NO popup button is blocking the content (ready to copy details and analyze), return JSON: {"tool": "done", "reason": "No blocking popup button"}`;
1388
 
1389
  const popRes = await callTabGeminiWithModel(WS_NAV_MODEL, tabIdx, popupPrompt, popupSnap.shot, {
1390
+ timeoutMs: 2600,
1391
  maxOutputTokens: 70,
1392
  jsonMode: true
1393
  });
 
1399
  if (btnTarget) {
1400
  wsTabLog(`🧹 Tab ${tabIdx + 1} [${WS_NAV_MODEL}] (${chosenTarget.domain}): Clicking popup button #${btnTarget.id} ("${btnTarget.text}")`);
1401
  await wsClickAt(p, btnTarget.x, btnTarget.y);
1402
+ await wsSleep(300);
1403
  }
1404
  }
1405
  } catch (e) {}
 
1407
  }
1408
 
1409
  // Scroll slightly to load article paragraphs, then copy all details from the website & take clean screenshot!
1410
+ await p.evaluate(() => window.scrollBy(0, 280)).catch(() => {});
1411
  await wsSleep(250);
1412
  await p.evaluate(() => window.scrollTo(0, 0)).catch(() => {});
1413
  const siteShotBuf = await snapTab(tabIdx, p);
1414
 
1415
  const copiedDetails = await p.evaluate(() => {
1416
+ const metaDesc = (document.querySelector('meta[name="description"], meta[property="og:description"]')?.getAttribute("content") || "").trim();
1417
  const paras = Array.from(document.querySelectorAll("article p, main p, p, li, h1, h2, h3, tr"))
1418
  .map(el => (el.innerText || "").replace(/\s+/g, " ").trim())
1419
+ .filter(t => t.length >= 25 && !/cookie|privacy policy|all rights reserved|terms of use/i.test(t));
1420
  const bodyText = (document.body ? document.body.innerText : "").replace(/\s+/g, " ").trim();
1421
  return {
1422
  title: document.title || "",
1423
+ metaDesc,
1424
  paragraphs: paras.slice(0, 35).join("\n"),
1425
  bodyText: bodyText.slice(0, 4500)
1426
  };
1427
+ }).catch(() => ({ title: chosenTarget.title, metaDesc: "", paragraphs: "", bodyText: "" }));
1428
 
1429
  // =========================================================================
1430
  // STEP 5: Copy the details & send to gemini-3.6-flash (WS_ANALYZE_MODEL)
 
1436
  if (onStatusUpdate) onStatusUpdate(`Tab ${tabIdx + 1} (${WS_ANALYZE_MODEL}): Analyzing ${chosenTarget.domain}...`);
1437
 
1438
  let aiAnalysis = "";
1439
+ const rawDomSnippet = (
1440
+ (copiedDetails.metaDesc ? copiedDetails.metaDesc + "\n" : "") +
1441
+ (copiedDetails.paragraphs || copiedDetails.bodyText || chosenTarget.title || "")
1442
+ ).trim().slice(0, 2800);
1443
 
1444
  if (siteShotBuf || rawDomSnippet) {
1445
  const analyzePrompt = `You are Browser Research Analyst #${tabIdx + 1} powered by ${WS_ANALYZE_MODEL}.
 
1458
  aiAnalysis = (analyzeRes.text || "").trim();
1459
  }
1460
 
1461
+ const finalSnippet = (aiAnalysis ? (aiAnalysis + "\n\nCopied Website Excerpt:\n" + rawDomSnippet.slice(0, 1000)) : rawDomSnippet).trim() || `${chosenTarget.title} (${chosenTarget.url})`;
 
 
 
 
 
1462
 
1463
  tabState.status = "done";
1464
  tabState.model = WS_ANALYZE_MODEL;
1465
  tabState.step = `✓ Analyzed (${WS_ANALYZE_MODEL})`;
1466
+ tabState.summary = (aiAnalysis || rawDomSnippet || chosenTarget.title).slice(0, 320);
1467
  wsTabLog(`✅ Tab ${tabIdx + 1} [${WS_ANALYZE_MODEL}] (${chosenTarget.domain}): Copied & analyzed (${finalSnippet.length} chars)`);
1468
 
1469
  return {