flagtldr / scripts /e2e /geo.mjs
botezx's picture
Grok Bot
FlagTLDR 0.5.0 (snapshot of local f98bb37)
043267b
Raw History Blame Contribute Delete
24.9 kB
// Account country/region e2e on the mock x.com (no real account):
// 1) passive: the mock page itself calls AboutAccountQuery (like X's "About this account" page) -> badge, 0 own requests
// 2) active lookup: visible authors only, one request per handle (dedupe), spacing >= 60/rate s, cache on reload
// 3) styles label/icon, region outline icons, self-declared 📍, ⚠ accuracy caveat -> screenshots
// 4) filter by region + unknown (collapse with "Pokaż"), summary prompt excludes collapsed replies
// 5) 429 -> one request, then backoff (no more requests) + toast; diag report has counts only (no handles/locations)
// v0.4.1: per-post "🌐 Sprawdź kraj" button (one-time note, 1 request, all posts of that author updated, cache shared
// across tabs), button countdown + queued click during X's 429 pause, queue status pill + toolbar badge
// node geo.mjs <chrome>
import puppeteer from "puppeteer-core";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { setTimeout as sleep } from "node:timers/promises";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
const EXT = process.env.EXT_DIR || path.join(ROOT, "extension");
const SHOTS = path.join(ROOT, "docs", "screenshots");
const CHROME = process.env.CHROME || process.argv[2];
const HANDLES = ["teza_autor", "ekonomistka", "hr_praktyk", "sceptyk", "troll123", "spamer"];
const log = (...a) => console.log("[geo-e2e]", ...a);
const assert = (c, m) => { if (!c) throw new Error("ASSERT: " + m); };
const browser = await puppeteer.launch({
executablePath: CHROME, headless: true,
args: [`--disable-extensions-except=${EXT}`, `--load-extension=${EXT}`,
"--host-resolver-rules=MAP x.com 127.0.0.1:8443", "--ignore-certificate-errors", "--no-sandbox", "--window-size=1280,900", "--lang=pl"],
defaultViewport: { width: 1280, height: 900 },
});
try {
const sw = await browser.waitForTarget((t) => t.type() === "service_worker" && t.url().endsWith("service-worker.js"), { timeout: 15000 });
const extId = new URL(sw.url()).host;
const opt = await browser.newPage();
opt.on("dialog", (d) => d.accept());
await opt.goto(`chrome-extension://${extId}/src/options/options.html`);
await opt.waitForFunction(() => document.getElementById("systemPrompt").value.length > 0);
const defaults = await opt.evaluate(() => chrome.runtime.sendMessage({ type: "getSettings" }));
// Unreleased: the feature is ON on demand (cache / passive + per-post button); automatic lookups and the filter stay OFF
assert(defaults.geoEnabled === true && defaults.geoActiveLookup === false && defaults.geoFilterEnabled === false, "geo defaults: on demand, auto OFF");
assert(defaults.geoClickLookup === true && defaults.geoQueuePill === true && defaults.geoAdaptive === true && defaults.geoRatePerMin === 12 && defaults.geoQueueMax === 20, "v0.4.1 defaults");
const set = (patch) => opt.evaluate(async (p) => {
const { settings } = await chrome.storage.local.get("settings");
await chrome.storage.local.set({ settings: { ...settings, ...p } });
}, patch);
const sw$ = (m) => opt.evaluate((mm) => chrome.runtime.sendMessage(mm), m);
const mock = (p) => opt.evaluate((u) => fetch(u).then((r) => r.text()).catch(() => ""), "https://x.com" + p);
const stats = async () => JSON.parse(await mock("/__mock/about-stats"));
await mock("/__mock/about-mode?ok");
const x = await browser.newPage();
const badges = () => x.$$eval("article[data-testid=tweet]", (as) => as.map((a) => {
const b = a.querySelector(".xa-geo"); const h = [...a.querySelectorAll('[data-testid="User-Name"] > span')].find((s) => s.textContent.startsWith("@"))?.textContent;
return { h, text: b ? b.innerText.replace(/\s+/g, " ").trim() : null, cls: b ? [...b.querySelectorAll("[class^=xa-geo-]")].map((e) => e.className.baseVal ?? e.className).join(",") : "",
art: a.className };
}));
// ---- 0a) defaults (Unreleased): per-post "🌐 Sprawdź kraj" buttons, but no request without a click ----
await x.goto("https://x.com/teza_autor/status/100", { waitUntil: "networkidle0" });
await x.waitForFunction(() => document.querySelectorAll(".xa-geo-ask-idle").length > 0, { timeout: 10000, polling: 200 });
await sleep(1500);
const asks = (await x.$$(".xa-geo-ask-idle")).length;
assert((await stats()).count === 0, "defaults: no automatic requests");
log(`defaults: ${asks} per-post check buttons, 0 requests`);
// ---- 0b) feature explicitly off: no badges, no requests ----
await set({ geoEnabled: false, geoDefaultsV2: true });
await x.goto("https://x.com/teza_autor/status/100", { waitUntil: "networkidle0" });
await sleep(1500);
assert((await x.$$(".xa-geo")).length === 0, "no badges while disabled");
assert((await stats()).count === 0, "no requests while disabled");
log("disabled: no badges, no requests");
// ---- 1) passive ----
await set({ geoEnabled: true, geoActiveLookup: false, geoShowSelf: true });
await x.goto("https://x.com/home?passive=ekonomistka", { waitUntil: "networkidle0" });
await x.waitForFunction(() => [...document.querySelectorAll(".xa-geo")].some((b) => /Zjednoczone Królestwo|🇬🇧/.test(b.textContent)), { timeout: 10000 });
const pst = await stats();
assert(pst.count === 1, "only the page's own AboutAccountQuery was sent (passive)");
log("passive: badge from X's own AboutAccountQuery response; requests total", pst.count, "(the page's own)");
log("passive badges:", JSON.stringify((await badges()).map((b) => [b.h, b.text])));
assert((await x.$$(".xa-geo-ask")).length > 0, "passive mode: authors without X data get the 'Sprawdź kraj' button");
// ---- 1b) click lookup (active OFF): one-time note, ONE request, every post of that author updated ----
await sw$({ type: "geoClearCache" });
await x.goto("https://x.com/teza_autor/status/100?virtual=1&theme=dark", { waitUntil: "networkidle0" });
await x.waitForSelector(".xa-geo-ask", { timeout: 10000 });
const byAuthor = (h) => x.$$eval(`article[data-xa-author="${h}"]`, (as) => as.map((a) => ({ ask: !!a.querySelector(".xa-geo-ask"), x: !!a.querySelector(".xa-geo-x, .xa-geo-region"), text: a.querySelector(".xa-geo")?.innerText || "" })));
const c0 = (await stats()).count;
const hrBefore = await byAuthor("hr_praktyk");
assert(hrBefore.length >= 2 && hrBefore.every((p) => p.ask), "hr_praktyk: several posts, all with the button (" + hrBefore.length + ")");
assert(await x.$("#xa-queue-pill"), "queue pill shown (click lookup on)");
await x.evaluate(() => document.querySelector('article[data-xa-author="hr_praktyk"] .xa-geo-ask').click());
await x.waitForSelector("#xa-geo-note-host", { timeout: 5000 });
await x.screenshot({ path: path.join(SHOTS, "geo-click-note.png") });
assert((await stats()).count === c0, "no request before the user confirms the note");
let tc = Date.now();
await x.click("#xa-geo-note-host >>> .yes");
await x.waitForFunction(() => { const as = document.querySelectorAll('article[data-xa-author="hr_praktyk"]');
return as.length && [...as].every((a) => !a.querySelector(".xa-geo-ask") && a.querySelector(".xa-geo-x, .xa-geo-region")); }, { timeout: 15000 });
const click1Ms = Date.now() - tc;
const s1 = await stats();
assert(s1.count === c0 + 1 && s1.handles.hr_praktyk === 1, "exactly one request for the clicked author");
const others = (await badges()).filter((b) => b.h !== "@hr_praktyk" && b.h !== "@ekonomistka");
assert(others.some((b) => /Sprawdź kraj|🌐\?/.test(b.text || "")), "other authors keep the button");
log("click lookup: 1 request, hr_praktyk posts updated:", (await byAuthor("hr_praktyk")).length);
// second click right after the first (no pacing gap): no note any more, flag within ~1 s
tc = Date.now();
await x.evaluate(() => document.querySelector('article[data-xa-author="sceptyk"] .xa-geo-ask').click());
await x.waitForFunction(() => [...document.querySelectorAll('article[data-xa-author="sceptyk"]')].every((a) => !a.querySelector(".xa-geo-ask") && a.querySelector(".xa-geo-x")), { timeout: 15000 });
const click2Ms = Date.now() - tc;
assert(!(await x.$("#xa-geo-note-host")), "note shown only once");
assert((await stats()).count === c0 + 2, "second click: one more request");
log("click -> flag:", click1Ms, "ms (first, after the note),", click2Ms, "ms (second, right after)");
assert(click1Ms < 1500 && click2Ms < 1500, "click path has no artificial delay (< 1.5 s to the flag)");
await x.evaluate(() => window.scrollTo(0, 0)); await sleep(1200);
await x.screenshot({ path: path.join(SHOTS, "geo-click-lookup.png") });
log("screenshots geo-click-note.png, geo-click-lookup.png");
// cache shared across tabs: a second tab shows the badge, no button, no request
const x2 = await browser.newPage();
await x2.goto("https://x.com/teza_autor/status/100?virtual=1&theme=dark", { waitUntil: "networkidle0" });
await x2.waitForFunction(() => { const as = document.querySelectorAll('article[data-xa-author="hr_praktyk"]');
return as.length && [...as].every((a) => a.querySelector(".xa-geo-x, .xa-geo-region") && !a.querySelector(".xa-geo-ask")); }, { timeout: 10000 });
assert((await stats()).count === c0 + 2, "second tab: from the shared cache, no request");
// v0.4.2: a lookup in one tab updates the other open tab at once (worker relays the author's state; no 2nd request)
const cX = (await stats()).count;
await x.evaluate(() => document.querySelector('article[data-xa-author="troll123"] .xa-geo-ask')?.click());
await x2.waitForFunction(() => { const as = document.querySelectorAll('article[data-xa-author="troll123"]');
return as.length && [...as].every((a) => a.querySelector(".xa-geo-x, .xa-geo-region") && !a.querySelector(".xa-geo-ask")); }, { timeout: 10000 });
assert((await stats()).count === cX + 1, "other tab updated without its own request");
log("cross-tab relay: click in tab 1 -> flag in tab 2 without reload, 1 request");
await x2.close(); await x.bringToFront();
log("cross-tab: badge from the shared cache, 0 requests");
// automatic mode at the slowest rate (6/min) with a queue: a click on a waiting author still runs at once
await sw$({ type: "geoClearCache" }); // a real queue: every author waits again
await set({ geoActiveLookup: true, geoRatePerMin: 6 });
await x.reload({ waitUntil: "networkidle0" });
// v0.4.2 (C): every automatically queued author shows "⏳ w kolejce" (position i of n) on ALL its posts
await x.waitForFunction(() => new Set([...document.querySelectorAll(".xa-geo-ask[data-xa-state=queued]")].map((b) => b.closest("article").dataset.xaAuthor)).size >= 3, { timeout: 20000 });
const qs = await x.$$eval("article[data-xa-author]", (as) => as.map((a) => { const b = a.querySelector(".xa-geo-ask");
return { h: a.dataset.xaAuthor, st: b?.dataset.xaState || "", pos: b?.dataset.xaPos || "", tot: b?.dataset.xaTotal || "", tip: b?.title || "", txt: b?.textContent || "", auto: !!b?.classList.contains("xa-geo-auto") }; }));
log("queue badges:", JSON.stringify(qs.map((q) => [q.h, q.st, q.pos + "/" + q.tot])));
const queuedQ = qs.filter((q) => q.st === "queued");
assert(queuedQ.every((q) => q.auto && /w kolejce/.test(q.txt) && new RegExp(`pozycja ${q.pos} z ${q.tot}`).test(q.tip)), "queued badge + 'pozycja i z n' tooltip");
const byAuth = {}; for (const q of qs) (byAuth[q.h] ||= []).push(q);
for (const [h, list] of Object.entries(byAuth)) if (list.length > 1) assert(new Set(list.map((q) => q.st + q.pos)).size === 1, "same badge on every post of @" + h);
const multi = Object.entries(byAuth).filter(([, l]) => l.length > 1).map(([h]) => h);
log("authors with several posts (same badge on each):", multi.join(", ") || "(none in view)");
// X re-creates a cell (virtualization): the new article gets the badge back on the next scan
assert(new Set(queuedQ.map((q) => q.pos)).size >= 3 && queuedQ.every((q) => q.tot === queuedQ[0].tot), "distinct positions, one queue length");
const victim = queuedQ[queuedQ.length - 1].h;
await x.evaluate((h) => { const a = document.querySelector(`article[data-xa-author="${h}"]`); const c = a.cloneNode(true);
c.querySelectorAll(".xa-geo").forEach((n) => n.remove()); for (const k of Object.keys(c.dataset)) if (k.startsWith("xa")) delete c.dataset[k];
c.classList.add("xa-recreated"); a.replaceWith(c); }, victim);
await x.waitForFunction(() => { const b = document.querySelector("article.xa-recreated .xa-geo-ask"); return b && /queued|loading/.test(b.dataset.xaState); }, { timeout: 5000 })
.catch(async () => { const st = await x.$eval("article.xa-recreated", (a) => a.querySelector(".xa-geo")?.outerHTML || "(no badge)"); throw new Error("re-created cell lost the badge: " + st); });
log("re-created cell of @" + victim + ": badge restored");
const stA = await stats(), cA = stA.count;
const target = await x.$eval(".xa-geo-ask[data-xa-state=queued]:not([data-xa-pos='1'])", (b) => b.closest("article").dataset.xaAuthor);
tc = Date.now();
await x.evaluate((h) => document.querySelector(`article[data-xa-author="${h}"] .xa-geo-ask`).click(), target);
await x.waitForFunction((h) => [...document.querySelectorAll(`article[data-xa-author="${h}"]`)].every((a) => !a.querySelector(".xa-geo-ask")), { timeout: 15000 }, target);
const click3Ms = Date.now() - tc, sA = await stats();
log("click while automatic queue waits (6/min):", target, click3Ms, "ms; requests", sA.count - cA);
assert(click3Ms < 1500, "click during automatic pacing runs immediately");
assert(sA.handles[target] === (stA.handles[target] || 0) + 1, "one request for the clicked author");
await set({ geoActiveLookup: false, geoRatePerMin: 12 }); await sleep(500);
// ---- 2) active lookup ----
await mock("/__mock/about-mode?ok"); await sw$({ type: "geoClearCache" });
await set({ geoActiveLookup: true, geoRatePerMin: 30, geoStyle: "label" });
await x.goto("https://x.com/teza_autor/status/100", { waitUntil: "networkidle0" });
const t0 = Date.now();
await sleep(2500);
const pillTxt = await x.$eval("#xa-queue-pill", (h) => h.shadowRoot.querySelector(".pill").textContent).catch(() => "");
log("pill while busy:", JSON.stringify(pillTxt));
assert(/w kolejce · \d+\/30 min/.test(pillTxt), "pill shows queue length and lookups/min vs limit");
await sleep(6500);
const vis = await stats();
log("visible-only: looked up", vis.count, "of", HANDLES.length, "authors before scrolling:", Object.keys(vis.handles).join(", "));
assert(vis.count > 0 && vis.count < HANDLES.length, "only visible authors are looked up");
await x.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
for (let i = 0; i < 60 && (await stats()).count < HANDLES.length; i++) await sleep(500);
await sleep(800);
await x.evaluate(() => window.scrollTo(0, 0)); await sleep(300);
const st = await stats();
log("active: requests", st.count, "per handle", JSON.stringify(st.handles), "in", Date.now() - t0, "ms");
assert(Object.values(st.handles).every((n) => n === 1), "deduped: one request per handle");
const gaps = st.times.slice(1).map((t, i) => t - st.times[i]);
log("spacing between requests (s):", gaps.map((g) => g.toFixed(2)).join(" "));
assert(gaps.every((g) => g >= 1.9), "rate limit 30/min -> >= 2 s spacing");
const b1 = await badges();
log("badges:", JSON.stringify(b1.map((b) => [b.h, b.text, b.cls])));
const byH = Object.fromEntries(b1.map((b) => [b.h?.replace("@", ""), b]));
assert(/🇵🇱/.test(byH.teza_autor.text) && /xa-geo-x/.test(byH.teza_autor.cls), "PL flag (X-determined)");
assert(/xa-geo-region/.test(byH.troll123.cls) && /Azja Południowa/.test(byH.troll123.text), "South Asia region outline");
assert(/xa-geo-region/.test(byH.hr_praktyk.cls), "Europe region outline");
assert(/⚠/.test(byH.sceptyk.text), "accuracy caveat");
assert(/📍/.test(byH.ekonomistka.text) && /Reykjav/.test(byH.ekonomistka.text), "self-declared shown separately");
assert(/xa-geo-self/.test(byH.spamer.cls) && !/xa-geo-x/.test(byH.spamer.cls), "spamer: self-declared only");
await x.screenshot({ path: path.join(SHOTS, "geo-badges.png") });
await set({ geoStyle: "icon" }); await sleep(1200);
await x.screenshot({ path: path.join(SHOTS, "geo-badges-icon.png") });
log("screenshots geo-badges.png, geo-badges-icon.png");
// cache: reload -> no new requests
await x.reload({ waitUntil: "networkidle0" }); await sleep(2500);
assert((await x.$$(".xa-geo")).length >= HANDLES.length, "badges from cache");
assert((await stats()).count === st.count, "reload served from persistent cache");
log("reload: 0 new requests (cache)");
// ---- 4) filter: block South Asia + unknown, collapse ----
await set({ geoStyle: "label", geoFilterEnabled: true, geoFilterMode: "collapse", geoFilterScope: "both", geoFilterList: "block",
geoFilterItems: ["region:south-asia", "unknown"], geoExcludeFromSummary: true });
await x.waitForFunction(() => document.querySelectorAll(".xa-geo-collapsed").length >= 2, { timeout: 10000 });
const col = (await badges()).filter((b) => /xa-geo-collapsed/.test(b.art)).map((b) => b.h);
log("collapsed:", col.join(", "));
assert(col.length === 2 && col.includes("@troll123") && col.includes("@spamer"), "South Asia + unknown collapsed");
await x.screenshot({ path: path.join(SHOTS, "geo-filter.png") });
// summary prompt must not contain the collapsed replies
await set({ diagEnabled: true }); await sleep(800);
await x.click('article[data-testid="tweet"] .xa-summary-btn');
await x.waitForFunction(() => /Kontrargumenty/.test(document.querySelector(".xa-result-host")?.shadowRoot.querySelector(".card").innerText || ""), { timeout: 120000 });
await sleep(1500);
const srep = await sw$({ type: "getDiagReport" });
const lst = srep.xPage?.lastSummaryThread;
log("summary thread:", JSON.stringify(lst));
assert(lst && lst.geoExcluded === 2, "2 collapsed authors excluded (grok mode: named in the prompt as accounts to skip)");
await x.evaluate(() => document.querySelectorAll(".xa-result-host").forEach((n) => n.remove()));
await set({ diagEnabled: false }); await sleep(800);
// reveal one
await x.click(".xa-geo-bar button"); await sleep(300);
assert((await x.$$(".xa-geo-collapsed")).length === 1, "Pokaż reveals one post");
// focal post never hidden; allow-list Poland only would hide everyone else but the focal post
await set({ geoFilterList: "allow", geoFilterItems: ["PL"], geoFilterMode: "dim" }); await sleep(1200);
const dim = (await badges()).filter((b) => /xa-geo-dimmed/.test(b.art)).map((b) => b.h);
log("allow-list PL, dim:", dim.join(", "));
// @troll123 was revealed by the user ("Pokaż") -> stays revealed for this page view
assert(dim.length === 4 && !dim.includes("@teza_autor") && !dim.includes("@troll123"), "allow-list dims all non-PL (except revealed)");
// scope timeline only -> no effect on /status/ page
await set({ geoFilterScope: "timeline" }); await sleep(1200);
assert((await x.$$(".xa-geo-dimmed")).length === 0, "timeline scope does not touch replies");
await set({ geoFilterScope: "both", geoFilterList: "block", geoFilterItems: ["region:south-asia", "unknown"], geoFilterMode: "collapse" }); await sleep(1200);
// ---- options screenshot ----
await opt.bringToFront(); await opt.reload(); await opt.waitForFunction(() => document.getElementById("systemPrompt").value.length > 0);
await opt.waitForFunction(() => document.querySelectorAll("#geoList .geo-opt").length > 200);
await opt.type("#geoSearch", "azja");
await opt.click("#geoStateBtn"); await sleep(400);
await opt.$eval("#geoSection", (e) => e.scrollIntoView({ block: "start" }));
await opt.setViewport({ width: 1280, height: 1500 }); await sleep(300);
const sec = await opt.$("#geoSection");
await sec.screenshot({ path: path.join(SHOTS, "options-geo.png") });
log("options state:", await opt.$eval("#geoState", (e) => e.textContent));
await opt.setViewport({ width: 1280, height: 900 });
// ---- 5) 429 ----
await x.bringToFront();
await mock("/__mock/about-mode?429"); await sw$({ type: "geoClearCache" });
const before = (await stats()).count;
await x.reload({ waitUntil: "networkidle0" });
await x.waitForSelector(".xa-toast", { timeout: 20000 });
const toast = await x.$eval(".xa-toast", (e) => e.textContent);
await sleep(6000);
const after = (await stats()).count;
const gst = await sw$({ type: "geoState" });
log("429: requests", after - before, "toast:", JSON.stringify(toast.slice(0, 90)), "backoff until", new Date(gst.backoffUntil).toISOString());
assert(after - before === 1, "exactly one request, then backoff");
assert(gst.backoffUntil > Date.now() + 60000 && gst.counters.http429 === 1, "backoff until reset");
assert(gst.counters.waits < 20, "no permit spinning during backoff (waits=" + gst.counters.waits + ")");
assert((await x.$$(".xa-geo-collapsed")).length === 0, "unchecked accounts are never hidden");
// during X's pause: buttons with a countdown; a click is queued (runs first when the pause ends)
await set({ geoFilterEnabled: false }); await sleep(1500);
const ask = await x.$eval(".xa-geo-ask[data-xa-pause]", (b) => ({ text: b.innerText, title: b.title }));
log("paused button:", JSON.stringify(ask.text), JSON.stringify(ask.title.split("\n")[0]));
assert(/X ogranicza zapytania, spróbuj za \d+ s/.test(ask.title), "429 countdown tooltip");
await x.evaluate(() => document.querySelector(".xa-geo-ask[data-xa-pause]").click()); await sleep(600);
assert(await x.$(".xa-geo-ask[data-xa-state=queued]"), "click during the pause is queued");
assert((await stats()).count === after, "the queued click waits for X's pause");
const pill429 = await x.$eval("#xa-queue-pill", (h) => h.shadowRoot.querySelector(".pill").textContent);
assert(/X: pauza \d+:\d\d/.test(pill429), "pill shows the 429 pause countdown: " + pill429);
{ const bb = await x.$eval("#xa-queue-pill", (h) => { const r = h.shadowRoot.querySelector(".pill").getBoundingClientRect(); return [r.x + r.width / 2, r.y + r.height / 2]; });
await x.mouse.click(bb[0], bb[1]); }
await x.waitForFunction(() => document.querySelector("#xa-queue-pill").shadowRoot.querySelector(".mini .presets button"), { timeout: 5000 });
const mini = await x.$eval("#xa-queue-pill", (h) => h.shadowRoot.querySelector(".mini").innerText);
assert(/Wyczyść kolejkę/.test(mini) && /ostrożnie 6\/min/.test(mini) && /szybko 30\/min/.test(mini) && /X: pauza \(429\)/.test(mini), "mini panel");
const badgeTexts = await opt.evaluate(async () => { const tabs = await chrome.tabs.query({}); return Promise.all(tabs.map((t) => chrome.action.getBadgeText({ tabId: t.id }))); });
log("toolbar badges:", JSON.stringify(badgeTexts));
assert(badgeTexts.some((t) => t === "1" || t === "II"), "toolbar badge shows the queue");
await x.screenshot({ path: path.join(SHOTS, "geo-queue-pill.png") });
// preset with risk note (12/min): confirm -> settings updated, queue kept
await x.evaluate(() => document.querySelector("#xa-queue-pill").shadowRoot.querySelector('.presets button[data-rate="30"]').click());
await x.waitForFunction(() => document.querySelector("#xa-queue-pill").shadowRoot.querySelector(".confirm .yes"), { timeout: 3000 });
await x.evaluate(() => document.querySelector("#xa-queue-pill").shadowRoot.querySelector(".confirm .yes").click()); await sleep(800);
assert((await sw$({ type: "getSettings" })).geoRatePerMin === 30, "preset saved");
assert(await x.$(".xa-geo-ask[data-xa-state=queued]"), "rate preset keeps the queue");
log("pill: 429 countdown, mini panel, preset 30/min, toolbar badge; screenshot geo-queue-pill.png");
// ---- diag report: counts only ----
await set({ diagEnabled: true });
let rep = null;
for (let i = 0; i < 30; i++) { rep = await sw$({ type: "getDiagReport" }); if (rep.xPage?.geo) break; await x.evaluate(() => window.scrollBy(0, 40)); await sleep(1000); }
const j = JSON.stringify(rep.geo || rep.report?.geo || rep);
log("diag geo:", JSON.stringify(rep.geo));
const all = JSON.stringify(rep);
log("diag page geo:", JSON.stringify(rep.xPage?.geo || null));
assert(all.includes("queueDrops") && all.includes("clickLookups"), "diag has click + queue drop counters");
for (const s of [...HANDLES, "Reykjav", "Lagos", "Warszawa"]) assert(!all.includes(s), "diag report leaks " + s);
for (const s of [...HANDLES, "Poland", "South Asia", "Reykjav", "Lagos", "Warszawa", "region:south-asia"]) assert(!j.includes(s), "diag leaks " + s);
await mock("/__mock/about-mode?ok"); await sw$({ type: "geoResume" });
await set({ diagEnabled: false, geoEnabled: false, geoActiveLookup: false, geoFilterEnabled: false, geoFilterItems: [], geoRatePerMin: 12, geoStyle: "label" });
log("OK");
} finally {
await browser.close();
}