Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(traffic): list the Google queries no prompt tracks, with Track and Track all (#1178)
Cihan98c6cc40b284
diff --git a/server/src/lib/gsc-suggestions.js b/server/src/lib/gsc-suggestions.jsindex 5177d9c49..27c1b1542 100644--- a/server/src/lib/gsc-suggestions.js+++ b/server/src/lib/gsc-suggestions.js@@ -72,17 +72,26 @@ export function normalizeTokens(text) {.filter((t) => t && !STOPWORDS.has(t));}-/** True when the query's meaningful tokens are mostly present in one prompt. */-export function isCoveredByPrompts(query, promptTexts) {+/** Each prompt's meaningful tokens, read once for checking many queries. */+export function promptTokenSets(promptTexts) {+ return promptTexts.map((text) => new Set(normalizeTokens(text)));+}++/** `isCoveredByPrompts` against prompts already split by `promptTokenSets`. */+export function isCoveredByTokenSets(query, tokenSets) {const queryTokens = normalizeTokens(query);if (queryTokens.length === 0) return true; // stopwords-only — nothing to track- return promptTexts.some((text) => {- const promptTokens = new Set(normalizeTokens(text));+ return tokenSets.some((promptTokens) => {const hits = queryTokens.filter((t) => promptTokens.has(t)).length;return hits / queryTokens.length >= COVERAGE_OVERLAP;});}+/** True when the query's meaningful tokens are mostly present in one prompt. */+export function isCoveredByPrompts(query, promptTexts) {+ return isCoveredByTokenSets(query, promptTokenSets(promptTexts));+}+/** Click-based rationale: protect what earns traffic, capture what doesn't convert. */export function classifyCandidate(c) {if (c.clicks >= PROTECT_MIN_CLICKS) return 'protect_traffic';diff --git a/server/src/lib/untracked-queries.js b/server/src/lib/untracked-queries.jsnew file mode 100644index 000000000..d1e24ebd1--- /dev/null+++ b/server/src/lib/untracked-queries.js@@ -0,0 +1,65 @@+/**+ * Google queries you don't track yet (AT-009, spec §3.6): the brand's+ * Search Console queries with clicks in a window, most clicks first, that no+ * active tracked prompt covers — by the rule Prompt Suggestions uses for+ * Google queries (gsc-suggestions.js), so the two pages agree. Read on+ * request, nothing stored; tracking one adds it as a prompt.+ */++import supabaseAdmin from '../config/supabase.js';+import { isCoveredByTokenSets, promptTokenSets } from './gsc-suggestions.js';+import { readAllRpcRows } from './rpc-pages.js';++/** The most clicked queries checked; past it the count reads "N+". */+export const UNTRACKED_QUERY_SCAN = 5000;++/** The brand's active prompts' texts, every one. */+async function activePromptTexts(brandId) {+ const { data, error } = await readAllRpcRows('prompts', (from, to) =>+ supabaseAdmin+ .from('prompts')+ .select('id, text, prompt_sets!inner(brand_id)')+ .eq('prompt_sets.brand_id', brandId)+ .eq('is_active', true)+ .order('id')+ .range(from, to),+ );+ if (error) throw new Error(error.message);+ return (data ?? []).map((p) => p.text).filter(Boolean);+}++/**+ * `since` null reads all time; `latest` ends the window on the latest day+ * Google has reported, keeping its length. Returns the first `limit`+ * untracked queries and how many there are (`capped`: more than the scan).+ */+export async function untrackedGoogleQueries(brandId, { since, until, latest = true, limit = 10 }) {+ const [{ data, error }, texts] = await Promise.all([+ supabaseAdmin.rpc('ai_traffic_google_queries', {+ p_brand_id: brandId,+ p_since: since,+ p_until: until,+ p_latest: latest,+ p_limit: UNTRACKED_QUERY_SCAN,+ }),+ activePromptTexts(brandId),+ ]);+ if (error) throw new Error(error.message);+ const raw = data ?? {};+ const tokenSets = promptTokenSets(texts);+ const untracked = (Array.isArray(raw.rows) ? raw.rows : [])+ .filter((r) => r.query && !isCoveredByTokenSets(r.query, tokenSets))+ .map((r) => ({+ query: r.query,+ clicks: Number(r.clicks) || 0,+ impressions: Number(r.impressions) || 0,+ }));+ return {+ lastDay: raw.last_day ?? null,+ since: raw.since ?? null,+ until: raw.until ?? null,+ count: untracked.length,+ capped: raw.capped === true,+ rows: untracked.slice(0, Math.max(0, limit)),+ };+}diff --git a/server/src/lib/untracked-queries.test.js b/server/src/lib/untracked-queries.test.jsnew file mode 100644index 000000000..50d0b7eb8--- /dev/null+++ b/server/src/lib/untracked-queries.test.js@@ -0,0 +1,115 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * Google queries you don't track yet (AT-009): Search Console's queries with+ * clicks, minus the ones an active prompt covers by Prompt Suggestions'+ * rule, most clicks first.+ */++const rpc = vi.fn();+let prompts = [];+const promptReads = [];++function promptsChain() {+ const calls = {};+ const chain = {+ select: () => chain,+ eq: (col, val) => {+ calls[col] = val;+ return chain;+ },+ order: () => chain,+ range: async (from, to) => {+ promptReads.push({ ...calls, from, to });+ return { data: prompts.slice(from, to + 1), error: null };+ },+ };+ return chain;+}++vi.mock('../config/supabase.js', () => ({+ default: { rpc: (...args) => rpc(...args), from: () => promptsChain() },+}));++const { UNTRACKED_QUERY_SCAN, untrackedGoogleQueries } = await import('./untracked-queries.js');++beforeEach(() => {+ rpc.mockReset();+ promptReads.length = 0;+ prompts = [+ { id: 'p1', text: 'Best espresso beans for a home grinder?' },+ { id: 'p2', text: 'Which coffee subscription ships to offices?' },+ ];+ rpc.mockResolvedValue({+ data: {+ last_day: '2026-10-17',+ since: '2026-10-11',+ until: '2026-10-17',+ capped: false,+ rows: [+ { query: 'espresso beans', clicks: 40, impressions: 900 },+ { query: 'cold brew ratio', clicks: '25', impressions: 610 },+ { query: 'coffee subscription offices', clicks: 12, impressions: 300 },+ { query: 'how to descale an espresso machine', clicks: 9, impressions: 400 },+ { query: 'the', clicks: 3, impressions: 50 },+ ],+ },+ error: null,+ });+});++describe('untrackedGoogleQueries', () => {+ it('keeps the queries no active prompt covers, most clicks first', async () => {+ const result = await untrackedGoogleQueries('b1', {+ since: '2026-10-13',+ until: '2026-10-19',+ limit: 1,+ });+ expect(rpc).toHaveBeenCalledWith('ai_traffic_google_queries', {+ p_brand_id: 'b1',+ p_since: '2026-10-13',+ p_until: '2026-10-19',+ p_latest: true,+ p_limit: UNTRACKED_QUERY_SCAN,+ });+ expect(promptReads[0]).toMatchObject({ 'prompt_sets.brand_id': 'b1', is_active: true });+ expect(result).toEqual({+ lastDay: '2026-10-17',+ since: '2026-10-11',+ until: '2026-10-17',+ count: 2,+ capped: false,+ rows: [{ query: 'cold brew ratio', clicks: 25, impressions: 610 }],+ });+ });++ it('reads every prompt past the 1,000-row page, and says when the scan was capped', async () => {+ prompts = [+ ...Array.from({ length: 1000 }, (_, i) => ({ id: `x${i}`, text: `filler prompt ${i}` })),+ { id: 'late', text: 'Cold brew ratio for a big batch' },+ ];+ rpc.mockResolvedValue({+ data: {+ last_day: '2026-10-17',+ since: null,+ until: '2026-10-17',+ capped: true,+ rows: [{ query: 'cold brew ratio', clicks: 25, impressions: 610 }],+ },+ error: null,+ });+ const result = await untrackedGoogleQueries('b1', { since: null, until: '2026-10-19' });+ expect(promptReads.map((r) => [r.from, r.to])).toEqual([+ [0, 999],+ [1000, 1999],+ ]);+ expect(result).toMatchObject({ count: 0, capped: true, rows: [] });+ });++ it('throws when the read fails', async () => {+ rpc.mockResolvedValue({ data: null, error: { message: 'boom' } });+ await expect(+ untrackedGoogleQueries('b1', { since: null, until: '2026-10-19' }),+ ).rejects.toThrow('boom');+ });+});diff --git a/server/src/routes/prompts-untracked-queries.test.js b/server/src/routes/prompts-untracked-queries.test.jsnew file mode 100644index 000000000..776e8e978--- /dev/null+++ b/server/src/routes/prompts-untracked-queries.test.js@@ -0,0 +1,107 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * GET /api/prompts/untracked-queries/:brandId (AT-009): Google queries you+ * don't track yet, for the AI Traffic page. The list itself is tested in+ * untracked-queries.test.js; this checks the days, the limit and access.+ */++const untrackedGoogleQueries = vi.fn();+let profileOrg;++function table(name) {+ const result = () => {+ if (name === 'brands') return { data: { id: 'b1', organization_id: 'o1' }, error: null };+ if (name === 'profiles') return { data: { organization_id: profileOrg }, error: null };+ return { data: [], error: null };+ };+ const chain = new Proxy(+ {},+ {+ get: (_t, prop) => {+ if (prop === 'then') {+ return (resolve, reject) => Promise.resolve(result()).then(resolve, reject);+ }+ if (prop === 'single' || prop === 'maybeSingle') return async () => result();+ return () => chain;+ },+ },+ );+ return chain;+}++vi.mock('../config/supabase.js', () => ({ default: { from: (name) => table(name) } }));+vi.mock('../lib/plan-guard.js', () => ({+ PlanLimitError: class extends Error {},+ enforceFeature: vi.fn(),+ enforceImproveQuota: vi.fn(),+ getImproveQuotaStatus: vi.fn(),+ requireFeature: () => (req, res, next) => next(),+ reserveRelevanceAllowance: vi.fn(),+ settleRelevanceUsage: vi.fn(),+}));+vi.mock('../lib/untracked-queries.js', () => ({+ UNTRACKED_QUERY_SCAN: 5000,+ untrackedGoogleQueries,+}));++const { default: router } = await import('./prompts.js');++const BRAND = '33333333-3333-3333-3333-333333333333';+let server;+let baseUrl;++const get = (query) => fetch(`${baseUrl}/untracked-queries/${BRAND}?${new URLSearchParams(query)}`);++beforeEach(async () => {+ untrackedGoogleQueries.mockReset().mockResolvedValue({ count: 0, rows: [] });+ profileOrg = 'o1';+ const app = express();+ app.use((req, _res, next) => {+ req.user = { id: 'u1' };+ req.log = { error: vi.fn(), info: vi.fn() };+ next();+ });+ app.use('/api/prompts', router);+ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/prompts`;+});++afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+});++describe('GET /api/prompts/untracked-queries/:brandId', () => {+ it("reads the page's days, all time without a first one", async () => {+ const res = await get({ since: '2026-10-13', until: '2026-10-19', limit: '0' });+ expect(res.status).toBe(200);+ expect(untrackedGoogleQueries).toHaveBeenCalledWith(BRAND, {+ since: '2026-10-13',+ until: '2026-10-19',+ limit: 0,+ });++ await get({ until: '2026-10-19' });+ expect(untrackedGoogleQueries).toHaveBeenLastCalledWith(BRAND, {+ since: null,+ until: '2026-10-19',+ limit: 10,+ });+ });++ it('rejects days it cannot read and a limit past the scan', async () => {+ expect((await get({ until: 'yesterday' })).status).toBe(400);+ expect((await get({ until: '2026-10-19', limit: '6000' })).status).toBe(400);+ expect(untrackedGoogleQueries).not.toHaveBeenCalled();+ });++ it("refuses a brand outside the member's organization", async () => {+ profileOrg = 'o2';+ const res = await get({ until: '2026-10-19' });+ expect(res.status).toBe(403);+ expect(untrackedGoogleQueries).not.toHaveBeenCalled();+ });+});diff --git a/server/src/routes/prompts.js b/server/src/routes/prompts.jsindex bcd23af09..335c1431b 100644--- a/server/src/routes/prompts.js+++ b/server/src/routes/prompts.js@@ -18,6 +18,7 @@ import { withRetry } from '../lib/retry.js';import { getGscSuggestionCandidates } from '../lib/gsc-suggestions.js';import { getGaSuggestionCandidates } from '../lib/ga-suggestions.js';import { suggestPromptsForPage } from '../lib/page-prompt-suggestions.js';+import { UNTRACKED_QUERY_SCAN, untrackedGoogleQueries } from '../lib/untracked-queries.js';import { RELEVANCE_SCALE, ratingCostUsd, toRelevance } from '../lib/suggestion-relevance.js';import {ACTIONABLE_STATES,@@ -586,6 +587,42 @@ router.get('/suggestions/:brandId', async (req, res) => {}});+const untrackedQueriesSchema = z.object({+ // The days the AI Traffic page reads: the range's first (absent for all+ // time) and last; the window then ends on Google's latest reported day.+ since: z.iso.date().optional(),+ until: z.iso.date(),+ limit: z.coerce.number().int().min(0).max(UNTRACKED_QUERY_SCAN).default(10),+});++/**+ * GET /api/prompts/untracked-queries/:brandId?since=&until=&limit=+ *+ * Google queries you don't track yet (AT-009): the brand's Search Console+ * queries with clicks that no active prompt covers, most clicks first, for+ * the AI Traffic page. Read on request; tracking one adds it as a prompt.+ */+router.get('/untracked-queries/:brandId', async (req, res) => {+ try {+ const parsed = untrackedQueriesSchema.safeParse(req.query ?? {});+ if (!parsed.success) {+ return res.status(400).json({ error: 'Invalid request', details: parsed.error.message });+ }+ await assertBrandAccess(req.params.brandId, req.user.id);+ const { since, until, limit } = parsed.data;+ const result = await untrackedGoogleQueries(req.params.brandId, {+ since: since ?? null,+ until,+ limit,+ });+ return res.json(result);+ } catch (error) {+ const status = error.status || 500;+ req.log.error({ err: error }, 'untracked queries error');+ return res.status(status).json({ error: error.message || 'Failed to read Google queries' });+ }+});+router.post('/suggestions/:id/dismiss', async (req, res) => {try {const { data: suggestion } = await supabaseAdmindiff --git a/supabase/migrations/00182_ai_traffic_google_queries.sql b/supabase/migrations/00182_ai_traffic_google_queries.sqlnew file mode 100644index 000000000..004485128--- /dev/null+++ b/supabase/migrations/00182_ai_traffic_google_queries.sql@@ -0,0 +1,96 @@+-- ============================================================================+-- 00182: Google queries you don't track yet (AT-009)+-- ============================================================================+-- Spec §3.6: the top Search Console queries by clicks that match no tracked+-- prompt, to track with one click. This reads the queries with clicks in+-- the window, most clicks first. Which of them a prompt already covers is+-- the server's call (server/src/lib/untracked-queries.js), with the rule+-- Prompt Suggestions uses for Google queries, so the two pages agree.+--+-- Google reports about two days late: with p_latest the window ends on the+-- latest day it has reported, keeping its length (§3.01), as the Google+-- clicks card's does (00174). All time (p_since null) reads every day kept.+-- At most p_limit queries; `capped` says there were more.+--+-- Security invoker: gsc_query_stats has a member select policy, so RLS+-- decides the brand. The server reads it as the service role, after+-- checking the member's access to the brand.++create or replace function public.ai_traffic_google_queries(+ p_brand_id uuid,+ p_since date,+ p_until date,+ p_latest boolean default false,+ p_limit integer default 5000+)+returns jsonb+language plpgsql+stable+security invoker+set search_path to 'public'+as $$+declare+ v_last date;+ v_since date;+ v_until date;+ v_rows jsonb;+ v_count integer;+begin+ select max(g.date) into v_last from public.gsc_query_stats g where g.brand_id = p_brand_id;+ if v_last is null then+ return jsonb_build_object(+ 'last_day', null, 'since', null, 'until', null, 'capped', false, 'rows', '[]'::jsonb+ );+ end if;++ v_since := p_since;+ v_until := p_until;+ if p_latest and v_last < p_until then+ v_until := v_last;+ if p_since is not null then+ v_since := v_last - (p_until - p_since);+ end if;+ end if;++ select+ coalesce(jsonb_agg(+ jsonb_build_object('query', q.query, 'clicks', q.clicks, 'impressions', q.impressions)+ order by q.clicks desc, q.impressions desc, q.query+ ), '[]'::jsonb),+ count(*)+ into v_rows, v_count+ from (+ select g.query, sum(g.clicks)::bigint as clicks, sum(g.impressions)::bigint as impressions+ from public.gsc_query_stats g+ where g.brand_id = p_brand_id+ and g.date >= coalesce(v_since, '-infinity'::date)+ and g.date <= v_until+ group by g.query+ having sum(g.clicks) > 0+ order by sum(g.clicks) desc, sum(g.impressions) desc, g.query+ limit greatest(p_limit, 0) + 1+ ) q;++ if v_count > p_limit then+ v_rows := v_rows - p_limit;+ end if;++ return jsonb_build_object(+ 'last_day', v_last,+ 'since', v_since,+ 'until', v_until,+ 'capped', v_count > p_limit,+ 'rows', v_rows+ );+end;+$$;++revoke all on function public.ai_traffic_google_queries(uuid, date, date, boolean, integer)+ from public, anon;+grant execute on function public.ai_traffic_google_queries(uuid, date, date, boolean, integer)+ to authenticated, service_role;++comment on function public.ai_traffic_google_queries(uuid, date, date, boolean, integer) is+ 'AI Traffic "Google queries you don''t track yet" (AT-009, spec §3.6): Search Console queries with clicks between two days, most clicks first, at most p_limit (capped says there were more). p_latest ends the window on Google''s latest reported day. The server drops the ones a tracked prompt covers. Security invoker: RLS decides the brand.';++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 0aea706fe..c8919d894 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -24855,3 +24855,103 @@ comment on function public.ai_traffic_google_pages(uuid, date, date, boolean, innotify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00182_ai_traffic_google_queries.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00182: Google queries you don't track yet (AT-009)+-- ============================================================================+-- Spec §3.6: the top Search Console queries by clicks that match no tracked+-- prompt, to track with one click. This reads the queries with clicks in+-- the window, most clicks first. Which of them a prompt already covers is+-- the server's call (server/src/lib/untracked-queries.js), with the rule+-- Prompt Suggestions uses for Google queries, so the two pages agree.+--+-- Google reports about two days late: with p_latest the window ends on the+-- latest day it has reported, keeping its length (§3.01), as the Google+-- clicks card's does (00174). All time (p_since null) reads every day kept.+-- At most p_limit queries; `capped` says there were more.+--+-- Security invoker: gsc_query_stats has a member select policy, so RLS+-- decides the brand. The server reads it as the service role, after+-- checking the member's access to the brand.++create or replace function public.ai_traffic_google_queries(+ p_brand_id uuid,+ p_since date,+ p_until date,+ p_latest boolean default false,+ p_limit integer default 5000+)+returns jsonb+language plpgsql+stable+security invoker+set search_path to 'public'+as $$+declare+ v_last date;+ v_since date;+ v_until date;+ v_rows jsonb;+ v_count integer;+begin+ select max(g.date) into v_last from public.gsc_query_stats g where g.brand_id = p_brand_id;+ if v_last is null then+ return jsonb_build_object(+ 'last_day', null, 'since', null, 'until', null, 'capped', false, 'rows', '[]'::jsonb+ );+ end if;++ v_since := p_since;+ v_until := p_until;+ if p_latest and v_last < p_until then+ v_until := v_last;+ if p_since is not null then+ v_since := v_last - (p_until - p_since);+ end if;+ end if;++ select+ coalesce(jsonb_agg(+ jsonb_build_object('query', q.query, 'clicks', q.clicks, 'impressions', q.impressions)+ order by q.clicks desc, q.impressions desc, q.query+ ), '[]'::jsonb),+ count(*)+ into v_rows, v_count+ from (+ select g.query, sum(g.clicks)::bigint as clicks, sum(g.impressions)::bigint as impressions+ from public.gsc_query_stats g+ where g.brand_id = p_brand_id+ and g.date >= coalesce(v_since, '-infinity'::date)+ and g.date <= v_until+ group by g.query+ having sum(g.clicks) > 0+ order by sum(g.clicks) desc, sum(g.impressions) desc, g.query+ limit greatest(p_limit, 0) + 1+ ) q;++ if v_count > p_limit then+ v_rows := v_rows - p_limit;+ end if;++ return jsonb_build_object(+ 'last_day', v_last,+ 'since', v_since,+ 'until', v_until,+ 'capped', v_count > p_limit,+ 'rows', v_rows+ );+end;+$$;++revoke all on function public.ai_traffic_google_queries(uuid, date, date, boolean, integer)+ from public, anon;+grant execute on function public.ai_traffic_google_queries(uuid, date, date, boolean, integer)+ to authenticated, service_role;++comment on function public.ai_traffic_google_queries(uuid, date, date, boolean, integer) is+ 'AI Traffic "Google queries you don''t track yet" (AT-009, spec §3.6): Search Console queries with clicks between two days, most clicks first, at most p_limit (capped says there were more). p_latest ends the window on Google''s latest reported day. The server drops the ones a tracked prompt covers. Security invoker: RLS decides the brand.';++notify pgrst, 'reload schema';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 090302b44..18c542c3a 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3135,6 +3135,7 @@"buyerAnswers": "Answers that bring buyers","pageStatus": "Pages by status","googlePages": "Is AI taking Google clicks",+ "googleQueries": "Untracked Google queries","visits": "Visits"},"columns": {@@ -3181,7 +3182,8 @@"clicks": "Clicks","previousClicks": "Clicks, previous period","days": "Days",- "previousDays": "Days, previous period"+ "previousDays": "Days, previous period",+ "query": "Query"},"metrics": {"visits": "AI-referred visits",@@ -3202,7 +3204,10 @@"conversionLowSample": "Low sample: fewer than 30 AI visits","noGooglePages": "No page data from Google Search Console yet","noGoogleClicksLost": "No page's impressions rose 15% while its CTR fell 20% in this range",- "googleHistoryShort": "Google Search Console's page history doesn't reach back to the period before this range"+ "googleHistoryShort": "Google Search Console's page history doesn't reach back to the period before this range",+ "noGoogleQueries": "No query data from Google Search Console yet",+ "noUntrackedQueries": "Every Google query with clicks in this range is tracked",+ "queriesCapped": "Only the 5,000 most clicked queries were checked"},"sourceStates": {"active": "Active",@@ -3371,7 +3376,8 @@"conversions": "where AI visitors convert","pageValue": "which valuable pages get no AI traffic","googleTrend": "AI visits against Google clicks",- "googlePages": "which pages AI may be taking Google clicks from"+ "googlePages": "which pages AI may be taking Google clicks from",+ "googleQueries": "Google queries you don't track yet"}},"google": {@@ -3400,6 +3406,27 @@"positionsTip": "See in Positions whether you're cited for a tracked prompt about this page","addPrompts": "Add prompts","addPromptsTip": "No tracked prompt is about this page yet"+ },+ "untracked": {+ "title": "Untracked Google queries",+ "untilDay": "until {day}",+ "legend": "Google queries with clicks that no tracked prompt covers. Track one to see whether AI answers name you for it; each uses a prompt slot.",+ "slotsLeft": "{count, plural, =0 {No prompt slots left on your plan.} one {# prompt slot left on your plan.} other {# prompt slots left on your plan.}}",+ "columns": {+ "query": "Query",+ "clicks": "Clicks",+ "impressions": "Impr."+ },+ "track": "Track",+ "trackAll": "Track all ({count})",+ "count": "{shown} of {count} queries · the export has them all",+ "tracked": "{count, plural, one {Tracking # query as a prompt} other {Tracking # queries as prompts}}",+ "planLimit": "{count, plural, one {# query needs another prompt slot} other {# queries need more prompt slots}}: your plan's are used up.",+ "noSlots": "No prompt slots left on your plan",+ "trackNotAllowed": "Only admins and managers can add prompts.",+ "failed": "Couldn't load these queries.",+ "noData": "Google Search Console has no queries for this brand yet.",+ "empty": "Every Google query with clicks in this range is tracked."}},"summaryLine": {@@ -3411,7 +3438,8 @@"top": "{platform} sent the most ({count})","best": "{platform} visitors convert best ({rate} of their visits had a key event)","topAndBest": "{platform} sent the most ({count}), and its visitors convert best ({rate} of their visits had a key event).",- "cited": "{count, plural, one {# page is cited in AI answers but gets no clicks.} other {# pages are cited in AI answers but get no clicks.}}"+ "cited": "{count, plural, one {# page is cited in AI answers but gets no clicks.} other {# pages are cited in AI answers but get no clicks.}}",+ "untracked": "{shown} Google {count, plural, one {query} other {queries}} with clicks {count, plural, one {isn't} other {aren't}} tracked as prompts."},"conversions": {"title": "Where AI visitors convert",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.test.tsxindex 09f038cf0..28a4a9639 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.test.tsx@@ -32,6 +32,9 @@ vi.mock('./_page-prompts-dialog', () => ({},}));+// The untracked queries card has its own tests.+vi.mock('./_untracked-queries', () => ({ UntrackedQueriesCard: () => null }));+const { GoogleSection } = await import('./_google-section');(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =@@ -108,6 +111,7 @@ async function render(source: SourceState | null = gsc()) {domain="acme.example"canConnectonConnected={() => {}}+ canTrack/></NextIntlClientProvider>,);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.tsxindex a24de9459..21d704eb7 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_google-section.tsx@@ -30,6 +30,7 @@ import {import { formatTrafficBucketDate } from './_charts';import { PagePromptsDialog } from './_page-prompts-dialog';import { NeedsTag, SourceUnavailable } from './_source-gate';+import { UntrackedQueriesCard } from './_untracked-queries';/** CTR as the table shows it: "3.1%". */function ctr(clicks: number, impressions: number): string {@@ -42,13 +43,16 @@ function days(since: string, until: string): string {}/**- * The Google Search Console section (AT-008 part B, spec §3.6). Its card- * "Is AI taking Google clicks?" lists the pages whose impressions rose 15% or+ * The Google Search Console section (AT-008 part B and AT-009, spec §3.6).+ * Its card "Is AI taking Google clicks?" lists the pages whose impressions rose 15% or* more while their CTR fell 20% or more against the period before: an AI* Overview may be answering in place of the click. Each page's next step is* the Positions panel of a tracked prompt about it, or Add prompts when* there is none.*+ * Beside it, the Google queries no tracked prompt covers yet, to track+ * (AT-009).+ ** Google reports about two days late, so the days compared end on the latest* it has reported, and the header says which (§3.01). The section needs* Search Console; until it has data it shows its state in full (§3.8b).@@ -61,7 +65,10 @@ export function GoogleSection({domain,canConnect,onConnected,- actions,+ canTrack,+ onQueriesTracked,+ pagesActions,+ queriesActions,}: {brandId: string;dateWindow: TrafficDateWindow;@@ -72,8 +79,13 @@ export function GoogleSection({domain: string | undefined;canConnect: boolean;onConnected: () => void;- /** The card's Excel / CSV buttons (AT-015). */- actions?: ReactNode;+ /** Admins and managers add prompts from the untracked queries. */+ canTrack: boolean;+ /** Queries became prompts: the summary line counts them again. */+ onQueriesTracked?: () => void;+ /** Each card's Excel / CSV buttons (AT-015). */+ pagesActions?: ReactNode;+ queriesActions?: ReactNode;}) {const t = useTranslations('traffic.google');// Tracking prompts for a page reads the list again, for its Positions link.@@ -229,38 +241,47 @@ export function GoogleSection({</CardContent></Card>) : (- <Card className={cn(!current && 'opacity-80')} aria-busy={!current}>- <CardHeader className="pb-2">- <div className="flex flex-wrap items-center justify-between gap-2">- <div className="flex flex-wrap items-baseline gap-x-2">- <CardTitle className="text-sm font-medium">{t('taking.title')}</CardTitle>- {result?.since && result.until && result.prevSince && result.prevUntil && (- <span className="text-xs text-muted-foreground">- {t('taking.compared', {- days: days(result.since, result.until),- prevDays: days(result.prevSince, result.prevUntil),- })}- </span>- )}+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">+ <Card className={cn(!current && 'opacity-80')} aria-busy={!current}>+ <CardHeader className="pb-2">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex flex-wrap items-baseline gap-x-2">+ <CardTitle className="text-sm font-medium">{t('taking.title')}</CardTitle>+ {result?.since && result.until && result.prevSince && result.prevUntil && (+ <span className="text-xs text-muted-foreground">+ {t('taking.compared', {+ days: days(result.since, result.until),+ prevDays: days(result.prevSince, result.prevUntil),+ })}+ </span>+ )}+ </div>+ {pagesActions}</div>- {actions}- </div>- </CardHeader>- <CardContent className="p-0">- {body}- {result && result.count > result.rows.length && (- <p className="px-6 pt-3 text-xs text-muted-foreground">- {t('taking.more', {- shown: formatNumber(result.rows.length),- count: formatNumber(result.count),- })}+ </CardHeader>+ <CardContent className="p-0">+ {body}+ {result && result.count > result.rows.length && (+ <p className="px-6 pt-3 text-xs text-muted-foreground">+ {t('taking.more', {+ shown: formatNumber(result.rows.length),+ count: formatNumber(result.count),+ })}+ </p>+ )}+ <p className="px-6 py-3 text-xs text-muted-foreground">+ {t('taking.legend', { min: formatNumber(GOOGLE_PAGES_MIN_IMPRESSIONS) })}</p>- )}- <p className="px-6 py-3 text-xs text-muted-foreground">- {t('taking.legend', { min: formatNumber(GOOGLE_PAGES_MIN_IMPRESSIONS) })}- </p>- </CardContent>- </Card>+ </CardContent>+ </Card>+ <UntrackedQueriesCard+ brandId={brandId}+ dateWindow={dateWindow}+ canTrack={canTrack}+ onTracked={onQueriesTracked}+ actions={queriesActions}+ />+ </div>)}<PagePromptsDialogdiff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsxindex 75e4b8acb..71793d5ab 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.test.tsx@@ -27,6 +27,8 @@ const getTrafficPages = vi.fn(async () => ({vi.mock('@/lib/actions/traffic', () => ({getTrafficGoogleTotals: (...args: unknown[]) => getTrafficGoogleTotals(...args),getTrafficPages: (...args: unknown[]) => getTrafficPages(...(args as [])),+ // The summary line's untracked Google queries (AT-009): tested with the line.+ getUntrackedGoogleQueries: async () => ({ count: 0, capped: false, rows: [] }),}));const connect = vi.fn();vi.mock('@/hooks/use-integration-connect', () => ({diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsxindex cd569cc2a..5ec76f798 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_kpis.tsx@@ -99,6 +99,7 @@ export function TrafficKpis({onConnected,onRangeChange,rangeLabel,+ queriesRevision = 0,}: {brandId: string;dateWindow: TrafficDateWindow;@@ -116,6 +117,8 @@ export function TrafficKpis({onRangeChange: (preset: DateRangePreset) => void;/** The page's own words for the range, for the summary line (AT-007). */rangeLabel: string;+ /** Bumped when Google queries were tracked: the summary line counts them again. */+ queriesRevision?: number;}) {const t = useTranslations('traffic.kpis');const tVisits = useTranslations('traffic.visits');@@ -238,6 +241,8 @@ export function TrafficKpis({summary={summary}summaryLoading={summaryLoading}gaSessions={gaSessions}+ gscReady={sources || sourcesFailed ? gscReady : undefined}+ queriesRevision={queriesRevision}/><div className={TRAFFIC_KPI_GRID}>{/* One visit per session; the sub-line gives the pageviews and thediff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.test.tsxindex e22775f25..df35cb381 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.test.tsx@@ -12,8 +12,10 @@ import type { TrafficDateWindow, TrafficSummary } from '@/lib/actions/traffic';*/const getTrafficPages = vi.fn();+const getUntrackedGoogleQueries = vi.fn();vi.mock('@/lib/actions/traffic', () => ({getTrafficPages: (...args: unknown[]) => getTrafficPages(...args),+ getUntrackedGoogleQueries: (...args: unknown[]) => getUntrackedGoogleQueries(...args),}));const { SummaryLine } = await import('./_summary-line');@@ -54,6 +56,7 @@ let root: Root;beforeEach(() => {getTrafficPages.mockReset().mockResolvedValue(cited(2));+ getUntrackedGoogleQueries.mockReset().mockResolvedValue({ count: 0, capped: false, rows: [] });container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);@@ -69,6 +72,8 @@ async function render({// 'loading' stands for undefined, which a default would swallow.gaSessions = 8000 as number | null | 'loading',summaryLoading = false,+ gscReady = false as boolean | 'loading',+ queriesRevision = 0,} = {}) {await act(async () => {root.render(@@ -80,6 +85,8 @@ async function render({summary={sum}summaryLoading={summaryLoading}gaSessions={gaSessions === 'loading' ? undefined : gaSessions}+ gscReady={gscReady === 'loading' ? undefined : gscReady}+ queriesRevision={queriesRevision}/></NextIntlClientProvider>,);@@ -134,6 +141,30 @@ describe('SummaryLine', () => {expect(text()).not.toContain('previous period');});+ it('states the untracked Google queries only with Search Console (AT-009)', async () => {+ getUntrackedGoogleQueries.mockResolvedValue({ count: 14, capped: false, rows: [] });+ await render({ gscReady: true });+ expect(getUntrackedGoogleQueries).toHaveBeenCalledWith('b1', WEEK, { limit: 0 });+ expect(text()).toContain("14 Google queries with clicks aren't tracked as prompts.");++ // Tracking some from the page counts them again.+ getUntrackedGoogleQueries.mockResolvedValue({ count: 13, capped: false, rows: [] });+ await render({ gscReady: true, queriesRevision: 1 });+ expect(getUntrackedGoogleQueries).toHaveBeenCalledTimes(2);+ expect(text()).toContain("13 Google queries with clicks aren't tracked as prompts.");++ getUntrackedGoogleQueries.mockClear();+ await render({ gscReady: false });+ expect(getUntrackedGoogleQueries).not.toHaveBeenCalled();+ expect(text()).not.toContain('Google queries');+ });++ it('says a floor when the server checked only the most clicked queries', async () => {+ getUntrackedGoogleQueries.mockResolvedValue({ count: 1, capped: true, rows: [] });+ await render({ gscReady: true });+ expect(text()).toContain("1+ Google query with clicks isn't tracked as prompts.");+ });+it('waits for Analytics and the summary rather than changing under the reader', async () => {await render({ gaSessions: 'loading' });expect(text()).toBe('');@@ -141,5 +172,8 @@ describe('SummaryLine', () => {await render({ summaryLoading: true });expect(text()).toBe('');++ await render({ gscReady: 'loading' });+ expect(text()).toBe('');});});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.tsxindex 20620082f..e63777f07 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_summary-line.tsx@@ -8,6 +8,7 @@ import { getPlatformName } from '@/lib/traffic-platforms';import { summaryLine } from '@/lib/traffic-summary-line';import {getTrafficPages,+ getUntrackedGoogleQueries,type TrafficDateWindow,type TrafficSummary,} from '@/lib/actions/traffic';@@ -15,8 +16,9 @@ import {/*** The summary line above the KPI cards (AT-007, spec §3.1): the range's* visits, their share of all traffic and change, the top and best-converting- * platforms, and the pages answers cite that nobody clicks, in one or two- * sentences with a fixed template. Analytics' facts appear only while it is+ * platforms, the pages answers cite that nobody clicks, and the Google+ * queries no prompt tracks (AT-009), in one or two sentences with a fixed+ * template. Analytics' and Search Console's facts appear only while they are* connected (§3.8b rule 5); the line waits for every number it states, so it* never changes under the reader.*/@@ -27,6 +29,8 @@ export function SummaryLine({summary,summaryLoading,gaSessions,+ gscReady,+ queriesRevision = 0,}: {brandId: string;dateWindow: TrafficDateWindow;@@ -40,12 +44,42 @@ export function SummaryLine({* connected or couldn't be read, undefined while it loads.*/gaSessions: number | null | undefined;+ /** Search Console has data for the brand; undefined while its state loads. */+ gscReady: boolean | undefined;+ /** Bumped when Google queries were tracked from the page: counts them again. */+ queriesRevision?: number;}) {const t = useTranslations('traffic.summaryLine');const key = `${brandId}|${dateWindow.dateFrom ?? ''}|${dateWindow.dateTo ?? ''}`;// The Cited, not clicked count for the range (AT-006), as the Pages tab counts it.const [cited, setCited] = useState<{ key: string; count: number | null } | null>(null);+ // Google queries no prompt tracks (AT-009), when Search Console is connected.+ const untrackedKey = `${key}|${queriesRevision}`;+ const [untracked, setUntracked] = useState<{+ key: string;+ count: number | null;+ capped: boolean;+ } | null>(null);++ useEffect(() => {+ if (!gscReady) return;+ let cancelled = false;+ getUntrackedGoogleQueries(brandId, dateWindow, { limit: 0 })+ .then((queries) => {+ if (!cancelled) {+ setUntracked({ key: untrackedKey, count: queries.count, capped: queries.capped });+ }+ })+ .catch(() => {+ // Best effort, as the cited count.+ if (!cancelled) setUntracked({ key: untrackedKey, count: null, capped: false });+ });+ return () => {+ cancelled = true;+ };+ }, [brandId, dateWindow, untrackedKey, gscReady]);+useEffect(() => {let cancelled = false;getTrafficPages(brandId, dateWindow, { tab: 'citedNotClicked', limit: 0 })@@ -62,7 +96,15 @@ export function SummaryLine({}, [brandId, dateWindow, key]);const citedNow = cited?.key === key ? cited : null;- if (!summary || summaryLoading || gaSessions === undefined || !citedNow) {+ const untrackedNow = gscReady ? (untracked?.key === untrackedKey ? untracked : null) : undefined;+ if (+ !summary ||+ summaryLoading ||+ gaSessions === undefined ||+ gscReady === undefined ||+ !citedNow ||+ untrackedNow === null+ ) {return <Skeleton className="h-4 w-2/3" />;}@@ -73,6 +115,7 @@ export function SummaryLine({platforms: summary.platformBreakdown,gaSessions,citedNotClicked: citedNow.count,+ untrackedQueries: untrackedNow?.count ?? null,});const range = rangeLabel.charAt(0).toUpperCase() + rangeLabel.slice(1);@@ -112,6 +155,14 @@ export function SummaryLine({}}if (line.citedNotClicked > 0) sentences.push(t('cited', { count: line.citedNotClicked }));+ if (line.untrackedQueries > 0) {+ sentences.push(+ t('untracked', {+ count: line.untrackedQueries,+ shown: `${formatNumber(line.untrackedQueries)}${untrackedNow?.capped ? '+' : ''}`,+ }),+ );+ }return <p className="text-sm text-muted-foreground">{sentences.join(' ')}</p>;}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_untracked-queries.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_untracked-queries.test.tsxnew file mode 100644index 000000000..76357f61d--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_untracked-queries.test.tsx@@ -0,0 +1,181 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../messages/en.json';+import type { TrafficDateWindow, TrafficUntrackedQueries } from '@/lib/actions/traffic';++/**+ * Google queries you don't track yet (AT-009, spec §3.6): the top Search+ * Console queries by clicks that no tracked prompt covers, Track for one and+ * Track all within the plan's prompt slots (PROMPT-012).+ */++const getUntrackedGoogleQueries = vi.fn();+vi.mock('@/lib/actions/traffic', () => ({+ getUntrackedGoogleQueries: (...args: unknown[]) => getUntrackedGoogleQueries(...args),+}));+const getLocationQuota = vi.fn();+vi.mock('@/lib/actions/prompt', () => ({+ getLocationQuota: (...args: unknown[]) => getLocationQuota(...args),+}));+const trackPagePrompts = vi.fn();+vi.mock('@/lib/actions/prompt-suggestions', () => ({+ trackPagePrompts: (...args: unknown[]) => trackPagePrompts(...args),+}));+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));+vi.mock('sonner', () => ({ toast }));++const { UntrackedQueriesCard } = await import('./_untracked-queries');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const WEEK: TrafficDateWindow = { dateFrom: '2026-10-12T09:00:00.000Z' };++const queries = (over: Partial<TrafficUntrackedQueries> = {}): TrafficUntrackedQueries => ({+ lastDay: '2026-10-17',+ since: '2026-10-11',+ until: '2026-10-17',+ count: 3,+ capped: false,+ rows: [+ { query: 'cold brew ratio', clicks: 25, impressions: 610 },+ { query: 'how to descale an espresso machine', clicks: 9, impressions: 400 },+ { query: 'oat milk latte', clicks: 4, impressions: 120 },+ ],+ ...over,+});++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ getUntrackedGoogleQueries.mockReset().mockResolvedValue(queries());+ getLocationQuota.mockReset().mockResolvedValue({ maxPrompts: 50, used: 40 });+ trackPagePrompts.mockReset().mockResolvedValue({ promptIds: ['n1'] });+ toast.success.mockReset();+ toast.error.mockReset();+ onTracked.mockReset();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++const onTracked = vi.fn();++async function render(canTrack = true) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <UntrackedQueriesCard+ brandId="b1"+ dateWindow={WEEK}+ canTrack={canTrack}+ onTracked={onTracked}+ />+ </NextIntlClientProvider>,+ );+ });+}++const text = () => container.textContent ?? '';+const button = (label: string) =>+ [...container.querySelectorAll('button')].find((b) => b.textContent === label);++describe('UntrackedQueriesCard', () => {+ it('lists the queries by clicks with the days read and the slots left', async () => {+ await render();+ expect(getUntrackedGoogleQueries).toHaveBeenCalledWith('b1', WEEK);+ expect(getLocationQuota).toHaveBeenCalledWith('b1');+ const rows = [...container.querySelectorAll('tbody tr')].map((r) =>+ [...r.querySelectorAll('td')].map((td) => td.textContent),+ );+ expect(rows).toEqual([+ ['cold brew ratio', '25', '610', 'Track'],+ ['how to descale an espresso machine', '9', '400', 'Track'],+ ['oat milk latte', '4', '120', 'Track'],+ ]);+ expect(text()).toContain('Oct 11 – Oct 17');+ expect(text()).toContain('3 of 3 queries');+ expect(text()).toContain('10 prompt slots left on your plan.');+ });++ it('tracks one query as a prompt, then reads the list again', async () => {+ await render();+ await act(async () => button('Track')!.click());+ expect(trackPagePrompts).toHaveBeenCalledWith('b1', null, [+ { text: 'cold brew ratio', topic: '' },+ ]);+ expect(toast.success).toHaveBeenCalledWith('Tracking 1 query as a prompt');+ expect(getUntrackedGoogleQueries).toHaveBeenCalledTimes(2);+ expect(onTracked).toHaveBeenCalledTimes(1);+ });++ it('tracks as many as the slots allow, and says when the plan ran out', async () => {+ getLocationQuota.mockResolvedValue({ maxPrompts: 50, used: 48 });+ trackPagePrompts.mockResolvedValue({ promptIds: ['n1'], error: 'limit', code: 'plan_limit' });+ await render();+ const all = button('Track all (2)');+ expect(all).toBeTruthy();+ await act(async () => all!.click());+ expect(trackPagePrompts).toHaveBeenCalledWith('b1', null, [+ { text: 'cold brew ratio', topic: '' },+ { text: 'how to descale an espresso machine', topic: '' },+ ]);+ expect(toast.error).toHaveBeenCalledWith(+ "1 query needs another prompt slot: your plan's are used up.",+ );+ });++ it('turns tracking off without slots or for members', async () => {+ getLocationQuota.mockResolvedValue({ maxPrompts: 50, used: 50 });+ await render();+ expect(button('Track')!.disabled).toBe(true);+ expect(button('Track all (0)')!.disabled).toBe(true);+ expect(button('Track')!.parentElement!.getAttribute('title')).toBe(+ 'No prompt slots left on your plan',+ );++ getLocationQuota.mockResolvedValue({ maxPrompts: -1, used: 3 });+ act(() => root.unmount());+ root = createRoot(container);+ await render(false);+ expect(button('Track')!.disabled).toBe(true);+ expect(button('Track all (3)')!.parentElement!.getAttribute('title')).toBe(+ 'Only admins and managers can add prompts.',+ );+ expect(text()).not.toContain('slots left');+ });++ it('says why there are no rows, and a floor past the scan', async () => {+ getUntrackedGoogleQueries.mockResolvedValue(queries({ count: 7000, capped: true }));+ await render();+ expect(text()).toContain('3 of 7,000+ queries');++ const empties: [Partial<TrafficUntrackedQueries>, string][] = [+ [{ rows: [], count: 0 }, 'Every Google query with clicks in this range is tracked.'],+ [{ lastDay: null, rows: [] }, 'Google Search Console has no queries for this brand yet.'],+ ];+ for (const [over, says] of empties) {+ getUntrackedGoogleQueries.mockResolvedValue(queries(over));+ act(() => root.unmount());+ root = createRoot(container);+ await render();+ expect(text()).toContain(says);+ }++ const quiet = vi.spyOn(console, 'error').mockImplementation(() => {});+ getUntrackedGoogleQueries.mockRejectedValue(new Error('boom'));+ act(() => root.unmount());+ root = createRoot(container);+ await render();+ expect(text()).toContain("Couldn't load these queries.");+ quiet.mockRestore();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_untracked-queries.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_untracked-queries.tsxnew file mode 100644index 000000000..78e0fba77--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_untracked-queries.tsx@@ -0,0 +1,228 @@+'use client';++import { useEffect, useState, type ReactNode } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { Loader2 } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import { Skeleton } from '@/components/ui/skeleton';+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@/components/ui/table';+import { cn } from '@/lib/utils';+import { formatNumber } from '@/lib/format';+import { getLocationQuota } from '@/lib/actions/prompt';+import { trackPagePrompts } from '@/lib/actions/prompt-suggestions';+import {+ getUntrackedGoogleQueries,+ type TrafficDateWindow,+ type TrafficUntrackedQueries,+} from '@/lib/actions/traffic';+import { formatTrafficBucketDate } from './_charts';++/**+ * Prompt slots left on the plan: null when the plan has no cap, or it+ * couldn't be read (the server still checks each prompt).+ */+function slotsLeftOf(quota: { maxPrompts: number; used: number } | null): number | null {+ if (!quota || quota.maxPrompts === -1) return null;+ return Math.max(0, quota.maxPrompts - quota.used);+}++/**+ * Google queries you don't track yet (AT-009, spec §3.6), beside "Is AI+ * taking Google clicks?" in the Google Search Console section: the top+ * Search Console queries by clicks that no tracked prompt covers. Track adds+ * a query as a prompt; Track all adds the listed ones, as many as the plan's+ * prompt slots allow (PROMPT-012). A tracked query leaves the list.+ */+export function UntrackedQueriesCard({+ brandId,+ dateWindow,+ canTrack,+ onTracked,+ actions,+}: {+ brandId: string;+ dateWindow: TrafficDateWindow;+ /** Admins and managers add prompts; others see the list. */+ canTrack: boolean;+ /** Queries became prompts: other counts on the page read again. */+ onTracked?: () => void;+ /** The card's Excel / CSV buttons (AT-015). */+ actions?: ReactNode;+}) {+ const t = useTranslations('traffic.google.untracked');+ // Tracking reads the list again: the tracked queries leave it.+ const [reloads, setReloads] = useState(0);+ const key = `${brandId}|${dateWindow.dateFrom ?? ''}|${dateWindow.dateTo ?? ''}|${reloads}`;+ const [loaded, setLoaded] = useState<{+ key: string;+ result: TrafficUntrackedQueries | null;+ slotsLeft: number | null;+ } | null>(null);+ const [tracking, setTracking] = useState<Set<string>>(new Set());++ useEffect(() => {+ let cancelled = false;+ Promise.all([+ getUntrackedGoogleQueries(brandId, dateWindow).catch((err) => {+ // Best effort: the rest of the page doesn't depend on this card.+ console.error('Failed to load the untracked Google queries:', err);+ return null;+ }),+ getLocationQuota(brandId).catch(() => null),+ ]).then(([result, quota]) => {+ if (!cancelled) setLoaded({ key, result, slotsLeft: slotsLeftOf(quota) });+ });+ return () => {+ cancelled = true;+ };+ }, [brandId, dateWindow, key, reloads]);++ const current = loaded?.key === key ? loaded : null;+ const result = current?.result ?? null;+ const slotsLeft = current?.slotsLeft ?? null;+ const busy = tracking.size > 0;++ const track = async (queries: string[]) => {+ setTracking(new Set(queries));+ const outcome = await trackPagePrompts(+ brandId,+ null,+ queries.map((text) => ({ text, topic: '' })),+ ).catch((err: Error) => ({ promptIds: [] as string[], error: err.message, code: undefined }));+ setTracking(new Set());+ const tracked = outcome.promptIds.length;+ if (tracked > 0) toast.success(t('tracked', { count: tracked }));+ if (outcome.error) {+ toast.error(+ outcome.code === 'plan_limit'+ ? t('planLimit', { count: queries.length - tracked })+ : outcome.error,+ );+ }+ if (tracked > 0) {+ setReloads((n) => n + 1);+ onTracked?.();+ }+ };++ const trackTitle = !canTrack ? t('trackNotAllowed') : slotsLeft === 0 ? t('noSlots') : undefined;+ const trackable = canTrack && slotsLeft !== 0 && !busy;+ const allCount = result ? Math.min(result.rows.length, slotsLeft ?? result.rows.length) : 0;++ const message = (text: string) => (+ <p className="px-6 py-4 text-sm text-muted-foreground">{text}</p>+ );+ const body = !current ? (+ <div className="px-6 py-4">+ <Skeleton className="h-4 w-56" />+ </div>+ ) : !result ? (+ message(t('failed'))+ ) : !result.lastDay ? (+ message(t('noData'))+ ) : result.rows.length === 0 ? (+ message(t('empty'))+ ) : (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="pl-6">{t('columns.query')}</TableHead>+ <TableHead className="text-right">{t('columns.clicks')}</TableHead>+ <TableHead className="text-right">{t('columns.impressions')}</TableHead>+ <TableHead className="pr-6" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {result.rows.map((row) => (+ <TableRow key={row.query} className="hover:bg-muted/50">+ <TableCell className="pl-6 max-w-[200px] xl:max-w-[280px]">+ <span className="line-clamp-1 text-sm" title={row.query}>+ {row.query}+ </span>+ </TableCell>+ <TableCell className="text-right text-sm font-semibold tabular-nums">+ {formatNumber(row.clicks)}+ </TableCell>+ <TableCell className="text-right text-sm tabular-nums">+ {formatNumber(row.impressions)}+ </TableCell>+ <TableCell className="pr-6 text-right">+ {/* A span carries the tooltip: a disabled button gets no hover. */}+ <span title={trackTitle}>+ <Button+ size="sm"+ variant="outline"+ className="h-7 gap-1.5 text-xs"+ disabled={!trackable}+ onClick={() => void track([row.query])}+ >+ {tracking.has(row.query) && <Loader2 className="h-3 w-3 animate-spin" />}+ {t('track')}+ </Button>+ </span>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ );++ return (+ <Card className={cn(!current && 'opacity-80')} aria-busy={!current}>+ <CardHeader className="pb-2">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex flex-wrap items-baseline gap-x-2">+ <CardTitle className="text-sm font-medium">{t('title')}</CardTitle>+ {result?.until && (+ <span className="text-xs text-muted-foreground">+ {result.since+ ? `${formatTrafficBucketDate(result.since)} – ${formatTrafficBucketDate(result.until)}`+ : t('untilDay', { day: formatTrafficBucketDate(result.until) })}+ </span>+ )}+ </div>+ {actions}+ </div>+ </CardHeader>+ <CardContent className="p-0">+ {body}+ {result && result.rows.length > 0 && (+ <div className="flex flex-wrap items-center justify-between gap-2 px-6 pt-3">+ <span className="text-xs text-muted-foreground">+ {t('count', {+ shown: formatNumber(result.rows.length),+ count: `${formatNumber(result.count)}${result.capped ? '+' : ''}`,+ })}+ </span>+ <span title={trackTitle}>+ <Button+ size="sm"+ variant="outline"+ className="h-7 gap-1.5 text-xs"+ disabled={!trackable || allCount === 0}+ onClick={() => void track(result.rows.slice(0, allCount).map((r) => r.query))}+ >+ {busy && tracking.size > 1 && <Loader2 className="h-3 w-3 animate-spin" />}+ {t('trackAll', { count: allCount })}+ </Button>+ </span>+ </div>+ )}+ <p className="px-6 py-3 text-xs text-muted-foreground">+ {slotsLeft !== null+ ? `${t('legend')} ${t('slotsLeft', { count: slotsLeft })}`+ : t('legend')}+ </p>+ </CardContent>+ </Card>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsxindex 85442c93f..c212cb4fd 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx@@ -430,6 +430,8 @@ function TrafficPageContent({ brand }: { brand: Brand }) {const [summary, setSummary] = useState<TrafficSummary | null>(null);const [trend, setTrend] = useState<TrafficTrendPoint[]>([]);const [trendView, setTrendView] = useState<'platforms' | 'google'>('platforms');+ // Bumped when Google queries are tracked, so the summary line counts again (AT-009).+ const [queriesRevision, setQueriesRevision] = useState(0);const [logs, setLogs] = useState<TrafficLog[]>([]);const [logsTotal, setLogsTotal] = useState(0);const [logsPageviews, setLogsPageviews] = useState(0);@@ -626,9 +628,10 @@ function TrafficPageContent({ brand }: { brand: Brand }) {/>);- // Google Search Console (AT-008, spec §3.6): pages whose impressions rose- // while their CTR fell. Search Console's own data, so it shows even when- // the snippet saw no visit in the range.+ // Google Search Console (AT-008, AT-009, spec §3.6): pages whose+ // impressions rose while their CTR fell, and the queries no tracked prompt+ // covers. Search Console's own data, so it shows even when the snippet saw+ // no visit in the range.const googleSection = (<GoogleSectionbrandId={brand.id}@@ -638,7 +641,10 @@ function TrafficPageContent({ brand }: { brand: Brand }) {domain={primaryDomain}canConnect={canManage}onConnected={() => void loadSources()}- actions={<TableExport exporter={exporter} section="googlePages" />}+ canTrack={canManage}+ onQueriesTracked={() => setQueriesRevision((n) => n + 1)}+ pagesActions={<TableExport exporter={exporter} section="googlePages" />}+ queriesActions={<TableExport exporter={exporter} section="googleQueries" />}/>);@@ -720,6 +726,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {canConnect={canManage}onConnected={() => void loadSources()}onRangeChange={handleDatePresetChange}+ queriesRevision={queriesRevision}/>{/* Charts row */}diff --git a/web/src/app/api/traffic/export/route.test.ts b/web/src/app/api/traffic/export/route.test.tsindex 5878a843b..610bb0745 100644--- a/web/src/app/api/traffic/export/route.test.ts+++ b/web/src/app/api/traffic/export/route.test.ts@@ -34,6 +34,7 @@ const loaders = vi.hoisted(() => ({getTrafficPages: vi.fn(),getTrafficConversions: vi.fn(),getTrafficGooglePages: vi.fn(),+ getUntrackedGoogleQueries: vi.fn(),}));vi.mock('@/lib/actions/traffic', () => loaders);@@ -111,6 +112,14 @@ beforeEach(() => {count: 0,rows: [],});+ loaders.getUntrackedGoogleQueries.mockResolvedValue({+ lastDay: '2026-10-17',+ since: '2026-10-11',+ until: '2026-10-17',+ count: 1,+ capped: false,+ rows: [{ query: 'cold brew ratio', clicks: 25, impressions: 610 }],+ });});const WINDOW = { dateFrom: '2026-10-11T09:00:00.000Z' };@@ -148,6 +157,7 @@ describe('GET /api/traffic/export', () => {'Answers that bring buyers','Pages by status','Is AI taking Google clicks',+ 'Untracked Google queries','Visits',]);@@ -185,6 +195,7 @@ describe('GET /api/traffic/export', () => {'answers-that-bring-buyers.csv','pages-by-status.csv','is-ai-taking-google-clicks.csv',+ 'untracked-google-queries.csv','visits.csv',]);for (const file of Object.values(files)) expect(startsWithBom(file)).toBe(true);diff --git a/web/src/app/api/traffic/export/route.ts b/web/src/app/api/traffic/export/route.tsindex 5f62a01e9..a11ee9413 100644--- a/web/src/app/api/traffic/export/route.ts+++ b/web/src/app/api/traffic/export/route.ts@@ -12,8 +12,10 @@ import {getTrafficSummary,getTrafficTrend,getTrafficVisitsForExport,+ getUntrackedGoogleQueries,} from '@/lib/actions/traffic';import { utcDay } from '@/lib/dates';+import { UNTRACKED_QUERY_SCAN } from '@/lib/traffic-google-pages';import {TRAFFIC_EXPORT_MAX_ROWS,TRAFFIC_EXPORT_SECTIONS,@@ -92,7 +94,7 @@ export async function GET(req: Request) {const wholePage = !q.section;try {- const [summary, trend, visits, sources, pageStatus, conversions, googlePages] =+ const [summary, trend, visits, sources, pageStatus, conversions, googlePages, googleQueries] =await Promise.all([needs('kpis', 'platforms', 'pages')? getTrafficSummary(q.brandId, window, { topPages: Number.MAX_SAFE_INTEGER })@@ -120,6 +122,10 @@ export async function GET(req: Request) {needs('googlePages')? getTrafficGooglePages(q.brandId, window, { limit: TRAFFIC_EXPORT_MAX_ROWS }): undefined,+ // Every Google query no tracked prompt covers, as far as the server checks (AT-009).+ needs('googleQueries')+ ? getUntrackedGoogleQueries(q.brandId, window, { limit: UNTRACKED_QUERY_SCAN })+ : undefined,]);// Larger than an export built on request should be (spec §3.9).if (visits === null) return Response.json({ error: 'too_large' }, { status: 413 });@@ -141,6 +147,7 @@ export async function GET(req: Request) {pageStatus,conversions,googlePages,+ googleQueries,sources,};diff --git a/web/src/lib/actions/traffic-untracked-queries.test.ts b/web/src/lib/actions/traffic-untracked-queries.test.tsnew file mode 100644index 000000000..500f32775--- /dev/null+++ b/web/src/lib/actions/traffic-untracked-queries.test.ts@@ -0,0 +1,78 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * AT-009 (spec §3.6): Google queries you don't track yet come from the+ * server, which decides "covers" by Prompt Suggestions' rule, over the+ * range's whole days.+ */++let session: { access_token: string } | null = { access_token: 'tok' };+vi.mock('@/lib/supabase/server', () => ({+ createClient: async () => ({ auth: { getSession: async () => ({ data: { session } }) } }),+}));+vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://api.test' }));++import { getUntrackedGoogleQueries } from './traffic';++const fetchMock = vi.fn();++beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-10-19T09:30:00.000Z'));+ session = { access_token: 'tok' };+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('getUntrackedGoogleQueries', () => {+ it("asks the server for the range's whole days and reads the answer", async () => {+ fetchMock.mockResolvedValue(+ new Response(+ JSON.stringify({+ lastDay: '2026-10-17',+ since: '2026-10-11',+ until: '2026-10-17',+ count: 2,+ capped: false,+ rows: [{ query: 'cold brew ratio', clicks: '25', impressions: 610 }],+ }),+ ),+ );+ const result = await getUntrackedGoogleQueries(+ 'b1',+ { dateFrom: '2026-10-12T09:30:00.000Z' },+ { limit: 1 },+ );+ expect(fetchMock).toHaveBeenCalledWith(+ 'http://api.test/api/prompts/untracked-queries/b1?until=2026-10-19&limit=1&since=2026-10-13',+ { headers: { Authorization: 'Bearer tok' } },+ );+ expect(result).toEqual({+ lastDay: '2026-10-17',+ since: '2026-10-11',+ until: '2026-10-17',+ count: 2,+ capped: false,+ rows: [{ query: 'cold brew ratio', clicks: 25, impressions: 610 }],+ });+ });++ it('sends no first day for all time, and throws on a failed read or no session', async () => {+ fetchMock.mockResolvedValue(new Response(JSON.stringify({ count: 0, rows: [] })));+ await getUntrackedGoogleQueries('b1', undefined);+ expect(fetchMock.mock.calls[0][0]).toBe(+ 'http://api.test/api/prompts/untracked-queries/b1?until=2026-10-19&limit=10',+ );++ fetchMock.mockResolvedValue(new Response(JSON.stringify({ error: 'boom' }), { status: 500 }));+ await expect(getUntrackedGoogleQueries('b1', undefined)).rejects.toThrow('boom');++ session = null;+ await expect(getUntrackedGoogleQueries('b1', undefined)).rejects.toThrow('Not authenticated');+ });+});diff --git a/web/src/lib/actions/traffic.ts b/web/src/lib/actions/traffic.tsindex 9e92a5248..51d5cd108 100644--- a/web/src/lib/actions/traffic.ts+++ b/web/src/lib/actions/traffic.ts@@ -1043,3 +1043,71 @@ export async function getTrafficGooglePages(})),};}++/** A Google query no tracked prompt covers (AT-009). */+export interface UntrackedQuery {+ query: string;+ clicks: number;+ impressions: number;+}++export interface TrafficUntrackedQueries {+ /** The latest day Google has reported for the brand; null with no Search Console data. */+ lastDay: string | null;+ /** The days read, ending on Google's latest; no first day for all time. */+ since: string | null;+ until: string | null;+ /** Every untracked query with clicks; `rows` holds the first `limit`. */+ count: number;+ /** More queries had clicks than the server checks: `count` is a floor. */+ capped: boolean;+ rows: UntrackedQuery[];+}++/**+ * Google queries you don't track yet (AT-009, spec §3.6): the brand's+ * Search Console queries with clicks that no active prompt covers, most+ * clicks first, over the range's whole days ending on Google's latest+ * reported day (§3.01). The server decides "covers", by the rule Prompt+ * Suggestions uses for Google queries.+ */+export async function getUntrackedGoogleQueries(+ brandId: string,+ window: TrafficDateWindow | undefined,+ { limit = 10 }: { limit?: number } = {},+): Promise<TrafficUntrackedQueries> {+ const supabase = await createClient();+ const {+ data: { session },+ } = await supabase.auth.getSession();+ if (!session) throw new Error('Not authenticated');++ const { from, to } = resolveTrafficWindow(window);+ const { since, until } = googlePagesWindow(from, to);+ const query = new URLSearchParams({ until, limit: String(limit) });+ if (since) query.set('since', since);+ const res = await fetch(+ `${API_BASE_URL}/api/prompts/untracked-queries/${encodeURIComponent(brandId)}?${query}`,+ { headers: { Authorization: `Bearer ${session.access_token}` } },+ );+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.error || `Server error: ${res.status}`);+ }+ const raw = (await res.json()) as Record<string, unknown>;+ const n = (v: unknown) => Number(v) || 0;+ const day = (v: unknown) => (typeof v === 'string' ? v : null);+ const list = Array.isArray(raw.rows) ? (raw.rows as Record<string, unknown>[]) : [];+ return {+ lastDay: day(raw.lastDay),+ since: day(raw.since),+ until: day(raw.until),+ count: n(raw.count),+ capped: raw.capped === true,+ rows: list.map((r) => ({+ query: String(r.query),+ clicks: n(r.clicks),+ impressions: n(r.impressions),+ })),+ };+}diff --git a/web/src/lib/traffic-export.test.ts b/web/src/lib/traffic-export.test.tsindex 0c61076ed..3e72e1404 100644--- a/web/src/lib/traffic-export.test.ts+++ b/web/src/lib/traffic-export.test.ts@@ -432,6 +432,49 @@ describe('trafficTable: Is AI taking Google clicks (AT-008)', () => {});});+describe('trafficTable: Untracked Google queries (AT-009)', () => {+ const googleQueries = (+ over: Partial<NonNullable<TrafficExportData['googleQueries']>> = {},+ ): NonNullable<TrafficExportData['googleQueries']> => ({+ lastDay: '2026-10-17',+ since: '2026-10-11',+ until: '2026-10-17',+ count: 2,+ capped: false,+ rows: [+ { query: 'cold brew ratio', clicks: 25, impressions: 610 },+ { query: 'oat milk latte', clicks: 4, impressions: 120 },+ ],+ ...over,+ });+ const table = (q: TrafficExportData['googleQueries']) =>+ trafficTable('googleQueries', data({ googleQueries: q }), label);++ it('holds every query with its clicks, impressions and the days read', () => {+ expect(table(googleQueries())).toEqual({+ headers: ['Query', 'Clicks', 'Impressions', 'Days'],+ rows: [+ ['cold brew ratio', 25, 610, '2026-10-11 – 2026-10-17'],+ ['oat milk latte', 4, 120, '2026-10-11 – 2026-10-17'],+ ],+ });+ expect(table(googleQueries({ since: null })).rows[0][3]).toBe('Start – 2026-10-17');+ expect(table(googleQueries({ capped: true })).rows.at(-1)).toEqual([+ 'Only the 5,000 most clicked queries were checked',+ null,+ null,+ null,+ ]);+ });++ it('says why there are no rows, never an empty sheet', () => {+ expect(table(googleQueries({ rows: [], count: 0 })).rows).toEqual([+ ['Every Google query with clicks in this range is tracked'],+ ]);+ expect(table(null).rows).toEqual([['No query data from Google Search Console yet']]);+ });+});+describe('filtersTable', () => {it('records the range, the filters, the sources and when', () => {const table = filtersTable(@@ -466,6 +509,7 @@ describe('trafficWorkbook', () => {'Answers that bring buyers','Pages by status','Is AI taking Google clicks',+ 'Untracked Google queries','Visits',]);// A bold header row, then the rows with their numbers as numbers.diff --git a/web/src/lib/traffic-export.ts b/web/src/lib/traffic-export.tsindex a6f83d855..e4614734f 100644--- a/web/src/lib/traffic-export.ts+++ b/web/src/lib/traffic-export.ts@@ -13,6 +13,7 @@ import type {TrafficConversions,TrafficGooglePages,TrafficLog,+ TrafficUntrackedQueries,TrafficPages,TrafficSources,TrafficSummary,@@ -40,6 +41,7 @@ export const TRAFFIC_EXPORT_SECTIONS = ['buyerAnswers','pageStatus','googlePages',+ 'googleQueries','visits',] as const;@@ -53,6 +55,7 @@ export const TRAFFIC_TABLE_SECTIONS = ['buyerAnswers','pageStatus','googlePages',+ 'googleQueries','visits',] as const;@@ -81,6 +84,8 @@ export interface TrafficExportData {conversions?: TrafficConversions | null;/** Is AI taking Google clicks?, every page (AT-008). */googlePages?: TrafficGooglePages | null;+ /** Google queries you don't track yet, every one the server checked (AT-009). */+ googleQueries?: TrafficUntrackedQueries | null;sources?: TrafficSources | null;}@@ -375,6 +380,26 @@ function googlePages(data: TrafficExportData, label: ExportLabel): ExportTable {};}+/** Google queries you don't track yet (AT-009): every one, with the days read. */+function googleQueries(data: TrafficExportData, label: ExportLabel): ExportTable {+ const q = data.googleQueries;+ const note = (key: string) => ({ headers: [label('columns.note')], rows: [[label(key)]] });+ if (!q || !q.lastDay) return note('notes.noGoogleQueries');+ if (q.rows.length === 0) return note('notes.noUntrackedQueries');+ const days = q.since ? `${q.since} – ${q.until}` : `${label('filters.start')} – ${q.until}`;+ const table: ExportTable = {+ headers: [+ label('columns.query'),+ label('columns.clicks'),+ label('columns.impressions'),+ label('columns.days'),+ ],+ rows: q.rows.map((row) => [row.query, row.clicks, row.impressions, days]),+ };+ if (!q.capped) return table;+ return { ...table, rows: [...table.rows, [label('notes.queriesCapped'), null, null, null]] };+}+function visits(data: TrafficExportData, label: ExportLabel): ExportTable {return {headers: [@@ -421,6 +446,8 @@ export function trafficTable(return pageStatus(data, label);case 'googlePages':return googlePages(data, label);+ case 'googleQueries':+ return googleQueries(data, label);case 'visits':return visits(data, label);}diff --git a/web/src/lib/traffic-google-pages.ts b/web/src/lib/traffic-google-pages.tsindex 2a9f38d2a..3db1726d3 100644--- a/web/src/lib/traffic-google-pages.ts+++ b/web/src/lib/traffic-google-pages.ts@@ -6,6 +6,12 @@/** Impressions a page needs in the period before to be compared. */export const GOOGLE_PAGES_MIN_IMPRESSIONS = 100;+/**+ * The most clicked Google queries the server checks for untracked ones+ * (AT-009): server/src/lib/untracked-queries.js's UNTRACKED_QUERY_SCAN.+ */+export const UNTRACKED_QUERY_SCAN = 5000;+const DAY_MS = 86_400_000;/**diff --git a/web/src/lib/traffic-sources.test.ts b/web/src/lib/traffic-sources.test.tsindex a07418dec..16e80aa01 100644--- a/web/src/lib/traffic-sources.test.ts+++ b/web/src/lib/traffic-sources.test.ts@@ -71,6 +71,7 @@ describe('sectionsNeeding', () => {'googleClicks','googleTrend','googlePages',+ 'googleQueries',]);});});diff --git a/web/src/lib/traffic-sources.ts b/web/src/lib/traffic-sources.tsindex 53558c33e..c4be29a21 100644--- a/web/src/lib/traffic-sources.ts+++ b/web/src/lib/traffic-sources.ts@@ -88,6 +88,7 @@ export const TRAFFIC_SECTION_SOURCES = {conversions: 'google-analytics',pageValue: 'google-analytics',googlePages: 'google-search-console',+ googleQueries: 'google-search-console',} as const satisfies Record<string, IntegrationProvider>;export type TrafficSection = keyof typeof TRAFFIC_SECTION_SOURCES;diff --git a/web/src/lib/traffic-summary-line.test.ts b/web/src/lib/traffic-summary-line.test.tsindex 3eea637cb..7ece158bf 100644--- a/web/src/lib/traffic-summary-line.test.ts+++ b/web/src/lib/traffic-summary-line.test.ts@@ -33,7 +33,9 @@ describe('summaryLine', () => {top: { platform: 'chatgpt.com', visits: 38 },best: { platform: 'perplexity.ai', rate: 16.1 },citedNotClicked: 2,+ untrackedQueries: 0,});+ expect(summaryLine(input({ untrackedQueries: 7 })).untrackedQueries).toBe(7);});it('leaves out what needs Google Analytics without it (§3.8b rule 5)', () => {diff --git a/web/src/lib/traffic-summary-line.ts b/web/src/lib/traffic-summary-line.tsindex b0e084713..c2656e5ce 100644--- a/web/src/lib/traffic-summary-line.ts+++ b/web/src/lib/traffic-summary-line.ts@@ -9,7 +9,9 @@* connected Google Analytics (§3.8b rule 5: without GA4 it never says* "Perplexity visitors convert best");* - the best-converting platform, only when at least two platforms have 30- * visits and 5 key events, the bar for comparing conversions (§5.4).+ * visits and 5 key events, the bar for comparing conversions (§5.4);+ * - the untracked Google queries, only from a connected Search Console+ * (AT-009).** Pure: the component renders the words.*/@@ -31,6 +33,8 @@ export interface SummaryLineInput {gaSessions: number | null;/** Pages answers cite 20+ times with no AI visit (AT-006); null while unknown. */citedNotClicked: number | null;+ /** Google queries with clicks no prompt tracks (AT-009); null without Search Console. */+ untrackedQueries?: number | null;}export interface SummaryLine {@@ -44,6 +48,8 @@ export interface SummaryLine {best: { platform: string; rate: number } | null;/** 0 says nothing. */citedNotClicked: number;+ /** 0 says nothing. */+ untrackedQueries: number;}/** The platform whose visits convert best, when two or more can be compared. */@@ -75,5 +81,6 @@ export function summaryLine(input: SummaryLineInput): SummaryLine {top: top && top.visits > 0 ? { platform: top.platform, visits: top.visits } : null,best: ga ? bestConvertingPlatform(input.platforms) : null,citedNotClicked: input.citedNotClicked ?? 0,+ untrackedQueries: input.untrackedQueries ?? 0,};}