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(prompts): say when a new location's first results come, and when the plan's locations are used up (PROMPT-015, part 6) (#1660)

Cihancfd8a353653b
diff --git a/docs/guides/prompts.mdx b/docs/guides/prompts.mdx
index 8062027d6..a48aedd32 100644
--- a/docs/guides/prompts.mdx
+++ b/docs/guides/prompts.mdx
@@ -75,6 +75,16 @@ If the choice would pass your plan's limit, the dialog says how many it needs an
- **Growth**: contact us for a custom plan;
- **Enterprise**: contact us to raise your limit.
+A location you just added has no answers yet. Until the next daily run asks it, its cells (in the Locations view and in a location column) say:
+
+- **Within 24h**: it's tracked there, and the first results come with the next daily run;
+- **Paused**: the prompt is paused, so it isn't asked anywhere until you resume it;
+- **No engine here**: none of the prompt's engines answers from that place; add an engine that does, or remove the location.
+
+**Within 24h** shows while the prompt is new (added in the last two days) or has answers in another location in the range. An older prompt with no answers anywhere in the range, such as days without a run, shows a dash.
+
+When your plan's prompt locations are used up, **+ Track** reads **Limit reached**. It still opens the dialog, which shows your plan's way to track more.
+
## Performance
The **Performance** filter groups prompts by where your brand is named in their AI answers over the selected range, across every platform the prompt tracks:
diff --git a/server/src/lib/cloro-countries.test.js b/server/src/lib/cloro-countries.test.js
index 4e2569041..e567c2cc0 100644
--- a/server/src/lib/cloro-countries.test.js
+++ b/server/src/lib/cloro-countries.test.js
@@ -7,7 +7,7 @@ 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 { CITY_SCRAPERS, COUNTRY_ONLY_SCRAPERS } from './locations.js';
import {
CLORO_COUNTRY_MODELS,
countryCodesIn,
@@ -220,6 +220,24 @@ describe('the provider models on both sides (PROMPT-015e)', () => {
expect(named.sort()).toEqual([...models].sort());
});
+ it("maps each engine to the provider's model as the API does", () => {
+ const mapped = web.match(/PLATFORM_MODELS[^=]*=\s*\{([^}]*)\}/);
+ expect(mapped).not.toBeNull();
+ const pairs = Object.fromEntries(
+ [...mapped[1].matchAll(/'([a-z-]+)':\s*'([a-z]+)'/g)].map((m) => [m[1], m[2]]),
+ );
+ expect(pairs).toEqual(CLORO_COUNTRY_MODELS);
+ });
+
+ it('leaves a US state to the models of the engines the API runs country-wide', () => {
+ const countryOnly = web.match(/COUNTRY_ONLY_MODELS[^=]*=\s*new Set\(\[([^\]]*)\]\)/);
+ expect(countryOnly).not.toBeNull();
+ const webModels = [...countryOnly[1].matchAll(/'([^']+)'/g)].map((m) => m[1]);
+ expect(webModels.sort()).toEqual(
+ [...new Set([...COUNTRY_ONLY_SCRAPERS].map((id) => CLORO_COUNTRY_MODELS[id]))].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();
diff --git a/web/messages/en.json b/web/messages/en.json
index c9cde10e2..42261d2f5 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -7467,7 +7467,16 @@
"trackLabel": "Track “{prompt}” in {location}",
"open": "{prompt} in {location}: open its positions",
"notNamed": "Not named",
- "noAnswers": "No answers in this location yet",
+ "noAnswers": "No answers here in this period",
+ "pending": "Within 24h",
+ "pendingTip": "Tracked in {location} from the next daily run: its first results come within 24 hours.",
+ "paused": "Paused",
+ "pausedTip": "This prompt is paused, so it isn't asked anywhere until you resume it.",
+ "noEngine": "No engine here",
+ "noEngineTip": "None of this prompt's engines answers from {location}, so nothing is asked there. Add an engine that does, or remove the location.",
+ "limit": "Limit reached",
+ "limitTip": "Your plan's prompt locations are used up ({used} of {max}). Open to see how to track here.",
+ "limitLabel": "Limit reached: “{prompt}” in {location}. Your plan's prompt locations are used up ({used} of {max}); open to see how to track here.",
"kind": {
"country": "Country",
"state": "US state",
@@ -7513,7 +7522,7 @@
"noPrompts": "Choose the prompts to add these locations to.",
"cancel": "Cancel",
"submit": "Track in {count, plural, =0 {these locations} one {# location} other {# locations}}",
- "done": "{count, plural, one {# prompt is} other {# prompts are}} now tracked in the new locations."
+ "done": "{count, plural, one {# prompt is} other {# prompts are}} now tracked in the new locations. The first results come with the next daily run, within 24 hours."
},
"performance": {
"label": "Performance",
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 0c6dda1b2..5c65b8b0b 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
@@ -97,7 +97,9 @@ describe('AddLocationsDialog', () => {
expect(scope('prompt p2').checked).toBe(true);
await act(async () => submit().click());
expect(actions.bulkUpdatePromptLocations).toHaveBeenCalledWith(['p2'], 'add', ['TR']);
- expect(toast.success).toHaveBeenCalledWith('1 prompt is now tracked in the new locations.');
+ expect(toast.success).toHaveBeenCalledWith(
+ '1 prompt is now tracked in the new locations. The first results come with the next daily run, within 24 hours.',
+ );
expect(onDone).toHaveBeenCalled();
});
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.tsx
index 67039471f..66c3965b4 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
@@ -7,8 +7,12 @@ import type { PromptLocationCell } from '@/lib/prompt-location-matrix';
import type { Prompt } from '@/types';
const getPromptLocationMatrix = vi.hoisted(() => vi.fn());
-vi.mock('@/lib/actions/prompt', () => ({ getPromptLocationMatrix }));
+const getLocationQuota = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/actions/prompt', () => ({ getPromptLocationMatrix, getLocationQuota }));
+const getTrackingCountries = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/actions/tracking-countries', () => ({ getTrackingCountries }));
+const { clearTrackingCountries } = await import('@/lib/use-tracking-countries');
const { LocationMatrix, clearLocationMatrixCache, loadLocationMatrix } =
await import('./_location-matrix');
@@ -21,8 +25,23 @@ const BRAND = '11111111-1111-1111-1111-111111111111';
let container: HTMLDivElement;
let root: Root;
-const prompt = (id: string, text: string, regions: string[], category = 'Coffee'): Prompt =>
- ({ id, text, regions, category }) as unknown as Prompt;
+const prompt = (
+ id: string,
+ text: string,
+ regions: string[],
+ category = 'Coffee',
+ over: Partial<Prompt> = {},
+): Prompt =>
+ ({
+ id,
+ text,
+ regions,
+ category,
+ isActive: true,
+ platforms: ['chatgpt-web'],
+ models: [],
+ ...over,
+ }) as unknown as Prompt;
const cell = (score: number, position: number | null = 3.2): PromptLocationCell => ({
score,
mentions: Math.round(score / 2),
@@ -56,13 +75,26 @@ async function render(canTrack = true) {
return container.textContent ?? '';
}
+/** Each row's cells as they show: without the text only screen readers get. */
const bodyRows = () =>
[...container.querySelectorAll('tbody tr')].map((tr) =>
- [...tr.querySelectorAll('td')].map((td) => td.textContent),
+ [...tr.querySelectorAll('td')].map((td) => {
+ const shown = td.cloneNode(true) as HTMLElement;
+ shown.querySelectorAll('.sr-only').forEach((el) => el.remove());
+ return shown.textContent;
+ }),
);
beforeEach(() => {
clearLocationMatrixCache();
+ clearTrackingCountries();
+ getLocationQuota.mockReset().mockResolvedValue({
+ maxPrompts: 200,
+ used: 152,
+ planId: 'growth',
+ planName: 'Growth',
+ });
+ getTrackingCountries.mockReset().mockResolvedValue([]);
getPromptLocationMatrix.mockReset().mockResolvedValue({
p1: { US: cell(62), TR: cell(35, null) },
p2: { US: cell(20, 6.4) },
@@ -164,6 +196,123 @@ describe('LocationMatrix', () => {
});
});
+describe('a location with no answers yet', () => {
+ async function renderRows(
+ list: Prompt[],
+ window: { from: string; to?: string } = { from: '2026-10-21T00:00:00Z' },
+ ) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <LocationMatrix
+ brandId={BRAND}
+ rows={list}
+ pageRows={list}
+ window={window}
+ onOpenCell={onOpenCell}
+ onTrack={onTrack}
+ />
+ </NextIntlClientProvider>,
+ );
+ });
+ }
+
+ it('says the next daily run asks it, within 24 hours', async () => {
+ getPromptLocationMatrix.mockResolvedValue({ p1: { US: cell(62) } });
+ await renderRows([prompt('p1', 'best specialty coffee subscription', ['US', 'TR'])]);
+ expect(bodyRows()[1]).toEqual([
+ 'best specialty coffee subscription',
+ 'Coffee',
+ // Locations sort by name: Türkiye (TR) before the US.
+ 'Within 24h',
+ '62',
+ '—',
+ ]);
+ // The reason reaches the keyboard and screen readers, not only the mouse.
+ const pending = [...container.querySelectorAll('button')].find(
+ (b) => b.textContent === 'Within 24h',
+ )!;
+ expect(document.getElementById(pending.getAttribute('aria-describedby')!)?.textContent).toBe(
+ 'Tracked in Türkiye from the next daily run: its first results come within 24 hours.',
+ );
+ });
+
+ it('waits only for a new prompt; an older one answered nowhere just had no run: a dash', async () => {
+ getPromptLocationMatrix.mockResolvedValue({});
+ const hourAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString();
+ await renderRows([
+ prompt('p1', 'older prompt', ['US', 'TR'], 'Coffee', { createdAt: '2026-09-01T00:00:00Z' }),
+ prompt('p2', 'new prompt', ['US', 'TR'], 'Coffee', { createdAt: hourAgo }),
+ ]);
+ const rows = bodyRows();
+ expect(rows[1].slice(2)).toEqual(['—', '—', '—']);
+ expect(container.querySelector('span[title="No answers here in this period"]')).not.toBeNull();
+ expect(rows[2].slice(2)).toEqual(['Within 24h', 'Within 24h', '—']);
+ });
+
+ it('shows a plain dash for a custom range that ended before today', async () => {
+ getPromptLocationMatrix.mockResolvedValue({ p1: { US: cell(62) } });
+ await renderRows([prompt('p1', 'best specialty coffee subscription', ['US', 'TR'])], {
+ from: '2026-09-01T00:00:00Z',
+ to: '2026-09-07T23:59:59Z',
+ });
+ expect(bodyRows()[1][2]).toBe('—');
+ expect(container.querySelector('span[title="No answers here in this period"]')).not.toBeNull();
+ });
+
+ it('says when the prompt is paused, or none of its engines answers from there (PROMPT-015e)', async () => {
+ getTrackingCountries.mockResolvedValue([
+ { code: 'US', models: ['chatgpt', 'copilot'] },
+ { code: 'KE', models: ['chatgpt'] },
+ ]);
+ getPromptLocationMatrix.mockResolvedValue({ p1: { US: cell(62) }, p2: { US: cell(40) } });
+ await renderRows([
+ prompt('p1', 'paused prompt', ['US', 'KE'], 'Coffee', { isActive: false }),
+ prompt('p2', 'copilot only', ['US', 'KE'], 'Coffee', { platforms: ['copilot-web'] }),
+ ]);
+ const rows = bodyRows();
+ // KE comes before US.
+ expect(rows[1][2]).toBe('Paused');
+ expect(rows[2][2]).toBe('No engine here');
+ const noEngine = [...container.querySelectorAll('button')].find(
+ (b) => b.textContent === 'No engine here',
+ )!;
+ expect(document.getElementById(noEngine.getAttribute('aria-describedby')!)?.textContent).toBe(
+ "None of this prompt's engines answers from Kenya, so nothing is asked there. Add an engine that does, or remove the location.",
+ );
+ });
+
+ it("says no engine answers from a US state when only Google's, run country-wide, would", async () => {
+ getTrackingCountries.mockResolvedValue([{ code: 'US', models: ['aimode', 'aioverview'] }]);
+ getPromptLocationMatrix.mockResolvedValue({ p1: { US: cell(62) } });
+ await renderRows([
+ prompt('p1', 'google only', ['US', 'US-CA'], 'Coffee', { platforms: ['google-aio'] }),
+ ]);
+ // US, then US-CA.
+ expect(bodyRows()[1].slice(2, 4)).toEqual(['62', 'No engine here']);
+ });
+
+ it('shows Limit reached instead of + Track once the plan’s locations are used up', async () => {
+ getLocationQuota.mockResolvedValue({
+ maxPrompts: 200,
+ used: 200,
+ planId: 'growth',
+ planName: 'Growth',
+ });
+ await render();
+ expect(container.textContent).not.toContain('+ Track');
+ const limit = container.querySelector(
+ 'button[aria-label="Limit reached: “same day coffee delivery near me” in Türkiye. Your plan\'s prompt locations are used up (200 of 200); open to see how to track here."]',
+ ) as HTMLButtonElement;
+ expect(limit.textContent).toBe('Limit reached');
+ expect(limit.title).toBe(
+ "Your plan's prompt locations are used up (200 of 200). Open to see how to track here.",
+ );
+ limit.click();
+ expect(onTrack).toHaveBeenCalledWith(rows[1], 'TR');
+ });
+});
+
describe('loadLocationMatrix', () => {
it('reads a location once a minute, and again after the cache is cleared', async () => {
const window = { from: '2026-10-21T00:00:00Z' };
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsx
index d1760e023..2015014c9 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsx
@@ -1,9 +1,11 @@
'use client';
-import { useEffect, useState } from 'react';
+import { useEffect, useId, useState } from 'react';
import { useTranslations } from 'next-intl';
+import { Clock, Lock } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import {
Table,
TableBody,
@@ -12,7 +14,11 @@ import {
TableHeader,
TableRow,
} from '@/components/ui/table';
-import { getPromptLocationMatrix } from '@/lib/actions/prompt';
+import {
+ getLocationQuota,
+ getPromptLocationMatrix,
+ type LocationQuota,
+} from '@/lib/actions/prompt';
import { formatNumber } from '@/lib/format';
import { createLimiter } from '@/lib/limiter';
import { HEAT_SHADES } from '@/lib/insights-topics';
@@ -28,8 +34,12 @@ import {
type LocationMetric,
type PromptLocationCell,
type PromptLocationMatrix,
+ awaitsFirstAnswers,
+ reachesToday,
} from '@/lib/prompt-location-matrix';
import { parseLocation, regionFlag, regionLabel } from '@/lib/region';
+import { answersFrom } from '@/lib/tracking-countries';
+import { useTrackingCountries } from '@/lib/use-tracking-countries';
import { cn } from '@/lib/utils';
import type { Prompt } from '@/types';
@@ -110,6 +120,84 @@ export function clearLocationMatrixCache() {
regionCache.clear();
}
+/**
+ * A location a prompt is tracked in that has no answers yet, and why: a
+ * paused prompt; none of its engines answering from there; or, usually,
+ * just added: the next daily run asks it, within 24 hours.
+ */
+export function LocationPending({
+ prompt,
+ region,
+ window,
+ awaiting,
+ className,
+}: {
+ prompt: Pick<Prompt, 'isActive' | 'platforms' | 'models'>;
+ region: string;
+ /** The table's window: one that ended before today just had no answers there. */
+ window: { to?: string };
+ /**
+ * Whether its first answers can still be on their way (awaitsFirstAnswers).
+ * If not, an active prompt just had none there in this window: a dash.
+ */
+ awaiting: boolean;
+ className?: string;
+}) {
+ const t = useTranslations('prompts.locations');
+ const countries = useTrackingCountries();
+ const tipId = useId();
+ const parsed = parseLocation(region);
+ const state = !reachesToday(window)
+ ? null
+ : !prompt.isActive
+ ? 'paused'
+ : parsed && !answersFrom(prompt, parsed, countries)
+ ? 'noEngine'
+ : awaiting
+ ? 'pending'
+ : null;
+ if (!state) {
+ return (
+ <span className={cn('text-xs text-muted-foreground', className)} title={t('noAnswers')}>
+ —
+ </span>
+ );
+ }
+ const tip = t(`${state}Tip`, { location: regionLabel(region) });
+ // Why, on hover and on keyboard focus; and for a screen reader, as the
+ // label's description.
+ return (
+ <>
+ <Tooltip>
+ <TooltipTrigger
+ delay={300}
+ closeDelay={0}
+ render={
+ <button
+ type="button"
+ aria-describedby={tipId}
+ className={cn(
+ 'inline-flex cursor-help items-center justify-center gap-1 rounded-md text-[11px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50',
+ state === 'noEngine'
+ ? 'text-amber-700 dark:text-amber-400'
+ : 'text-muted-foreground',
+ className,
+ )}
+ />
+ }
+ >
+ {state === 'pending' && <Clock className="h-3 w-3" aria-hidden />}
+ {t(state)}
+ </TooltipTrigger>
+ <TooltipContent className="max-w-72">{tip}</TooltipContent>
+ </Tooltip>
+ <span id={tipId} className="sr-only">
+ {tip}
+ </span>
+ </>
+ );
+}
+
/** A location's kind, for its column's second line. */
function locationKind(code: string): 'country' | 'state' | 'city' {
const parsed = parseLocation(code);
@@ -151,6 +239,24 @@ export function LocationMatrix({
const allRegions = matrixLocations(rows);
const regions = allRegions.slice(0, MATRIX_REGIONS);
const key = matrixKey(brandId, window, regions);
+ // The plan's prompt locations, so + Track says when they're used up.
+ const [quota, setQuota] = useState<LocationQuota | null>(null);
+ // Read again when the brand's tracked locations change, not on every render.
+ const canTrack = Boolean(onTrack);
+ const tracked = rows.reduce((n, p) => n + (p.isActive ? p.regions.length : 0), 0);
+ useEffect(() => {
+ if (!canTrack) return;
+ let cancelled = false;
+ getLocationQuota(brandId)
+ .then((q) => {
+ if (!cancelled) setQuota(q);
+ })
+ .catch((err) => console.error('Failed to read the plan usage:', err));
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId, canTrack, tracked]);
+ const limitReached = quota !== null && quota.maxPrompts !== -1 && quota.used >= quota.maxPrompts;
const [read, setRead] = useState<{ key: string; matrix: PromptLocationMatrix | 'failed' } | null>(
null,
);
@@ -337,6 +443,12 @@ export function LocationMatrix({
{pageRows.map((p) => {
const values = valuesOf(p);
const gap = rowGap(values);
+ // Its empty locations wait for their first answers only while it's
+ // new, or answered elsewhere (a location just added).
+ const awaiting = awaitsFirstAnswers(
+ p,
+ Object.values(matrix[p.id] ?? {}).some((c) => c.runs > 0),
+ );
return (
<TableRow key={p.id}>
<TableCell className="max-w-[320px] pl-6 text-sm font-medium">
@@ -356,7 +468,24 @@ export function LocationMatrix({
if (!p.regions.includes(r)) {
return (
<TableCell key={r} className="px-1 py-1.5">
- {onTrack ? (
+ {onTrack && limitReached ? (
+ // The plan's locations are used up: the dialog says how to get more.
+ <button
+ type="button"
+ aria-label={t('limitLabel', {
+ prompt: p.text,
+ location: where,
+ used: quota!.used,
+ max: quota!.maxPrompts,
+ })}
+ title={t('limitTip', { used: quota!.used, max: quota!.maxPrompts })}
+ onClick={() => onTrack(p, r)}
+ className="flex w-full items-center justify-center gap-1 rounded-md border border-dashed py-1.5 text-[11px] text-amber-700 transition-colors hover:border-amber-500/60 dark:text-amber-400"
+ >
+ <Lock className="h-3 w-3" aria-hidden />
+ {t('limit')}
+ </button>
+ ) : onTrack ? (
<button
type="button"
aria-label={t('trackLabel', { prompt: p.text, location: where })}
@@ -373,13 +502,14 @@ export function LocationMatrix({
}
if (!cell || cell.runs === 0) {
return (
- <TableCell key={r} className="px-1 py-1.5">
- <span
- className="block text-center text-xs text-muted-foreground"
- title={t('noAnswers')}
- >
- —
- </span>
+ <TableCell key={r} className="px-1 py-1.5 text-center">
+ <LocationPending
+ prompt={p}
+ region={r}
+ window={window}
+ awaiting={awaiting}
+ className="w-full py-1.5"
+ />
</TableCell>
);
}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index 11da985a5..85a6b47b3 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -199,7 +199,12 @@ import {
import { BulkActionBar } from './_bulk-action-bar';
import { ColumnsPanel } from './_columns-panel';
import { PromptLimitActions } from './_prompt-limit-actions';
-import { LocationMatrix, clearLocationMatrixCache, loadLocationMatrix } from './_location-matrix';
+import {
+ LocationMatrix,
+ LocationPending,
+ clearLocationMatrixCache,
+ loadLocationMatrix,
+} from './_location-matrix';
import { AddLocationsDialog, type AddLocationsPreset } from './_add-locations-dialog';
import { getPromptTableViews, type PromptTableViews } from '@/lib/actions/prompt-table-views';
import {
@@ -209,6 +214,7 @@ import {
type PromptColumnId,
} from '@/lib/prompt-table-columns';
import {
+ awaitsFirstAnswers,
matrixLocations,
metricValue,
type PromptLocationMatrix,
@@ -3997,6 +4003,14 @@ function AllPromptsTab({
const vol = volumeByPromptId.get(p.id);
const vis = visibility[p.id];
const status = promptStatus(p, now);
+ // Its empty location columns wait for their first answers only
+ // while it's new, or answered elsewhere (a location just added).
+ const awaiting = awaitsFirstAnswers(
+ p,
+ Boolean(vis) ||
+ Object.values(locationMatrix?.[p.id] ?? {}).some((c) => c.runs > 0),
+ now,
+ );
const cells: Record<PromptColumnId, React.ReactNode> = {
topic: (
<TableCell key="topic">
@@ -4211,13 +4225,27 @@ function AllPromptsTab({
{columns.map((id) => {
const loc = parseLocationColumn(id);
if (!loc) return cells[id as PromptColumnId];
- const value = metricValue(locationMatrix?.[p.id]?.[loc.region], loc.metric);
+ const located = locationMatrix?.[p.id]?.[loc.region];
+ const value = metricValue(located, loc.metric);
+ // Tracked there, no answers yet: when they'll come, or why not.
+ const pending =
+ locationMatrix !== null &&
+ p.regions.includes(loc.region) &&
+ (!located || located.runs === 0);
return (
<TableCell
key={id}
className="bg-muted/20 text-right text-sm font-semibold tabular-nums"
>
- {value === null ? (
+ {pending ? (
+ <LocationPending
+ prompt={p}
+ region={loc.region}
+ window={positionsWindow}
+ awaiting={awaiting}
+ className="font-normal"
+ />
+ ) : value === null ? (
<span className="text-xs font-normal text-muted-foreground">—</span>
) : loc.metric === 'position' ? (
`#${value.toFixed(1)}`
diff --git a/web/src/components/dashboard/location-picker.test.tsx b/web/src/components/dashboard/location-picker.test.tsx
index 2041089a9..f1be711e9 100644
--- a/web/src/components/dashboard/location-picker.test.tsx
+++ b/web/src/components/dashboard/location-picker.test.tsx
@@ -46,7 +46,7 @@ describe('LocationPicker', () => {
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.
+ // No Google engine in Germany: its cities aren't offered; Türkiye's are.
expect(text).toContain('İstanbul');
expect(text).not.toContain('Berlin');
// A brand region no engine answers from isn't offered.
diff --git a/web/src/components/dashboard/location-picker.tsx b/web/src/components/dashboard/location-picker.tsx
index cd5055030..7a0b85e59 100644
--- a/web/src/components/dashboard/location-picker.tsx
+++ b/web/src/components/dashboard/location-picker.tsx
@@ -1,6 +1,6 @@
'use client';
-import { useEffect, useMemo, useState } from 'react';
+import { useMemo } from 'react';
import { X } from 'lucide-react';
import { CITIES } from '@/config/cities';
@@ -13,14 +13,8 @@ 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 { useTrackingCountries } from '@/lib/use-tracking-countries';
+import { CITY_MODELS, ENGINE_LABELS, countryName, missingEngines } from '@/lib/tracking-countries';
import { Badge } from '@/components/ui/badge';
import {
Combobox,
@@ -64,28 +58,6 @@ 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);
diff --git a/web/src/lib/prompt-location-matrix.test.ts b/web/src/lib/prompt-location-matrix.test.ts
index cc047ae56..198ff9bc6 100644
--- a/web/src/lib/prompt-location-matrix.test.ts
+++ b/web/src/lib/prompt-location-matrix.test.ts
@@ -1,5 +1,8 @@
import { describe, expect, it } from 'vitest';
+import { endOfDayIn } from '@/lib/time-zone';
import {
+ awaitsFirstAnswers,
+ reachesToday,
cellShade,
locationAverages,
matrixInsights,
@@ -93,3 +96,45 @@ describe('matrixInsights', () => {
});
});
});
+
+describe('reachesToday', () => {
+ const now = Date.parse('2026-10-28T12:00:00Z');
+ it('holds for a preset, and a custom range that ends today', () => {
+ expect(reachesToday({}, now, 'UTC')).toBe(true);
+ expect(reachesToday({ to: '2026-10-28T23:59:59.999Z' }, now, 'UTC')).toBe(true);
+ });
+ it("doesn't for a range that ended before", () => {
+ expect(reachesToday({ to: '2026-10-20T23:59:59Z' }, now, 'UTC')).toBe(false);
+ });
+ it("doesn't for a range that ended yesterday, on the viewer's clock", () => {
+ // Yesterday's last moment in Istanbul is less than a day ago.
+ const yesterday = endOfDayIn('2026-10-27', 'Europe/Istanbul');
+ expect(reachesToday({ to: yesterday }, now, 'Europe/Istanbul')).toBe(false);
+ expect(
+ reachesToday({ to: endOfDayIn('2026-10-28', 'Europe/Istanbul') }, now, 'Europe/Istanbul'),
+ ).toBe(true);
+ // Past 21:00 UTC it is already the 29th in Istanbul, still the 28th in New York.
+ const late = Date.parse('2026-10-28T22:30:00Z');
+ expect(
+ reachesToday({ to: endOfDayIn('2026-10-28', 'Europe/Istanbul') }, late, 'Europe/Istanbul'),
+ ).toBe(false);
+ expect(
+ reachesToday({ to: endOfDayIn('2026-10-28', 'America/New_York') }, late, 'America/New_York'),
+ ).toBe(true);
+ });
+});
+
+describe('awaitsFirstAnswers', () => {
+ const now = Date.parse('2026-10-28T12:00:00Z');
+ it('waits for a prompt added within two days, answered nowhere yet', () => {
+ expect(awaitsFirstAnswers({ createdAt: '2026-10-28T09:00:00Z' }, false, now)).toBe(true);
+ expect(awaitsFirstAnswers({ createdAt: '2026-10-26T12:00:01Z' }, false, now)).toBe(true);
+ });
+ it("doesn't for an older one answered nowhere in the window: a dash", () => {
+ expect(awaitsFirstAnswers({ createdAt: '2026-10-26T12:00:00Z' }, false, now)).toBe(false);
+ expect(awaitsFirstAnswers({ createdAt: '2026-09-01T00:00:00Z' }, false, now)).toBe(false);
+ });
+ it('waits at a place with no answers when the prompt has some elsewhere (just added)', () => {
+ expect(awaitsFirstAnswers({ createdAt: '2026-09-01T00:00:00Z' }, true, now)).toBe(true);
+ });
+});
diff --git a/web/src/lib/prompt-location-matrix.ts b/web/src/lib/prompt-location-matrix.ts
index 783f6ec68..d437d1528 100644
--- a/web/src/lib/prompt-location-matrix.ts
+++ b/web/src/lib/prompt-location-matrix.ts
@@ -1,4 +1,5 @@
import { heatShade } from '@/lib/insights-topics';
+import { dayIn, startOfDayIn, viewerTimeZone } from '@/lib/time-zone';
/**
* The Tracked Prompts Locations view (PROMPT-015b): each tracked prompt in
@@ -35,6 +36,43 @@ export const MATRIX_REGIONS = 12;
/** The matrix's database reads running at once, at most: each is a heavy aggregate. */
export const MATRIX_READS_AT_ONCE = 3;
+/**
+ * Whether a window runs up to today on the viewer's clock, so a location
+ * with no answers in it can still get them from the next daily run. A
+ * custom range that ended earlier, yesterday included, can't.
+ */
+export function reachesToday(
+ window: { to?: string },
+ now = Date.now(),
+ timeZone = viewerTimeZone(),
+): boolean {
+ if (!window.to) return true;
+ return Date.parse(window.to) >= Date.parse(startOfDayIn(dayIn(now, timeZone), timeZone));
+}
+
+/**
+ * How long after it's added a prompt can still be waiting for its first
+ * answers: the next daily run comes within a day, and a second day spares
+ * a slow run.
+ */
+export const FIRST_ANSWERS_MS = 48 * 60 * 60 * 1000;
+
+/**
+ * Whether a place an active prompt is tracked in, with no answers there in
+ * a window reaching today, can still get its first ones from the next
+ * daily run ("Within 24h"): the prompt was added within FIRST_ANSWERS_MS,
+ * or it has answers elsewhere in the window, so the place was most likely
+ * just added. An older prompt with answers nowhere just had none in this
+ * window, a range without a run or a failed one: a dash.
+ */
+export function awaitsFirstAnswers(
+ prompt: { createdAt: string },
+ answeredElsewhere: boolean,
+ now = Date.now(),
+): boolean {
+ return answeredElsewhere || now - Date.parse(prompt.createdAt) < FIRST_ANSWERS_MS;
+}
+
/** A cell's value for the metric; null without answers there (or, for position, never named). */
export function metricValue(
cell: PromptLocationCell | undefined,
diff --git a/web/src/lib/tracking-countries.test.ts b/web/src/lib/tracking-countries.test.ts
index 349ffec1c..3c6e5251f 100644
--- a/web/src/lib/tracking-countries.test.ts
+++ b/web/src/lib/tracking-countries.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { countryName, isCountryCode, missingEngines } from './tracking-countries';
+import { answersFrom, countryName, isCountryCode, missingEngines } from './tracking-countries';
/** The countries the tracking engines answer from (PROMPT-015e). */
@@ -24,3 +24,56 @@ describe('missingEngines', () => {
expect(missingEngines(all[0], all)).toEqual([]);
});
});
+
+describe('answersFrom', () => {
+ const countries = [
+ { code: 'TR', models: ['chatgpt', 'copilot', 'aimode'] },
+ { code: 'KE', models: ['chatgpt', 'aimode'] },
+ { code: 'US', models: ['chatgpt', 'copilot', 'aimode', 'aioverview'] },
+ ];
+ const country = (code: string) => ({ country: code, state: null });
+
+ it("says whether any of the prompt's engines answers from the country", () => {
+ expect(answersFrom({ platforms: ['copilot-web'] }, country('KE'), countries)).toBe(false);
+ expect(
+ answersFrom({ platforms: ['copilot-web', 'chatgpt-web'] }, country('KE'), countries),
+ ).toBe(true);
+ // A country no engine lists.
+ expect(answersFrom({ platforms: ['chatgpt-web'] }, country('BO'), countries)).toBe(false);
+ });
+
+ it("asks a city only of Google's engines, and lets the API models answer anywhere", () => {
+ const istanbul = { country: 'TR', state: null, city: 'ISTANBUL' };
+ expect(answersFrom({ platforms: ['chatgpt-web'] }, istanbul, countries)).toBe(false);
+ expect(answersFrom({ platforms: ['google-aimode'] }, istanbul, countries)).toBe(true);
+ expect(
+ answersFrom({ platforms: [], models: ['gpt-5'] }, { ...istanbul, country: 'BO' }, countries),
+ ).toBe(true);
+ });
+
+ it("doesn't count Google's engines in a US state: the run asks them country-wide", () => {
+ const california = { country: 'US', state: 'CA' };
+ expect(answersFrom({ platforms: ['google-aio', 'google-aimode'] }, california, countries)).toBe(
+ false,
+ );
+ expect(answersFrom({ platforms: ['google-aio', 'chatgpt-web'] }, california, countries)).toBe(
+ true,
+ );
+ expect(answersFrom({ platforms: [], models: ['gpt-5'] }, california, countries)).toBe(true);
+ // In the country itself they answer.
+ expect(answersFrom({ platforms: ['google-aio'] }, country('US'), countries)).toBe(true);
+ // Without the lists, the state still isn't theirs.
+ expect(answersFrom({ platforms: ['google-aimode'] }, california, null)).toBe(false);
+ });
+
+ it('restricts nothing without the lists, or for an engine the provider does not list', () => {
+ expect(answersFrom({ platforms: ['copilot-web'] }, country('KE'), [])).toBe(true);
+ expect(answersFrom({ platforms: ['grok-web'] }, country('KE'), countries)).toBe(true);
+ });
+
+ it('gives an engine no list was read for the benefit of the doubt, as the run does', () => {
+ // No country lists Gemini: the run asks it anywhere.
+ expect(answersFrom({ platforms: ['gemini-web'] }, country('KE'), countries)).toBe(true);
+ expect(answersFrom({ platforms: ['gemini-web'] }, country('BO'), countries)).toBe(true);
+ });
+});
diff --git a/web/src/lib/tracking-countries.ts b/web/src/lib/tracking-countries.ts
index c7fc71a14..257f56923 100644
--- a/web/src/lib/tracking-countries.ts
+++ b/web/src/lib/tracking-countries.ts
@@ -16,9 +16,27 @@ export const ENGINE_LABELS: Record<string, string> = {
aioverview: 'Google AI Overview',
};
+/** The provider's model for each scraper, as the API's CLORO_COUNTRY_MODELS. */
+export const PLATFORM_MODELS: Record<string, string> = {
+ 'chatgpt-web': 'chatgpt',
+ 'chatgpt-shopping': 'chatgpt',
+ 'perplexity-web': 'perplexity',
+ 'copilot-web': 'copilot',
+ 'gemini-web': 'gemini',
+ 'google-aimode': 'aimode',
+ 'google-aio': 'aioverview',
+};
+
/** Engines that answer from a city, by the provider's model name (PROMPT-015d). */
export const CITY_MODELS: ReadonlySet<string> = new Set(['aimode', 'aioverview']);
+/**
+ * Engines that can't ask from a US state, by the provider's model name: the
+ * API runs them country-wide and records their answers as the country's
+ * (COUNTRY_ONLY_SCRAPERS, #691), so a state's column never gets them.
+ */
+export const COUNTRY_ONLY_MODELS: ReadonlySet<string> = new Set(['aimode', 'aioverview']);
+
export interface TrackingCountry {
code: string;
/** The provider's engines that answer from it. */
@@ -62,3 +80,29 @@ export function missingEngines(
const engines = new Set(all.flatMap((c) => c.models));
return [...engines].filter((m) => !country.models.includes(m)).sort();
}
+
+/**
+ * Whether any of a prompt's engines gets answers recorded for a location, as
+ * the tracking run asks them: a city only of the engines that ask from one,
+ * a US state only of those that don't run country-wide, and either only
+ * where the engine answers from the country. The API models answer from
+ * anywhere. An engine the provider doesn't list, or has no list read for, is
+ * given the benefit of the doubt, as the run gives it; with no lists read,
+ * all are.
+ */
+export function answersFrom(
+ engines: { platforms: readonly string[]; models?: readonly string[] | null },
+ location: { country: string; state?: string | null; city?: string | null },
+ countries: readonly TrackingCountry[] | null,
+): boolean {
+ if ((engines.models?.length ?? 0) > 0) return true;
+ const listed = new Set((countries ?? []).flatMap((c) => c.models));
+ const entry = countries?.find((c) => c.code === location.country);
+ return engines.platforms.some((platform) => {
+ const model = PLATFORM_MODELS[platform];
+ if (!model) return true;
+ if (location.city && !CITY_MODELS.has(model)) return false;
+ if (location.state && COUNTRY_ONLY_MODELS.has(model)) return false;
+ return !listed.has(model) || Boolean(entry?.models.includes(model));
+ });
+}
diff --git a/web/src/lib/use-tracking-countries.ts b/web/src/lib/use-tracking-countries.ts
new file mode 100644
index 000000000..a47a5b2ae
--- /dev/null
+++ b/web/src/lib/use-tracking-countries.ts
@@ -0,0 +1,32 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { getTrackingCountries } from '@/lib/actions/tracking-countries';
+import type { TrackingCountry } from '@/lib/tracking-countries';
+
+/** The engines' countries, read once per page (PROMPT-015e); empty when none were read. */
+let countriesRead: Promise<TrackingCountry[]> | null = null;
+
+/** Forgets the read, so the next page reads again (tests). */
+export function clearTrackingCountries() {
+ countriesRead = null;
+}
+
+export 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;
+}