diff --git a/.changeset/connect-ai-reports.md b/.changeset/connect-ai-reports.md new file mode 100644 index 0000000..1a05c6f --- /dev/null +++ b/.changeset/connect-ai-reports.md @@ -0,0 +1,7 @@ +--- +"@workspace/web": patch +"@workspace/lib": patch +"@workspace/config": patch +--- + +Connect Google and Bing AI reports through your signed-in browser without file uploads, and separate browser visibility from API answers. diff --git a/.changeset/seo-sources-and-ux-polish.md b/.changeset/seo-sources-and-ux-polish.md new file mode 100644 index 0000000..ee33b5c --- /dev/null +++ b/.changeset/seo-sources-and-ux-polish.md @@ -0,0 +1,6 @@ +--- +"@workspace/web": patch +"@workspace/lib": patch +--- + +Add Cloudflare AI crawler and Bing Webmaster data sources, upgrade GSC period comparisons and AEO site audits, and improve sidebar, overview pulse, and data source setup UX. diff --git a/apps/browser-lab/server.mjs b/apps/browser-lab/server.mjs index 5f1c5ce..03cec3e 100644 --- a/apps/browser-lab/server.mjs +++ b/apps/browser-lab/server.mjs @@ -14,6 +14,7 @@ import { summarize, validateInput, } from "./core.mjs"; +import { readWebmasterReport } from "./webmaster-reports.mjs"; const here = path.dirname(fileURLToPath(import.meta.url)); const directory = defaultRunDirectory(); @@ -134,6 +135,19 @@ async function handle(request, response) { const url = new URL(request.url, `http://127.0.0.1:${port}`); if (request.method === "GET") return handleRead(url, request, response); if (request.method === "POST" && url.pathname === "/api/browser/profile") return selectProfile(request, response); + if (request.method === "POST" && url.pathname === "/api/reports") { + if (!authorized(request)) return json(response, 403, { error: "Invalid local runner token" }); + const input = await bodyOf(request); + if (!["connect", "sync"].includes(input.action)) return json(response, 400, { error: "Invalid report action" }); + if (active) + return json(response, 409, { error: "The browser is busy. Retry after the current operation finishes." }); + active = { status: "reading-report" }; + try { + return json(response, 200, await readWebmasterReport(input)); + } finally { + active = null; + } + } if (request.method !== "POST" || !["/api/run", "/api/collect"].includes(url.pathname)) return json(response, 404, { error: "Not found" }); return handleCollection(request, response, url); diff --git a/apps/browser-lab/webmaster-reports.mjs b/apps/browser-lab/webmaster-reports.mjs new file mode 100644 index 0000000..5289221 --- /dev/null +++ b/apps/browser-lab/webmaster-reports.mjs @@ -0,0 +1,254 @@ +import { setTimeout as sleep } from "node:timers/promises"; +import { createBrowser, parseRows } from "./core.mjs"; + +export function reportUrl(source, property) { + if (!["bing", "google"].includes(source)) throw new Error("Unsupported report source."); + if (typeof property !== "string" || property.length > 2048) throw new Error("Invalid website."); + const domain = property.startsWith("sc-domain:"); + const parsed = new URL(domain ? `https://${property.slice(10)}` : property); + if (!["https:", "http:"].includes(parsed.protocol) || parsed.username || parsed.password || parsed.port) + throw new Error("Invalid website."); + if (source === "bing" && domain) throw new Error("Bing requires a website URL."); + const url = new URL( + source === "bing" + ? "https://www.bing.com/webmasters/aiperformance" + : "https://search.google.com/search-console/performance/search-analytics/ai", + ); + url.searchParams.set(source === "bing" ? "siteUrl" : "resource_id", property); + return url.href; +} + +// Read only responses generated by the official report page. No cookies, +// session tokens or undocumented request payloads are replayed or persisted. +export function responseJson(text) { + const start = text.indexOf("\n{"); + if (start < 0) throw new Error("Report response unavailable."); + const body = text + .slice(start + 1) + .split("\n")[0] + .trim(); + return JSON.parse(body); +} + +export function googleFrames(text) { + return text + .split("\n") + .filter((line) => line.startsWith('[["wrb.fr"')) + .flatMap((line) => JSON.parse(line)) + .filter((frame) => frame[0] === "wrb.fr" && typeof frame[2] === "string") + .map((frame) => ({ rpc: frame[1], data: JSON.parse(frame[2]) })); +} + +function count(value) { + if (!Number.isSafeInteger(value) || value < 0) throw new Error("Invalid report count."); + return value; +} +function dates(rows) { + if (!rows.length) throw new Error("The report has no dated observations yet."); + const sorted = rows.map((row) => row.key).sort(); + return { startDate: sorted[0], endDate: sorted.at(-1) }; +} + +export function parseBingHistory(data, property) { + if (data.SiteUrl !== property || !Array.isArray(data.CitationStats)) throw new Error("Report website mismatch."); + const rows = data.CitationStats.map((row) => ({ key: row.Date.slice(0, 10), value: count(row.Citations) })); + return { ...dates(rows), rows, total: count(data.TotalCitations) }; +} + +export function parseGoogleReport(text, property) { + const frames = googleFrames(text).filter(({ data }) => data?.[0]?.[0] === property); + const history = frames.findLast( + ({ rpc, data }) => + rpc === "OLiH4d" && + data?.[6]?.[2]?.length === 1 && + data[6][2][0][0] === "IMPRESSIONS" && + data?.[1]?.[0]?.length > 1, + )?.data; + const pages = frames.findLast( + ({ rpc, data }) => rpc === "nDAfwb" && data?.[1]?.[1]?.[0]?.[9] === "PAGES" && data[1][1][1]?.[9] === "IMPRESSIONS", + )?.data; + if (!history || !pages) throw new Error("AI report unavailable or its format has changed."); + // These observed request descriptors distinguish the AI report and its filters. + if ( + history[0][5]?.[15] !== 4 || + pages[0][5]?.[15] !== 4 || + JSON.stringify(history[0][5][2]) !== "[[null,null,null,3]]" || + JSON.stringify(history[0][5][3]) !== '[[6,["WEB"]]]' || + JSON.stringify(history[0][5].slice(1)) !== JSON.stringify(pages[0][5].slice(1)) + ) + throw new Error("AI report filters could not be verified."); + const daily = history[1][0].map((row) => { + if (!Number.isFinite(row[0]) || row[1]?.length !== 1) throw new Error("Invalid daily report."); + return { key: new Date(row[0]).toISOString().slice(0, 10), value: count(row[1][0]) }; + }); + const pageRows = pages[1][0].map((row) => { + const cells = row?.[0]; + if (typeof cells?.[0]?.[40] !== "string" || cells?.[1]?.[8] !== 6) + throw new Error("AI page report format changed."); + return { key: cells[0][40], value: count(cells[1][1]) }; + }); + return { ...dates(daily), daily, pages: pageRows, total: count(history[1][1][1][0]) }; +} + +async function waitFor(read, delay, accept = () => true) { + for (let attempt = 0; attempt < 12; attempt++) { + try { + const value = await read(); + if (accept(value)) return value; + } catch { + /* Page is still loading. */ + } + await delay(1500); + } + throw new Error( + "The AI report could not be read. Check website access, sign-in and report availability, then retry.", + ); +} + +function appendBingBatch(rows, batch, name, key, total) { + if (!Number.isSafeInteger(batch.TotalNumOfRecords) || batch.TotalNumOfRecords < 0) + throw new Error("Report pagination could not be verified."); + if (total !== undefined && total !== batch.TotalNumOfRecords) + throw new Error("Report changed during synchronization. Retry."); + for (const row of batch[name]) { + if (typeof row[key] !== "string" || rows.has(row[key])) throw new Error("Duplicate report page. Retry."); + rows.set(row[key], { key: row[key], value: count(row.Citations) }); + } + return batch.TotalNumOfRecords; +} + +async function bingTable(call, name, property, delay) { + const endpoint = `aiperformance/${name === "Pages" ? "pages" : "searchqueries"}/stats`; + const key = name === "Pages" ? "PageUrl" : "GroundingQuery"; + await call("snapshot", {}); + const tabs = parseRows(await call("query", { selector: '[role="tab"]', extract: { text: ".@text", id: ".@id" } })); + const tab = tabs.find((item) => item.text === (name === "Pages" ? "Pages" : "Grounding Queries")); + if (!tab?.id) throw new Error("AI report tab unavailable."); + await call("click", { selector: `[id=${JSON.stringify(tab.id)}]` }); + const rows = new Map(); + let total; + for (let page = 0; page < 80; page++) { + const batch = await waitFor( + async () => responseJson(await call("network", { body: endpoint, maxBody: 2_000_000 })), + delay, + (data) => + data.SiteUrl === property && + Array.isArray(data[name]) && + (data[name].length === 0 || !rows.has(data[name][0][key])), + ); + total = appendBingBatch(rows, batch, name, key, total); + if (rows.size === total) return [...rows.values()]; + if (rows.size > total || total > 2000 || !batch[name].length) + throw new Error("Report exceeds the supported row limit."); + await call("snapshot", {}); + await call("click", { selector: 'button[aria-label="Go to next Page"]' }); + } + throw new Error("Report pagination did not finish. No partial report was saved."); +} + +export async function readWebmasterReport(input, options = {}) { + const url = reportUrl(input.source, input.property); + const browser = options.browser || createBrowser(); + const delay = options.delay || sleep; + const openingUrl = + input.source === "google" + ? `https://search.google.com/search-console?resource_id=${encodeURIComponent(input.property)}` + : url; + const space = JSON.parse( + await browser("spaces", { + action: "open", + url: openingUrl, + label: `BeatGEO · ${input.source} AI reports`, + leaseMs: 600_000, + profileId: input.profileId || process.env.BEAT_BROWSER_PROFILE_ID || undefined, + }), + ); + if (!space.spaceId || !Number.isInteger(space.tabId) || space.state !== "running") + throw new Error("Connect your Chrome first."); + const call = (tool, params) => browser(tool, { ...params, spaceId: space.spaceId, tabId: space.tabId }); + let synced = false; + try { + let history; + if (input.source === "bing") { + history = await waitFor( + async () => + parseBingHistory( + responseJson( + await call("network", { + body: "aiperformance/citationstats", + maxBody: 2_000_000, + }), + ), + input.property, + ), + delay, + ); + if (input.action === "connect") return { ready: true, property: input.property, url }; + const queries = await bingTable(call, "Queries", input.property, delay); + const pages = await bingTable(call, "Pages", input.property, delay); + synced = true; + return { + ready: true, + property: input.property, + url, + ...dates(history.rows), + total: history.total, + tables: [ + { dimension: "date", rows: history.rows }, + { dimension: "page", rows: pages }, + { dimension: "query", rows: queries }, + ], + coverage: "All rows returned by the official report; platform sampling applies.", + }; + } + const sectionSelector = '[aria-label="“效果”报告部分"], [aria-label="Performance report section"]'; + const sections = await waitFor( + async () => + parseRows(await call("query", { selector: sectionSelector, extract: { expanded: ".@aria-expanded" } })), + delay, + (rows) => rows.length > 0, + ); + if (sections[0].expanded === "false") { + await call("snapshot", {}); + await call("click", { selector: sectionSelector }); + } + await waitFor( + async () => + parseRows( + await call("query", { selector: 'a[href*="/performance/search-analytics/ai"]', extract: { href: ".@href" } }), + ), + delay, + (rows) => rows.length > 0, + ); + await call("snapshot", {}); + await call("click", { selector: 'a[href*="/performance/search-analytics/ai"]' }); + history = await waitFor( + async () => + parseGoogleReport( + await call("network", { + body: "rpcids=OLiH4d", + maxBody: 2_000_000, + }), + input.property, + ), + delay, + ); + if (input.action === "connect") return { ready: true, property: input.property, url }; + synced = true; + return { + ready: true, + property: input.property, + url, + startDate: history.startDate, + endDate: history.endDate, + total: history.total, + tables: [ + { dimension: "date", rows: history.daily }, + { dimension: "page", rows: history.pages }, + ], + coverage: "Rows returned by the official AI report; page results may be limited by Google.", + }; + } finally { + await browser("spaces", { action: "finish", spaceId: space.spaceId, keep: synced ? [] : "all" }).catch(() => {}); + } +} diff --git a/apps/browser-lab/webmaster-reports.test.mjs b/apps/browser-lab/webmaster-reports.test.mjs new file mode 100644 index 0000000..8bd1c07 --- /dev/null +++ b/apps/browser-lab/webmaster-reports.test.mjs @@ -0,0 +1,138 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + parseBingHistory, + parseGoogleReport, + readWebmasterReport, + reportUrl, + responseJson, +} from "./webmaster-reports.mjs"; + +function googleFixture({ property = "sc-domain:example.com", metric = "IMPRESSIONS", value = 7, feature = 4 } = {}) { + const descriptor = (dimension) => [ + [dimension], + null, + [[null, null, null, 3]], + [[6, ["WEB"]]], + null, + null, + null, + null, + null, + null, + true, + null, + null, + 2, + null, + feature, + ]; + const history = [ + [property, 27, null, null, null, descriptor(1)], + [ + [ + [Date.UTC(2026, 9, 1), [value]], + [Date.UTC(2026, 9, 2), [3]], + ], + [null, [10]], + ], + 1, + [0], + null, + null, + [null, null, [[metric]]], + ]; + const key = Array(41).fill(null); + key[40] = "https://docs.example.com/a"; + const column = (name) => { + const c = Array(10).fill(null); + c[9] = name; + return c; + }; + const pages = [ + [property, 32, null, null, null, descriptor(3)], + [[[[key, [null, 10, null, null, null, null, null, null, 6]]]], [column("PAGES"), column(metric)]], + ]; + return `200 report\n\n)]}'\n\n${JSON.stringify([ + ["wrb.fr", "OLiH4d", JSON.stringify(history)], + ["wrb.fr", "nDAfwb", JSON.stringify(pages)], + ])}\n`; +} + +test("reads exact AI impressions and dates from matching official report frames", () => { + const result = parseGoogleReport(googleFixture(), "sc-domain:example.com"); + assert.deepEqual(result.daily, [ + { key: "2026-10-01", value: 7 }, + { key: "2026-10-02", value: 3 }, + ]); + assert.deepEqual(result.pages, [{ key: "https://docs.example.com/a", value: 10 }]); + assert.equal(result.total, 10); +}); +test("rejects other properties, ordinary search reports and changed metric contracts", () => { + for (const options of [{ property: "sc-domain:other.test" }, { metric: "CLICKS" }, { feature: 1 }, { value: -1 }]) + assert.throws(() => parseGoogleReport(googleFixture(options), "sc-domain:example.com")); +}); +test("Bing uses exact numeric counts and verifies the returned website", () => { + const data = { + SiteUrl: "https://example.com/", + CitationStats: [{ Date: "2026-10-01T00:00:00", Citations: 1234 }], + TotalCitations: 1234, + }; + assert.equal(parseBingHistory(data, data.SiteUrl).rows[0].value, 1234); + assert.throws(() => parseBingHistory(data, "https://other.test/")); + assert.throws(() => parseBingHistory({ ...data, TotalCitations: "1.2K" }, data.SiteUrl)); + assert.deepEqual(responseJson(`200 /report\n\n${JSON.stringify(data)}\n`), data); +}); +test("website selection cannot redirect the reader to an arbitrary host", () => { + assert.equal(new URL(reportUrl("google", "sc-domain:example.com")).hostname, "search.google.com"); + assert.throws(() => reportUrl("bing", "https://user:password@example.com/")); + assert.throws(() => reportUrl("other", "https://example.com/")); +}); +test("Bing follows every report page before returning a snapshot", async () => { + let page = 0, + table = "Queries"; + const site = "https://example.com/"; + const handlers = { + spaces: (args) => JSON.stringify(args.action === "open" ? { spaceId: "s", tabId: 1, state: "running" } : {}), + snapshot: () => "AI Performance", + query: () => + JSON.stringify([ + { id: "q", text: "Grounding Queries" }, + { id: "p", text: "Pages" }, + ]), + click: (args) => { + if (args.selector.includes('id="p"')) { + table = "Pages"; + page = 0; + } else if (args.selector.includes("next Page")) page++; + return "Clicked"; + }, + network: (args) => { + if (args.body.includes("citationstats")) + return `200\n\n${JSON.stringify({ SiteUrl: site, CitationStats: [{ Date: "2026-10-01", Citations: 9 }], TotalCitations: 9 })}`; + const key = table === "Pages" ? "PageUrl" : "GroundingQuery"; + return `200\n\n${JSON.stringify({ SiteUrl: site, TotalNumOfRecords: 2, [table]: [{ [key]: table === "Pages" ? `${site}${page}` : `query ${page}`, Citations: 4 }] })}`; + }, + }; + const browser = async (tool, args) => handlers[tool](args); + const result = await readWebmasterReport( + { source: "bing", property: site, action: "sync" }, + { browser, delay: async () => {} }, + ); + assert.equal(result.tables.find((t) => t.dimension === "page").rows.length, 2); + assert.equal(result.tables.find((t) => t.dimension === "query").rows.length, 2); +}); +test("a missing report never returns a successful empty snapshot", async () => { + const browser = async (tool, args) => + tool === "spaces" + ? JSON.stringify(args.action === "open" ? { spaceId: "s", tabId: 1, state: "running" } : {}) + : "Sign in"; + await assert.rejects( + () => + readWebmasterReport( + { source: "bing", property: "https://example.com/", action: "sync" }, + { browser, delay: async () => {} }, + ), + /could not be read/, + ); +}); diff --git a/apps/web/.storybook/main.ts b/apps/web/.storybook/main.ts index b129b97..588260b 100644 --- a/apps/web/.storybook/main.ts +++ b/apps/web/.storybook/main.ts @@ -78,6 +78,9 @@ const config: StorybookConfig = { "workspace-fn", "evidence-summary", "site-audit-fn", + "connections", + "local-navigation", + "traffic-fn", ].map((module) => ({ find: new RegExp(`^@/server/${module}(\\.ts)?$`), replacement: path.resolve(mocksDir, "server-workflow.ts"), diff --git a/apps/web/src/components/ai-platform-reports.tsx b/apps/web/src/components/ai-platform-reports.tsx index ded5f06..62ae105 100644 --- a/apps/web/src/components/ai-platform-reports.tsx +++ b/apps/web/src/components/ai-platform-reports.tsx @@ -1,18 +1,14 @@ import { useQuery, useQueryClient } from "@tanstack/react-query"; -import { - type AiReport, - type AiReportDimension, - type AiReportInput, - type AiReportSource, - compareAiReports, - parseAiReport, -} from "@workspace/lib/ai-reports"; +import { type AiReport, compareAiReports } from "@workspace/lib/ai-reports"; import { Button } from "@workspace/ui/components/button"; import { Input } from "@workspace/ui/components/input"; -import { useMemo, useState } from "react"; +import { useState } from "react"; import { useBrandId } from "@/hooks/use-brand-id"; import { useT } from "@/lib/i18n"; -import { deleteAiReportFn, importAiReportFn, listAiReportsFn } from "@/server/ai-reports"; +import { deleteAiReportFn, listAiReportsFn } from "@/server/ai-reports"; + +import { AiReportConnections } from "./ai-report-connections"; +import { TrendChart } from "./trend-chart"; const fieldClass = "h-10 w-full min-w-0 rounded-md border bg-background px-3 text-sm"; export function AiPlatformReports() { @@ -24,17 +20,7 @@ function ReportWorkspace({ brandId }: { brandId: string }) { client = useQueryClient(); const queryKey = ["ai-platform-reports", brandId]; const query = useQuery({ queryKey, queryFn: () => listAiReportsFn({ data: { brandId } }) }); - const [input, setInput] = useState({ - source: "bing", - dimension: "page", - site: "", - startDate: "", - endDate: "", - scope: "", - content: "", - }); - const [confirmed, setConfirmed] = useState(false), - [busy, setBusy] = useState(false), + const [busy, setBusy] = useState(false), [message, setMessage] = useState(""); const [selected, setSelected] = useState(""), [previous, setPrevious] = useState(""), @@ -42,84 +28,15 @@ function ReportWorkspace({ brandId }: { brandId: string }) { [offset, setOffset] = useState(0); const reports = query.data ?? []; const { report, comparison, rows } = reportView(reports, selected, previous, filter); - const preview = useMemo(() => { - if (!input.content) return { data: null, error: "" }; - try { - return { data: parseAiReport(input), error: "" }; - } catch (error) { - return { data: null, error: error instanceof Error ? error.message : "Invalid report." }; - } - }, [input]); - function update(patch: Partial) { - setInput((v) => ({ ...v, ...patch })); - setConfirmed(false); - setMessage(""); - } - async function save() { - if (!preview.data || !confirmed || busy) return; - setBusy(true); - setMessage(""); - try { - const result = await importAiReportFn({ data: { ...input, brandId } }); - await client.invalidateQueries({ queryKey }); - setSelected(result.id); - setPrevious(""); - setOffset(0); - setMessage(result.duplicate ? "This report is already saved; no counts were added." : "AI report saved."); - } catch (error) { - setMessage(error instanceof Error ? error.message : "Could not save AI report."); - } finally { - setBusy(false); - } - } return (

{t("AI platform reports")}

- {t( - "Import platform observations separately from your monitored questions. Imports do not enable automatic synchronization.", - )} + {t("Connect your website accounts and sync AI visibility directly. No files to download or upload.")}

-
- {(["bing", "google"] as const).map((source) => { - const latest = reports.find((r) => r.source === source); - return ( -
-

- {source === "bing" ? "Bing AI Performance" : "Google Search Console · AI"} -

-

- {t( - source === "bing" - ? "Citations · Microsoft and supported partners" - : "Impressions · Google AI Overviews and AI Mode", - )} -

-

- {query.isPending - ? t("Loading…") - : query.isError - ? t("Could not load AI reports.") - : latest - ? `${latest.startDate} – ${latest.endDate} · ${latest.site}` - : t("No AI report imported")} -

- - {t("Open official dashboard")} - -
- ); - })} -
+ client.invalidateQueries({ queryKey })} /> {query.isError && (

{t("Could not load AI reports.")}{" "} @@ -128,141 +45,31 @@ function ReportWorkspace({ brandId }: { brandId: string }) {

)} -
- {t("Import AI report CSV")} -

- {t( - "Export one table from the AI report, then provide its website, dates and filters. Supported: page, daily history, and Bing grounding queries. Use exact counts, not Topic Portfolio opportunity ranges. CSV only; extract ZIP exports first. Maximum 2 MB / 2,000 rows.", - )} -

-
- - - - - - - -
- {preview.error && ( -

- {t(preview.error)} -

- )} - {preview.data && ( -
-

- {t("Import preview")} · {preview.data.rows.length} {t("rows")} ·{" "} - {t(input.source === "bing" ? "Citations" : "Impressions")} -

-
- - - {preview.data.rows.slice(0, 5).map((r) => ( - - - - - ))} - -
{r.key}{r.value ?? "—"}
-
- -
- )} - -
{message && (

{t(message)}

)} + {!query.isPending && !query.isError && !report && ( +

+ {t("No AI data synchronized yet. Connect an account above, then choose Sync now.")} +

+ )} {report && (

{t("Saved AI observations")}

+
+
+

+ {t("Official report total")} · {t(report.source === "bing" ? "Citations" : "Impressions")} +

+

{report.total?.toLocaleString() ?? "—"}

+
+
+

{t("Returned observations")}

+

{report.rows.length.toLocaleString()}

+
+

- {report.site} · {report.startDate} – {report.endDate} · {report.scope} + {report.site} · {report.startDate} – {report.endDate} · {t(report.scope)}
- {t("Imported at")}: {new Date(report.importedAt).toLocaleString()} + {report.coverage && ( + <> + {t(report.coverage)} +
+ + )} + {t("Saved at")}: {new Date(report.importedAt).toLocaleString()}

{t( "Compare only equal-length, non-overlapping periods from the same source, dimension, website and filters. Missing rows are unknown, not zero. Daily reports remain separate observations. Row sums are not site totals; different platforms are never added together.", )}

+ {report.dimension === "date" && report.rows.length > 0 && ( + ({ date: row.key, value: row.value }))} + label={t(report.source === "bing" ? "Citations" : "Impressions")} + color="var(--primary)" + className="aspect-auto h-64 w-full" + unit="count" + /> + )} { - if (!window.confirm(t("Remove this imported report? The original file is unchanged."))) return; + if (!window.confirm(t("Remove this saved snapshot? The official report is unchanged."))) return; setBusy(true); try { await deleteAiReportFn({ data: { brandId, id: report.id } }); @@ -384,7 +206,7 @@ function ReportWorkspace({ brandId }: { brandId: string }) { } }} > - {t("Remove import")} + {t("Remove snapshot")}
@@ -398,5 +220,7 @@ function reportView(reports: AiReport[], selected: string, previous: string, fil const baseline = reports.find((r) => r.id === previous); const comparison = report && baseline ? compareAiReports(report, baseline) : null; const rows = (comparison ?? report?.rows ?? []).filter((r) => r.key.toLowerCase().includes(filter.toLowerCase())); + if (report?.dimension !== "date") + rows.sort((a, b) => (b.value ?? -1) - (a.value ?? -1) || a.key.localeCompare(b.key)); return { report, comparison, rows }; } diff --git a/apps/web/src/components/ai-report-connections.tsx b/apps/web/src/components/ai-report-connections.tsx new file mode 100644 index 0000000..71b6459 --- /dev/null +++ b/apps/web/src/components/ai-report-connections.tsx @@ -0,0 +1,216 @@ +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { Link } from "@tanstack/react-router"; +import type { AiReportSource } from "@workspace/lib/ai-reports"; +import { Button } from "@workspace/ui/components/button"; +import { useState } from "react"; +import { useBrandParams } from "@/hooks/use-route-params"; +import { useT } from "@/lib/i18n"; +import { disconnectAiConnectionFn, getAiConnectionsFn, readAiConnectionFn } from "@/server/ai-report-connections"; + +export function AiReportConnections({ brandId, onSynced }: { brandId: string; onSynced: () => Promise }) { + const params = useBrandParams(); + const t = useT(), + client = useQueryClient(); + const queryKey = ["ai-report-connections", brandId]; + const query = useQuery({ queryKey, queryFn: () => getAiConnectionsFn({ data: { brandId } }) }); + const [busy, setBusy] = useState(null), + [message, setMessage] = useState(""); + const [selected, setSelected] = useState>({}); + async function run(source: AiReportSource, property: string, action: "connect" | "sync" | "disconnect") { + setBusy(`${source}:${action}`); + setMessage(""); + try { + if (action === "disconnect") { + await disconnectAiConnectionFn({ data: { brandId, source } }); + setMessage("Connection removed. Saved reports are kept."); + } else { + const result = await readAiConnectionFn({ data: { brandId, source, property, action } }); + setMessage( + result.ok + ? action === "connect" + ? "Report access verified. Ready to sync." + : "AI report synchronized." + : result.error, + ); + } + await Promise.all([client.invalidateQueries({ queryKey }), onSynced()]); + } catch (error) { + setMessage(error instanceof Error ? error.message : "Could not sync AI report."); + } finally { + setBusy(null); + } + } + if (query.isPending) return

{t("Loading…")}

; + if (query.isError) + return ( +
+ {t("Could not load connections.")} +
+ ); + return ( +
+
+

{t("Connect → Choose website → Sync AI data")}

+

+ {t( + "AI reports are read from your signed-in Chrome through BeatBrowser. Keep Chrome and BeatGEO open. Connecting does not start question monitoring.", + )} +

+

+ {t( + "Google search performance continues to use your existing Google authorization. AI report access is checked separately.", + )} +

+ + {t("Choose Chrome workspace")} + +
+
+ {(["bing", "google"] as const).map((source) => ( + c.source === source)} + selected={selected[source]} + onSelect={(value) => setSelected((v) => ({ ...v, [source]: value }))} + busy={busy} + run={run} + /> + ))} +
+ {message && ( +

+ {t(message)} +

+ )} +
+ ); +} + +function statusLabel(ready: boolean, state: string) { + if (ready) return "Access verified"; + return state === "needs-attention" ? "Connection needs attention" : "Not connected"; +} +function connectLabel(source: AiReportSource, busy: string | null, ready: boolean) { + if (busy === `${source}:connect`) return "Checking connection…"; + if (ready) return "Check connection"; + return source === "bing" ? "Connect Bing" : "Connect Google AI"; +} +function connectionFields(stored?: Record) { + const text = (key: string) => (typeof stored?.[key] === "string" ? (stored[key] as string) : ""); + return { + property: text("property"), + state: text("state"), + error: text("error"), + lastSyncedAt: text("lastSyncedAt"), + checkedAt: text("checkedAt"), + }; +} +function SourceCard({ + source, + websites, + stored, + selected, + onSelect, + busy, + run, +}: { + source: AiReportSource; + websites: string[]; + stored?: Record; + selected?: string; + onSelect: (value: string) => void; + busy: string | null; + run: (source: AiReportSource, property: string, action: "connect" | "sync" | "disconnect") => Promise; +}) { + const t = useT(); + const connection = connectionFields(stored); + const properties = reportProperties(source, websites); + const saved = properties.includes(connection.property) ? connection.property : ""; + const property = selected ?? (saved || properties[0] || ""); + const ready = connection.state === "ready" && saved === property; + const official = + source === "bing" + ? `https://www.bing.com/webmasters/aiperformance?siteUrl=${encodeURIComponent(property)}` + : `https://search.google.com/search-console/performance/search-analytics/ai?resource_id=${encodeURIComponent(property)}`; + return ( +
+
+

{source === "bing" ? "Bing Webmaster Tools" : "Google Search Console"}

+

+ {t(source === "bing" ? "AI citations · Pages · Grounding queries" : "AI impressions · Pages · Daily history")} +

+
+ +

{t(statusLabel(ready, connection.state))}

+ {connection.error && ( +

+ {t(connection.error)} +

+ )} + {connection.lastSyncedAt && ( +

+ {t("Last synchronized")}: {new Date(connection.lastSyncedAt).toLocaleString()} +

+ )} + {connection.checkedAt && ( +

+ {t("Access last checked")}: {new Date(connection.checkedAt).toLocaleString()} +

+ )} +
+ + + {connection.state && ( + + )} +
+ + {t("Open official dashboard / sign in")} + +

+ {t( + "Reads the official default three-month report. Actual dates and available rows are saved with each snapshot. Sync runs when you click; no background schedule is enabled.", + )} +

+
+ ); +} + +function reportProperties(source: AiReportSource, websites: string[]) { + return source === "bing" + ? websites + : [...new Set(websites.flatMap((site) => [`sc-domain:${new URL(site).hostname}`, site]))]; +} diff --git a/apps/web/src/components/app-sidebar.tsx b/apps/web/src/components/app-sidebar.tsx index 01c03b0..2e37484 100644 --- a/apps/web/src/components/app-sidebar.tsx +++ b/apps/web/src/components/app-sidebar.tsx @@ -13,9 +13,11 @@ import { IconPlugConnected, IconSchool, IconSearch, + IconShieldCheck, IconTarget, IconWorld, } from "@tabler/icons-react"; +import { useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { brandLinkParams, orgLinkParams } from "@workspace/lib/app-urls"; import type { BrandWithPrompts } from "@workspace/lib/db/schema"; @@ -30,14 +32,18 @@ import { SidebarMenuItem, useSidebar, } from "@workspace/ui/components/sidebar"; +import { FormSelect } from "@/components/form-select"; import { Logo } from "@/components/logo"; import { NavAppInfo } from "@/components/nav-app-info"; import { type NavGroup, type NavItem, NavMain } from "@/components/nav-main"; import { useLooseRouteContext } from "@/hooks/use-route-context"; +import { useT } from "@/lib/i18n"; import { INSIGHT_PAGES } from "@/lib/insight-navigation"; import type { OrganizationSummary } from "@/lib/organizations/types"; import { SEO_PAGES } from "@/lib/seo-navigation"; import type { ShellScope } from "@/lib/shell-scope"; +import { getConnectionsFn } from "@/server/connections"; +import { selectLocalWebsiteFn } from "@/server/local-navigation"; export type AppSidebarProps = ShellScope; @@ -63,6 +69,11 @@ function brandGroups(organization: OrganizationSummary, brand: SidebarBrand, seo link: { to: "/app/org/$org/brand/$brand/opportunities", params, hash: "search" }, icon: IconSearch, }, + { + title: "Website check", + link: { to: "/app/org/$org/brand/$brand/opportunities", params, hash: "website" }, + icon: IconShieldCheck, + }, ]; if (seoEnabled) seo.push( @@ -202,13 +213,102 @@ export function AppSidebar({ organization, brand }: AppSidebarProps) { + {organization && organization.brands.length > 0 && ( + + )} + {Boolean(context.canManageConnections) && } ); } + +function SidebarWebsiteSwitcher({ + organization, + current, +}: { + organization: OrganizationSummary; + current: SidebarBrand | undefined; +}) { + const t = useT(); + const currentKey = current ? current.slug || current.id : ""; + return ( +
+ { + if (value === currentKey) return; + const target = organization.brands.find((item) => (item.slug || item.id) === value); + if (!target) return; + try { + await selectLocalWebsiteFn({ data: { brandId: target.id } }); + window.location.assign("/app"); + } catch { + // Fall back silently if selection fails. + } + }} + options={organization.brands.map((item) => ({ + value: item.slug || item.id, + label: item.name, + }))} + /> +
+ ); +} + +function SidebarRuntimeStrip({ + organization, + brand, +}: { + organization: OrganizationSummary | undefined; + brand: SidebarBrand | undefined; +}) { + const t = useT(); + const { setOpenMobile } = useSidebar(); + const status = useQuery({ + queryKey: ["connections"], + queryFn: () => getConnectionsFn(), + refetchInterval: 30000, + retry: false, + }); + if (!status.data) return null; + const workerOk = status.data.runtime.worker === "ready"; + const browserOnline = Boolean(status.data.browser.online); + const chromeReady = Boolean(browserOnline && status.data.browser.selectedProfileId); + const chromeDot = chromeReady ? "bg-emerald-400" : browserOnline ? "bg-amber-400" : "bg-muted-foreground/50"; + const chromeLabel = chromeReady ? "Chrome ready" : browserOnline ? "Chrome setup" : "Chrome"; + const settingsLink = + organization && brand + ? { to: "/app/org/$org/brand/$brand/settings/brand" as const, params: brandLinkParams(organization, brand) } + : { to: "/setup" as const }; + return ( +
+ setOpenMobile(false)} + className="inline-flex items-center gap-1.5 hover:text-foreground" + > + + {t(workerOk ? "Worker ready" : "Worker offline")} + + setOpenMobile(false)} + className="inline-flex items-center gap-1.5 hover:text-foreground" + > + + {t(chromeLabel)} + +
+ ); +} diff --git a/apps/web/src/components/bing-panel.tsx b/apps/web/src/components/bing-panel.tsx new file mode 100644 index 0000000..d7161ba --- /dev/null +++ b/apps/web/src/components/bing-panel.tsx @@ -0,0 +1,289 @@ +import type { BingSummary } from "@workspace/lib/traffic/bing"; +import { Button } from "@workspace/ui/components/button"; +import { Card, CardContent, CardHeader, CardTitle } from "@workspace/ui/components/card"; +import { Input } from "@workspace/ui/components/input"; +import { Label } from "@workspace/ui/components/label"; +import { useState } from "react"; +import { DeltaBadge, StatusPill } from "@/components/status-badges"; +import { TrendChart } from "@/components/trend-chart"; +import { useLocale, useT } from "@/lib/i18n"; +import type { TrafficData } from "@/server/traffic-core"; + +type Props = { + settingsOnly?: boolean; + data: TrafficData; + busy: boolean; + onConnect: (apiKey: string, siteUrl?: string) => void; + onSync: () => void; + onDisconnect: () => void; +}; + +function deltaText(cur: number, prev: number) { + const diff = cur - prev; + const sign = diff > 0 ? "+" : ""; + if (prev <= 0) return `${sign}${diff}`; + return `${sign}${diff} (${sign}${((diff / prev) * 100).toFixed(1)}%)`; +} + +export function BingPanel({ settingsOnly = false, data, busy, onConnect, onSync, onDisconnect }: Props) { + const t = useT(); + const summary = data.bing?.snapshot as BingSummary | null; + const connected = Boolean(data.bing?.connected); + const defaultSiteUrl = data.bing?.config?.siteUrl || `https://${data.site}/`; + + return ( + + + {t("Bing Webmaster")} +

+ {t("Read-only Bing search clicks, impressions, queries and crawl stats (used alongside Google for GEO).")} +

+
+ + {settingsOnly ? ( + + ) : ( + + )} + +
+ ); +} + +function BingSettingsForm({ + connected, + defaultSiteUrl, + busy, + onConnect, + onSync, + onDisconnect, +}: { + connected: boolean; + defaultSiteUrl: string; + busy: boolean; + onConnect: (apiKey: string, siteUrl?: string) => void; + onSync: () => void; + onDisconnect: () => void; +}) { + const t = useT(); + const [apiKey, setApiKey] = useState(""); + const [siteUrl, setSiteUrl] = useState(defaultSiteUrl); + return ( +
+
+ + setApiKey(e.target.value)} + /> +

+ {t("BeatGEO calls read-only Get* endpoints only and never submits URLs.")} +

+
+
+ + setSiteUrl(e.target.value)} + /> +
+
+ + {connected && ( + <> + + + + )} +
+
+ ); +} + +function BingOverview({ + connected, + siteUrl, + busy, + summary, + onSync, +}: { + connected: boolean; + siteUrl: string; + busy: boolean; + summary: BingSummary | null; + onSync: () => void; +}) { + const t = useT(); + if (!connected) { + return ( +

+ {t("Connect Bing Webmaster API in Brand settings to compare Bing traffic and crawl health.")} +

+ ); + } + return ( +
+
+ {siteUrl} + +
+ {summary && } +
+ ); +} + +function BingSummaryView({ summary }: { summary: BingSummary }) { + const t = useT(); + const { locale } = useLocale(); + const [view, setView] = useState<"queries" | "pages">("queries"); + const [filter, setFilter] = useState(""); + const num = (v: number) => new Intl.NumberFormat(locale).format(v); + const sourceRows = view === "queries" ? summary.queries : summary.pages; + const rows = sourceRows.filter((row) => row.key.toLowerCase().includes(filter.toLowerCase())); + const dailySeries = summary.days.map((day) => ({ date: day.date, value: day.clicks })); + + return ( +
+

+ {summary.cur7d ? `${summary.cur7d.from} – ${summary.cur7d.to}` : t("No recent traffic rows")} ·{" "} + {t("Last successful data fetch")}: {new Date(summary.fetchedAt).toLocaleString(locale)} +

+ {summary.cur7d && } + {dailySeries.length > 1 && ( +
+

{t("Daily Bing clicks")}

+
+ +
+
+ )} +
+ + + setFilter(e.target.value)} + /> +
+ {rows.length > 0 ? ( +
+ + + + {[ + view === "queries" ? t("Search query") : t("Page"), + t("Clicks"), + t("Impressions"), + t("CTR"), + t("Average position"), + ].map((h) => ( + + ))} + + + + {rows.slice(0, 50).map((row) => ( + + + + + + + + ))} + +
+ {h} +
{row.key}{num(row.clicks)}{num(row.impressions)}{(row.ctr * 100).toFixed(2)}%{row.position.toFixed(1)}
+
+ ) : ( +

{t("No Bing rows match this filter.")}

+ )} +

+ {t( + "Bing Webmaster API typically lags by ~1 day. Full 4xx/5xx URL lists are not exposed via API and require exporting from Bing Webmaster Tools.", + )} +

+
+ ); +} + +function BingMetricsGrid({ summary, num }: { summary: BingSummary; num: (v: number) => string }) { + const t = useT(); + const cur = summary.cur7d!; + const prev = summary.prev7d; + const crawl = summary.latestCrawl; + const hasErrors = Boolean(crawl && crawl.code4xx + crawl.code5xx > 0); + return ( +
+
+
{t("Bing clicks (7d)")}
+
+ {num(cur.clicks)} + {prev && } +
+
+
+
{t("Bing impressions (7d)")}
+
+ {num(cur.impressions)} + {prev && ( + + )} +
+
+
+
{t("Pages in Bing index")}
+
{crawl ? num(crawl.inIndex) : "—"}
+
+
+
{t("Crawl errors (4xx / 5xx)")}
+
+ + {crawl ? `${crawl.code4xx} / ${crawl.code5xx}` : "—"} + + {crawl && } +
+
+
+ ); +} diff --git a/apps/web/src/components/brand-setup.tsx b/apps/web/src/components/brand-setup.tsx index 6e01ea7..0467988 100644 --- a/apps/web/src/components/brand-setup.tsx +++ b/apps/web/src/components/brand-setup.tsx @@ -1,3 +1,4 @@ +import { IconCheck } from "@tabler/icons-react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useNavigate } from "@tanstack/react-router"; import { Button } from "@workspace/ui/components/button"; @@ -17,14 +18,20 @@ import { export function BrandSetup({ website, + sources, actions, monitoringActions, connectedWebsite = false, + connectedSourcesCount = 0, + defaultStep = "website", }: { website: ReactNode; + sources?: ReactNode; actions?: ReactNode; monitoringActions?: ReactNode; connectedWebsite?: boolean; + connectedSourcesCount?: number; + defaultStep?: string; }) { const t = useT(); const client = useQueryClient(); @@ -72,8 +79,8 @@ export function BrandSetup({ const hash = usePublicHash(); const navigate = useNavigate(); - const steps = setupSteps(connectedWebsite, status.data); - const active = steps.some((step) => step.id === hash) ? hash : "website"; + const steps = setupSteps(connectedWebsite, Boolean(sources), connectedSourcesCount, status.data); + const active = resolveActiveStep(steps, hash, defaultStep); return (
@@ -85,24 +92,12 @@ export function BrandSetup({
{actions} -
- +
+ void navigate({ hash: id, replace: true, resetScroll: false })} + />
{status.error && (

@@ -112,6 +107,11 @@ export function BrandSetup({

+ {sources && ( + + )} {hasEnabledPrompts && }
@@ -455,7 +464,10 @@ function useEarlySignalCaption(loading: boolean, totalRuns: number): string | un /** Website per brand or competitor name, so the ranking can show each one's icon. */ function rankingDomainsFor(brand: BrandWithPrompts | undefined): Record { if (!brand) return {}; - return Object.fromEntries([[brand.name, brand.website], ...brand.competitors.map((c) => [c.name, c.domains[0]])]); + return Object.fromEntries([ + [brand.name, brand.website], + ...(brand.competitors ?? []).map((c) => [c.name, c.domains[0]]), + ]); } function BaselineNotice({ totalRuns }: { totalRuns: number }) { @@ -473,6 +485,16 @@ function BaselineNotice({ totalRuns }: { totalRuns: number }) { ); } +function OnboardingShell({ brandId, children }: { brandId: string | undefined; children: ReactNode }) { + return ( +
+ + {brandId && } + {children} +
+ ); +} + function DashboardPage() { const t = useT(); const brandId = useBrandId(); @@ -501,27 +523,26 @@ function DashboardPage() { if (!isLoadingBrand && !brand?.onboarded) { return ( -
- + -
+ ); } // No runs yet: the dashboard has nothing to plot, so point at what to do next. if (!loadingVisibility && totalRuns === 0) { return ( -
- + 0} /> -
+ ); } return (
-
+
+ {brand?.id && } {earlySignal && }

{t( diff --git a/apps/web/src/routes/_authed/app/org/$org/brand/$brand/search-console.tsx b/apps/web/src/routes/_authed/app/org/$org/brand/$brand/search-console.tsx index 156f37a..03a6f99 100644 --- a/apps/web/src/routes/_authed/app/org/$org/brand/$brand/search-console.tsx +++ b/apps/web/src/routes/_authed/app/org/$org/brand/$brand/search-console.tsx @@ -1,6 +1,7 @@ -import { createFileRoute } from "@tanstack/react-router"; +import { createFileRoute, Link } from "@tanstack/react-router"; import { PageHeader } from "@/components/page-header"; import { TrafficSources } from "@/components/traffic-sources"; +import { useBrandParams } from "@/hooks/use-route-params"; import { useT } from "@/lib/i18n"; import { pageHead } from "@/lib/route-head"; export const Route = createFileRoute("/_authed/app/org/$org/brand/$brand/search-console")({ @@ -13,12 +14,23 @@ export const Route = createFileRoute("/_authed/app/org/$org/brand/$brand/search- }); function SearchConsolePage() { const t = useT(); + const params = useBrandParams(); return ( + {t("Manage data sources")} + + } > diff --git a/apps/web/src/routes/_authed/app/org/$org/brand/$brand/settings/brand.tsx b/apps/web/src/routes/_authed/app/org/$org/brand/$brand/settings/brand.tsx index c4172d3..12a4fa8 100644 --- a/apps/web/src/routes/_authed/app/org/$org/brand/$brand/settings/brand.tsx +++ b/apps/web/src/routes/_authed/app/org/$org/brand/$brand/settings/brand.tsx @@ -1,5 +1,5 @@ import { IconInfoCircle } from "@tabler/icons-react"; -import { useQueryClient } from "@tanstack/react-query"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; import { createFileRoute, Link, useNavigate } from "@tanstack/react-router"; import { brandSegment, brandSlugPrefix, normalizeSlug } from "@workspace/lib/app-urls"; import { cleanAndValidateDomain } from "@workspace/lib/citations/domain-categories"; @@ -13,6 +13,7 @@ import { FormSelect } from "@/components/form-select"; import { SlugField } from "@/components/slug-field"; import { TagsInput } from "@/components/tags-input"; import { TrafficSources } from "@/components/traffic-sources"; +import { useBrandId } from "@/hooks/use-brand-id"; import { useBrand } from "@/hooks/use-brands"; import { citationKeys } from "@/hooks/use-citations"; import { dashboardKeys } from "@/hooks/use-dashboard-summary"; @@ -23,6 +24,7 @@ import { pageHead } from "@/lib/route-head"; import { useWriteErrorMessage } from "@/lib/write-errors"; import { updateBrandFn } from "@/server/brands"; import { selectLocalWebsiteFn } from "@/server/local-navigation"; +import { getTrafficFn } from "@/server/traffic-fn"; export const Route = createFileRoute("/_authed/app/org/$org/brand/$brand/settings/brand")({ staticData: { crumb: "Brand" }, @@ -36,11 +38,25 @@ export const Route = createFileRoute("/_authed/app/org/$org/brand/$brand/setting function BrandSettingsPage() { const t = useT(); const organization = useOrganization(); + const brandId = useBrandId(); const params = useBrandParams(); const [switchError, setSwitchError] = useState(""); const { google } = Route.useSearch(); + const traffic = useQuery({ + queryKey: ["traffic", brandId], + queryFn: () => getTrafficFn({ data: { brandId } }), + retry: false, + }); + const connectedSourcesCount = [ + traffic.data?.gsc?.connected, + traffic.data?.ga?.connected, + traffic.data?.bing?.connected, + traffic.data?.cloudflare?.connected, + ].filter(Boolean).length; return ( { const brand = organization.brands.find((brand) => (brand.slug || brand.id) === value); @@ -100,15 +116,19 @@ function BrandSettingsPage() {

-
-

Google Search Console · Analytics

-

- {t("Optional. Connect Google to add your site's search performance and traffic data.")} -

- -
} + sources={ +
+

{t("Search & traffic data sources")}

+

+ {t( + "Optional. Connect Google Search Console, GA4, Bing Webmaster and Cloudflare crawlers for this website.", + )} +

+ +
+ } /> ); } @@ -311,7 +331,11 @@ function BrandDetailsForm() {
{error &&
{error}
} - {success &&
{success}
} + {success && ( +
+ {t(success)} +
+ )}