Skip to content

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.

feat(tracking): offer and run only the countries each engine answers from, read daily from the provider (PROMPT-015, part 5) (#1659)

Cihan858f11d0ed50
diff --git a/docs/guides/prompts.mdx b/docs/guides/prompts.mdx
index 8a33ef034..8062027d6 100644
--- a/docs/guides/prompts.mdx
+++ b/docs/guides/prompts.mdx
@@ -63,7 +63,7 @@ Click a cell to open the prompt's Positions panel for that location. A location
**+ Add location** in the Locations view, or **+ Track** in a cell, opens **Track in more locations**:
-1. Pick one or more countries, US states or cities (about 50 countries and 50 major cities).
+1. Pick one or more countries, US states or cities (50 major cities). The countries are the ones the AI engines answer from, read from the tracking provider every day: a country one engine doesn't answer from says so ("not on Copilot"), and that engine is skipped there while the others run.
2. Choose which prompts to ask there: the one you clicked, the selected ones, a topic, or every prompt shown.
3. Check **Plan usage**. Every prompt in every location counts once on your plan's prompt locations; for example, 50 prompts in two more places use 100 more. Paused prompts don't count.
diff --git a/server/src/lib/catalog/__fixtures__/fake-db.js b/server/src/lib/catalog/__fixtures__/fake-db.js
index 6016943cc..d78de08b6 100644
--- a/server/src/lib/catalog/__fixtures__/fake-db.js
+++ b/server/src/lib/catalog/__fixtures__/fake-db.js
@@ -49,6 +49,7 @@ export function fakeDb({ maxRows = Infinity } = {}) {
if (table === 'catalog_categories') return `${row.brand_id}|${row.name}`;
if (table === 'catalog_source_credentials') return row.source_id;
if (table === 'catalog_category_pages') return `${row.brand_id}|${row.category}`;
+ if (table === 'cloro_countries') return `${row.model}|${row.country}`;
if (table === 'content_shopping_checks') return row.draft_id;
return `${row.brand_id}|${row.source}|${row.external_id}`;
};
diff --git a/server/src/lib/cloro-countries.js b/server/src/lib/cloro-countries.js
new file mode 100644
index 000000000..2f99daef7
--- /dev/null
+++ b/server/src/lib/cloro-countries.js
@@ -0,0 +1,198 @@
+import supabaseAdmin from '../config/supabase.js';
+import { CLORO_API } from './cloro-scraper.js';
+import { logger } from './logger.js';
+import { readAllRpcRows } from './rpc-pages.js';
+import { locationsForScraper, parseLocation } from './locations.js';
+
+/**
+ * The countries each tracking engine answers from (PROMPT-015e, 00364).
+ *
+ * The provider supports a different set of countries per engine, and asking
+ * an engine in a country it doesn't support fails. Its GET /v1/countries is
+ * the only source of truth, so the daily run reads every engine's list
+ * before tracking (refreshCloroCountries) and keeps it in `cloro_countries`:
+ * the location picker offers only countries some engine answers from, and
+ * the tracking run skips an engine in a country it doesn't support
+ * (supportsCountry). A list that can't be read keeps the last one; with no
+ * list at all (no provider key, or before the first read) nothing is
+ * restricted.
+ */
+
+/** The provider's `model` for each scraper. The API models (OpenAI, Claude) aren't the provider's. */
+export const CLORO_COUNTRY_MODELS = {
+ 'chatgpt-web': 'chatgpt',
+ 'chatgpt-shopping': 'chatgpt',
+ 'perplexity-web': 'perplexity',
+ 'copilot-web': 'copilot',
+ 'gemini-web': 'gemini',
+ 'google-aimode': 'aimode',
+ // AI Overview is asked through Google Search; its own list says where one shows.
+ 'google-aio': 'aioverview',
+};
+
+const MODELS = [...new Set(Object.values(CLORO_COUNTRY_MODELS))];
+
+/** One engine's list read takes this long at most: a slow provider can't hold the daily run. */
+const READ_MS = 15_000;
+
+/**
+ * The codes in an answer, in the shapes a list of countries may come in:
+ * `["US", …]`, `{ countries: [...] }`, or entries `{ code }` / `{ country }`.
+ * Null for any other shape. Codes are read as two capital letters; anything
+ * else is dropped.
+ */
+export function countryCodesIn(body) {
+ const list = Array.isArray(body) ? body : Array.isArray(body?.countries) ? body.countries : null;
+ if (!list) return null;
+ const code = (entry) =>
+ typeof entry === 'string' ? entry : (entry?.code ?? entry?.country ?? null);
+ return [
+ ...new Set(
+ list
+ .map(code)
+ .filter((c) => typeof c === 'string')
+ .map((c) => c.trim().toUpperCase())
+ .filter((c) => /^[A-Z]{2}$/.test(c)),
+ ),
+ ];
+}
+
+/**
+ * One engine's countries, as ISO codes; null when there's no key, the read
+ * failed, or the answer holds no codes (an empty list included, so a bad
+ * answer never empties the table). An answer in no known shape is logged.
+ */
+export async function fetchCloroCountries(
+ model,
+ { fetchImpl = fetch, apiKey = process.env.CLORO_API_KEY } = {},
+) {
+ if (!apiKey) return null;
+ const res = await fetchImpl(`${CLORO_API}/v1/countries?model=${encodeURIComponent(model)}`, {
+ headers: { Authorization: `Bearer ${apiKey}` },
+ signal: AbortSignal.timeout(READ_MS),
+ });
+ if (!res.ok) throw new Error(`countries ${model}: HTTP ${res.status}`);
+ const body = await res.json();
+ const codes = countryCodesIn(body);
+ if (!codes?.length) {
+ logger.warn(
+ {
+ model,
+ shape: Array.isArray(body) ? `array of ${body.length}` : typeof body,
+ keys: body && typeof body === 'object' && !Array.isArray(body) ? Object.keys(body) : [],
+ },
+ '[cloro-countries] answer holds no country codes; last list kept',
+ );
+ return null;
+ }
+ return codes;
+}
+
+/**
+ * Reads every engine's list and writes it: the codes it lists, and the ones
+ * it no longer lists removed. An engine whose read fails keeps its last
+ * list, and so does one whose new list is under half its last: an answer
+ * cut short would otherwise stop tracking in most countries at once.
+ * Returns, per engine, how many countries it answers from, or why not.
+ */
+export async function refreshCloroCountries({
+ db = supabaseAdmin,
+ fetchImpl,
+ apiKey = process.env.CLORO_API_KEY,
+ now = new Date(),
+} = {}) {
+ if (!apiKey) return { skipped: 'no provider key' };
+ const at = now.toISOString();
+ const outcome = {};
+ // The lists as kept, to tell a list that shrank from one that changed.
+ const last = await loadSupportedCountries({ db }).catch((err) => {
+ logger.warn({ err: { message: err?.message } }, '[cloro-countries] last lists unreadable');
+ return null;
+ });
+ await Promise.all(
+ MODELS.map(async (model) => {
+ let codes;
+ try {
+ codes = await fetchCloroCountries(model, { fetchImpl, apiKey });
+ } catch (err) {
+ logger.warn({ err: { message: err?.message }, model }, '[cloro-countries] read failed');
+ outcome[model] = 'kept';
+ return;
+ }
+ if (!codes) {
+ outcome[model] = 'kept';
+ return;
+ }
+ const before = last?.get(model)?.size ?? 0;
+ if (codes.length < before / 2) {
+ logger.warn(
+ { model, before, now: codes.length },
+ '[cloro-countries] list shrank by more than half; last list kept',
+ );
+ outcome[model] = 'kept';
+ return;
+ }
+ const { error } = await db.from('cloro_countries').upsert(
+ codes.map((country) => ({ model, country, refreshed_at: at })),
+ { onConflict: 'model,country' },
+ );
+ if (error) {
+ logger.error({ err: error, model }, '[cloro-countries] write failed');
+ outcome[model] = 'kept';
+ return;
+ }
+ // What it no longer lists wasn't stamped by this read.
+ const { error: dropError } = await db
+ .from('cloro_countries')
+ .delete()
+ .eq('model', model)
+ .lt('refreshed_at', at);
+ if (dropError) logger.error({ err: dropError, model }, '[cloro-countries] prune failed');
+ outcome[model] = codes.length;
+ }),
+ );
+ logger.info({ outcome }, '[cloro-countries] refreshed');
+ return outcome;
+}
+
+/** The lists as kept: provider model → its countries. Empty when none were read. */
+export async function loadSupportedCountries({ db = supabaseAdmin } = {}) {
+ const { data, error } = await readAllRpcRows('cloro_countries', (from, to) =>
+ db
+ .from('cloro_countries')
+ .select('model, country')
+ .order('model')
+ .order('country')
+ .range(from, to),
+ );
+ if (error) throw new Error(`cloro_countries read: ${error.message}`);
+ const supported = new Map();
+ for (const { model, country } of data ?? []) {
+ if (!supported.has(model)) supported.set(model, new Set());
+ supported.get(model).add(country);
+ }
+ return supported;
+}
+
+/**
+ * Whether a scraper can be asked from a country. True when there's nothing
+ * to check against: no country (an untargeted run), a scraper the provider
+ * doesn't list, or no list read for it.
+ */
+export function supportsCountry(supported, scraperId, country) {
+ const model = CLORO_COUNTRY_MODELS[scraperId];
+ if (!country || !model) return true;
+ const countries = supported.get(model);
+ return !countries?.size || countries.has(country);
+}
+
+/**
+ * The locations a scraper is asked from: locationsForScraper's (cities only
+ * for Google's engines, states collapsed where they can't be targeted),
+ * less the countries the scraper doesn't answer from.
+ */
+export function supportedLocations(locations, scraperId, supported) {
+ return locationsForScraper(locations, scraperId).filter((code) =>
+ supportsCountry(supported, scraperId, parseLocation(code).country),
+ );
+}
diff --git a/server/src/lib/cloro-countries.test.js b/server/src/lib/cloro-countries.test.js
new file mode 100644
index 000000000..4e2569041
--- /dev/null
+++ b/server/src/lib/cloro-countries.test.js
@@ -0,0 +1,231 @@
+import { readFileSync } from 'node:fs';
+import { describe, expect, it, vi } from 'vitest';
+
+// The module reaches the supabase admin client at import time, whose config
+// hard-exits when SUPABASE_* env is absent (as in CI).
+vi.mock('../config/supabase.js', () => ({ default: {} }));
+
+import { fakeDb } from './catalog/__fixtures__/fake-db.js';
+import { logger } from './logger.js';
+import { CITY_SCRAPERS } from './locations.js';
+import {
+ CLORO_COUNTRY_MODELS,
+ countryCodesIn,
+ fetchCloroCountries,
+ loadSupportedCountries,
+ refreshCloroCountries,
+ supportedLocations,
+ supportsCountry,
+} from './cloro-countries.js';
+
+/** The countries each tracking engine answers from (PROMPT-015e). */
+
+const answer = (lists) =>
+ vi.fn(async (url) => {
+ const model = new URL(url).searchParams.get('model');
+ const list = lists[model];
+ if (list instanceof Error) throw list;
+ if (list === 500) return { ok: false, status: 500, json: async () => ({}) };
+ return { ok: true, status: 200, json: async () => list ?? ['US'] };
+ });
+
+describe('fetchCloroCountries', () => {
+ it("reads an engine's codes with the key, and nothing without one", async () => {
+ const fetchImpl = answer({ chatgpt: ['us', 'GB', 'GB', 'xx1', 7] });
+ expect(await fetchCloroCountries('chatgpt', { fetchImpl, apiKey: 'k' })).toEqual(['US', 'GB']);
+ expect(fetchImpl.mock.calls[0][0]).toBe('https://api.cloro.dev/v1/countries?model=chatgpt');
+ expect(fetchImpl.mock.calls[0][1].headers).toEqual({ Authorization: 'Bearer k' });
+ expect(await fetchCloroCountries('chatgpt', { fetchImpl, apiKey: '' })).toBeNull();
+ });
+
+ it('reads an empty or malformed answer as no list, never as "no countries"', async () => {
+ expect(
+ await fetchCloroCountries('gemini', { fetchImpl: answer({ gemini: [] }), apiKey: 'k' }),
+ ).toBeNull();
+ expect(
+ await fetchCloroCountries('gemini', {
+ fetchImpl: answer({ gemini: { codes: [] } }),
+ apiKey: 'k',
+ }),
+ ).toBeNull();
+ await expect(
+ fetchCloroCountries('gemini', { fetchImpl: answer({ gemini: 500 }), apiKey: 'k' }),
+ ).rejects.toThrow('HTTP 500');
+ });
+});
+
+describe('countryCodesIn', () => {
+ it('reads the codes in each shape a list may come in', () => {
+ expect(countryCodesIn(['us', ' GB ', 'GB', 'USA', 7, null])).toEqual(['US', 'GB']);
+ expect(countryCodesIn({ countries: ['US', 'TR'] })).toEqual(['US', 'TR']);
+ expect(countryCodesIn([{ code: 'us' }, { code: 'XYZ' }, { name: 'Peru' }])).toEqual(['US']);
+ expect(countryCodesIn([{ country: 'TR', name: 'Türkiye' }, { country: 'de' }])).toEqual([
+ 'TR',
+ 'DE',
+ ]);
+ expect(countryCodesIn({ countries: [{ code: 'KE' }] })).toEqual(['KE']);
+ });
+
+ it('reads any other shape as no list', () => {
+ for (const body of [null, 'US', 42, { codes: ['US'] }, { countries: 'US' }]) {
+ expect(countryCodesIn(body)).toBeNull();
+ }
+ });
+});
+
+describe('fetchCloroCountries, in any shape', () => {
+ it('reads a wrapped list and listed entries alike', async () => {
+ const fetchImpl = answer({
+ chatgpt: { countries: ['US', 'GB'] },
+ gemini: [{ code: 'US' }, { code: 'KE' }],
+ copilot: [{ country: 'TR' }],
+ });
+ expect(await fetchCloroCountries('chatgpt', { fetchImpl, apiKey: 'k' })).toEqual(['US', 'GB']);
+ expect(await fetchCloroCountries('gemini', { fetchImpl, apiKey: 'k' })).toEqual(['US', 'KE']);
+ expect(await fetchCloroCountries('copilot', { fetchImpl, apiKey: 'k' })).toEqual(['TR']);
+ });
+
+ it('says so, and keeps the last list, when an answer is in no known shape', async () => {
+ const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {});
+ try {
+ const fetchImpl = answer({ gemini: { data: { list: ['US'] } } });
+ expect(await fetchCloroCountries('gemini', { fetchImpl, apiKey: 'k' })).toBeNull();
+ expect(warn).toHaveBeenCalledWith(
+ { model: 'gemini', shape: 'object', keys: ['data'] },
+ '[cloro-countries] answer holds no country codes; last list kept',
+ );
+ } finally {
+ warn.mockRestore();
+ }
+ });
+});
+
+describe('refreshCloroCountries', () => {
+ it('keeps a list that shrank by more than half, and takes one that shrank less', async () => {
+ const fake = fakeDb();
+ await refreshCloroCountries({
+ db: fake.db,
+ apiKey: 'k',
+ now: new Date('2026-10-27T06:00:00Z'),
+ fetchImpl: answer({
+ chatgpt: ['US', 'GB', 'DE', 'FR', 'TR', 'JP'],
+ aimode: ['US', 'GB', 'DE', 'FR'],
+ }),
+ });
+ const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {});
+ try {
+ const outcome = await refreshCloroCountries({
+ db: fake.db,
+ apiKey: 'k',
+ now: new Date('2026-10-28T06:00:00Z'),
+ // ChatGPT down to two of six: cut short. AI Mode two of four: half, taken.
+ fetchImpl: answer({ chatgpt: ['US', 'GB'], aimode: ['US', 'GB'] }),
+ });
+ expect(outcome).toMatchObject({ chatgpt: 'kept', aimode: 2 });
+ expect(warn).toHaveBeenCalledWith(
+ { model: 'chatgpt', before: 6, now: 2 },
+ '[cloro-countries] list shrank by more than half; last list kept',
+ );
+ } finally {
+ warn.mockRestore();
+ }
+ const supported = await loadSupportedCountries({ db: fake.db });
+ expect(supported.get('chatgpt').size).toBe(6);
+ expect([...supported.get('aimode')].sort()).toEqual(['GB', 'US']);
+ });
+
+ it('writes each engine’s list, drops what it no longer lists, and keeps a list it could not read', async () => {
+ const fake = fakeDb();
+ const day1 = new Date('2026-10-27T06:00:00Z');
+ await refreshCloroCountries({
+ db: fake.db,
+ apiKey: 'k',
+ now: day1,
+ fetchImpl: answer({ chatgpt: ['US', 'GB', 'CZ'], copilot: ['US', 'BR'] }),
+ });
+ const day2 = new Date('2026-10-28T06:00:00Z');
+ const outcome = await refreshCloroCountries({
+ db: fake.db,
+ apiKey: 'k',
+ now: day2,
+ fetchImpl: answer({
+ // CZ dropped from ChatGPT; Copilot's read fails and keeps yesterday's.
+ chatgpt: ['US', 'GB'],
+ copilot: new Error('timeout'),
+ }),
+ });
+ expect(outcome).toMatchObject({ chatgpt: 2, copilot: 'kept' });
+ const supported = await loadSupportedCountries({ db: fake.db });
+ expect([...supported.get('chatgpt')].sort()).toEqual(['GB', 'US']);
+ expect([...supported.get('copilot')].sort()).toEqual(['BR', 'US']);
+ });
+
+ it('reads nothing without the provider key', async () => {
+ const fetchImpl = answer({});
+ expect(await refreshCloroCountries({ db: fakeDb().db, apiKey: '', fetchImpl })).toEqual({
+ skipped: 'no provider key',
+ });
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+});
+
+describe('supportsCountry and supportedLocations', () => {
+ const supported = new Map([
+ ['copilot', new Set(['US', 'TR'])],
+ ['aimode', new Set(['US', 'TR', 'KE'])],
+ ]);
+
+ it('asks an engine only where it answers from', () => {
+ expect(supportsCountry(supported, 'copilot-web', 'KE')).toBe(false);
+ expect(supportsCountry(supported, 'copilot-web', 'TR')).toBe(true);
+ });
+
+ it('restricts nothing it has no list for', () => {
+ // No list read for ChatGPT, the API models aren't the provider's, an untargeted run.
+ expect(supportsCountry(supported, 'chatgpt-web', 'KE')).toBe(true);
+ expect(supportsCountry(supported, 'gpt-5', 'KE')).toBe(true);
+ expect(supportsCountry(supported, 'copilot-web', null)).toBe(true);
+ expect(supportsCountry(new Map(), 'copilot-web', 'KE')).toBe(true);
+ });
+
+ it('skips a country an engine does not support, cities and states included', () => {
+ const codes = ['US', 'KE', 'TR~ISTANBUL', 'US-CA'];
+ expect(supportedLocations(codes, 'copilot-web', supported)).toEqual(['US', 'US-CA']);
+ expect(supportedLocations(codes, 'google-aimode', supported)).toEqual([
+ 'US',
+ 'KE',
+ 'TR~ISTANBUL',
+ ]);
+ expect(supportedLocations([], 'copilot-web', supported)).toEqual([null]);
+ });
+});
+
+/**
+ * The web names the provider's engines and knows which answer from a city
+ * (web/src/lib/tracking-countries.ts): the same models the API reads lists
+ * for, or the location picker would leave an engine unnamed or offer a city
+ * where no engine asks from one.
+ */
+describe('the provider models on both sides (PROMPT-015e)', () => {
+ const web = readFileSync(
+ new URL('../../../web/src/lib/tracking-countries.ts', import.meta.url),
+ 'utf8',
+ );
+ const models = new Set(Object.values(CLORO_COUNTRY_MODELS));
+
+ it('names every model the API reads a list for, and no other', () => {
+ const labels = web.match(/ENGINE_LABELS[^=]*=\s*\{([^}]*)\}/);
+ expect(labels).not.toBeNull();
+ const named = [...labels[1].matchAll(/^\s*'?([a-z]+)'?:/gm)].map((m) => m[1]);
+ expect(named.sort()).toEqual([...models].sort());
+ });
+
+ it("takes a city on the models of the API's city engines", () => {
+ const cities = web.match(/CITY_MODELS[^=]*=\s*new Set\(\[([^\]]*)\]\)/);
+ expect(cities).not.toBeNull();
+ const webModels = [...cities[1].matchAll(/'([^']+)'/g)].map((m) => m[1]);
+ expect(webModels.sort()).toEqual(
+ [...new Set([...CITY_SCRAPERS].map((id) => CLORO_COUNTRY_MODELS[id]))].sort(),
+ );
+ });
+});
diff --git a/server/src/lib/cloro-scraper.js b/server/src/lib/cloro-scraper.js
index 5544e3d99..8c03f0d5e 100644
--- a/server/src/lib/cloro-scraper.js
+++ b/server/src/lib/cloro-scraper.js
@@ -10,7 +10,7 @@
import logger from './logger.js';
import { stripEntityMarkup } from './entity-markup.js';
-const CLORO_API = 'https://api.cloro.dev';
+export const CLORO_API = 'https://api.cloro.dev';
export const SCRAPER_TASK_TYPES = {
'chatgpt-web': 'CHATGPT',
diff --git a/server/src/server.js b/server/src/server.js
index b548485b4..3c69ed7b1 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -57,6 +57,7 @@ import { sweepActionTasks } from './lib/action-center/task-writer/index.js';
import { sweepTaskChecks } from './lib/action-center/task-checks.js';
import { sendHealthReport } from './lib/health/report.js';
import { checkPromptUsageCounters } from './lib/prompt-usage-counters.js';
+import { refreshCloroCountries } from './lib/cloro-countries.js';
const app = express();
app.set('trust proxy', 1);
@@ -147,6 +148,13 @@ async function runDailyTracking() {
// self-hosted, since both paths funnel through here).
await cleanupStalePendingTasks();
+ // Read the countries each engine answers from (PROMPT-015e) before
+ // tracking, so today's runs skip what an engine doesn't support and the
+ // location picker offers what it does. A failed read keeps yesterday's.
+ await refreshCloroCountries().catch((err) => {
+ logger.error({ err }, '[cloro-countries] refresh crashed');
+ });
+
// Recover pulses whose fire-and-forget trigger died with the process
// (OOM, deploy, crash) after the run had already stamped. Non-blocking —
// today's runs and their own pulses are independent of this sweep.
diff --git a/server/src/workers/tracking-worker.js b/server/src/workers/tracking-worker.js
index b9d79d544..2c0e96d48 100644
--- a/server/src/workers/tracking-worker.js
+++ b/server/src/workers/tracking-worker.js
@@ -20,6 +20,7 @@ import {
locationsForScraper,
parseLocation,
} from '../lib/locations.js';
+import { loadSupportedCountries, supportedLocations } from '../lib/cloro-countries.js';
import { settleTrackingRun } from '../lib/run-settlement.js';
import logger from '../lib/logger.js';
@@ -324,18 +325,37 @@ export async function processTrackingJob({ brandId, promptId, promptIds, source,
logger.warn({ brandId, codes: unknownCities }, 'skipping city codes no city list names');
}
+ // The countries each engine answers from (PROMPT-015e, read daily): an
+ // engine isn't asked in a country it doesn't support, which would fail and
+ // cost a task. Nothing is skipped when no list was read.
+ const supportedCountries = await loadSupportedCountries().catch((err) => {
+ logger.error({ err, brandId }, 'engine country lists unreadable; nothing skipped');
+ return new Map();
+ });
+ const scraperLocations = (prompt, scraperId) =>
+ supportedLocations(locationsFor(prompt), scraperId, supportedCountries);
+
// 4. Count total tasks: one per prompt × engine × location that engine can
// actually run. Google AIO / AI Mode have no sub-country mechanism, so
// their state locations collapse to one country-wide task — counting them
// per state would promise the progress bar work that is never submitted.
let totalTasks = 0;
+ let unsupported = 0;
for (const prompt of prompts) {
const locations = locationsFor(prompt);
totalTasks += allowedModelsFor(prompt).length * locationsForModels(locations).length;
for (const scraperId of allowedPlatformsFor(prompt)) {
- totalTasks += locationsForScraper(locations, scraperId).length;
+ const runnable = scraperLocations(prompt, scraperId).length;
+ totalTasks += runnable;
+ unsupported += locationsForScraper(locations, scraperId).length - runnable;
}
}
+ if (unsupported > 0) {
+ logger.info(
+ { brandId, skipped: unsupported },
+ 'engine × country pairs the engine does not support, skipped',
+ );
+ }
// 5. Shared counters & helper
let insertedCount = 0;
@@ -377,7 +397,7 @@ export async function processTrackingJob({ brandId, promptId, promptIds, source,
// `region` carries the full location code — it is what gets stamped on
// the result row, so a Google run collapsed to its country is recorded
// as the country it actually ran in, not the state that was asked for.
- for (const region of locationsForScraper(locationsFor(prompt), scraperId)) {
+ for (const region of scraperLocations(prompt, scraperId)) {
scraperTasks.push({ prompt, scraperId, region });
}
}
diff --git a/supabase/migrations/00364_cloro_countries.sql b/supabase/migrations/00364_cloro_countries.sql
new file mode 100644
index 000000000..8769e8eeb
--- /dev/null
+++ b/supabase/migrations/00364_cloro_countries.sql
@@ -0,0 +1,35 @@
+-- ============================================================================
+-- 00364: the countries each tracking engine answers from (PROMPT-015e)
+-- ============================================================================
+-- The AI engines' provider (Cloro) supports a different set of countries per
+-- engine, and asking an engine in a country it doesn't support fails. Its
+-- GET /v1/countries?model= is the only source of truth, so the API reads it
+-- daily, before the tracking runs, and keeps it here:
+--
+-- * the location picker offers only countries some engine answers from;
+-- * the tracking run skips an engine in a country it doesn't support.
+--
+-- A model whose read fails keeps its last list. An empty table (no provider
+-- key, or before the first read) restricts nothing.
+
+create table if not exists public.cloro_countries (
+ model text not null check (char_length(model) between 1 and 40),
+ country text not null check (country ~ '^[A-Z]{2}$'),
+ refreshed_at timestamptz not null default now(),
+ primary key (model, country)
+);
+
+alter table public.cloro_countries enable row level security;
+revoke all on table public.cloro_countries from anon, authenticated;
+grant select on table public.cloro_countries to authenticated;
+grant all on table public.cloro_countries to service_role;
+
+-- Not a customer's data: every signed-in member may read it; the API writes.
+drop policy if exists "cloro_countries: read" on public.cloro_countries;
+create policy "cloro_countries: read" on public.cloro_countries
+ for select to authenticated using (true);
+
+comment on table public.cloro_countries is
+ 'Countries each tracking engine answers from (PROMPT-015e, 00364), read daily from the provider''s GET /v1/countries?model=. Empty restricts nothing.';
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 3808795d4..0fb3b3621 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -42160,6 +42160,45 @@ comment on table public.prompt_table_views is
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00364_cloro_countries.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00364: the countries each tracking engine answers from (PROMPT-015e)
+-- ============================================================================
+-- The AI engines' provider (Cloro) supports a different set of countries per
+-- engine, and asking an engine in a country it doesn't support fails. Its
+-- GET /v1/countries?model= is the only source of truth, so the API reads it
+-- daily, before the tracking runs, and keeps it here:
+--
+-- * the location picker offers only countries some engine answers from;
+-- * the tracking run skips an engine in a country it doesn't support.
+--
+-- A model whose read fails keeps its last list. An empty table (no provider
+-- key, or before the first read) restricts nothing.
+
+create table if not exists public.cloro_countries (
+ model text not null check (char_length(model) between 1 and 40),
+ country text not null check (country ~ '^[A-Z]{2}$'),
+ refreshed_at timestamptz not null default now(),
+ primary key (model, country)
+);
+
+alter table public.cloro_countries enable row level security;
+revoke all on table public.cloro_countries from anon, authenticated;
+grant select on table public.cloro_countries to authenticated;
+grant all on table public.cloro_countries to service_role;
+
+-- Not a customer's data: every signed-in member may read it; the API writes.
+drop policy if exists "cloro_countries: read" on public.cloro_countries;
+create policy "cloro_countries: read" on public.cloro_countries
+ for select to authenticated using (true);
+
+comment on table public.cloro_countries is
+ 'Countries each tracking engine answers from (PROMPT-015e, 00364), read daily from the provider''s GET /v1/countries?model=. Empty restricts nothing.';
+
+notify pgrst, 'reload schema';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00365_action_outcome_mixed.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.test.tsx
index ed0066cb1..0c6dda1b2 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.test.tsx
@@ -10,6 +10,8 @@ const actions = vi.hoisted(() => ({
bulkUpdatePromptLocations: vi.fn(),
}));
vi.mock('@/lib/actions/prompt', () => actions);
+// The engines' countries (PROMPT-015e): none read, so the picker's own list.
+vi.mock('@/lib/actions/tracking-countries', () => ({ getTrackingCountries: async () => [] }));
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
vi.mock('sonner', () => ({ toast }));
vi.mock('@/i18n/navigation', () => ({
diff --git a/web/src/components/dashboard/location-picker.test.tsx b/web/src/components/dashboard/location-picker.test.tsx
new file mode 100644
index 000000000..2041089a9
--- /dev/null
+++ b/web/src/components/dashboard/location-picker.test.tsx
@@ -0,0 +1,62 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/** The location picker, on the engines' countries (PROMPT-015e). */
+
+const getTrackingCountries = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/actions/tracking-countries', () => ({ getTrackingCountries }));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ vi.resetModules();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+async function open() {
+ const { LocationPicker } = await import('./location-picker');
+ await act(async () => {
+ root.render(<LocationPicker value={[]} onChange={() => {}} maxSelectable={null} allowEmpty />);
+ });
+ const trigger = container.querySelector('button') as HTMLButtonElement;
+ await act(async () => trigger.click());
+ return document.body.textContent ?? '';
+}
+
+describe('LocationPicker', () => {
+ it('offers the countries the engines answer from, says which engines miss one, and cities only where Google answers', async () => {
+ getTrackingCountries.mockResolvedValue([
+ { code: 'US', models: ['chatgpt', 'copilot', 'aimode'] },
+ { code: 'TR', models: ['chatgpt', 'copilot', 'aimode'] },
+ { code: 'BO', models: ['chatgpt', 'aimode'] },
+ { code: 'DE', models: ['chatgpt', 'copilot'] },
+ ]);
+ const text = await open();
+ expect(text).toContain('Bolivia');
+ expect(text).toContain('Country · not on Copilot');
+ // No Google engine in Germany: its cities aren't offered; Turkey's are.
+ expect(text).toContain('İstanbul');
+ expect(text).not.toContain('Berlin');
+ // A brand region no engine answers from isn't offered.
+ expect(text).not.toContain('Japan');
+ });
+
+ it("falls back to its own list when the engines' countries were never read", async () => {
+ getTrackingCountries.mockResolvedValue([]);
+ const text = await open();
+ expect(text).toContain('Japan');
+ expect(text).toContain('Berlin');
+ });
+});
diff --git a/web/src/components/dashboard/location-picker.tsx b/web/src/components/dashboard/location-picker.tsx
index 2205113e5..cd5055030 100644
--- a/web/src/components/dashboard/location-picker.tsx
+++ b/web/src/components/dashboard/location-picker.tsx
@@ -1,6 +1,6 @@
'use client';
-import { useMemo } from 'react';
+import { useEffect, useMemo, useState } from 'react';
import { X } from 'lucide-react';
import { CITIES } from '@/config/cities';
@@ -13,6 +13,14 @@ import {
parseLocation,
regionLabel,
} from '@/lib/region';
+import { getTrackingCountries } from '@/lib/actions/tracking-countries';
+import {
+ CITY_MODELS,
+ ENGINE_LABELS,
+ countryName,
+ missingEngines,
+ type TrackingCountry,
+} from '@/lib/tracking-countries';
import { Badge } from '@/components/ui/badge';
import {
Combobox,
@@ -56,6 +64,31 @@ export interface LocationPickerProps {
allowEmpty?: boolean;
}
+/** The engines' countries, read once per page (PROMPT-015e); empty when none were read. */
+let countriesRead: Promise<TrackingCountry[]> | null = null;
+
+function useTrackingCountries(): TrackingCountry[] | null {
+ const [countries, setCountries] = useState<TrackingCountry[] | null>(null);
+ useEffect(() => {
+ let cancelled = false;
+ countriesRead ??= getTrackingCountries().catch((err) => {
+ console.error('Failed to read the tracking countries:', err);
+ countriesRead = null;
+ return [];
+ });
+ countriesRead.then((list) => {
+ if (!cancelled) setCountries(list);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+ return countries;
+}
+
+/** The brand regions first, as people look for them, then every other country by name. */
+const POPULAR = TRACKING_COUNTRIES.slice(0, 18).map((c) => c.code);
+
/** Engines with no sub-country mechanism — mirrors the worker's collapse. */
const COUNTRY_ONLY_PLATFORMS = new Set(['google-aio', 'google-aimode']);
@@ -82,30 +115,54 @@ export function LocationPicker({
countNoun = 'tracked',
allowEmpty = false,
}: LocationPickerProps) {
- const options = useMemo<LocationOption[]>(
- () => [
- ...TRACKING_COUNTRIES.map((region) => ({
- value: region.code,
- // Found by its other names too: "Turkey" or "Turkiye" finds Türkiye.
- label: locationSearchText(region.code),
- sublabel: 'Country',
- })),
+ // The countries the engines answer from, as the API last read them; until
+ // then, or without a read, the picker's own list (PROMPT-015e).
+ const engineCountries = useTrackingCountries();
+ const options = useMemo<LocationOption[]>(() => {
+ const read = engineCountries?.length ? engineCountries : null;
+ const countries = read
+ ? [...read]
+ .sort(
+ (a, b) =>
+ (POPULAR.includes(a.code) ? POPULAR.indexOf(a.code) : 99) -
+ (POPULAR.includes(b.code) ? POPULAR.indexOf(b.code) : 99) ||
+ countryName(a.code).localeCompare(countryName(b.code)),
+ )
+ .map((country) => {
+ const missing = missingEngines(country, read).map((m) => ENGINE_LABELS[m] ?? m);
+ return {
+ value: country.code,
+ // Found by its other names too: "Turkey" or "Turkiye" finds Türkiye.
+ label: locationSearchText(country.code),
+ sublabel: missing.length ? `Country · not on ${missing.join(', ')}` : 'Country',
+ };
+ })
+ : TRACKING_COUNTRIES.map((region) => ({
+ value: region.code,
+ label: locationSearchText(region.code),
+ sublabel: 'Country',
+ }));
+ // A city only where Google's engines answer from its country.
+ const cityCountries = read
+ ? new Set(read.filter((c) => c.models.some((m) => CITY_MODELS.has(m))).map((c) => c.code))
+ : null;
+ return [
+ ...countries,
...US_STATES.map((state) => ({
value: locationCode('US', state.code),
label: state.label,
sublabel: 'United States · state',
})),
// Cities (PROMPT-015d): asked by Google's engines and the API models.
- ...CITIES.map((city) => ({
+ ...CITIES.filter((city) => !cityCountries || cityCountries.has(city.country)).map((city) => ({
value: cityCode(city.country, city.id),
// Found typed with or without its marks, or by its country: "Ist" finds
// İstanbul, "Sao" São Paulo, "Turkey" every city in Türkiye.
label: locationSearchText(cityCode(city.country, city.id)),
sublabel: `City · ${regionLabel(city.country)}`,
})),
- ],
- [],
- );
+ ];
+ }, [engineCountries]);
const selected = new Set(value);
const atCap = maxSelectable !== null && value.length >= maxSelectable;
diff --git a/web/src/lib/actions/tracking-countries.test.ts b/web/src/lib/actions/tracking-countries.test.ts
new file mode 100644
index 000000000..5170f0393
--- /dev/null
+++ b/web/src/lib/actions/tracking-countries.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it, vi } from 'vitest';
+
+/** The engines' countries, as the API last read them (PROMPT-015e). */
+
+const rows = [
+ { country: 'KE', model: 'aimode' },
+ { country: 'KE', model: 'chatgpt' },
+ { country: 'US', model: 'aimode' },
+ { country: 'US', model: 'copilot' },
+];
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => {
+ const q = {
+ select: () => q,
+ order: () => q,
+ range: async () => ({ data: rows, error: null }),
+ };
+ return { from: () => q };
+ }),
+}));
+
+const { getTrackingCountries } = await import('./tracking-countries');
+
+describe('getTrackingCountries', () => {
+ it('lists each country with the engines that answer from it', async () => {
+ expect(await getTrackingCountries()).toEqual([
+ { code: 'KE', models: ['aimode', 'chatgpt'] },
+ { code: 'US', models: ['aimode', 'copilot'] },
+ ]);
+ });
+});
diff --git a/web/src/lib/actions/tracking-countries.ts b/web/src/lib/actions/tracking-countries.ts
new file mode 100644
index 000000000..ee7a517ec
--- /dev/null
+++ b/web/src/lib/actions/tracking-countries.ts
@@ -0,0 +1,35 @@
+'use server';
+
+import { createClient } from '@/lib/supabase/server';
+import type { TrackingCountry } from '@/lib/tracking-countries';
+
+/** Rows read per page: PostgREST stops a read at 1000. */
+const PAGE = 1000;
+
+/**
+ * The countries the tracking engines answer from (PROMPT-015e), as the API
+ * last read them from the provider; each with its engines. Empty before the
+ * first read, or without the provider key: the picker then offers its own
+ * list.
+ */
+export async function getTrackingCountries(): Promise<TrackingCountry[]> {
+ const supabase = await createClient();
+ const rows: { model: string; country: string }[] = [];
+ for (let from = 0; from < 20 * PAGE; from += PAGE) {
+ const { data, error } = await supabase
+ .from('cloro_countries')
+ .select('model, country')
+ .order('country')
+ .order('model')
+ .range(from, from + PAGE - 1);
+ if (error) throw new Error(error.message);
+ rows.push(...(data ?? []));
+ if ((data ?? []).length < PAGE) break;
+ }
+ const byCountry = new Map<string, string[]>();
+ for (const { model, country } of rows) {
+ if (!byCountry.has(country)) byCountry.set(country, []);
+ byCountry.get(country)!.push(model);
+ }
+ return [...byCountry].map(([code, models]) => ({ code, models }));
+}
diff --git a/web/src/lib/region.test.ts b/web/src/lib/region.test.ts
index e1b8d786e..323719712 100644
--- a/web/src/lib/region.test.ts
+++ b/web/src/lib/region.test.ts
@@ -78,6 +78,12 @@ describe('location codes', () => {
expect(cityCode('tr', 'izmir')).toBe('TR~IZMIR');
});
+ it('takes any country the engines may answer from, by its own name (PROMPT-015e)', () => {
+ expect(isValidLocation('BO')).toBe(true);
+ expect(regionLabel('BO')).toBe('Bolivia');
+ expect(isValidLocation('EU')).toBe(false);
+ });
+
it('names Türkiye as Türkiye, and finds it and its cities by its other names too', () => {
expect(regionLabel('TR')).toBe('Türkiye');
expect(locationSearchText('TR')).toBe('Türkiye Turkiye Turkey');
diff --git a/web/src/lib/region.ts b/web/src/lib/region.ts
index 6a77aa977..d18158ab7 100644
--- a/web/src/lib/region.ts
+++ b/web/src/lib/region.ts
@@ -1,5 +1,6 @@
import { CITIES } from '@/config/cities';
import { TRACKING_COUNTRIES, US_STATES } from '@/config/prompt-options';
+import { countryName, isCountryCode } from '@/lib/tracking-countries';
/**
* Tracking locations (#691).
@@ -50,7 +51,9 @@ export function parseLocation(code: string): ParsedLocation | null {
return CITY_LABELS.has(normalized) ? { country, state: null, city } : null;
}
const [country, state, ...rest] = normalized.split('-');
- if (rest.length > 0 || !REGION_LABELS.has(country)) return null;
+ // Any country (PROMPT-015e): the picker offers those an engine answers
+ // from, and the run skips an engine in one it doesn't.
+ if (rest.length > 0 || !(REGION_LABELS.has(country) || isCountryCode(country))) return null;
if (state === undefined) return { country, state: null };
if (country !== 'US' || !STATE_LABELS.has(state)) return null;
return { country, state };
@@ -83,7 +86,7 @@ export function regionLabel(code: string): string {
if (!parsed) return code.trim();
if (parsed.city) return CITY_LABELS.get(normalizeRegionCode(code)) ?? parsed.city;
if (parsed.state) return STATE_LABELS.get(parsed.state) ?? parsed.state;
- return REGION_LABELS.get(parsed.country) ?? parsed.country;
+ return REGION_LABELS.get(parsed.country) ?? countryName(parsed.country);
}
export function regionFlag(code: string): string {
diff --git a/web/src/lib/tracking-countries.test.ts b/web/src/lib/tracking-countries.test.ts
new file mode 100644
index 000000000..349ffec1c
--- /dev/null
+++ b/web/src/lib/tracking-countries.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest';
+import { countryName, isCountryCode, missingEngines } from './tracking-countries';
+
+/** The countries the tracking engines answer from (PROMPT-015e). */
+
+describe('isCountryCode and countryName', () => {
+ it('knows any country by its code, and no group', () => {
+ expect(isCountryCode('BO')).toBe(true);
+ expect(countryName('BO')).toBe('Bolivia');
+ expect(isCountryCode('XK')).toBe(true);
+ for (const group of ['EU', 'UN', 'ZZ', 'EZ', 'QO']) expect(isCountryCode(group)).toBe(false);
+ expect(isCountryCode('bo')).toBe(false);
+ expect(isCountryCode('B1')).toBe(false);
+ });
+});
+
+describe('missingEngines', () => {
+ it('names the engines a country is not answered by', () => {
+ const all = [
+ { code: 'US', models: ['chatgpt', 'copilot', 'aimode'] },
+ { code: 'KE', models: ['chatgpt', 'aimode'] },
+ ];
+ expect(missingEngines(all[1], all)).toEqual(['copilot']);
+ expect(missingEngines(all[0], all)).toEqual([]);
+ });
+});
diff --git a/web/src/lib/tracking-countries.ts b/web/src/lib/tracking-countries.ts
new file mode 100644
index 000000000..c7fc71a14
--- /dev/null
+++ b/web/src/lib/tracking-countries.ts
@@ -0,0 +1,64 @@
+/**
+ * The countries prompts can be tracked in, as the tracking engines answer
+ * from them (PROMPT-015e): the API reads each engine's list from the
+ * provider daily (cloro_countries, 00364); getTrackingCountries reads it.
+ * Country names come from the browser's own region names, so any country
+ * the provider adds reads right without a list here.
+ */
+
+/** The provider's engines, as the location picker names them. */
+export const ENGINE_LABELS: Record<string, string> = {
+ chatgpt: 'ChatGPT',
+ perplexity: 'Perplexity',
+ copilot: 'Copilot',
+ gemini: 'Gemini',
+ aimode: 'Google AI Mode',
+ aioverview: 'Google AI Overview',
+};
+
+/** Engines that answer from a city, by the provider's model name (PROMPT-015d). */
+export const CITY_MODELS: ReadonlySet<string> = new Set(['aimode', 'aioverview']);
+
+export interface TrackingCountry {
+ code: string;
+ /** The provider's engines that answer from it. */
+ models: string[];
+}
+
+// Two-letter codes that name a group, not a country, or nothing.
+const NOT_COUNTRIES = new Set(['EU', 'EZ', 'UN', 'QO', 'ZZ', 'XA', 'XB']);
+
+let names: Intl.DisplayNames | null = null;
+function displayNames(): Intl.DisplayNames {
+ names ??= new Intl.DisplayNames(['en'], { type: 'region' });
+ return names;
+}
+
+/** True for an ISO 3166-1 country code the runtime knows (`PL`, `KE`), not a group (`EU`). */
+export function isCountryCode(code: string): boolean {
+ if (!/^[A-Z]{2}$/.test(code) || NOT_COUNTRIES.has(code)) return false;
+ try {
+ const name = displayNames().of(code);
+ return Boolean(name) && name !== code;
+ } catch {
+ return false;
+ }
+}
+
+/** A country's English name, from the runtime; the code when it has none. */
+export function countryName(code: string): string {
+ try {
+ return displayNames().of(code) ?? code;
+ } catch {
+ return code;
+ }
+}
+
+/** The engines a country isn't answered by, among those any country is. */
+export function missingEngines(
+ country: TrackingCountry,
+ all: readonly TrackingCountry[],
+): string[] {
+ const engines = new Set(all.flatMap((c) => c.models));
+ return [...engines].filter((m) => !country.models.includes(m)).sort();
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 234e567d7..5153c9590 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -1388,6 +1388,24 @@ export type Database = {
}
Relationships: []
}
+ cloro_countries: {
+ Row: {
+ country: string
+ model: string
+ refreshed_at: string
+ }
+ Insert: {
+ country: string
+ model: string
+ refreshed_at?: string
+ }
+ Update: {
+ country?: string
+ model?: string
+ refreshed_at?: string
+ }
+ Relationships: []
+ }
cloro_pending_tasks: {
Row: {
brand_id: string