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(tracking): track prompts in cities, asked by the engines that can answer from one (PROMPT-015, part 4) (#1658)
Cihanceac6d4c45b3
diff --git a/docs/guides/prompts.mdx b/docs/guides/prompts.mdxindex b476e35a7..8a33ef034 100644--- a/docs/guides/prompts.mdx+++ b/docs/guides/prompts.mdx@@ -48,7 +48,7 @@ Admins and managers can tick **Share with everyone on <brand>**: their columns b### Location columns and the Locations view-A prompt tracked in several locations (countries or US states) has figures for each one. In **Columns**, **Add a location column** adds a metric in one location, such as *Visibility · Turkey*, as its own column.+A prompt tracked in several locations (countries or US states) has figures for each one. In **Columns**, **Add a location column** adds a metric in one location, such as *Visibility · Türkiye*, as its own column.**View: Table | Locations**, above the table, switches to the **Locations** view:@@ -63,10 +63,12 @@ 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 or US states (about 50 countries).+1. Pick one or more countries, US states or cities (about 50 countries and 50 major cities).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.+**Cities** are asked by the engines that can answer from a city: Google AI Mode, Google AI Overview and the API models (OpenAI, Claude). ChatGPT, Perplexity, Copilot, Gemini and Grok answer per country, so they skip a city, and their answers stay in the country's column; track the country too to see them. A city column in the Locations view says *AI Mode · AIO · APIs*. A city counts as one location on your plan, like a country, on every plan. If none of the chosen prompts runs one of those engines, the dialog says so and adds nothing.+If the choice would pass your plan's limit, the dialog says how many it needs and how many are left, and saves nothing. Pick fewer prompts or places, or:- **Starter**: upgrade, or contact us for a custom plan;diff --git a/server/src/lib/cities.js b/server/src/lib/cities.jsnew file mode 100644index 000000000..1ce4c2a26--- /dev/null+++ b/server/src/lib/cities.js@@ -0,0 +1,364 @@+/**+ * Cities a prompt can be tracked in (PROMPT-015d). A city is the location+ * code `<country>~<CITY>` (`TR~ISTANBUL`). Only the engines that can ask+ * from a city run there: Google AI Overview and AI Mode, with Google's+ * canonical name as the provider's `location`, and the API models, with+ * `user_location.city`. The other engines answer per country, so a city+ * code is skipped for them (locations.js).+ *+ * The web keeps the same ids and countries in `web/src/config/cities.ts`;+ * both lists must change together.+ *+ * - `name`, `region`: what the API models' `user_location` takes.+ * - `google`: Google's canonical location name, as Google Ads geotargets+ * spell it.+ */+/**+ * Türkiye as Google's geotargets spell it, in ASCII: Google renamed it from+ * Turkey. Still to be confirmed with a real request; if Google reads it+ * otherwise, this line is the only one to change.+ */+const GOOGLE_TURKIYE = 'Turkiye';++export const CITIES = [+ {+ country: 'US',+ id: 'NEW_YORK',+ name: 'New York',+ region: 'New York',+ google: 'New York,New York,United States',+ },+ {+ country: 'US',+ id: 'LOS_ANGELES',+ name: 'Los Angeles',+ region: 'California',+ google: 'Los Angeles,California,United States',+ },+ {+ country: 'US',+ id: 'CHICAGO',+ name: 'Chicago',+ region: 'Illinois',+ google: 'Chicago,Illinois,United States',+ },+ {+ country: 'US',+ id: 'HOUSTON',+ name: 'Houston',+ region: 'Texas',+ google: 'Houston,Texas,United States',+ },+ {+ country: 'US',+ id: 'SAN_FRANCISCO',+ name: 'San Francisco',+ region: 'California',+ google: 'San Francisco,California,United States',+ },+ {+ country: 'US',+ id: 'MIAMI',+ name: 'Miami',+ region: 'Florida',+ google: 'Miami,Florida,United States',+ },+ {+ country: 'US',+ id: 'SEATTLE',+ name: 'Seattle',+ region: 'Washington',+ google: 'Seattle,Washington,United States',+ },+ {+ country: 'US',+ id: 'BOSTON',+ name: 'Boston',+ region: 'Massachusetts',+ google: 'Boston,Massachusetts,United States',+ },+ {+ country: 'US',+ id: 'AUSTIN',+ name: 'Austin',+ region: 'Texas',+ google: 'Austin,Texas,United States',+ },+ {+ country: 'US',+ id: 'ATLANTA',+ name: 'Atlanta',+ region: 'Georgia',+ google: 'Atlanta,Georgia,United States',+ },+ {+ country: 'GB',+ id: 'LONDON',+ name: 'London',+ region: 'England',+ google: 'London,England,United Kingdom',+ },+ {+ country: 'GB',+ id: 'MANCHESTER',+ name: 'Manchester',+ region: 'England',+ google: 'Manchester,England,United Kingdom',+ },+ {+ country: 'GB',+ id: 'BIRMINGHAM',+ name: 'Birmingham',+ region: 'England',+ google: 'Birmingham,England,United Kingdom',+ },+ {+ country: 'GB',+ id: 'EDINBURGH',+ name: 'Edinburgh',+ region: 'Scotland',+ google: 'Edinburgh,Scotland,United Kingdom',+ },+ {+ country: 'DE',+ id: 'BERLIN',+ name: 'Berlin',+ region: 'Berlin',+ google: 'Berlin,Berlin,Germany',+ },+ {+ country: 'DE',+ id: 'MUNICH',+ name: 'Munich',+ region: 'Bavaria',+ google: 'Munich,Bavaria,Germany',+ },+ {+ country: 'DE',+ id: 'HAMBURG',+ name: 'Hamburg',+ region: 'Hamburg',+ google: 'Hamburg,Hamburg,Germany',+ },+ {+ country: 'DE',+ id: 'FRANKFURT',+ name: 'Frankfurt',+ region: 'Hesse',+ google: 'Frankfurt,Hesse,Germany',+ },+ {+ country: 'DE',+ id: 'COLOGNE',+ name: 'Cologne',+ region: 'North Rhine-Westphalia',+ google: 'Cologne,North Rhine-Westphalia,Germany',+ },+ {+ country: 'FR',+ id: 'PARIS',+ name: 'Paris',+ region: 'Ile-de-France',+ google: 'Paris,Ile-de-France,France',+ },+ {+ country: 'FR',+ id: 'LYON',+ name: 'Lyon',+ region: 'Auvergne-Rhone-Alpes',+ google: 'Lyon,Auvergne-Rhone-Alpes,France',+ },+ {+ country: 'FR',+ id: 'MARSEILLE',+ name: 'Marseille',+ region: "Provence-Alpes-Cote d'Azur",+ google: "Marseille,Provence-Alpes-Cote d'Azur,France",+ },+ {+ country: 'TR',+ id: 'ISTANBUL',+ name: 'Istanbul',+ region: 'Istanbul',+ google: `Istanbul,Istanbul,${GOOGLE_TURKIYE}`,+ },+ {+ country: 'TR',+ id: 'ANKARA',+ name: 'Ankara',+ region: 'Ankara',+ google: `Ankara,Ankara,${GOOGLE_TURKIYE}`,+ },+ {+ country: 'TR',+ id: 'IZMIR',+ name: 'Izmir',+ region: 'Izmir',+ google: `Izmir,Izmir,${GOOGLE_TURKIYE}`,+ },+ {+ country: 'TR',+ id: 'BURSA',+ name: 'Bursa',+ region: 'Bursa',+ google: `Bursa,Bursa,${GOOGLE_TURKIYE}`,+ },+ {+ country: 'TR',+ id: 'ANTALYA',+ name: 'Antalya',+ region: 'Antalya',+ google: `Antalya,Antalya,${GOOGLE_TURKIYE}`,+ },+ { country: 'JP', id: 'TOKYO', name: 'Tokyo', region: 'Tokyo', google: 'Tokyo,Tokyo,Japan' },+ { country: 'JP', id: 'OSAKA', name: 'Osaka', region: 'Osaka', google: 'Osaka,Osaka,Japan' },+ {+ country: 'BR',+ id: 'SAO_PAULO',+ name: 'Sao Paulo',+ region: 'State of Sao Paulo',+ google: 'Sao Paulo,State of Sao Paulo,Brazil',+ },+ {+ country: 'BR',+ id: 'RIO_DE_JANEIRO',+ name: 'Rio de Janeiro',+ region: 'State of Rio de Janeiro',+ google: 'Rio de Janeiro,State of Rio de Janeiro,Brazil',+ },+ {+ country: 'IN',+ id: 'MUMBAI',+ name: 'Mumbai',+ region: 'Maharashtra',+ google: 'Mumbai,Maharashtra,India',+ },+ {+ country: 'IN',+ id: 'NEW_DELHI',+ name: 'New Delhi',+ region: 'Delhi',+ google: 'New Delhi,Delhi,India',+ },+ {+ country: 'IN',+ id: 'BENGALURU',+ name: 'Bengaluru',+ region: 'Karnataka',+ google: 'Bengaluru,Karnataka,India',+ },+ {+ country: 'AU',+ id: 'SYDNEY',+ name: 'Sydney',+ region: 'New South Wales',+ google: 'Sydney,New South Wales,Australia',+ },+ {+ country: 'AU',+ id: 'MELBOURNE',+ name: 'Melbourne',+ region: 'Victoria',+ google: 'Melbourne,Victoria,Australia',+ },+ {+ country: 'CA',+ id: 'TORONTO',+ name: 'Toronto',+ region: 'Ontario',+ google: 'Toronto,Ontario,Canada',+ },+ {+ country: 'CA',+ id: 'VANCOUVER',+ name: 'Vancouver',+ region: 'British Columbia',+ google: 'Vancouver,British Columbia,Canada',+ },+ {+ country: 'CA',+ id: 'MONTREAL',+ name: 'Montreal',+ region: 'Quebec',+ google: 'Montreal,Quebec,Canada',+ },+ {+ country: 'NL',+ id: 'AMSTERDAM',+ name: 'Amsterdam',+ region: 'North Holland',+ google: 'Amsterdam,North Holland,Netherlands',+ },+ {+ country: 'NL',+ id: 'ROTTERDAM',+ name: 'Rotterdam',+ region: 'South Holland',+ google: 'Rotterdam,South Holland,Netherlands',+ },+ { country: 'IT', id: 'ROME', name: 'Rome', region: 'Lazio', google: 'Rome,Lazio,Italy' },+ { country: 'IT', id: 'MILAN', name: 'Milan', region: 'Lombardy', google: 'Milan,Lombardy,Italy' },+ {+ country: 'ES',+ id: 'MADRID',+ name: 'Madrid',+ region: 'Community of Madrid',+ google: 'Madrid,Community of Madrid,Spain',+ },+ {+ country: 'ES',+ id: 'BARCELONA',+ name: 'Barcelona',+ region: 'Catalonia',+ google: 'Barcelona,Catalonia,Spain',+ },+ { country: 'KR', id: 'SEOUL', name: 'Seoul', region: 'Seoul', google: 'Seoul,Seoul,South Korea' },+ {+ country: 'SE',+ id: 'STOCKHOLM',+ name: 'Stockholm',+ region: 'Stockholm County',+ google: 'Stockholm,Stockholm County,Sweden',+ },+ {+ country: 'MX',+ id: 'MEXICO_CITY',+ name: 'Mexico City',+ region: 'Mexico City',+ google: 'Mexico City,Mexico City,Mexico',+ },+ {+ country: 'SG',+ id: 'SINGAPORE',+ name: 'Singapore',+ region: 'Singapore',+ google: 'Singapore,Singapore',+ },+ {+ country: 'AE',+ id: 'DUBAI',+ name: 'Dubai',+ region: 'Dubai',+ google: 'Dubai,Dubai,United Arab Emirates',+ },+ {+ country: 'AE',+ id: 'ABU_DHABI',+ name: 'Abu Dhabi',+ region: 'Abu Dhabi',+ google: 'Abu Dhabi,Abu Dhabi,United Arab Emirates',+ },+];++const BY_CODE = new Map(CITIES.map((c) => [`${c.country}~${c.id}`, c]));++/** The city a code names (`TR~ISTANBUL`), or null. */+export function cityFor(code) {+ return (+ BY_CODE.get(+ String(code ?? '')+ .trim()+ .toUpperCase(),+ ) ?? null+ );+}diff --git a/server/src/lib/cities.test.js b/server/src/lib/cities.test.jsnew file mode 100644index 000000000..71d543fac--- /dev/null+++ b/server/src/lib/cities.test.js@@ -0,0 +1,48 @@+import { readFileSync } from 'node:fs';+import { describe, expect, it } from 'vitest';+import { CITIES, cityFor } from './cities.js';+import { CITY_SCRAPERS, COUNTRY_ONLY_SCRAPERS } from './locations.js';++/**+ * The cities and the engines that ask from them (PROMPT-015d) are listed on+ * both sides: the web offers them (web/src/config/cities.ts, the location+ * picker), the API runs them. A city or an engine on one side only would be+ * offered and never run, or run and never offered; these tests keep them+ * together.+ */++const read = (path) => readFileSync(new URL(`../../../${path}`, import.meta.url), 'utf8');+const quoted = (list) => [...list.matchAll(/'([^']+)'/g)].map((m) => m[1]);++describe('cities on both sides (PROMPT-015d)', () => {+ it('lists the same cities, in the same order, as the web', () => {+ const web = [+ ...read('web/src/config/cities.ts').matchAll(/country:\s*'([A-Z]{2})',\s*id:\s*'([A-Z_]+)'/g),+ ].map((m) => `${m[1]}~${m[2]}`);+ expect(web.length).toBeGreaterThan(40);+ expect(CITIES.map((c) => `${c.country}~${c.id}`)).toEqual(web);+ for (const code of web) expect(cityFor(code)?.google).toBeTruthy();+ });++ it("asks Google from Türkiye's cities as Turkiye", () => {+ const turkiye = CITIES.filter((c) => c.country === 'TR');+ expect(turkiye.length).toBeGreaterThan(0);+ for (const city of turkiye) expect(city.google).toMatch(/,Turkiye$/);+ });++ it('runs a city on the engines the web says ask from one', () => {+ const web = read('web/src/config/cities.ts').match(+ /CITY_PLATFORMS[^=]*=\s*new Set\(\[([^\]]*)\]\)/,+ );+ expect(web).not.toBeNull();+ expect([...CITY_SCRAPERS].sort()).toEqual(quoted(web[1]).sort());+ });++ it('runs country-wide the engines the location picker says have no states', () => {+ const web = read('web/src/components/dashboard/location-picker.tsx').match(+ /COUNTRY_ONLY_PLATFORMS\s*=\s*new Set\(\[([^\]]*)\]\)/,+ );+ expect(web).not.toBeNull();+ expect([...COUNTRY_ONLY_SCRAPERS].sort()).toEqual(quoted(web[1]).sort());+ });+});diff --git a/server/src/lib/cloro-scraper.js b/server/src/lib/cloro-scraper.jsindex 9a7f59e46..5544e3d99 100644--- a/server/src/lib/cloro-scraper.js+++ b/server/src/lib/cloro-scraper.js@@ -32,8 +32,11 @@ function getApiKey() {return key;}-export function buildRequestBody(promptText, scraperId, region, state) {+export function buildRequestBody(promptText, scraperId, region, state, location) {const country = region || 'US';+ // A city (PROMPT-015d): Google's canonical name, which the Google+ // endpoints take as `location` beside the country. Only they get it.+ const locationField = location ? { location } : {};// State-level geo-targeting (#554): the AI endpoints accept a USPS state// code alongside country US and route through an in-state proxy. Google@@ -62,6 +65,7 @@ export function buildRequestBody(promptText, scraperId, region, state) {return {query: promptText,country,+ ...locationField,include: {html: false,aioverview: { markdown: true },@@ -73,6 +77,7 @@ export function buildRequestBody(promptText, scraperId, region, state) {return {prompt: promptText,country,+ ...locationField,include: {html: false,markdown: true,@@ -259,19 +264,26 @@ export function parseScraperResponse(result, scraperId) {* @param {string} promptText* @param {string} scraperId* @param {string} [region]- * @param {{ webhookUrl?: string, state?: string }} [opts] - `state` is the+ * @param {{ webhookUrl?: string, state?: string, location?: string }} [opts] - `state` is the* USPS code of the location this task targets (#554, per-prompt since- * #691); only forwarded on US AI-endpoint tasks.+ * #691); only forwarded on US AI-endpoint tasks. `location` is a city's+ * Google canonical name (PROMPT-015d), forwarded on Google tasks only.* @returns {Promise<{ taskId: string, scraperId: string }>}*/export async function submitScraperTask(promptText, scraperId, region, opts = {}) {const taskType = SCRAPER_TASK_TYPES[scraperId];if (!taskType) throw new Error(`Unknown scraper: ${scraperId}`);- const payload = buildRequestBody(promptText, scraperId, region, opts.state);+ const payload = buildRequestBody(promptText, scraperId, region, opts.state, opts.location);logger.info(- { taskType, scraperId, region: region || 'US', state: payload.state },+ {+ taskType,+ scraperId,+ region: region || 'US',+ state: payload.state,+ location: payload.location,+ },'submitting cloro scraper task',);diff --git a/server/src/lib/cloro-scraper.test.js b/server/src/lib/cloro-scraper.test.jsindex 4d77ab833..9a7a0cfd0 100644--- a/server/src/lib/cloro-scraper.test.js+++ b/server/src/lib/cloro-scraper.test.js@@ -480,3 +480,24 @@ describe('cloro-scraper – buildRequestBody state targeting (#554)', () => {expect(buildRequestBody('p', 'chatgpt-web', null, 'NY').state).toBe('NY');});});++describe('cloro-scraper – buildRequestBody city targeting (PROMPT-015d)', () => {+ it("sends a city's Google name to the Google engines, beside the country", () => {+ const location = 'Istanbul,Istanbul,Turkiye';+ expect(buildRequestBody('p', 'google-aimode', 'TR', undefined, location)).toMatchObject({+ country: 'TR',+ location,+ });+ expect(buildRequestBody('p', 'google-aio', 'TR', undefined, location)).toMatchObject({+ country: 'TR',+ location,+ });+ expect(buildRequestBody('p', 'google-aio', 'TR')).not.toHaveProperty('location');+ });++ it('never sends it to the other engines', () => {+ expect(+ buildRequestBody('p', 'chatgpt-web', 'TR', undefined, 'Istanbul,Istanbul,Turkiye'),+ ).not.toHaveProperty('location');+ });+});diff --git a/server/src/lib/locations.js b/server/src/lib/locations.jsindex 7a5c4f0e3..b265ffb0c 100644--- a/server/src/lib/locations.js+++ b/server/src/lib/locations.js@@ -1,3 +1,5 @@+import { cityFor } from './cities.js';+/*** Tracking locations (#691).*@@ -74,20 +76,36 @@ export const US_STATE_NAMES = {* Scrapers with no sub-country targeting mechanism. Google AIO / AI Mode* locate through location/uule parameters Cloro's AI endpoints don't accept,* so a state code means nothing to them: they can only be run country-wide- * (#691, carried over from #554).+ * (#691, carried over from #554). The web's location picker lists the same+ * engines (cities.test.js keeps them together).*/-const COUNTRY_ONLY_SCRAPERS = new Set(['google-aio', 'google-aimode']);+export const COUNTRY_ONLY_SCRAPERS = new Set(['google-aio', 'google-aimode']);++/**+ * Scrapers that can ask from a city (PROMPT-015d): Google's, through the+ * provider's `location`. The others answer per country (or US state), so a+ * city code is skipped for them rather than run again country-wide. The+ * web's CITY_PLATFORMS is the same list (cities.test.js).+ */+export const CITY_SCRAPERS = new Set(['google-aio', 'google-aimode']);/*** Split a location code into what the providers actually take.* `US-CA` → `{ country: 'US', state: 'CA' }`; `DE` → `{ country: 'DE',- * state: null }`. Unparsable or empty input yields a null country, which the- * callers treat as "no targeting" — the same as a prompt with no regions.+ * state: null }`; `TR~ISTANBUL` → `{ country: 'TR', state: null, city }`+ * (cities.js; an unknown city reads as its country). Unparsable or empty+ * input yields a null country, which the callers treat as "no targeting" —+ * the same as a prompt with no regions.*/export function parseLocation(code) {if (typeof code !== 'string') return { country: null, state: null };const trimmed = code.trim().toUpperCase();if (!trimmed) return { country: null, state: null };+ if (trimmed.includes('~')) {+ const country = trimmed.split('~')[0];+ if (!/^[A-Z]{2}$/.test(country)) return { country: null, state: null };+ return { country, state: null, city: cityFor(trimmed) };+ }const [country, state] = trimmed.split('-');if (!/^[A-Z]{2}$/.test(country || '')) return { country: null, state: null };@@ -98,9 +116,27 @@ export function parseLocation(code) {return { country, state: null };}+/** True for a city code (`TR~ISTANBUL`). */+export function isCityCode(code) {+ return typeof code === 'string' && code.includes('~');+}++/**+ * True for a city code no city in cities.js names (PROMPT-015d): there is+ * nothing to ask from, and asking country-wide instead would record the+ * country's answers as the city's, so no engine runs it.+ */+export function isUnknownCity(code) {+ return isCityCode(code) && !cityFor(code);+}+/*** The locations one scraper should actually be run for.*+ * A city code (PROMPT-015d) is kept only for the engines that can ask from+ * a city (CITY_SCRAPERS) and dropped for the rest: they answer per country,+ * and the prompt's country, when tracked, already runs them.+ ** Every code a state-capable engine can use survives as-is. For the* country-only engines the list collapses to its distinct countries, so a* prompt targeting California and Texas submits ONE country-wide Google task@@ -110,12 +146,20 @@ export function parseLocation(code) {* Order is preserved so task submission stays deterministic.*/export function locationsForScraper(locations, scraperId) {- const list = Array.isArray(locations) && locations.length > 0 ? locations : [null];+ const given = locationsForModels(locations);+ // A city is run only by the engines that can ask from one (PROMPT-015d).+ const list = CITY_SCRAPERS.has(scraperId) ? given : given.filter((code) => !isCityCode(code));if (!COUNTRY_ONLY_SCRAPERS.has(scraperId)) return list;const seen = new Set();const collapsed = [];for (const code of list) {+ // A city is asked from the city itself; only states collapse to their country.+ if (isCityCode(code)) {+ if (!seen.has(code)) collapsed.push(code);+ seen.add(code);+ continue;+ }const { country } = parseLocation(code);const key = country ?? '';if (seen.has(key)) continue;@@ -125,6 +169,16 @@ export function locationsForScraper(locations, scraperId) {return collapsed;}+/**+ * The locations the API models are run for: every code, each read by+ * userLocationFor, but a city no list names (isUnknownCity). No locations+ * means one untargeted run; only unknown cities means none.+ */+export function locationsForModels(locations) {+ const given = Array.isArray(locations) && locations.length > 0 ? locations : [null];+ return given.filter((code) => !isUnknownCity(code));+}+/*** `user_location` for the API models' web-search tool, or null when the* prompt is untargeted. `region` carries the full state name because that is@@ -133,9 +187,14 @@ export function locationsForScraper(locations, scraperId) {* states existed, so untargeted and country-targeted runs are unchanged.*/export function userLocationFor(code) {- const { country, state } = parseLocation(code);+ const { country, state, city } = parseLocation(code);if (!country) return null;const location = { type: 'approximate', country };if (state) location.region = US_STATE_NAMES[state];+ // A city (PROMPT-015d): both providers take `city`, beside its region.+ if (city) {+ location.region = city.region;+ location.city = city.name;+ }return location;}diff --git a/server/src/lib/locations.test.js b/server/src/lib/locations.test.jsindex fbac27e4a..c5c8e4701 100644--- a/server/src/lib/locations.test.js+++ b/server/src/lib/locations.test.js@@ -1,5 +1,11 @@import { describe, it, expect } from 'vitest';-import { parseLocation, locationsForScraper, userLocationFor } from './locations.js';+import {+ isUnknownCity,+ locationsForModels,+ locationsForScraper,+ parseLocation,+ userLocationFor,+} from './locations.js';describe('parseLocation', () => {it('splits a US state code into country and state', () => {@@ -72,3 +78,50 @@ describe('userLocationFor', () => {expect(userLocationFor('')).toBeNull();});});++describe('cities (PROMPT-015d)', () => {+ it('reads a city code as its country and city, and an unknown city as its country', () => {+ expect(parseLocation('tr~istanbul')).toMatchObject({+ country: 'TR',+ state: null,+ city: { name: 'Istanbul', google: 'Istanbul,Istanbul,Turkiye' },+ });+ expect(parseLocation('TR~NOWHERE')).toEqual({ country: 'TR', state: null, city: null });+ expect(parseLocation('T1~ISTANBUL')).toEqual({ country: null, state: null });+ });++ it("runs a city only on Google's engines, and never twice", () => {+ const codes = ['TR', 'TR~ISTANBUL', 'TR~ANKARA'];+ expect(locationsForScraper(codes, 'chatgpt-web')).toEqual(['TR']);+ expect(locationsForScraper(codes, 'google-aimode')).toEqual(['TR', 'TR~ISTANBUL', 'TR~ANKARA']);+ expect(locationsForScraper(['US-CA', 'US~NEW_YORK'], 'google-aio')).toEqual([+ 'US',+ 'US~NEW_YORK',+ ]);+ // A prompt tracked only in cities: nothing for the engines that can't ask from one.+ expect(locationsForScraper(['TR~ISTANBUL'], 'perplexity-web')).toEqual([]);+ });++ it('runs a city no list names on no engine, rather than country-wide under its name', () => {+ expect(isUnknownCity('TR~NOWHERE')).toBe(true);+ expect(isUnknownCity('TR~ISTANBUL')).toBe(false);+ expect(isUnknownCity('TR')).toBe(false);+ const codes = ['TR~NOWHERE', 'TR~ISTANBUL'];+ expect(locationsForScraper(codes, 'google-aimode')).toEqual(['TR~ISTANBUL']);+ expect(locationsForScraper(['TR~NOWHERE'], 'google-aio')).toEqual([]);+ expect(locationsForModels(codes)).toEqual(['TR~ISTANBUL']);+ expect(locationsForModels(['TR~NOWHERE'])).toEqual([]);+ // No locations at all is still one untargeted run.+ expect(locationsForModels([])).toEqual([null]);+ expect(locationsForModels(['DE', 'US-CA'])).toEqual(['DE', 'US-CA']);+ });++ it('gives the API models the city and its region', () => {+ expect(userLocationFor('TR~ISTANBUL')).toEqual({+ type: 'approximate',+ country: 'TR',+ region: 'Istanbul',+ city: 'Istanbul',+ });+ });+});diff --git a/server/src/workers/tracking-worker.js b/server/src/workers/tracking-worker.jsindex 716a68629..b9d79d544 100644--- a/server/src/workers/tracking-worker.js+++ b/server/src/workers/tracking-worker.js@@ -14,7 +14,12 @@ import { refreshPromptClusters } from '../lib/prompt-clusters.js';import { refreshSitePages } from '../lib/site-pages.js';import { updateTargetUrlStats } from '../lib/target-url-stats.js';import { persistCitationRows } from '../lib/citation-rows.js';-import { parseLocation, locationsForScraper } from '../lib/locations.js';+import {+ isUnknownCity,+ locationsForModels,+ locationsForScraper,+ parseLocation,+} from '../lib/locations.js';import { settleTrackingRun } from '../lib/run-settlement.js';import logger from '../lib/logger.js';@@ -304,11 +309,20 @@ export async function processTrackingJob({ brandId, promptId, promptIds, source,const allowedPlatformsFor = (prompt) => runnablePlatforms(prompt.platforms, { shoppingEnabled });- // A prompt's tracked locations (#691): country codes and US state codes- // (`US-CA`) alike. No locations means one untargeted run, which is what an- // empty list has always meant here.+ // A prompt's tracked locations (#691): country codes, US state codes+ // (`US-CA`) and city codes (`TR~ISTANBUL`, PROMPT-015d) alike. No locations+ // means one untargeted run, which is what an empty list has always meant+ // here. locationsForScraper keeps a city only for Google's engines; the API+ // models take every code (userLocationFor). A city no list names is run by+ // neither: its answers would be the country's, recorded as the city's.const locationsFor = (prompt) =>prompt.regions && prompt.regions.length > 0 ? prompt.regions : [null];+ const unknownCities = [+ ...new Set(prompts.flatMap((prompt) => locationsFor(prompt).filter(isUnknownCity))),+ ];+ if (unknownCities.length > 0) {+ logger.warn({ brandId, codes: unknownCities }, 'skipping city codes no city list names');+ }// 4. Count total tasks: one per prompt × engine × location that engine can// actually run. Google AIO / AI Mode have no sub-country mechanism, so@@ -317,7 +331,7 @@ export async function processTrackingJob({ brandId, promptId, promptIds, source,let totalTasks = 0;for (const prompt of prompts) {const locations = locationsFor(prompt);- totalTasks += allowedModelsFor(prompt).length * locations.length;+ totalTasks += allowedModelsFor(prompt).length * locationsForModels(locations).length;for (const scraperId of allowedPlatformsFor(prompt)) {totalTasks += locationsForScraper(locations, scraperId).length;}@@ -394,10 +408,11 @@ export async function processTrackingJob({ brandId, promptId, promptIds, source,// brand's single state column (#691): different prompts can target// different places, and a brand-wide override would silently win// over them.- const { country, state } = parseLocation(t.region);+ const { country, state, city } = parseLocation(t.region);return submitScraperTask(t.prompt.text, t.scraperId, country, {webhookUrl,state,+ location: city?.google,}).then((res) => ({...res,meta: t,@@ -774,7 +789,7 @@ export async function processTrackingJob({ brandId, promptId, promptIds, source,const locations = locationsFor(prompt);for (const modelName of modelsToRun) {- for (const region of locations) {+ for (const region of locationsForModels(locations)) {modelTasks.push({ prompt, modelName, region });}}diff --git a/web/messages/en.json b/web/messages/en.jsonindex dfea06b4e..c9cde10e2 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -7473,6 +7473,8 @@"state": "US state","city": "City"},+ "cityEngines": "AI Mode · AIO · APIs",+ "cityEnginesTip": "Google AI Mode, AI Overview and the API models answer from this city. ChatGPT, Perplexity, Copilot, Gemini and Grok answer per country.","weakest": "Weakest location","weakestBody": "Visibility, against {overall} across all locations · {untracked, plural, =0 {every prompt tracked there} one {# prompt not tracked there} other {# prompts not tracked there}}","strongest": "Strongest location",@@ -7506,6 +7508,8 @@"over": "This needs {adding, plural, one {# more tracked location} other {# more tracked locations}}; {left, plural, =0 {none are} one {# is} other {# are}} left on your {plan} plan.","overHint": "Pick fewer prompts or places. {plan, select, starter {Or upgrade your plan, or contact us for a custom plan.} growth {Or contact us for a custom plan.} other {Or contact us to raise your limit.}}","nothing": "These prompts are already tracked in these locations.",+ "cityBlocked": "None of these prompts runs an engine that answers from a city (Google AI Mode, AI Overview or an API model). Add one of those engines to the prompts first.",+ "cityPartly": "{count, plural, one {# of these prompts doesn't} other {# of these prompts don't}} run an engine that answers from a city; a city counts on the plan for them but isn't asked there.","noPrompts": "Choose the prompts to add these locations to.","cancel": "Cancel","submit": "Track in {count, plural, =0 {these locations} one {# location} other {# locations}}",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.tsxindex dd408a2a1..ed0066cb1 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@@ -90,7 +90,7 @@ describe('AddLocationsDialog', () => {it("opens on a cell's prompt and location, prices it, and tracks it there", async () => {const text = await render({ promptId: 'p2', locations: ['TR'] });expect(text).toContain('Track in more locations');- expect(text).toContain('Turkey');+ expect(text).toContain('Türkiye');expect(text).toContain('152 → 153 of 200 tracked locations');expect(scope('prompt p2').checked).toBe(true);await act(async () => submit().click());@@ -153,6 +153,21 @@ describe('AddLocationsDialog', () => {expect(document.body.querySelector('a[href="/dashboard/settings?tab=billing"]')).not.toBeNull();});+ it('turns a city off for prompts no engine of which answers from one (PROMPT-015d)', async () => {+ let text = await render({ locations: ['TR~ISTANBUL'] });+ expect(text).toContain('İstanbul');+ expect(text).toContain('None of these prompts runs an engine that answers from a city');+ expect(submit().disabled).toBe(true);+ // One prompt asks Google AI Mode: the city can be added, with a note for the rest.+ prompts[0] = { ...prompts[0], platforms: ['google-aimode'] } as Prompt;+ act(() => root.unmount());+ root = createRoot(container);+ text = await render({ locations: ['TR~ISTANBUL'] });+ expect(text).toContain("2 of these prompts don't run an engine that answers from a city");+ expect(submit().disabled).toBe(false);+ prompts[0] = prompt('p1', ['US']);+ });+it("says what the server refused, and changes nothing it didn't save", async () => {actions.bulkUpdatePromptLocations.mockResolvedValue({error: 'Your Growth plan allows up to 200 active prompt locations',diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.tsxindex ee0bb27ec..241e2f1c3 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_add-locations-dialog.tsx@@ -20,6 +20,8 @@ import {type LocationQuota,} from '@/lib/actions/prompt';import { planBulkLocationChange } from '@/lib/prompt-locations';+import { CITY_PLATFORMS } from '@/config/cities';+import { parseLocation } from '@/lib/region';import { cn } from '@/lib/utils';import type { Prompt } from '@/types';import { PromptLimitActions } from './_prompt-limit-actions';@@ -109,6 +111,12 @@ export function AddLocationsDialog({'add',locations,);+ // A city is asked only by Google's engines and the API models (PROMPT-015d).+ const askingCity = locations.some((code) => parseLocation(code)?.city);+ const asksFromCity = (p: Prompt) =>+ (p.platforms ?? []).some((id) => CITY_PLATFORMS.has(id)) || (p.models?.length ?? 0) > 0;+ const noCityEngine = askingCity ? targets.filter((p) => !asksFromCity(p)).length : 0;+ const cityBlocked = askingCity && targets.length > 0 && noCityEngine === targets.length;const unlimited = quota === null || quota.maxPrompts === -1;const after = (quota?.used ?? 0) + change.delta;const over = !unlimited && quota !== null && after > quota.maxPrompts;@@ -255,6 +263,14 @@ export function AddLocationsDialog({</div></div>)}+ {noCityEngine > 0 && (+ <p+ role={cityBlocked ? 'alert' : undefined}+ className="rounded-lg border bg-muted/40 p-3 text-xs text-muted-foreground"+ >+ {cityBlocked ? t('cityBlocked') : t('cityPartly', { count: noCityEngine })}+ </p>+ )}{targets.length === 0 ? (<p className="text-xs text-muted-foreground">{t('noPrompts')}</p>) : (@@ -275,7 +291,9 @@ export function AddLocationsDialog({</Button><ButtononClick={() => void save()}- disabled={saving || over || targets.length === 0 || change.changes.length === 0}+ disabled={+ saving || over || cityBlocked || targets.length === 0 || change.changes.length === 0+ }>{saving && <Loader2 className="animate-spin" />}{t('submit', { count: locations.length })}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_columns-panel.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_columns-panel.test.tsxindex fc074c9f5..6540ff7ad 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_columns-panel.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_columns-panel.test.tsx@@ -147,9 +147,9 @@ describe('ColumnsPanel', () => {const add = [...document.querySelectorAll('button')].find((b) => b.textContent === 'Add')!;await act(async () => add.click());expect(views.mine?.order.at(-1)).toBe('loc:position:TR');- expect(item('Position · Turkey')).toBeDefined();+ expect(item('Position · Türkiye')).toBeDefined();const remove = document.querySelector(- 'button[aria-label="Remove Position · Turkey"]',+ 'button[aria-label="Remove Position · Türkiye"]',) as HTMLButtonElement;await act(async () => remove.click());expect(views.mine?.order).not.toContain('loc:position:TR');diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.test.tsxindex 42e16fca0..67039471f 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.test.tsx@@ -88,7 +88,7 @@ describe('LocationMatrix', () => {regions: ['US', 'TR'],});expect(text).toContain('United States');- expect(text).toContain('Turkey');+ expect(text).toContain('Türkiye');expect(bodyRows()).toEqual([['All prompts · average', '—', '41', '35', '—'],['best specialty coffee subscription', 'Coffee', '62', '35', '27'],@@ -98,6 +98,18 @@ describe('LocationMatrix', () => {expect(text).toContain('Biggest gap between locations');});+ it('marks a city column with the engines that answer from it (PROMPT-015d)', async () => {+ rows[0] = prompt('p1', 'best specialty coffee subscription', ['US', 'TR', 'TR~ISTANBUL']);+ getPromptLocationMatrix.mockResolvedValue({+ p1: { US: cell(62), TR: cell(35), 'TR~ISTANBUL': cell(41) },+ });+ const text = await render();+ expect(text).toContain('İstanbul');+ expect(text).toContain('City');+ expect(text).toContain('AI Mode · AIO · APIs');+ rows[0] = prompt('p1', 'best specialty coffee subscription', ['US', 'TR']);+ });+it('switches the metric, and reads a prompt never named there as such', async () => {await render();const position = [...container.querySelectorAll('button')].find(@@ -118,13 +130,13 @@ describe('LocationMatrix', () => {await render();(container.querySelector(- 'button[aria-label="best specialty coffee subscription in Turkey: open its positions"]',+ 'button[aria-label="best specialty coffee subscription in Türkiye: open its positions"]',) as HTMLButtonElement).click();expect(onOpenCell).toHaveBeenCalledWith('p1', 'TR');(container.querySelector(- 'button[aria-label="Track “same day coffee delivery near me” in Turkey"]',+ 'button[aria-label="Track “same day coffee delivery near me” in Türkiye"]',) as HTMLButtonElement).click();expect(onTrack).toHaveBeenCalledWith(rows[1], 'TR');diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsxindex 571d88f58..d1760e023 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsx@@ -113,7 +113,7 @@ export function clearLocationMatrixCache() {/** A location's kind, for its column's second line. */function locationKind(code: string): 'country' | 'state' | 'city' {const parsed = parseLocation(code);- return parsed?.state ? 'state' : 'country';+ return parsed?.city ? 'city' : parsed?.state ? 'state' : 'country';}/**@@ -301,6 +301,14 @@ export function LocationMatrix({<span className="block text-[11px] font-normal text-muted-foreground">{t(`kind.${locationKind(r)}`)}</span>+ {locationKind(r) === 'city' && (+ <span+ className="mt-0.5 inline-block rounded-full bg-muted px-1.5 text-[10px] font-normal text-muted-foreground"+ title={t('cityEnginesTip')}+ >+ {t('cityEngines')}+ </span>+ )}</TableHead>))}<TableHead className="pr-6 text-right" title={t('gapTip')}>diff --git a/web/src/components/dashboard/location-picker.tsx b/web/src/components/dashboard/location-picker.tsxindex c4283975b..2205113e5 100644--- a/web/src/components/dashboard/location-picker.tsx+++ b/web/src/components/dashboard/location-picker.tsx@@ -3,8 +3,16 @@import { useMemo } from 'react';import { X } from 'lucide-react';+import { CITIES } from '@/config/cities';import { TRACKING_COUNTRIES, US_STATES } from '@/config/prompt-options';-import { formatRegionDisplay, locationCode, parseLocation } from '@/lib/region';+import {+ cityCode,+ formatRegionDisplay,+ locationCode,+ locationSearchText,+ parseLocation,+ regionLabel,+} from '@/lib/region';import { Badge } from '@/components/ui/badge';import {Combobox,@@ -78,7 +86,8 @@ export function LocationPicker({() => [...TRACKING_COUNTRIES.map((region) => ({value: region.code,- label: region.label,+ // Found by its other names too: "Turkey" or "Turkiye" finds Türkiye.+ label: locationSearchText(region.code),sublabel: 'Country',})),...US_STATES.map((state) => ({@@ -86,6 +95,14 @@ export function LocationPicker({label: state.label,sublabel: 'United States · state',})),+ // Cities (PROMPT-015d): asked by Google's engines and the API models.+ ...CITIES.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)}`,+ })),],[],);@@ -98,6 +115,7 @@ export function LocationPicker({const canRemove = allowEmpty || value.length > 1;const hasStatePick = value.some((code) => parseLocation(code)?.state);+ const hasCityPick = value.some((code) => parseLocation(code)?.city);const countryOnlyEngines = (platforms ?? []).filter((id) => COUNTRY_ONLY_PLATFORMS.has(id));const showCountryOnlyNote = hasStatePick && countryOnlyEngines.length > 0;@@ -125,7 +143,7 @@ export function LocationPicker({<Combobox items={options} value={null} onValueChange={add}><ComboboxTrigger className="w-full"><span className="truncate text-muted-foreground">- {atCap ? 'Plan limit reached' : 'Add a country or US state'}+ {atCap ? 'Plan limit reached' : 'Add a country, US state or city'}</span></ComboboxTrigger><ComboboxContent>@@ -171,6 +189,13 @@ export function LocationPicker({</div>)}+ {hasCityPick && (+ <p className="mt-1.5 text-[11px] text-muted-foreground">+ A city is asked by Google AI Mode, AI Overview and the API models. ChatGPT, Perplexity,+ Copilot, Gemini and Grok answer per country, so track the country too to see them.+ </p>+ )}+{showCountryOnlyNote && (<p className="mt-1.5 text-[11px] text-muted-foreground">Google AI Overviews and AI Mode have no state-level targeting — they run once per country,diff --git a/web/src/config/cities.ts b/web/src/config/cities.tsnew file mode 100644index 000000000..44476de6f--- /dev/null+++ b/web/src/config/cities.ts@@ -0,0 +1,63 @@+/**+ * Cities a prompt can be tracked in (PROMPT-015d): the location code+ * `<country>~<CITY>` (`TR~ISTANBUL`). Google AI Overview and AI Mode and the+ * API models ask from the city; the other engines answer per country, so+ * they skip it. The API keeps the same ids, with what the providers take,+ * in `server/src/lib/cities.js`; both lists change together.+ */+export const CITIES: readonly { country: string; id: string; label: string }[] = [+ { country: 'US', id: 'NEW_YORK', label: 'New York' },+ { country: 'US', id: 'LOS_ANGELES', label: 'Los Angeles' },+ { country: 'US', id: 'CHICAGO', label: 'Chicago' },+ { country: 'US', id: 'HOUSTON', label: 'Houston' },+ { country: 'US', id: 'SAN_FRANCISCO', label: 'San Francisco' },+ { country: 'US', id: 'MIAMI', label: 'Miami' },+ { country: 'US', id: 'SEATTLE', label: 'Seattle' },+ { country: 'US', id: 'BOSTON', label: 'Boston' },+ { country: 'US', id: 'AUSTIN', label: 'Austin' },+ { country: 'US', id: 'ATLANTA', label: 'Atlanta' },+ { country: 'GB', id: 'LONDON', label: 'London' },+ { country: 'GB', id: 'MANCHESTER', label: 'Manchester' },+ { country: 'GB', id: 'BIRMINGHAM', label: 'Birmingham' },+ { country: 'GB', id: 'EDINBURGH', label: 'Edinburgh' },+ { country: 'DE', id: 'BERLIN', label: 'Berlin' },+ { country: 'DE', id: 'MUNICH', label: 'Munich' },+ { country: 'DE', id: 'HAMBURG', label: 'Hamburg' },+ { country: 'DE', id: 'FRANKFURT', label: 'Frankfurt' },+ { country: 'DE', id: 'COLOGNE', label: 'Cologne' },+ { country: 'FR', id: 'PARIS', label: 'Paris' },+ { country: 'FR', id: 'LYON', label: 'Lyon' },+ { country: 'FR', id: 'MARSEILLE', label: 'Marseille' },+ { country: 'TR', id: 'ISTANBUL', label: 'İstanbul' },+ { country: 'TR', id: 'ANKARA', label: 'Ankara' },+ { country: 'TR', id: 'IZMIR', label: 'İzmir' },+ { country: 'TR', id: 'BURSA', label: 'Bursa' },+ { country: 'TR', id: 'ANTALYA', label: 'Antalya' },+ { country: 'JP', id: 'TOKYO', label: 'Tokyo' },+ { country: 'JP', id: 'OSAKA', label: 'Osaka' },+ { country: 'BR', id: 'SAO_PAULO', label: 'São Paulo' },+ { country: 'BR', id: 'RIO_DE_JANEIRO', label: 'Rio de Janeiro' },+ { country: 'IN', id: 'MUMBAI', label: 'Mumbai' },+ { country: 'IN', id: 'NEW_DELHI', label: 'New Delhi' },+ { country: 'IN', id: 'BENGALURU', label: 'Bengaluru' },+ { country: 'AU', id: 'SYDNEY', label: 'Sydney' },+ { country: 'AU', id: 'MELBOURNE', label: 'Melbourne' },+ { country: 'CA', id: 'TORONTO', label: 'Toronto' },+ { country: 'CA', id: 'VANCOUVER', label: 'Vancouver' },+ { country: 'CA', id: 'MONTREAL', label: 'Montréal' },+ { country: 'NL', id: 'AMSTERDAM', label: 'Amsterdam' },+ { country: 'NL', id: 'ROTTERDAM', label: 'Rotterdam' },+ { country: 'IT', id: 'ROME', label: 'Rome' },+ { country: 'IT', id: 'MILAN', label: 'Milan' },+ { country: 'ES', id: 'MADRID', label: 'Madrid' },+ { country: 'ES', id: 'BARCELONA', label: 'Barcelona' },+ { country: 'KR', id: 'SEOUL', label: 'Seoul' },+ { country: 'SE', id: 'STOCKHOLM', label: 'Stockholm' },+ { country: 'MX', id: 'MEXICO_CITY', label: 'Mexico City' },+ { country: 'SG', id: 'SINGAPORE', label: 'Singapore' },+ { country: 'AE', id: 'DUBAI', label: 'Dubai' },+ { country: 'AE', id: 'ABU_DHABI', label: 'Abu Dhabi' },+];++/** Engines that answer from a city (scrapers), beside the API models. */+export const CITY_PLATFORMS: ReadonlySet<string> = new Set(['google-aio', 'google-aimode']);diff --git a/web/src/config/prompt-options.ts b/web/src/config/prompt-options.tsindex f2f2ff8a4..0080ddcbe 100644--- a/web/src/config/prompt-options.ts+++ b/web/src/config/prompt-options.ts@@ -5,7 +5,7 @@ export const REGIONS = [{ code: 'GB', label: 'United Kingdom' },{ code: 'DE', label: 'Germany' },{ code: 'FR', label: 'France' },- { code: 'TR', label: 'Turkey' },+ { code: 'TR', label: 'Türkiye' },{ code: 'JP', label: 'Japan' },{ code: 'BR', label: 'Brazil' },{ code: 'IN', label: 'India' },diff --git a/web/src/lib/region.test.ts b/web/src/lib/region.test.tsindex 162a550a2..e1b8d786e 100644--- a/web/src/lib/region.test.ts+++ b/web/src/lib/region.test.ts@@ -1,9 +1,11 @@import { describe, expect, it } from 'vitest';import {+ cityCode,formatRegionDisplay,isValidLocation,locationCode,+ locationSearchText,parseLocation,regionFlag,regionLabel,@@ -66,6 +68,25 @@ describe('location codes', () => {expect(isValidLocation('ZZ')).toBe(false);});+ it('reads a city as its country and city, by its own name (PROMPT-015d)', () => {+ expect(parseLocation('tr~istanbul')).toEqual({ country: 'TR', state: null, city: 'ISTANBUL' });+ expect(isValidLocation('TR~ISTANBUL')).toBe(true);+ expect(isValidLocation('TR~NOWHERE')).toBe(false);+ expect(isValidLocation('DE~ISTANBUL')).toBe(false);+ expect(regionLabel('TR~ISTANBUL')).toBe('İstanbul');+ expect(regionFlag('TR~ISTANBUL')).toBe(regionFlag('TR'));+ expect(cityCode('tr', 'izmir')).toBe('TR~IZMIR');+ });++ 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');+ expect(locationSearchText('TR~IZMIR')).toBe('İzmir Izmir Türkiye Turkiye Turkey');+ expect(locationSearchText('BR~SAO_PAULO')).toBe('São Paulo Sao Paulo Brazil');+ expect(locationSearchText('DE')).toBe('Germany');+ expect(locationSearchText('US-CA')).toBe('California');+ });+it('takes the tracking countries beyond the brand regions (PROMPT-015c)', () => {expect(isValidLocation('PL')).toBe(true);expect(regionLabel('PL')).toBe('Poland');diff --git a/web/src/lib/region.ts b/web/src/lib/region.tsindex 6a8e7e3a0..6a77aa977 100644--- a/web/src/lib/region.ts+++ b/web/src/lib/region.ts@@ -1,11 +1,13 @@+import { CITIES } from '@/config/cities';import { TRACKING_COUNTRIES, US_STATES } from '@/config/prompt-options';/*** Tracking locations (#691).*- * A location code is either a bare ISO country (`DE`) or an ISO 3166-2 US- * state (`US-CA`). One code is one tracked location: one set of scraper and- * model calls, one plan-quota unit, one `prompt_results.region` value.+ * A location code is a bare ISO country (`DE`), an ISO 3166-2 US state+ * (`US-CA`) or a city (`TR~ISTANBUL`, PROMPT-015d). One code is one tracked+ * location: one set of scraper and model calls, one plan-quota unit, one+ * `prompt_results.region` value.** `server/src/lib/locations.js` keeps a deliberately identical parse — both* sides must agree on which codes are valid, or the picker would offer@@ -20,6 +22,10 @@ const STATE_LABELS: ReadonlyMap<string, string> = new Map(US_STATES.map((state) => [state.code, state.label]),);+const CITY_LABELS: ReadonlyMap<string, string> = new Map(+ CITIES.map((city) => [`${city.country}~${city.id}`, city.label]),+);+function normalizeRegionCode(code: string): string {return code.trim().toUpperCase();}@@ -28,6 +34,8 @@ export interface ParsedLocation {country: string;/** USPS code when the location targets a US state, else null. */state: string | null;+ /** The city's id when the location is a city (PROMPT-015d), else absent. */+ city?: string;}/**@@ -37,6 +45,10 @@ export interface ParsedLocation {*/export function parseLocation(code: string): ParsedLocation | null {const normalized = normalizeRegionCode(code);+ if (normalized.includes('~')) {+ const [country, city] = normalized.split('~');+ 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;if (state === undefined) return { country, state: null };@@ -49,6 +61,11 @@ export function isValidLocation(code: string): boolean {return parseLocation(code) !== null;}+/** The code for a city (PROMPT-015d): `TR~ISTANBUL`. */+export function cityCode(country: string, id: string): string {+ return `${normalizeRegionCode(country)}~${normalizeRegionCode(id)}`;+}+/** Build the code for a country, or for one of its states. */export function locationCode(country: string, state?: string | null): string {const normalizedCountry = normalizeRegionCode(country);@@ -64,6 +81,7 @@ export function locationCode(country: string, state?: string | null): string {export function regionLabel(code: string): string {const parsed = parseLocation(code);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;}@@ -84,3 +102,26 @@ export function formatRegionDisplay(code: string): string {const flag = regionFlag(code);return flag ? `${flag} ${label}` : label;}++/** A name without its accents and dots: İstanbul → Istanbul, Türkiye → Turkiye. */+function withoutMarks(name: string): string {+ return name.normalize('NFD').replace(/[\u0300-\u036f]/g, '');+}++/** Other names a country is searched by: Türkiye by its former English one. */+const COUNTRY_ALIASES: ReadonlyMap<string, readonly string[]> = new Map([['TR', ['Turkey']]]);++/**+ * What the location picker's search finds a code by: its name, the name+ * without its marks ("Ist" finds İstanbul, "Turkiye" Türkiye), a country's+ * other names, and for a city its country's too ("Turkey" finds İzmir).+ */+export function locationSearchText(code: string): string {+ const parsed = parseLocation(code);+ if (!parsed) return code.trim();+ const name = regionLabel(code);+ const names = [name, withoutMarks(name)];+ if (parsed.city) names.push(locationSearchText(parsed.country));+ else if (!parsed.state) names.push(...(COUNTRY_ALIASES.get(parsed.country) ?? []));+ return [...new Set(names)].join(' ');+}