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

Upload 2 files

Browse files
Files changed (1) hide show
  1. server.js +441 -539
server.js CHANGED
@@ -663,13 +663,13 @@ const WS_AUTO_CLOSE_POPUPS_FN = () => {
663
  };
664
 
665
  // 3-Tab Browser Search Model Routing:
666
- // - WS_NAV_MODEL ('gemini-3.5-flash-lite'): Used for ALL NAVIGATION (reading Red-Marked Google Search screenshots, scrolling past YT links, clicking the website title, and checking/closing popup buttons on the opened website)
667
  // - WS_ANALYZE_MODEL ('gemini-3.6-flash'): Used for READING & ANALYZING the copied website details + screenshot
668
  const WS_OPEN_MODEL = "gemini-3.5-flash-lite";
669
  const WS_NAV_MODEL = "gemini-3.5-flash-lite";
670
  const WS_ANALYZE_MODEL = "gemini-3.6-flash";
671
 
672
- // Custom URL filter: strictly excludes YouTube, video sites, and non-Google search engines (Bing/Yahoo/DuckDuckGo)
673
  function isNonYoutubeWebUrl(rawUrl) {
674
  if (!rawUrl || typeof rawUrl !== "string") return false;
675
  const u = rawUrl.trim();
@@ -698,7 +698,7 @@ function isNonYoutubeWebUrl(rawUrl) {
698
  return false;
699
  }
700
  if (
701
- /^(google\.(com|co\.[a-z]{2}|[a-z]{2})|webcache\.googleusercontent\.com|accounts\.google\.com|support\.google\.com|maps\.google\.com|translate\.google\.com|policies\.google\.com)$/i.test(host)
702
  ) {
703
  return false;
704
  }
@@ -711,85 +711,195 @@ function isNonYoutubeWebUrl(rawUrl) {
711
  }
712
  }
713
 
714
- const WS_STEALTH_INIT_FN = () => {
 
715
  try { Object.defineProperty(navigator, 'webdriver', { get: () => undefined }); } catch (e) {}
716
  try { Object.defineProperty(navigator, 'languages', { get: () => ['en-IN', 'en-US', 'en', 'hi-IN'] }); } catch (e) {}
717
  try { Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5] }); } catch (e) {}
718
  try { window.chrome = { runtime: {} }; } catch (e) {}
719
  };
720
 
721
- async function callTabGeminiWithModel(preferredModel, tabIdx, promptText, imageBuffer, opts = {}) {
722
- const timeoutMs = opts.timeoutMs || 5200;
723
- const maxOutputTokens = opts.maxOutputTokens || 340;
724
- const jsonMode = Boolean(opts.jsonMode);
 
725
 
726
- const allGeminiProviders = VISION_PROVIDERS.filter(p => p.type === "gemini" && p.key);
727
- const uniqueKeys = [];
728
- for (const p of allGeminiProviders) {
729
- if (p.key && !uniqueKeys.includes(p.key)) uniqueKeys.push(p.key);
 
 
 
 
 
 
 
 
730
  }
731
- if (process.env.GEMINI_API_KEY && !uniqueKeys.includes(process.env.GEMINI_API_KEY)) {
732
- uniqueKeys.push(process.env.GEMINI_API_KEY);
 
 
 
 
 
 
 
 
 
 
 
 
733
  }
734
- if (uniqueKeys.length === 0) return { text: "", modelUsed: preferredModel };
735
 
736
- const orderedKeys = preferredModel === WS_ANALYZE_MODEL
737
- ? [...uniqueKeys].reverse()
738
- : [...uniqueKeys];
739
- const rotatedKeys = orderedKeys.map((_, idx) => orderedKeys[(idx + tabIdx) % orderedKeys.length]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
740
 
741
- const modelChain = preferredModel === WS_NAV_MODEL
742
- ? [WS_NAV_MODEL, "gemini-3.1-flash-lite", "gemini-2.5-flash"]
743
- : [WS_ANALYZE_MODEL, "gemini-3.5-flash", "gemini-2.5-flash"];
744
 
745
- for (const modelId of modelChain) {
746
- for (const apiKey of rotatedKeys) {
 
747
  try {
748
- const parts = [{ text: promptText }];
749
- if (imageBuffer && imageBuffer.length) {
750
- parts.unshift({ inlineData: { mimeType: "image/jpeg", data: imageBuffer.toString("base64") } });
751
- }
752
- const generationConfig = {
753
- temperature: 0.1,
754
- maxOutputTokens
755
- };
756
- if (jsonMode) generationConfig.responseMimeType = "application/json";
757
- if (/^gemini-2\.5-flash/.test(modelId)) {
758
- generationConfig.thinkingConfig = { thinkingBudget: 0 };
 
 
 
759
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
760
 
761
- const resp = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${modelId}:generateContent?key=${apiKey}`, {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
762
  method: "POST",
763
- headers: { "Content-Type": "application/json" },
764
- body: JSON.stringify({
765
- contents: [{ role: "user", parts }],
766
- generationConfig
767
- }),
768
  signal: AbortSignal.timeout(timeoutMs)
769
  });
770
-
771
- if (!resp.ok) {
772
- if (resp.status === 404) break;
773
  continue;
774
  }
775
- const data = await resp.json();
776
- const text = ((data.candidates && data.candidates[0] && data.candidates[0].content && data.candidates[0].content.parts) || [])
777
- .filter(part => part.text && !part.thought)
778
- .map(part => part.text)
779
  .join("")
780
  .trim();
781
  if (text) {
782
- return { text, modelUsed: preferredModel };
 
783
  }
784
  } catch (e) {}
785
  }
786
  }
787
- return { text: "", modelUsed: preferredModel };
 
 
 
 
 
 
 
 
 
 
788
  }
789
 
790
  async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate) {
791
  const TIMEOUT_MS = 40000; // Strict 40-second timeout
792
- const VIEW_W = 1280, VIEW_H = 720;
793
  const startTime = Date.now();
794
  webSearchTabsState.active = true;
795
  webSearchTabsState.query = query;
@@ -797,14 +907,14 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
797
  webSearchTabsState.timeoutMs = TIMEOUT_MS;
798
  webSearchTabsState.fallbackStage = "";
799
  webSearchTabsState.logs = [];
800
- wsTabLog(`🚀 Launching 3-Tab Google India Visual Search for: "${query}" (Nav: ${WS_NAV_MODEL} | Analyze: ${WS_ANALYZE_MODEL} | 40s timeout)`);
801
 
802
  for (let i = 0; i < 3; i++) {
803
- webSearchTabsState.tabs[i].url = "https://www.google.com/?gl=in&hl=en-IN";
804
- webSearchTabsState.tabs[i].domain = "google.co.in";
805
  webSearchTabsState.tabs[i].title = `Agent #${i + 1} • Google Search (India)`;
806
  webSearchTabsState.tabs[i].status = "running";
807
- webSearchTabsState.tabs[i].step = `1/5 Opening Google India (${WS_NAV_MODEL})`;
808
  webSearchTabsState.tabs[i].model = WS_NAV_MODEL;
809
  webSearchTabsState.tabs[i].summary = "";
810
  webSearchTabsState.tabs[i].error = "";
@@ -823,31 +933,28 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
823
  }
824
  };
825
 
826
- const wsClamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
827
- const wsSleep = (ms) => new Promise(r => setTimeout(r, ms));
828
- const wsRnd = (a, b) => a + Math.random() * (b - a);
829
 
830
  try {
831
  const workPromise = (async () => {
832
  const browserInstance = await getSharedBrowser();
833
- // STRICT INDIA LOCALE, TIMEZONE & GEOLOCATION -> Always returns INDIA Google Search results, never USA results!
834
  context = await browserInstance.newContext({
835
  viewport: { width: VIEW_W, height: VIEW_H },
836
  userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
837
  locale: "en-IN",
838
  timezoneId: "Asia/Kolkata",
839
- geolocation: { latitude: 28.6139, longitude: 77.2090 }, // New Delhi, India
840
  permissions: ["geolocation"],
841
- extraHTTPHeaders: {
842
- "Accept-Language": "en-IN,en;q=0.9,hi-IN;q=0.8"
843
- },
844
  acceptDownloads: false
845
  });
846
 
847
- await context.addInitScript(WS_STEALTH_INIT_FN);
848
  await context.addInitScript(WS_CURSOR_INIT);
849
 
850
- // STRICT GOOGLE-ONLY NETWORK GUARD: Block any navigation to Bing, DuckDuckGo, or Yahoo!
851
  await context.route("**/*", async (route) => {
852
  try {
853
  const reqUrl = route.request().url().toLowerCase();
@@ -858,11 +965,12 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
858
  return route.continue().catch(() => {});
859
  });
860
 
 
 
 
861
  // Create 3 pages (tabs) in parallel and attach live CDP Screencast to each tab!
862
  const pages = await Promise.all([0, 1, 2].map(async (tabIdx) => {
863
  const p = await context.newPage();
864
- p.setDefaultTimeout(8500);
865
- p.setDefaultNavigationTimeout(12000);
866
  p.__curX = VIEW_W / 2;
867
  p.__curY = VIEW_H / 2;
868
  try {
@@ -880,41 +988,31 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
880
  return p;
881
  }));
882
 
883
- const snapTab = async (tabIdx, p) => {
 
884
  try {
885
- const buf = await p.screenshot({ type: "jpeg", quality: 62, timeout: 3500 });
886
- webSearchTabsState.tabs[tabIdx].lastFrame = buf;
887
- webSearchTabsState.tabs[tabIdx].frameSeq++;
888
- return buf;
889
- } catch (e) {
890
- return webSearchTabsState.tabs[tabIdx].lastFrame;
891
- }
892
- };
893
-
894
- const wsUpdateCursor = async (p, x, y, isClick) => {
895
- try {
896
- await p.evaluate(([ax, ay, ac]) => {
897
- if (window.__moveSearchCursor) window.__moveSearchCursor(ax, ay, !!ac);
898
- if (window.__updateAICursor) window.__updateAICursor(ax, ay, !!ac);
899
- }, [x, y, !!isClick]);
900
  } catch (e) {}
901
  };
902
 
903
- const wsMoveMouse = async (p, tx, ty, steps) => {
904
  if (!p || p.isClosed()) return;
905
  const sx = p.__curX || (VIEW_W / 2);
906
  const sy = p.__curY || (VIEW_H / 2);
907
- tx = wsClamp(tx, 4, VIEW_W - 4);
908
- ty = wsClamp(ty, 4, VIEW_H - 4);
909
  const dx = tx - sx, dy = ty - sy, dist = Math.hypot(dx, dy);
910
  if (dist < 4) {
911
  p.__curX = tx; p.__curY = ty;
912
  try { await p.mouse.move(tx, ty); } catch (e) {}
913
- return wsUpdateCursor(p, tx, ty, false);
914
  }
915
  const dev = Math.min(dist * 0.22, 45), nx = -dy / dist, ny = dx / dist, off = (Math.random() * 2 - 1) * dev;
916
  const ctrlX = (sx + tx) / 2 + nx * off, ctrlY = (sy + ty) / 2 + ny * off;
917
- const n = steps || Math.max(8, Math.min(Math.floor(dist / 26), 16));
918
  for (let i = 1; i <= n; i++) {
919
  const t = i / n, te = t * t * (3 - 2 * t), inv = 1 - te;
920
  let x = inv * inv * sx + 2 * inv * te * ctrlX + te * te * tx;
@@ -923,494 +1021,316 @@ async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate
923
  try {
924
  await p.mouse.move(x, y);
925
  p.__curX = x; p.__curY = y;
926
- if (i % 2 === 0 || i === n) await wsUpdateCursor(p, x, y, false);
927
  } catch (e) {}
928
- await wsSleep(10);
929
  }
930
  p.__curX = tx; p.__curY = ty;
931
  try { await p.mouse.move(tx, ty); } catch (e) {}
932
- await wsUpdateCursor(p, tx, ty, false);
933
  };
934
 
935
- const wsClickAt = async (p, x, y) => {
936
- await wsMoveMouse(p, x, y);
937
- await wsSleep(35 + Math.random() * 35);
938
- await wsUpdateCursor(p, x, y, true);
939
  try {
940
  await p.mouse.down();
941
- await wsSleep(45 + Math.random() * 40);
942
  await p.mouse.up();
943
  } catch (e) {}
944
- await wsSleep(45);
945
  };
946
 
947
- const wsTypeSearchBox = async (p, selectorList, searchText) => {
948
- let loc = null;
949
- for (const sel of selectorList) {
950
- const candidate = p.locator(sel).first();
951
- try {
952
- if (await candidate.isVisible({ timeout: 1500 })) {
953
- loc = candidate;
954
- break;
955
- }
956
- } catch (e) {}
957
- }
958
- if (!loc) return false;
959
- try { await loc.scrollIntoViewIfNeeded({ timeout: 1500 }); } catch (e) {}
960
  try {
961
  const box = await loc.boundingBox();
962
  if (box && box.width > 0 && box.height > 0) {
963
- await wsClickAt(
964
- p,
965
- wsClamp(box.x + box.width * wsRnd(0.3, 0.7), 6, VIEW_W - 6),
966
- wsClamp(box.y + box.height * wsRnd(0.3, 0.7), 6, VIEW_H - 6)
967
- );
968
  } else {
969
- await loc.click({ timeout: 1800 });
970
  }
971
  } catch (e) {
972
- try { await loc.click({ timeout: 1800 }); } catch (e2) {}
973
  }
 
 
 
 
 
 
974
  try {
975
- await p.keyboard.press("Control+A");
976
- await p.keyboard.press("Backspace");
 
 
977
  } catch (e) {}
978
- const s = String(searchText);
979
- const delay = 11;
980
- const tmo = Math.max(5000, s.length * (delay + 30));
981
- if (typeof loc.pressSequentially === "function") {
982
- await loc.pressSequentially(s, { delay, timeout: tmo });
983
- } else {
984
- await loc.type(s, { delay, timeout: tmo });
985
- }
986
- await wsSleep(90);
987
- const navPromise = p.waitForNavigation({ waitUntil: "domcontentloaded", timeout: 7000 }).catch(() => {});
988
- await p.keyboard.press("Enter");
989
- await navPromise;
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 {
1007
- const uObj = new URL(h, window.location.origin);
1008
- const realTarget = uObj.searchParams.get("q") || uObj.searchParams.get("url");
1009
- if (realTarget && realTarget.startsWith("http")) return realTarget;
1010
- } catch (e) {}
1011
- }
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") ||
1025
- host === "youtu.be" ||
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.") ||
1033
- host.includes("gstatic.com") ||
1034
- host.includes("googleapis.com") ||
1035
- host.includes("googleusercontent.com")
1036
- ) {
1037
- return false;
1038
- }
1039
- if (/\/(watch\?v=|shorts\/|reel\/)/i.test(u.pathname + u.search)) return false;
1040
- return true;
1041
- } catch (e) {
1042
- return false;
1043
- }
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!
1125
- const takeWebsitePopupCheckSnap = async (tabIdx, p) => {
 
1126
  try { await p.evaluate(WS_CURSOR_INIT); } catch (e) {}
1127
- const buttons = await p.evaluate(() => {
1128
- document.querySelectorAll(".ai-marker-box").forEach(el => el.remove());
1129
- document.querySelectorAll("[data-ai-id]").forEach(el => el.removeAttribute("data-ai-id"));
1130
- const candidates = Array.from(document.querySelectorAll('button, [role="button"], input[type="button"], input[type="submit"], a[class*="close" i], a[class*="accept" i], div[aria-label*="close" i], span[aria-label*="close" i]'));
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);
1138
- if (s.display === "none" || s.visibility === "hidden" || parseFloat(s.opacity) < 0.1) continue;
1139
- const txt = (el.innerText || el.value || el.getAttribute("aria-label") || el.getAttribute("title") || "").replace(/\s+/g, " ").trim().slice(0, 45);
1140
- if (!txt) continue;
1141
- el.setAttribute("data-ai-id", String(id));
1142
- const badge = document.createElement("div");
1143
- badge.className = "ai-marker-box";
1144
- badge.innerText = String(id);
1145
- badge.style.cssText = `position:fixed;top:${Math.max(0, Math.round(r.top - 4))}px;left:${Math.max(0, Math.round(r.left - 4))}px;background:#ff7675;color:#fff;font-size:11px;font-weight:bold;padding:1px 5px;border-radius:4px;z-index:2147483647;pointer-events:none;border:1px solid #fff;`;
1146
- document.body.appendChild(badge);
1147
- list.push({
1148
- id,
1149
- text: txt,
1150
- x: Math.round(r.left + r.width / 2),
1151
- y: Math.round(r.top + r.height / 2)
1152
- });
1153
- id++;
1154
  }
1155
- return list;
1156
- }).catch(() => []);
1157
-
1158
- const shot = await snapTab(tabIdx, p);
1159
- try { await p.evaluate(() => document.querySelectorAll(".ai-marker-box").forEach(el => el.remove())); } catch (e) {}
1160
- return { shot, buttons };
 
 
 
 
 
 
 
 
1161
  };
1162
 
1163
- // Coordinate chosen URLs/domains across the 3 tabs so ALL 3 TABS OPEN 3 DIFFERENT WEBSITES!
1164
  const usedDomains = new Set(["google.com", "www.google.com", "google.co.in", "www.google.co.in", "youtube.com", "youtu.be", "facebook.com", "instagram.com", "twitter.com", "x.com"]);
1165
  const usedUrls = new Set();
1166
 
1167
- // Run all 3 tabs concurrently!
1168
  const tabResults = await Promise.all([0, 1, 2].map(async (tabIdx) => {
1169
  const p = pages[tabIdx];
1170
  const tabState = webSearchTabsState.tabs[tabIdx];
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";
1178
- tabState.step = `1/5 Google India Search (${WS_NAV_MODEL})`;
1179
- const googleIndiaHome = "https://www.google.com/?gl=in&hl=en-IN&gws_rd=cr";
1180
- tabState.url = googleIndiaHome;
1181
- tabState.domain = "google.co.in";
1182
-
1183
- await p.goto(googleIndiaHome, { waitUntil: "domcontentloaded", timeout: 8000 }).catch(() => {});
1184
- await p.evaluate(WS_STEALTH_INIT_FN).catch(() => {});
1185
- await p.evaluate(WS_CURSOR_INIT).catch(() => {});
1186
  await p.evaluate(WS_AUTO_CLOSE_POPUPS_FN).catch(() => {});
1187
- await snapTab(tabIdx, p);
1188
-
1189
- wsTabLog(`⌨️ Tab ${tabIdx + 1} [${WS_NAV_MODEL}]: Typing "${query}" on Google India...`);
1190
- await wsTypeSearchBox(
1191
- p,
1192
- ['textarea[name="q"]', 'input[name="q"]', 'textarea[title*="Search"]', 'input[title*="Search"]'],
1193
- query
1194
- );
1195
-
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(() => {});
1202
- await p.waitForSelector('#search, #rso, #main, a[href^="http"] h3', { timeout: 5500 }).catch(() => {});
1203
- await wsSleep(350);
1204
- }
1205
 
1206
- await p.evaluate(WS_CURSOR_INIT).catch(() => {});
1207
- await p.evaluate(WS_AUTO_CLOSE_POPUPS_FN).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})`;
 
1377
  await p.evaluate(WS_AUTO_CLOSE_POPUPS_FN).catch(() => {});
1378
- const popupSnap = await takeWebsitePopupCheckSnap(tabIdx, p);
1379
-
1380
- if (popupSnap.buttons && popupSnap.buttons.length > 0 && popupSnap.shot) {
1381
- const popupPrompt = `You are Browser Navigator #${tabIdx + 1} (${WS_NAV_MODEL}) inspecting opened website: ${chosenTarget.domain}.
1382
- Look at the screenshot with RED numbered markers on buttons:
1383
- ${popupSnap.buttons.slice(0, 20).map(b => `- ID #${b.id}: "${b.text}"`).join("\n")}
1384
-
1385
- Is there a popup, cookie banner, modal overlay, or close/accept button blocking the article content?
1386
- - If YES, return JSON to click that button: {"tool": "click", "id": <button_id>, "reason": "Closing blocking popup"}
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
- });
1394
- if (popRes.text) {
1395
- try {
1396
- const parsedPop = JSON.parse(popRes.text.replace(/^```(?:json)?\s*/i, "").replace(/```\s*$/i, "").trim());
1397
- if (parsedPop && parsedPop.tool === "click" && parsedPop.id != null) {
1398
- const btnTarget = popupSnap.buttons.find(b => Number(b.id) === Number(parsedPop.id));
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) {}
1406
  }
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();
@@ -1424,52 +1344,34 @@ Is there a popup, cookie banner, modal overlay, or close/accept button blocking
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)
1431
- // to READ, ANALYZE, and GIVE the comprehensive information!
1432
- // =========================================================================
1433
- tabState.model = WS_ANALYZE_MODEL;
1434
- tabState.step = `5/5 Analyzing Details (${WS_ANALYZE_MODEL})`;
1435
- wsTabLog(`🧠 Tab ${tabIdx + 1} [${WS_ANALYZE_MODEL}]: Copied details from ${chosenTarget.domain} — analyzing with ${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}.
1446
  User Query: "${rawUserPrompt || query}"
1447
- Website Opened (India Google Search): ${chosenTarget.url} (${copiedDetails.title || chosenTarget.title})
1448
  Copied Website Details & Text:
1449
- ${rawDomSnippet.slice(0, 2400)}
1450
 
1451
  Look at the snapped webpage screenshot and the copied website details above. Read and analyze the page thoroughly to extract all key facts, numbers, dates, names, prices/scores/updates, and live details (prioritizing India context) that answer "${rawUserPrompt || query}". Also include 1-2 verbatim sentences from the page. Keep it factual and detailed (under 200 words).`;
1452
 
1453
- const analyzeRes = await callTabGeminiWithModel(WS_ANALYZE_MODEL, tabIdx, analyzePrompt, siteShotBuf, {
1454
- timeoutMs: 6500,
1455
- maxOutputTokens: 380,
1456
- jsonMode: false
1457
- });
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 {
1470
- title: copiedDetails.title || chosenTarget.title || chosenTarget.domain,
1471
- url: chosenTarget.url,
1472
- domain: chosenTarget.domain,
1473
  snippet: finalSnippet.slice(0, 2000)
1474
  };
1475
  } catch (tabErr) {
 
663
  };
664
 
665
  // 3-Tab Browser Search Model Routing:
666
+ // - WS_NAV_MODEL ('gemini-3.5-flash-lite'): Used for ALL NAVIGATION (Google Search Red-Marker screenshot inspection, scrolling, clicking website result URLs, and popup button dismissal)
667
  // - WS_ANALYZE_MODEL ('gemini-3.6-flash'): Used for READING & ANALYZING the copied website details + screenshot
668
  const WS_OPEN_MODEL = "gemini-3.5-flash-lite";
669
  const WS_NAV_MODEL = "gemini-3.5-flash-lite";
670
  const WS_ANALYZE_MODEL = "gemini-3.6-flash";
671
 
672
+ // Custom URL filter: strictly excludes YouTube, video sites, and non-Google search engines
673
  function isNonYoutubeWebUrl(rawUrl) {
674
  if (!rawUrl || typeof rawUrl !== "string") return false;
675
  const u = rawUrl.trim();
 
698
  return false;
699
  }
700
  if (
701
+ /^(google\.(com|co\.[a-z]{2}|[a-z]{2})|webcache\.googleusercontent\.com|accounts\.google\.com|support\.google\.com|maps\.google\.com|translate\.google\.com|policies\.google\.com|gstatic\.com|googleapis\.com)$/i.test(host)
702
  ) {
703
  return false;
704
  }
 
711
  }
712
  }
713
 
714
+ // Exact stealth init script from browser-agent (1).html (localized for India)
715
+ const WS_BA_STEALTH_FN = () => {
716
  try { Object.defineProperty(navigator, 'webdriver', { get: () => undefined }); } catch (e) {}
717
  try { Object.defineProperty(navigator, 'languages', { get: () => ['en-IN', 'en-US', 'en', 'hi-IN'] }); } catch (e) {}
718
  try { Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5] }); } catch (e) {}
719
  try { window.chrome = { runtime: {} }; } catch (e) {}
720
  };
721
 
722
+ // ExactBA_MARKER_FN from browser-agent (1).html — draws Red Numbered Boxes (#ff7675) with [data-ai-id] on all visible interactive elements,
723
+ // and attaches unwrapped href + domain on links while skipping YouTube links!
724
+ const WS_BA_MARKER_FN = () => {
725
+ document.querySelectorAll('.ai-marker-box, .ws-red-marker-box').forEach(el => el.remove());
726
+ document.querySelectorAll('[data-ai-id]').forEach(el => el.removeAttribute('data-ai-id'));
727
 
728
+ function unwrapHref(rawHref) {
729
+ if (!rawHref || typeof rawHref !== 'string') return '';
730
+ let h = rawHref.trim();
731
+ if (h.startsWith('/url?')) h = window.location.origin + h;
732
+ if (h.includes('google.') && (h.includes('/url?') || h.includes('?q=http') || h.includes('&q=http') || h.includes('?url=http') || h.includes('&url=http'))) {
733
+ try {
734
+ const uObj = new URL(h, window.location.origin);
735
+ const realTarget = uObj.searchParams.get('q') || uObj.searchParams.get('url');
736
+ if (realTarget && realTarget.startsWith('http')) return realTarget;
737
+ } catch (e) {}
738
+ }
739
+ return h;
740
  }
741
+
742
+ function isTrulyVisible(el) {
743
+ if (!el || el.disabled) return false;
744
+ const rect = el.getBoundingClientRect();
745
+ if (rect.width < 2 || rect.height < 2) return false;
746
+ if (rect.bottom <= -50 || rect.top >= window.innerHeight + 50 || rect.right <= -50 || rect.left >= window.innerWidth + 50) return false;
747
+ let curr = el, depth = 0;
748
+ while (curr && curr !== document.body && depth < 10) {
749
+ const s = window.getComputedStyle(curr);
750
+ if (s.display === 'none' || s.visibility === 'hidden' || parseFloat(s.opacity) < 0.05) return false;
751
+ curr = curr.parentElement;
752
+ depth++;
753
+ }
754
+ return true;
755
  }
 
756
 
757
+ const selectors = 'a[href], button, input:not([type="hidden"]), textarea, select, [role="button"], [role="link"], [role="search"], [role="textbox"], [contenteditable="true"]';
758
+ const elements = Array.from(document.querySelectorAll(selectors));
759
+ const items = [];
760
+ let id = 1;
761
+
762
+ for (const el of elements) {
763
+ if (items.length >= 150) break;
764
+ if (el.id === 'ai-virtual-cursor' || el.closest('#ai-virtual-cursor') || el.getAttribute('data-ai-ignore')) continue;
765
+ if (!isTrulyVisible(el)) continue;
766
+
767
+ const tag = el.tagName.toLowerCase();
768
+ const anchor = tag === 'a' ? el : el.closest('a[href]');
769
+ let rawHref = '';
770
+ if (anchor) {
771
+ rawHref = (typeof anchor.href === 'string' && anchor.href) ? anchor.href : (anchor.getAttribute('href') || '');
772
+ }
773
+ const cleanHref = unwrapHref(rawHref);
774
+
775
+ // Skip YouTube links completely so the AI never clicks YouTube videos
776
+ if (cleanHref && /youtube\.com|youtu\.be|ytimg\.com/i.test(cleanHref)) continue;
777
+
778
+ if (anchor) anchor.removeAttribute('target');
779
+
780
+ const rect = el.getBoundingClientRect();
781
+ el.setAttribute('data-ai-id', String(id));
782
+ if (anchor && !anchor.getAttribute('data-ai-id')) anchor.setAttribute('data-ai-id', String(id));
783
+
784
+ const badge = document.createElement('div');
785
+ badge.className = 'ai-marker-box';
786
+ badge.innerText = String(id);
787
+ 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 5px;border-radius:4px;z-index:2147483647;pointer-events:none;box-shadow:0 2px 4px rgba(0,0,0,0.2);border:1px solid #fff;';
788
+ document.body.appendChild(badge);
789
 
790
+ const hEl = anchor ? (anchor.querySelector('h3, h2, [role="heading"]') || el) : el;
791
+ let text = (hEl.innerText || el.innerText || el.value || el.placeholder || el.getAttribute('aria-label') || '').replace(/\s+/g, ' ').trim();
792
+ if (text.includes('\n')) text = text.split('\n')[0].trim();
793
 
794
+ let domain = '';
795
+ let isExternalResult = false;
796
+ if (cleanHref && /^https?:\/\//i.test(cleanHref)) {
797
  try {
798
+ domain = new URL(cleanHref).hostname.replace(/^www\./i, '').toLowerCase();
799
+ if (
800
+ domain &&
801
+ !domain.includes('google.') &&
802
+ !domain.includes('gstatic.com') &&
803
+ !domain.includes('googleapis.com') &&
804
+ !domain.includes('googleusercontent.com') &&
805
+ domain !== 'youtube.com' &&
806
+ domain !== 'youtu.be' &&
807
+ !domain.includes('bing.com') &&
808
+ !domain.includes('duckduckgo.com') &&
809
+ !domain.includes('yahoo.com')
810
+ ) {
811
+ isExternalResult = true;
812
  }
813
+ } catch (e) {}
814
+ }
815
+
816
+ items.push({
817
+ id: id,
818
+ tag: tag,
819
+ text: text.slice(0, 80),
820
+ href: isExternalResult ? cleanHref : '',
821
+ domain: isExternalResult ? domain : '',
822
+ hasHeading: Boolean(anchor && anchor.querySelector('h3, h2, [role="heading"]'))
823
+ });
824
+ id++;
825
+ }
826
+ return items;
827
+ };
828
+
829
+ const WS_BA_CLEANUP_FN = () => {
830
+ document.querySelectorAll('.ai-marker-box, .ws-red-marker-box').forEach(el => el.remove());
831
+ };
832
 
833
+ // Exact Gemini REST caller modeled on baGeminiOnce in browser-agent (1).html (using x-goog-api-key header, model rotation, and 15s timeout)
834
+ let wsKeyRR = 0;
835
+ function wsGetGeminiKeys() {
836
+ const out = [];
837
+ const add = (k) => { k = String(k || '').trim(); if (k && !out.includes(k)) out.push(k); };
838
+ add(process.env.GEMINI_API_KEY);
839
+ for (let i = 1; i <= 5; i++) add(process.env['GEMINI_API_KEY_' + i]);
840
+ for (const p of VISION_PROVIDERS) {
841
+ if (p && p.type === 'gemini' && p.key) add(p.key);
842
+ }
843
+ return out;
844
+ }
845
+
846
+ async function wsCallGemini(preferredModel, tabIdx, shotBuffer, promptText, jsonMode = true, timeoutMs = 14000) {
847
+ const keys = wsGetGeminiKeys();
848
+ if (!keys.length) return "";
849
+ const models = preferredModel === WS_NAV_MODEL
850
+ ? [WS_NAV_MODEL, "gemini-3.1-flash-lite", "gemini-3.5-flash", "gemini-2.5-flash"]
851
+ : [WS_ANALYZE_MODEL, "gemini-3.5-flash", "gemini-2.5-flash", "gemini-3.1-flash-lite"];
852
+
853
+ for (const model of models) {
854
+ for (let i = 0; i < keys.length; i++) {
855
+ const key = keys[(wsKeyRR + tabIdx + i) % keys.length];
856
+ try {
857
+ const gen = { temperature: 0.1 };
858
+ if (jsonMode) gen.responseMimeType = "application/json";
859
+ if (/^gemini-2\.5-flash/.test(model)) gen.thinkingConfig = { thinkingBudget: 0 };
860
+ const parts = [{ text: promptText }];
861
+ if (shotBuffer && shotBuffer.length) {
862
+ parts.unshift({ inlineData: { mimeType: "image/jpeg", data: shotBuffer.toString("base64") } });
863
+ }
864
+ const r = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent`, {
865
  method: "POST",
866
+ headers: { "Content-Type": "application/json", "x-goog-api-key": key },
867
+ body: JSON.stringify({ contents: [{ role: "user", parts }], generationConfig: gen }),
 
 
 
868
  signal: AbortSignal.timeout(timeoutMs)
869
  });
870
+ const d = await r.json().catch(() => ({}));
871
+ if (!r.ok) {
872
+ if (r.status === 404) break; // Model ID not available on endpoint -> try next model in chain immediately
873
  continue;
874
  }
875
+ const text = ((d.candidates && d.candidates[0] && d.candidates[0].content && d.candidates[0].content.parts) || [])
876
+ .filter(p => p.text && !p.thought)
877
+ .map(p => p.text)
 
878
  .join("")
879
  .trim();
880
  if (text) {
881
+ wsKeyRR = (wsKeyRR + 1) % keys.length;
882
+ return text;
883
  }
884
  } catch (e) {}
885
  }
886
  }
887
+ return "";
888
+ }
889
+
890
+ function wsParseDecision(raw) {
891
+ try {
892
+ let t = String(raw || "").trim().replace(/^```(?:json)?\s*/i, "").replace(/```\s*$/i, "").trim();
893
+ let d = JSON.parse(t);
894
+ if (Array.isArray(d)) d = d[0];
895
+ if (d && typeof d === "object") return d;
896
+ } catch (e) {}
897
+ return null;
898
  }
899
 
900
  async function performThreeTabBrowserSearch(query, rawUserPrompt, onStatusUpdate) {
901
  const TIMEOUT_MS = 40000; // Strict 40-second timeout
902
+ const VIEW_W = 1280, VIEW_H = 800;
903
  const startTime = Date.now();
904
  webSearchTabsState.active = true;
905
  webSearchTabsState.query = query;
 
907
  webSearchTabsState.timeoutMs = TIMEOUT_MS;
908
  webSearchTabsState.fallbackStage = "";
909
  webSearchTabsState.logs = [];
910
+ wsTabLog(`🚀 Launching 3-Tab Google India Browser Agent for: "${query}" (Nav: ${WS_NAV_MODEL} | Analyze: ${WS_ANALYZE_MODEL} | 40s timeout)`);
911
 
912
  for (let i = 0; i < 3; i++) {
913
+ webSearchTabsState.tabs[i].url = "https://www.google.com";
914
+ webSearchTabsState.tabs[i].domain = "google.com";
915
  webSearchTabsState.tabs[i].title = `Agent #${i + 1} • Google Search (India)`;
916
  webSearchTabsState.tabs[i].status = "running";
917
+ webSearchTabsState.tabs[i].step = `1/5 Opening google.com (${WS_NAV_MODEL})`;
918
  webSearchTabsState.tabs[i].model = WS_NAV_MODEL;
919
  webSearchTabsState.tabs[i].summary = "";
920
  webSearchTabsState.tabs[i].error = "";
 
933
  }
934
  };
935
 
936
+ const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, Number(v)));
937
+ const baSleep = (ms) => new Promise(r => setTimeout(r, ms));
938
+ const rnd = (a, b) => a + Math.random() * (b - a);
939
 
940
  try {
941
  const workPromise = (async () => {
942
  const browserInstance = await getSharedBrowser();
 
943
  context = await browserInstance.newContext({
944
  viewport: { width: VIEW_W, height: VIEW_H },
945
  userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
946
  locale: "en-IN",
947
  timezoneId: "Asia/Kolkata",
948
+ geolocation: { latitude: 28.6139, longitude: 77.2090 },
949
  permissions: ["geolocation"],
950
+ extraHTTPHeaders: { "Accept-Language": "en-IN,en;q=0.9,hi-IN;q=0.8" },
 
 
951
  acceptDownloads: false
952
  });
953
 
954
+ await context.addInitScript(WS_BA_STEALTH_FN);
955
  await context.addInitScript(WS_CURSOR_INIT);
956
 
957
+ // Strictly block Bing, DuckDuckGo, and Yahoo so the browser ONLY ever searches on Google!
958
  await context.route("**/*", async (route) => {
959
  try {
960
  const reqUrl = route.request().url().toLowerCase();
 
965
  return route.continue().catch(() => {});
966
  });
967
 
968
+ context.setDefaultTimeout(8000);
969
+ context.setDefaultNavigationTimeout(15000);
970
+
971
  // Create 3 pages (tabs) in parallel and attach live CDP Screencast to each tab!
972
  const pages = await Promise.all([0, 1, 2].map(async (tabIdx) => {
973
  const p = await context.newPage();
 
 
974
  p.__curX = VIEW_W / 2;
975
  p.__curY = VIEW_H / 2;
976
  try {
 
988
  return p;
989
  }));
990
 
991
+ // Exact mouse & typing helpers from browser-agent (1).html (baMoveMouse, baClickAt, baTypeInto, baSafeClick, baTakeSnap)
992
+ const baCursorTo = async (p, x, y, click) => {
993
  try {
994
+ await p.evaluate(([a, b, c]) => {
995
+ if (window.__moveSearchCursor) window.__moveSearchCursor(a, b, !!c);
996
+ if (window.__updateAICursor) window.__updateAICursor(a, b, !!c);
997
+ }, [x, y, !!click]);
 
 
 
 
 
 
 
 
 
 
 
998
  } catch (e) {}
999
  };
1000
 
1001
+ const baMoveMouse = async (p, tx, ty, steps) => {
1002
  if (!p || p.isClosed()) return;
1003
  const sx = p.__curX || (VIEW_W / 2);
1004
  const sy = p.__curY || (VIEW_H / 2);
1005
+ tx = clamp(tx, 2, VIEW_W - 2);
1006
+ ty = clamp(ty, 2, VIEW_H - 2);
1007
  const dx = tx - sx, dy = ty - sy, dist = Math.hypot(dx, dy);
1008
  if (dist < 4) {
1009
  p.__curX = tx; p.__curY = ty;
1010
  try { await p.mouse.move(tx, ty); } catch (e) {}
1011
+ return baCursorTo(p, tx, ty, false);
1012
  }
1013
  const dev = Math.min(dist * 0.22, 45), nx = -dy / dist, ny = dx / dist, off = (Math.random() * 2 - 1) * dev;
1014
  const ctrlX = (sx + tx) / 2 + nx * off, ctrlY = (sy + ty) / 2 + ny * off;
1015
+ const n = steps || Math.max(10, Math.min(Math.floor(dist / 22), 20));
1016
  for (let i = 1; i <= n; i++) {
1017
  const t = i / n, te = t * t * (3 - 2 * t), inv = 1 - te;
1018
  let x = inv * inv * sx + 2 * inv * te * ctrlX + te * te * tx;
 
1021
  try {
1022
  await p.mouse.move(x, y);
1023
  p.__curX = x; p.__curY = y;
1024
+ if (i % 2 === 0 || i === n) await baCursorTo(p, x, y, false);
1025
  } catch (e) {}
1026
+ await baSleep(10);
1027
  }
1028
  p.__curX = tx; p.__curY = ty;
1029
  try { await p.mouse.move(tx, ty); } catch (e) {}
1030
+ await baCursorTo(p, tx, ty, false);
1031
  };
1032
 
1033
+ const baClickAt = async (p, x, y) => {
1034
+ await baMoveMouse(p, x, y);
1035
+ await baSleep(45 + Math.random() * 40);
1036
+ await baCursorTo(p, x, y, true);
1037
  try {
1038
  await p.mouse.down();
1039
+ await baSleep(55 + Math.random() * 45);
1040
  await p.mouse.up();
1041
  } catch (e) {}
1042
+ await baSleep(55);
1043
  };
1044
 
1045
+ const baTypeInto = async (p, loc, text, delay) => {
1046
+ await loc.scrollIntoViewIfNeeded({ timeout: 2500 });
 
 
 
 
 
 
 
 
 
 
 
1047
  try {
1048
  const box = await loc.boundingBox();
1049
  if (box && box.width > 0 && box.height > 0) {
1050
+ await baClickAt(p, clamp(box.x + box.width * rnd(0.3, 0.7), 5, VIEW_W - 5), clamp(box.y + box.height * rnd(0.3, 0.7), 5, VIEW_H - 5));
 
 
 
 
1051
  } else {
1052
+ await loc.click({ timeout: 2500 });
1053
  }
1054
  } catch (e) {
1055
+ try { await loc.click({ timeout: 2500 }); } catch (e2) {}
1056
  }
1057
+ await p.keyboard.press("Control+A");
1058
+ await p.keyboard.press("Backspace");
1059
+ const s = String(text);
1060
+ const d = delay || 10, tmo = Math.max(8000, s.length * (d + 40));
1061
+ if (typeof loc.pressSequentially === "function") await loc.pressSequentially(s, { delay: d, timeout: tmo });
1062
+ else await loc.type(s, { delay: d, timeout: tmo });
1063
  try {
1064
+ await loc.evaluate((el) => {
1065
+ el.dispatchEvent(new Event("input", { bubbles: true }));
1066
+ el.dispatchEvent(new Event("change", { bubbles: true }));
1067
+ });
1068
  } catch (e) {}
 
 
 
 
 
 
 
 
 
 
 
 
 
1069
  };
1070
 
1071
+ // Exact baSafeClick from browser-agent (1).html + guaranteed navigation follow-through
1072
+ const baSafeClick = async (p, id, expectedHref) => {
1073
+ const loc = p.locator(`[data-ai-id="${parseInt(id, 10)}"]`).first();
1074
+ const navErr = (m) => /execution context was destroyed|navigated|navigation|target closed/i.test(m);
1075
+ const beforeUrl = p.url();
1076
+ try {
1077
+ await loc.scrollIntoViewIfNeeded({ timeout: 2500 });
1078
+ const box = await loc.boundingBox();
1079
+ if (box && box.width > 0 && box.height > 0) {
1080
+ await baClickAt(p, clamp(box.x + box.width * rnd(0.35, 0.65), 5, VIEW_W - 5), clamp(box.y + box.height * rnd(0.35, 0.65), 5, VIEW_H - 5));
1081
+ } else {
1082
+ await loc.click({ timeout: 2500 });
 
 
 
 
 
 
 
 
1083
  }
1084
+ } catch (e) {
1085
+ if (!navErr(String(e.message))) {
 
1086
  try {
1087
+ await p.evaluate((i) => {
1088
+ const el = document.querySelector('[data-ai-id="' + i + '"]');
1089
+ if (el) {
1090
+ const a = el.tagName.toLowerCase() === "a" ? el : el.closest("a");
1091
+ if (a) { a.removeAttribute("target"); a.click(); }
1092
+ else el.click();
1093
+ }
1094
+ }, id);
1095
+ } catch (e2) {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1096
  }
1097
+ }
1098
+ // Wait up to 1.8s to see if clicking the element initiated navigation
1099
+ for (let w = 0; w < 9; w++) {
1100
+ await baSleep(200);
1101
+ if (p.url() !== beforeUrl && !/google\.[^/]+\/search/i.test(p.url())) break;
1102
+ }
1103
+ // If clicking a search result link on Google Search still hasn't left Google Search, trigger direct anchor click or goto expectedHref
1104
+ if (expectedHref && (p.url() === beforeUrl || /google\.[^/]+\/search/i.test(p.url()))) {
1105
+ try {
1106
+ await p.evaluate((i) => {
1107
+ const el = document.querySelector('[data-ai-id="' + i + '"]');
1108
+ const a = el && (el.tagName.toLowerCase() === "a" ? el : el.closest("a"));
1109
+ if (a && a.href) { a.removeAttribute("target"); a.click(); }
1110
+ }, id);
1111
+ } catch (e) {}
1112
+ await baSleep(600);
1113
+ if (p.url() === beforeUrl || /google\.[^/]+\/search/i.test(p.url())) {
1114
+ await p.goto(expectedHref, { waitUntil: "domcontentloaded", timeout: 8000 }).catch(() => {});
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1115
  }
1116
+ }
 
 
 
 
1117
  };
1118
 
1119
+ // Exact baTakeSnap from browser-agent (1).html: injects Red Markers, takes screenshot WITH Red Markers, updates live frame, then cleans up
1120
+ const baTakeSnap = async (tabIdx, p, keepMarkersOnScreen = false) => {
1121
+ try { await p.waitForLoadState("domcontentloaded", { timeout: 2500 }); } catch (e) {}
1122
  try { await p.evaluate(WS_CURSOR_INIT); } catch (e) {}
1123
+ let elements = [];
1124
+ for (let i = 0; i < 3; i++) {
1125
+ try {
1126
+ elements = await p.evaluate(WS_BA_MARKER_FN);
1127
+ break;
1128
+ } catch (e) {
1129
+ await baSleep(300);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1130
  }
1131
+ }
1132
+ let shot = null;
1133
+ try {
1134
+ shot = await p.screenshot({ type: "jpeg", quality: 62, timeout: 5000 });
1135
+ webSearchTabsState.tabs[tabIdx].lastFrame = shot;
1136
+ webSearchTabsState.tabs[tabIdx].frameSeq++;
1137
+ } catch (e) {
1138
+ shot = webSearchTabsState.tabs[tabIdx].lastFrame || Buffer.alloc(0);
1139
+ }
1140
+ if (!keepMarkersOnScreen) {
1141
+ try { await p.evaluate(WS_BA_CLEANUP_FN); } catch (e) {}
1142
+ }
1143
+ webSearchTabsState.tabs[tabIdx].url = p.url();
1144
+ return { shot, elements: elements || [] };
1145
  };
1146
 
1147
+ // Shared sets so Tab 1, Tab 2, Tab 3 NEVER click the same website domain!
1148
  const usedDomains = new Set(["google.com", "www.google.com", "google.co.in", "www.google.co.in", "youtube.com", "youtu.be", "facebook.com", "instagram.com", "twitter.com", "x.com"]);
1149
  const usedUrls = new Set();
1150
 
1151
+ // Run all 3 tabs concurrently using the exact browser-agent (1).html workflow!
1152
  const tabResults = await Promise.all([0, 1, 2].map(async (tabIdx) => {
1153
  const p = pages[tabIdx];
1154
  const tabState = webSearchTabsState.tabs[tabIdx];
1155
  try {
1156
  // =========================================================================
1157
+ // STEP 1: Open https://www.google.com (India locale), take Red-Marker snap,
1158
+ // type the search query into Google's search box, and press Enter!
1159
  // =========================================================================
1160
  tabState.model = WS_NAV_MODEL;
1161
  tabState.status = "running";
1162
+ tabState.step = `1/5 Opening google.com (${WS_NAV_MODEL})`;
1163
+ await p.goto("https://www.google.com/?gl=in&hl=en-IN", { waitUntil: "domcontentloaded", timeout: 10000 }).catch(() => {});
 
 
 
 
 
 
1164
  await p.evaluate(WS_AUTO_CLOSE_POPUPS_FN).catch(() => {});
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1165
 
1166
+ let snap = await baTakeSnap(tabIdx, p);
1167
+ tabState.step = `1/5 Typing Search on Google (${WS_NAV_MODEL})`;
1168
+ wsTabLog(`⌨️ Tab ${tabIdx + 1} [${WS_NAV_MODEL}]: Typing "${query}" into Google Search...`);
1169
+
1170
+ // Find the Google search box element ID from BA_MARKER_FN (or use textarea[name="q"] / input[name="q"])
1171
+ const searchInputItem = snap.elements.find(e => (e.tag === "textarea" || e.tag === "input") && /search| खोज/i.test(e.text || "")) ||
1172
+ snap.elements.find(e => e.tag === "textarea") ||
1173
+ snap.elements.find(e => e.tag === "input");
1174
+ const searchLoc = searchInputItem
1175
+ ? p.locator(`[data-ai-id="${searchInputItem.id}"]`).first()
1176
+ : p.locator('textarea[name="q"], input[name="q"]').first();
1177
+
1178
+ await baTypeInto(p, searchLoc, query, 10);
1179
+ const navWaitSearch = p.waitForNavigation({ waitUntil: "domcontentloaded", timeout: 7500 }).catch(() => {});
1180
+ await p.keyboard.press("Enter");
1181
+ await navWaitSearch;
1182
+ await baSleep(500);
1183
 
1184
  // =========================================================================
1185
+ // STEP 2: Exact baWorker Loop on Google Search using gemini-3.5-flash-lite!
1186
+ // Takes screenshot WITH Red Markers, sends to gemini-3.5-flash-lite,
1187
+ // scrolls if needed, and clicks the website result URL!
1188
  // =========================================================================
1189
+ await baSleep(tabIdx * 180); // Stagger slightly so Tab 1, Tab 2, Tab 3 claim 3 different websites
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1190
 
1191
+ let openedWebsite = null;
1192
+ for (let step = 1; step <= 4; step++) {
 
 
 
1193
  tabState.model = WS_NAV_MODEL;
1194
+ tabState.step = `2/5 Red Markers -> ${WS_NAV_MODEL} (Step ${step})`;
1195
+ snap = await baTakeSnap(tabIdx, p);
1196
+
1197
+ // Identify all visible external website links on the Google Search screen
1198
+ const allExternalLinks = snap.elements.filter(el => el.href && el.domain && isNonYoutubeWebUrl(el.href));
1199
+ // Prefer links with a domain not yet claimed by another tab
1200
+ let eligibleLinks = allExternalLinks.filter(el => !usedDomains.has(el.domain) && !usedUrls.has(el.href));
1201
+ // If all visible domains were already claimed by other tabs, allow unclaimed URLs
1202
+ if (eligibleLinks.length === 0) {
1203
+ eligibleLinks = allExternalLinks.filter(el => !usedUrls.has(el.href));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1204
  }
1205
 
1206
+ // Ask gemini-3.5-flash-lite (with the Red-Marked screenshot + elements) what to do, just like baPrompt in browser-agent (1).html!
1207
+ const navPrompt = `
1208
+ User Goal: "Search Google (India) for '${rawUserPrompt || query}' and click a non-YouTube website result link to open it."
1209
+ Step: ${step}/4. Current URL: ${p.url()}
1210
+ Already Claimed Websites by Other Tabs (DO NOT click these): ${Array.from(usedDomains).join(", ")}
1211
+ Eligible Website Result Links on Screen (Red Numbered Markers): ${JSON.stringify(eligibleLinks.map(e => ({ id: e.id, title: e.text, domain: e.domain, url: e.href })))}
1212
+ All Interactive Elements on Screen: ${JSON.stringify(snap.elements.slice(0, 80).map(e => ({ id: e.id, tag: e.tag, text: e.text, domain: e.domain })))}
1213
+
1214
+ CRITICAL INSTRUCTIONS:
1215
+ 1. STRICT RULE: ONLY use Google Search. NEVER use goto to open Bing, DuckDuckGo, or Yahoo.
1216
+ 2. If Eligible Website Result Links on Screen is empty (or you need to scroll down past YouTube videos / AI overview to see more website links) and Step < 4, respond with:
1217
+ {"tool": "scroll", "direction": "down", "reason": "Scrolling down on Google Search to find website links"}
1218
+ 3. Otherwise, you MUST click the best website link from "Eligible Website Result Links on Screen" by returning its exact Red Marker ID:
1219
+ {"tool": "click", "id": ${eligibleLinks[0] ? eligibleLinks[0].id : 1}, "reason": "Clicking Google search result website"}
1220
+ Respond with valid JSON for ONE tool: "click" or "scroll".`;
1221
+
1222
+ const rawDec = await wsCallGemini(WS_NAV_MODEL, tabIdx, snap.shot, navPrompt, true, 12000);
1223
+ const dec = wsParseDecision(rawDec);
1224
+
1225
+ // If there are 0 eligible website links in the current viewport (or Gemini asked to scroll and we haven't scrolled 3 times yet when eligibleLinks is small)
1226
+ if (eligibleLinks.length === 0 || (dec && dec.tool === "scroll" && step < 3 && eligibleLinks.length < 2)) {
1227
+ tabState.step = `2/5 Scrolling Google (${WS_NAV_MODEL})`;
1228
+ wsTabLog(`📜 Tab ${tabIdx + 1} [${WS_NAV_MODEL}]: Scrolling down on Google Search...`);
1229
+ await p.mouse.wheel(0, 520).catch(async () => {
1230
+ await p.evaluate(() => window.scrollBy(0, 520)).catch(() => {});
1231
+ });
1232
+ await baSleep(550);
1233
+ continue;
1234
  }
1235
 
1236
+ // Determine which eligible website link to click: use Gemini's chosen ID if it matches an eligible website link, otherwise use the top eligible website link!
1237
+ let chosenLink = eligibleLinks[0];
1238
+ if (dec && dec.id != null) {
1239
+ const matched = eligibleLinks.find(e => Number(e.id) === Number(dec.id)) ||
1240
+ allExternalLinks.find(e => Number(e.id) === Number(dec.id));
1241
+ if (matched && !usedDomains.has(matched.domain)) {
1242
+ chosenLink = matched;
1243
+ }
1244
+ }
1245
+ if (!chosenLink && allExternalLinks.length > 0) {
1246
+ chosenLink = allExternalLinks[tabIdx % allExternalLinks.length];
1247
  }
1248
+ if (!chosenLink) continue;
1249
+
1250
+ // Reserve this domain & URL so the other 2 tabs pick different websites!
1251
+ usedDomains.add(chosenLink.domain);
1252
+ usedUrls.add(chosenLink.href);
1253
+ openedWebsite = chosenLink;
1254
+
1255
+ // Re-inject Red Markers before clicking so [data-ai-id] is present on the DOM element for baSafeClick!
1256
+ await p.evaluate(WS_BA_MARKER_FN).catch(() => {});
1257
+ tabState.step = `3/5 Clicking #${chosenLink.id} ${chosenLink.domain} (${WS_NAV_MODEL})`;
1258
+ tabState.domain = chosenLink.domain;
1259
+ tabState.title = chosenLink.text || chosenLink.domain;
1260
+ wsTabLog(`🖱️ Tab ${tabIdx + 1} [${WS_NAV_MODEL}]: Clicking Red Marker #${chosenLink.id} "${(chosenLink.text || "").slice(0, 50)}" (${chosenLink.domain})`);
1261
+ if (onStatusUpdate) onStatusUpdate(`Tab ${tabIdx + 1} (${WS_NAV_MODEL}): Clicking ${chosenLink.domain}...`);
1262
+
1263
+ await baSafeClick(p, chosenLink.id, chosenLink.href);
1264
+ await p.evaluate(WS_BA_CLEANUP_FN).catch(() => {});
1265
  tabState.url = p.url();
1266
+ break;
1267
+ }
1268
 
1269
+ if (!openedWebsite) {
1270
+ wsTabLog(`⚠️ Tab ${tabIdx + 1}: Could not find a website link to click on Google Search.`);
1271
+ tabState.status = "error";
1272
+ tabState.error = "No website link found";
1273
+ return null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1274
  }
1275
 
1276
  // =========================================================================
1277
+ // STEP 3: Website is now OPEN! Take a Red-Marked Screenshot of the website
1278
+ // and send to gemini-3.5-flash-lite to check if any popup/cookie button
1279
+ // needs clicking. If no button blocks -> copy details & analyze!
1280
  // =========================================================================
1281
  tabState.model = WS_NAV_MODEL;
1282
+ tabState.step = `4/5 Checking Website Popups (${WS_NAV_MODEL})`;
1283
+ await baSleep(450);
1284
  await p.evaluate(WS_AUTO_CLOSE_POPUPS_FN).catch(() => {});
1285
+
1286
+ const siteSnap = await baTakeSnap(tabIdx, p);
1287
+ const buttonElements = siteSnap.elements.filter(e => e.tag === "button" || e.tag === "a" || e.tag === "input");
1288
+ if (buttonElements.length > 0 && siteSnap.shot) {
1289
+ const popupCheckPrompt = `
1290
+ You have opened the website: ${p.url()} (${openedWebsite.domain}).
1291
+ Look at the screenshot with RED numbered markers and the interactive buttons below:
1292
+ ${JSON.stringify(buttonElements.slice(0, 30).map(b => ({ id: b.id, tag: b.tag, text: b.text })))}
1293
+
1294
+ INSTRUCTIONS:
1295
+ 1. If a popup, modal, cookie consent banner, or overlay close button ("Accept", "Agree", "Close", "Got it", "X", "Dismiss") is blocking the article, respond with:
1296
+ {"tool": "click", "id": <id>, "reason": "Dismissing popup button"}
1297
+ 2. If NO popup button is blocking the article and the webpage content is visible, respond with:
1298
+ {"tool": "done", "reason": "Website is clean, ready to copy details and analyze"}
1299
+ Respond with valid JSON for ONE tool: "click" or "done".`;
1300
+
1301
+ const rawPopDec = await wsCallGemini(WS_NAV_MODEL, tabIdx, siteSnap.shot, popupCheckPrompt, true, 9000);
1302
+ const popDec = wsParseDecision(rawPopDec);
1303
+ if (popDec && popDec.tool === "click" && popDec.id != null) {
1304
+ wsTabLog(`🧹 Tab ${tabIdx + 1} [${WS_NAV_MODEL}] (${openedWebsite.domain}): Clicking popup button #${popDec.id} (${popDec.reason || "closing popup"})`);
1305
+ await p.evaluate(WS_BA_MARKER_FN).catch(() => {});
1306
+ await baSafeClick(p, popDec.id, null);
1307
+ await p.evaluate(WS_BA_CLEANUP_FN).catch(() => {});
1308
+ await baSleep(350);
 
 
 
 
1309
  }
1310
  }
1311
 
1312
+ // =========================================================================
1313
+ // STEP 4: Copy the details from the opened website, take a clean screenshot,
1314
+ // and call gemini-3.6-flash (WS_ANALYZE_MODEL) to READ, ANALYZE & GIVE INFO!
1315
+ // =========================================================================
1316
+ tabState.model = WS_ANALYZE_MODEL;
1317
+ tabState.step = `5/5 Copying & Analyzing (${WS_ANALYZE_MODEL})`;
1318
+ wsTabLog(`🧠 Tab ${tabIdx + 1} [${WS_ANALYZE_MODEL}]: Copying details from ${openedWebsite.domain} & analyzing with ${WS_ANALYZE_MODEL}...`);
1319
+ if (onStatusUpdate) onStatusUpdate(`Tab ${tabIdx + 1} (${WS_ANALYZE_MODEL}): Analyzing ${openedWebsite.domain}...`);
1320
+
1321
+ await p.evaluate(WS_BA_CLEANUP_FN).catch(() => {});
1322
+ await p.evaluate(() => window.scrollBy(0, 300)).catch(() => {});
1323
+ await baSleep(250);
1324
  await p.evaluate(() => window.scrollTo(0, 0)).catch(() => {});
1325
+
1326
+ let cleanShot = null;
1327
+ try {
1328
+ cleanShot = await p.screenshot({ type: "jpeg", quality: 65, timeout: 4500 });
1329
+ webSearchTabsState.tabs[tabIdx].lastFrame = cleanShot;
1330
+ webSearchTabsState.tabs[tabIdx].frameSeq++;
1331
+ } catch (e) {
1332
+ cleanShot = siteSnap.shot;
1333
+ }
1334
 
1335
  const copiedDetails = await p.evaluate(() => {
1336
  const metaDesc = (document.querySelector('meta[name="description"], meta[property="og:description"]')?.getAttribute("content") || "").trim();
 
1344
  paragraphs: paras.slice(0, 35).join("\n"),
1345
  bodyText: bodyText.slice(0, 4500)
1346
  };
1347
+ }).catch(() => ({ title: openedWebsite.text, metaDesc: "", paragraphs: "", bodyText: "" }));
1348
 
 
 
 
 
 
 
 
 
 
 
1349
  const rawDomSnippet = (
1350
  (copiedDetails.metaDesc ? copiedDetails.metaDesc + "\n" : "") +
1351
+ (copiedDetails.paragraphs || copiedDetails.bodyText || openedWebsite.text || "")
1352
+ ).trim().slice(0, 3000);
1353
 
1354
+ const analyzePrompt = `You are Browser Research Analyst #${tabIdx + 1} powered by ${WS_ANALYZE_MODEL}.
 
1355
  User Query: "${rawUserPrompt || query}"
1356
+ Website Opened (from Google India Search): ${openedWebsite.href} (${copiedDetails.title || openedWebsite.text})
1357
  Copied Website Details & Text:
1358
+ ${rawDomSnippet.slice(0, 2500)}
1359
 
1360
  Look at the snapped webpage screenshot and the copied website details above. Read and analyze the page thoroughly to extract all key facts, numbers, dates, names, prices/scores/updates, and live details (prioritizing India context) that answer "${rawUserPrompt || query}". Also include 1-2 verbatim sentences from the page. Keep it factual and detailed (under 200 words).`;
1361
 
1362
+ const aiAnalysis = await wsCallGemini(WS_ANALYZE_MODEL, tabIdx, cleanShot, analyzePrompt, false, 14000);
1363
+ const finalSnippet = (aiAnalysis ? (aiAnalysis + "\n\nCopied Website Excerpt:\n" + rawDomSnippet.slice(0, 1000)) : rawDomSnippet).trim() || `${openedWebsite.text} (${openedWebsite.href})`;
 
 
 
 
 
 
 
1364
 
1365
  tabState.status = "done";
1366
  tabState.model = WS_ANALYZE_MODEL;
1367
  tabState.step = `✓ Analyzed (${WS_ANALYZE_MODEL})`;
1368
+ tabState.summary = (aiAnalysis || rawDomSnippet || openedWebsite.text).slice(0, 320);
1369
+ wsTabLog(`✅ Tab ${tabIdx + 1} [${WS_ANALYZE_MODEL}] (${openedWebsite.domain}): Copied & analyzed (${finalSnippet.length} chars)`);
1370
 
1371
  return {
1372
+ title: copiedDetails.title || openedWebsite.text || openedWebsite.domain,
1373
+ url: openedWebsite.href,
1374
+ domain: openedWebsite.domain,
1375
  snippet: finalSnippet.slice(0, 2000)
1376
  };
1377
  } catch (tabErr) {