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(prompts): compare each tracked prompt across its locations in a Locations view (PROMPT-015, part 2) (#1656)
Cihan29051ea55023
diff --git a/docs/guides/prompts.mdx b/docs/guides/prompts.mdxindex fc13cbc47..d0b039cda 100644--- a/docs/guides/prompts.mdx+++ b/docs/guides/prompts.mdx@@ -46,6 +46,19 @@ Click a prompt's text to open its own page, with its visibility, mentions, citatAdmins and managers can tick **Share with everyone on <brand>**: their columns become the brand's view, which everyone without columns of their own sees. Anyone can still change their own, and **Reset** goes back to the brand's view, or to the default columns when the brand has none.+### 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.++**View: Table | Locations**, above the table, switches to the **Locations** view:++- one row per prompt and one column per location your prompts track, the most-tracked first (12 at most);+- **Visibility**, **Position**, **Mentions** or **Citations**, shaded light to dark as in Brand Visibility's Topics vs competitors (for Position, named earlier is darker);+- an **All prompts · average** row, and a **Gap** column: the best location minus the worst, for the metric shown;+- three cards: the weakest location, the strongest one, and the prompt that differs most between locations.++Click a cell to open the prompt's Positions panel for that location. A location the prompt isn't tracked in shows **+ Track** for admins, managers and analysts. The date range and filters work as in the table, and a location's numbers equal the table filtered to it.+## PerformanceThe **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/web/messages/en.json b/web/messages/en.jsonindex f6ff0833b..500bd0153 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -7425,7 +7425,13 @@"reset": "Reset to default","resetToBrand": "Reset to the brand's view","failed": "Couldn't save your columns. Try again.",- "forbidden": "Only admins and managers can share a view with the brand."+ "forbidden": "Only admins and managers can share a view with the brand.",+ "remove": "Remove {column}",+ "addLocation": "Add a location column",+ "metric": "Metric",+ "location": "Location",+ "add": "Add",+ "locationLimit": "{count} location columns at most."},"tips": {"status": "New: added in the last 24 hours. Active: being tracked. Paused: not tracked.",@@ -7441,6 +7447,47 @@"lastRun": "When this prompt was last checked."}},+ "locations": {+ "view": "View",+ "table": "Table",+ "locations": "Locations",+ "metric": "Metric",+ "metrics": {+ "visibility": "Visibility",+ "position": "Position",+ "mentions": "Mentions",+ "citations": "Citations"+ },+ "prompt": "Prompt",+ "topic": "Topic",+ "average": "All prompts · average",+ "gap": "Gap",+ "gapTip": "Best minus worst tracked location, for the metric shown.",+ "track": "+ Track",+ "trackLabel": "Track “{prompt}” in {location}",+ "open": "{prompt} in {location}: open its positions",+ "notNamed": "Not named",+ "noAnswers": "No answers in this location yet",+ "kind": {+ "country": "Country",+ "state": "US state",+ "city": "City"+ },+ "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",+ "strongestBody": "Visibility across its {tracked, plural, one {# tracked prompt} other {# tracked prompts}}",+ "widest": "Biggest gap between locations",+ "widestBody": "{low} in {lowAt}, {high} in {highAt}",+ "low": "Low",+ "high": "High",+ "late": "Named late",+ "first": "Named first",+ "legend": "A cell opens the prompt's Positions panel for that location.",+ "none": "Your prompts aren't tracked in a location yet. Add one from a prompt's Edit.",+ "failed": "Couldn't read the locations right now. Try again in a moment.",+ "capped": "Showing the {count} locations your prompts track most."+ },"performance": {"label": "Performance","title": "Where your brand is named in this prompt's AI answers: Best in the first third of the brands listed, Good in the middle, Late in the last third, Missing in fewer than half the answers. Late and Missing list the furthest behind first.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsxindex 07e568823..203087389 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsx@@ -6,25 +6,12 @@ import { Link } from '@/i18n/navigation';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { cn } from '@/lib/utils';import { numberFormat } from '@/lib/number-format';-import { heatShade, topicHeatmap, type TopicCompetitors } from '@/lib/insights-topics';+import { HEAT_SHADES, heatShade, topicHeatmap, type TopicCompetitors } from '@/lib/insights-topics';import { TONE_TEXT } from './kpi-format';/** Rows shown before "Show all". */const VISIBLE_ROWS = 6;-/**- * Cell shades, light to dark: soft theme-relative tints, so they read in- * both themes and a full table doesn't turn into dark blocks. The text keeps- * its color on every shade.- */-const SHADES = [- 'bg-muted/40 text-muted-foreground',- 'bg-foreground/[0.06] text-foreground',- 'bg-foreground/[0.12] text-foreground',- 'bg-foreground/[0.2] text-foreground',- 'bg-foreground/[0.32] text-foreground',-] as const;-/*** "Topics vs competitors" (VIS-010), as in the v2 mockup: a row per topic,* a column for you and each competitor on the trend (pinned, or the@@ -98,7 +85,7 @@ export function TopicHeatmap({title={t('openTopic', { topic: row.name })}className={cn('block rounded-md px-1 py-1.5 text-center font-semibold tabular-nums transition-opacity hover:opacity-80',- SHADES[heatShade(value, low, high)],+ HEAT_SHADES[heatShade(value, low, high)],// Too few answers to read much into: shown, but faded.row.status === 'lowSample' && 'opacity-50',)}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 1cfc9fd49..fc074c9f5 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@@ -41,6 +41,7 @@ function render() {canManage={canManage}views={views}onViewsChange={onViewsChange}+ locations={['US', 'TR']}/></NextIntlClientProvider>,);@@ -134,6 +135,26 @@ describe('ColumnsPanel', () => {expect(views).toEqual({ mine: null, brand });});+ it('adds a metric in one of the brand’s locations as a column, and removes it (PROMPT-015b)', async () => {+ await open();+ const [metric, location] = [...document.querySelectorAll('select')] as HTMLSelectElement[];+ await act(async () => {+ metric.value = 'position';+ metric.dispatchEvent(new Event('change', { bubbles: true }));+ location.value = 'TR';+ location.dispatchEvent(new Event('change', { bubbles: true }));+ });+ 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();+ const remove = document.querySelector(+ 'button[aria-label="Remove Position · Turkey"]',+ ) as HTMLButtonElement;+ await act(async () => remove.click());+ expect(views.mine?.order).not.toContain('loc:position:TR');+ });+it("keeps a member's change off the brand's view when they have none of their own", async () => {canManage = false;const brand = toggleColumn(DEFAULT_COLUMNS_VIEW, 'work', false);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_columns-panel.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_columns-panel.tsxindex 652b34a72..48e89d37b 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_columns-panel.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_columns-panel.tsx@@ -3,7 +3,7 @@import { useRef, useState } from 'react';import { useTranslations } from 'next-intl';import { toast } from 'sonner';-import { ChevronDown, ChevronUp, Columns3, GripVertical } from 'lucide-react';+import { ChevronDown, ChevronUp, Columns3, GripVertical, X } from 'lucide-react';import { Button } from '@/components/ui/button';import { Checkbox } from '@/components/ui/checkbox';import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@/components/ui/popover';@@ -13,14 +13,21 @@ import {type PromptTableViews,} from '@/lib/actions/prompt-table-views';import {+ MAX_LOCATION_COLUMNS,+ addLocationColumn,effectiveView,+ isLocationColumn,moveColumn,+ parseLocationColumn,+ removeColumn,sameView,toggleColumn,visibleColumns,- type PromptColumnId,type PromptColumnsView,+ type TableColumnId,} from '@/lib/prompt-table-columns';+import { LOCATION_METRICS, type LocationMetric } from '@/lib/prompt-location-matrix';+import { regionLabel } from '@/lib/region';import { cn } from '@/lib/utils';/** Changes are saved this long after the last one, so a few clicks save once. */@@ -30,7 +37,8 @@ const SAVE_AFTER_MS = 600;* The Tracked Prompts table's Columns panel (PROMPT-015a): show, hide and* order the columns, saved for the person; an admin or manager can share* theirs with everyone on the brand. Reset goes back to the brand's shared- * view, or the default.+ * view, or the default. A metric in one of the brand's locations can be+ * added as a column (PROMPT-015b).*/export function ColumnsPanel({brandId,@@ -38,21 +46,33 @@ export function ColumnsPanel({canManage,views,onViewsChange,+ locations,}: {brandId: string;brandName: string;canManage: boolean;views: PromptTableViews;onViewsChange: (views: PromptTableViews) => void;+ /** The locations the brand's prompts track, for location columns. */+ locations: string[];}) {const t = useTranslations('prompts.columns.picker');const tLabels = useTranslations('prompts.columns.labels');+ const tMetrics = useTranslations('prompts.locations.metrics');const view = effectiveView(views.mine, views.brand);// Linked to the brand's view only once an admin or manager shared their// own: someone just looking at the brand's view changes theirs alone.const shared =canManage && views.mine !== null && views.brand !== null && sameView(views.brand, views.mine);- const [dragging, setDragging] = useState<PromptColumnId | null>(null);+ const [dragging, setDragging] = useState<TableColumnId | null>(null);+ const [newMetric, setNewMetric] = useState<LocationMetric>('visibility');+ const [newRegion, setNewRegion] = useState('');+ const region = locations.includes(newRegion) ? newRegion : (locations[0] ?? '');+ const locationCount = view.order.filter(isLocationColumn).length;+ const labelOf = (id: TableColumnId) => {+ const loc = parseLocationColumn(id);+ return loc ? `${tMetrics(loc.metric)} · ${regionLabel(loc.region)}` : tLabels(id);+ };const timer = useRef<ReturnType<typeof setTimeout> | null>(null);const report = (result: Awaited<ReturnType<typeof savePromptTableView>>) => {@@ -115,7 +135,8 @@ export function ColumnsPanel({<span className="text-xs">{t('always')}</span></li>{view.order.map((id, i) => {- const label = tLabels(id);+ const label = labelOf(id);+ const location = isLocationColumn(id);const visible = !view.hidden.includes(id);return (<li@@ -174,10 +195,66 @@ export function ColumnsPanel({><ChevronDown /></Button>+ {location && (+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ aria-label={t('remove', { column: label })}+ onClick={() => change(removeColumn(view, id))}+ >+ <X />+ </Button>+ )}</li>);})}</ul>+ {locations.length > 0 && (+ <div className="space-y-2 border-t pt-3">+ <p className="text-xs font-medium text-muted-foreground">{t('addLocation')}</p>+ <div className="flex flex-wrap items-center gap-2">+ <select+ aria-label={t('metric')}+ value={newMetric}+ onChange={(e) => setNewMetric(e.target.value as LocationMetric)}+ className="h-8 flex-1 rounded-md border bg-background px-2 text-xs"+ >+ {LOCATION_METRICS.map((m) => (+ <option key={m} value={m}>+ {tMetrics(m)}+ </option>+ ))}+ </select>+ <select+ aria-label={t('location')}+ value={region}+ onChange={(e) => setNewRegion(e.target.value)}+ className="h-8 flex-1 rounded-md border bg-background px-2 text-xs"+ >+ {locations.map((r) => (+ <option key={r} value={r}>+ {regionLabel(r)}+ </option>+ ))}+ </select>+ <Button+ type="button"+ size="sm"+ className="h-8"+ disabled={!region || locationCount >= MAX_LOCATION_COLUMNS}+ onClick={() => change(addLocationColumn(view, newMetric, region))}+ >+ {t('add')}+ </Button>+ </div>+ {locationCount >= MAX_LOCATION_COLUMNS && (+ <p className="text-xs text-muted-foreground">+ {t('locationLimit', { count: MAX_LOCATION_COLUMNS })}+ </p>+ )}+ </div>+ )}{canManage ? (<div className="flex items-start gap-2.5 rounded-lg border bg-muted/30 p-3"><Checkboxdiff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.test.tsxnew file mode 100644index 000000000..42e16fca0--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.test.tsx@@ -0,0 +1,208 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../messages/en.json';+import type { PromptLocationCell } from '@/lib/prompt-location-matrix';+import type { Prompt } from '@/types';++const getPromptLocationMatrix = vi.hoisted(() => vi.fn());+vi.mock('@/lib/actions/prompt', () => ({ getPromptLocationMatrix }));++const { LocationMatrix, clearLocationMatrixCache, loadLocationMatrix } =+ await import('./_location-matrix');++/** Tracked Prompts' Locations view (PROMPT-015b). */++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++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 cell = (score: number, position: number | null = 3.2): PromptLocationCell => ({+ score,+ mentions: Math.round(score / 2),+ citations: 2,+ position,+ runs: 6,+});++const rows = [+ prompt('p1', 'best specialty coffee subscription', ['US', 'TR']),+ prompt('p2', 'same day coffee delivery near me', ['US']),+];+const onOpenCell = vi.fn();+const onTrack = vi.fn();++async function render(canTrack = true) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <LocationMatrix+ brandId={BRAND}+ rows={rows}+ pageRows={rows}+ window={{ from: '2026-10-21T00:00:00Z' }}+ onOpenCell={onOpenCell}+ onTrack={canTrack ? onTrack : undefined}+ />+ </NextIntlClientProvider>,+ );+ });+ return container.textContent ?? '';+}++const bodyRows = () =>+ [...container.querySelectorAll('tbody tr')].map((tr) =>+ [...tr.querySelectorAll('td')].map((td) => td.textContent),+ );++beforeEach(() => {+ clearLocationMatrixCache();+ getPromptLocationMatrix.mockReset().mockResolvedValue({+ p1: { US: cell(62), TR: cell(35, null) },+ p2: { US: cell(20, 6.4) },+ });+ onOpenCell.mockReset();+ onTrack.mockReset();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('LocationMatrix', () => {+ it('reads each tracked location, the most tracked first, and shows each prompt there', async () => {+ const text = await render();+ expect(getPromptLocationMatrix).toHaveBeenCalledWith(BRAND, {+ from: '2026-10-21T00:00:00Z',+ to: undefined,+ regions: ['US', 'TR'],+ });+ expect(text).toContain('United States');+ expect(text).toContain('Turkey');+ expect(bodyRows()).toEqual([+ ['All prompts · average', '—', '41', '35', '—'],+ ['best specialty coffee subscription', 'Coffee', '62', '35', '27'],+ ['same day coffee delivery near me', 'Coffee', '20', '+ Track', '—'],+ ]);+ expect(text).toContain('Weakest location');+ expect(text).toContain('Biggest gap between locations');+ });++ it('switches the metric, and reads a prompt never named there as such', async () => {+ await render();+ const position = [...container.querySelectorAll('button')].find(+ (b) => b.textContent === 'Position',+ )!;+ await act(async () => position.click());+ expect(position.getAttribute('aria-pressed')).toBe('true');+ expect(bodyRows()[1]).toEqual([+ 'best specialty coffee subscription',+ 'Coffee',+ '#3.2',+ 'Not named',+ '—',+ ]);+ });++ it("opens a cell's positions for its location, and tracks a prompt where it isn't", async () => {+ await render();+ (+ container.querySelector(+ 'button[aria-label="best specialty coffee subscription in Turkey: 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"]',+ ) as HTMLButtonElement+ ).click();+ expect(onTrack).toHaveBeenCalledWith(rows[1], 'TR');+ });++ it("offers no + Track to a member who can't edit, and says when nothing is tracked in a location", async () => {+ await render(false);+ expect(container.textContent).not.toContain('+ Track');+ act(() => root.unmount());+ root = createRoot(container);+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <LocationMatrix+ brandId={BRAND}+ rows={[prompt('p3', 'untargeted', [])]}+ pageRows={[prompt('p3', 'untargeted', [])]}+ window={{ from: '2026-10-21T00:00:00Z' }}+ onOpenCell={onOpenCell}+ />+ </NextIntlClientProvider>,+ );+ });+ expect(container.textContent).toContain("Your prompts aren't tracked in a location yet.");+ });+});++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' };+ await loadLocationMatrix(BRAND, window, ['US', 'TR']);+ expect(await loadLocationMatrix(BRAND, window, ['US'])).toEqual({+ p1: { US: cell(62) },+ p2: { US: cell(20, 6.4) },+ });+ expect(getPromptLocationMatrix).toHaveBeenCalledTimes(1);+ clearLocationMatrixCache();+ await loadLocationMatrix(BRAND, window, ['US', 'TR']);+ expect(getPromptLocationMatrix).toHaveBeenCalledTimes(2);+ });++ it('reads only a location not read yet, as a new location column needs', async () => {+ const window = { from: '2026-10-21T00:00:00Z' };+ await loadLocationMatrix(BRAND, window, ['US']);+ getPromptLocationMatrix.mockResolvedValueOnce({ p1: { DE: cell(50) } });+ expect(await loadLocationMatrix(BRAND, window, ['US', 'DE'])).toEqual({+ p1: { US: cell(62), DE: cell(50) },+ p2: { US: cell(20, 6.4) },+ });+ expect(getPromptLocationMatrix).toHaveBeenLastCalledWith(BRAND, {+ from: '2026-10-21T00:00:00Z',+ to: undefined,+ regions: ['DE'],+ });+ expect(getPromptLocationMatrix).toHaveBeenCalledTimes(2);+ });++ it('runs one read at a time, so a read-ahead never adds to one running', async () => {+ const window = { from: '2026-10-21T00:00:00Z' };+ let finish = () => {};+ getPromptLocationMatrix.mockImplementationOnce(+ () => new Promise((resolve) => (finish = () => resolve({ p1: { US: cell(62) } }))),+ );+ const first = loadLocationMatrix(BRAND, window, ['US']);+ const second = loadLocationMatrix(BRAND, window, ['US', 'TR']);+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(getPromptLocationMatrix).toHaveBeenCalledTimes(1);+ finish();+ await Promise.all([first, second]);+ expect(getPromptLocationMatrix).toHaveBeenCalledTimes(2);+ expect(getPromptLocationMatrix.mock.calls[1][1].regions).toEqual(['TR']);+ });++ it('reads again after a failed read', async () => {+ getPromptLocationMatrix.mockRejectedValueOnce(new Error('down'));+ const window = { from: '2026-10-21T00:00:00Z' };+ await expect(loadLocationMatrix(BRAND, window, ['US'])).rejects.toThrow('down');+ await loadLocationMatrix(BRAND, window, ['US']);+ expect(getPromptLocationMatrix).toHaveBeenCalledTimes(2);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsxnew file mode 100644index 000000000..5e4d2deb1--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_location-matrix.tsx@@ -0,0 +1,407 @@+'use client';++import { useEffect, useState } from 'react';+import { useTranslations } from 'next-intl';+import { Skeleton } from '@/components/ui/skeleton';+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@/components/ui/table';+import { getPromptLocationMatrix } from '@/lib/actions/prompt';+import { formatNumber } from '@/lib/format';+import { createLimiter } from '@/lib/limiter';+import { HEAT_SHADES } from '@/lib/insights-topics';+import {+ LOCATION_METRICS,+ MATRIX_REGIONS,+ cellShade,+ locationAverages,+ matrixInsights,+ matrixLocations,+ metricValue,+ rowGap,+ type LocationMetric,+ type PromptLocationCell,+ type PromptLocationMatrix,+} from '@/lib/prompt-location-matrix';+import { parseLocation, regionFlag, regionLabel } from '@/lib/region';+import { cn } from '@/lib/utils';+import type { Prompt } from '@/types';++/**+ * Each location's figures read in the last minute, by brand, window and+ * location: switching views reads nothing again, and a location column+ * added to the table reads only its own location.+ */+const MATRIX_CACHE_MS = 60_000;+const regionCache = new Map<+ string,+ { at: number; read: Promise<Record<string, PromptLocationCell>> }+>();+/**+ * One matrix read from the page at a time, read-ahead included: the server+ * runs MATRIX_READS_AT_ONCE of a read's database reads at once, so the page+ * never runs more than that.+ */+const serverReads = createLimiter(1);++export function matrixKey(+ brandId: string,+ window: { from: string; to?: string },+ regions: string[],+) {+ return `${brandId}:${window.from}:${window.to ?? ''}:${regions.join(',')}`;+}++/**+ * The matrix for these locations: each location read in the last minute+ * as it was, the others in one new read (getPromptLocationMatrix). Also how+ * the view's Locations button reads ahead on hover, so the view opens on+ * data already there.+ */+export function loadLocationMatrix(+ brandId: string,+ window: { from: string; to?: string },+ regions: string[],+): Promise<PromptLocationMatrix> {+ const now = Date.now();+ const keyOf = (region: string) => matrixKey(brandId, window, [region]);+ const missing = regions.filter((r) => {+ const kept = regionCache.get(keyOf(r));+ return !kept || now - kept.at >= MATRIX_CACHE_MS;+ });+ if (missing.length) {+ const read = serverReads(() =>+ getPromptLocationMatrix(brandId, { from: window.from, to: window.to, regions: missing }),+ );+ for (const region of missing) {+ const key = keyOf(region);+ const one = read.then((matrix) => {+ const cells: Record<string, PromptLocationCell> = {};+ for (const [promptId, byRegion] of Object.entries(matrix)) {+ if (byRegion[region]) cells[promptId] = byRegion[region];+ }+ return cells;+ });+ regionCache.set(key, { at: now, read: one });+ one.catch(() => {+ if (regionCache.get(key)?.read === one) regionCache.delete(key);+ });+ }+ }+ return Promise.all(regions.map((r) => regionCache.get(keyOf(r))!.read)).then((reads) => {+ const matrix: PromptLocationMatrix = {};+ reads.forEach((cells, i) => {+ for (const [promptId, cell] of Object.entries(cells)) {+ (matrix[promptId] ??= {})[regions[i]] = cell;+ }+ });+ return matrix;+ });+}++/** After prompts or their locations change: the next read is a new one. */+export function clearLocationMatrixCache() {+ regionCache.clear();+}++/** 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';+}++/**+ * Tracked Prompts' Locations view (PROMPT-015b): each prompt in each+ * location the brand tracks, side by side, for one metric at a time, in+ * Brand Visibility's Topics vs competitors shades. A cell opens the+ * prompt's Positions panel for that location; one the prompt isn't tracked+ * in offers + Track.+ */+export function LocationMatrix({+ brandId,+ rows,+ pageRows,+ window,+ onOpenCell,+ onTrack,+}: {+ brandId: string;+ /** Every row the filters keep, for the averages and the cards. */+ rows: Prompt[];+ /** The rows on this page of the table. */+ pageRows: Prompt[];+ /** The table's window. */+ window: { from: string; to?: string };+ onOpenCell: (promptId: string, region: string) => void;+ /** Adds the location to the prompt; undefined for members who can't edit. */+ onTrack?: (prompt: Prompt, region: string) => void;+}) {+ const t = useTranslations('prompts.locations');+ const [metric, setMetric] = useState<LocationMetric>('visibility');+ const allRegions = matrixLocations(rows);+ const regions = allRegions.slice(0, MATRIX_REGIONS);+ const key = matrixKey(brandId, window, regions);+ const [read, setRead] = useState<{ key: string; matrix: PromptLocationMatrix | 'failed' } | null>(+ null,+ );++ useEffect(() => {+ if (!regions.length) return;+ let cancelled = false;+ loadLocationMatrix(brandId, window, regions)+ .then((matrix) => {+ if (!cancelled) setRead({ key, matrix });+ })+ .catch((err) => {+ console.error('Failed to read the locations view:', err);+ if (!cancelled) setRead({ key, matrix: 'failed' });+ });+ return () => {+ cancelled = true;+ };+ // `regions` is in `key`.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [key]);++ if (!regions.length) {+ return <p className="px-6 py-10 text-center text-sm text-muted-foreground">{t('none')}</p>;+ }+ const matrix = read?.key === key ? read.matrix : undefined;+ if (matrix === undefined) {+ return (+ <div className="space-y-3 p-6">+ <Skeleton className="h-16 w-full" />+ <Skeleton className="h-[320px] w-full" />+ </div>+ );+ }+ if (matrix === 'failed') {+ return <p className="px-6 py-10 text-center text-sm text-muted-foreground">{t('failed')}</p>;+ }++ const valuesOf = (p: Prompt) => regions.map((r) => metricValue(matrix[p.id]?.[r], metric));+ const inView = pageRows.flatMap((p) => valuesOf(p).filter((v): v is number => v !== null));+ const averages = locationAverages(+ matrix,+ rows.map((p) => p.id),+ regions,+ metric,+ );+ const insights = matrixInsights(matrix, rows, regions);+ const shown = (v: number) =>+ metric === 'position' ? `#${v.toFixed(1)}` : formatNumber(Math.round(v));+ const label = (r: string) => `${regionFlag(r)} ${regionLabel(r)}`.trim();++ return (+ <div className="space-y-4 pt-2">+ <div className="flex flex-wrap items-center gap-3 px-6">+ <div+ role="group"+ aria-label={t('metric')}+ className="inline-flex gap-0.5 rounded-full border bg-background p-0.5"+ >+ {LOCATION_METRICS.map((m) => (+ <button+ key={m}+ type="button"+ aria-pressed={metric === m}+ onClick={() => setMetric(m)}+ className={cn(+ 'h-7 rounded-full px-3 text-xs transition-colors',+ metric === m+ ? 'bg-foreground font-medium text-background'+ : 'text-muted-foreground hover:text-foreground',+ )}+ >+ {t(`metrics.${m}`)}+ </button>+ ))}+ </div>+ {allRegions.length > regions.length && (+ <span className="text-xs text-muted-foreground">+ {t('capped', { count: MATRIX_REGIONS })}+ </span>+ )}+ </div>++ <div className="grid gap-3 px-6 sm:grid-cols-3">+ {insights.weakest && (+ <div className="space-y-0.5 rounded-xl border p-3">+ <p className="text-xs text-muted-foreground">{t('weakest')}</p>+ <p className="text-base font-semibold">+ {label(insights.weakest.region)} · {insights.weakest.average}+ </p>+ <p className="text-xs text-muted-foreground">+ {t('weakestBody', {+ overall: insights.overall ?? 0,+ untracked: insights.weakest.untracked,+ })}+ </p>+ </div>+ )}+ {insights.strongest && (+ <div className="space-y-0.5 rounded-xl border p-3">+ <p className="text-xs text-muted-foreground">{t('strongest')}</p>+ <p className="text-base font-semibold">+ {label(insights.strongest.region)} · {insights.strongest.average}+ </p>+ <p className="text-xs text-muted-foreground">+ {t('strongestBody', { tracked: insights.strongest.tracked })}+ </p>+ </div>+ )}+ {insights.widest && (+ <div className="min-w-0 space-y-0.5 rounded-xl border p-3">+ <p className="text-xs text-muted-foreground">{t('widest')}</p>+ <p className="truncate text-base font-semibold" title={insights.widest.text}>+ “{insights.widest.text}”+ </p>+ <p className="text-xs text-muted-foreground">+ {t('widestBody', {+ low: insights.widest.low,+ lowAt: regionLabel(insights.widest.lowAt),+ high: insights.widest.high,+ highAt: regionLabel(insights.widest.highAt),+ })}+ </p>+ </div>+ )}+ </div>++ <Table stickyHeader stickyFirstColumn>+ <TableHeader>+ <TableRow>+ <TableHead className="pl-6">{t('prompt')}</TableHead>+ <TableHead>{t('topic')}</TableHead>+ {regions.map((r) => (+ <TableHead key={r} className="min-w-[96px] text-center">+ <span className="block text-xs font-medium text-foreground">{label(r)}</span>+ <span className="block text-[11px] font-normal text-muted-foreground">+ {t(`kind.${locationKind(r)}`)}+ </span>+ </TableHead>+ ))}+ <TableHead className="pr-6 text-right" title={t('gapTip')}>+ {t('gap')}+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ <TableRow className="bg-muted/30 hover:bg-muted/30">+ <TableCell className="pl-6 text-sm font-medium">{t('average')}</TableCell>+ <TableCell className="text-xs text-muted-foreground">—</TableCell>+ {averages.map((v, i) => (+ <TableCell key={regions[i]} className="px-1 py-1.5">+ <div+ className={cn(+ 'rounded-md py-1.5 text-center text-sm font-semibold tabular-nums',+ HEAT_SHADES[cellShade(v, inView, metric)],+ )}+ >+ {v === null ? '—' : shown(v)}+ </div>+ </TableCell>+ ))}+ <TableCell className="pr-6 text-right text-xs text-muted-foreground">—</TableCell>+ </TableRow>+ {pageRows.map((p) => {+ const values = valuesOf(p);+ const gap = rowGap(values);+ return (+ <TableRow key={p.id}>+ <TableCell className="max-w-[320px] pl-6 text-sm font-medium">+ <span className="line-clamp-2" title={p.text}>+ {p.text}+ </span>+ </TableCell>+ <TableCell className="max-w-[140px]">+ <span className="block truncate text-xs text-muted-foreground">+ {p.category?.trim() || '—'}+ </span>+ </TableCell>+ {regions.map((r, i) => {+ const cell = matrix[p.id]?.[r];+ const v = values[i];+ const where = regionLabel(r);+ if (!p.regions.includes(r)) {+ return (+ <TableCell key={r} className="px-1 py-1.5">+ {onTrack ? (+ <button+ type="button"+ aria-label={t('trackLabel', { prompt: p.text, location: where })}+ onClick={() => onTrack(p, r)}+ className="block w-full rounded-md border border-dashed py-1.5 text-center text-xs text-muted-foreground transition-colors hover:border-foreground/40 hover:text-foreground"+ >+ {t('track')}+ </button>+ ) : (+ <span className="block text-center text-xs text-muted-foreground">—</span>+ )}+ </TableCell>+ );+ }+ 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>+ );+ }+ return (+ <TableCell key={r} className="px-1 py-1.5">+ <button+ type="button"+ aria-label={t('open', { prompt: p.text, location: where })}+ onClick={() => onOpenCell(p.id, r)}+ className={cn(+ 'block w-full rounded-md py-1.5 text-center text-sm font-semibold tabular-nums transition-shadow hover:ring-1 hover:ring-foreground/30',+ HEAT_SHADES[cellShade(v, inView, metric)],+ )}+ >+ {v === null ? t('notNamed') : shown(v)}+ </button>+ </TableCell>+ );+ })}+ <TableCell className="pr-6 text-right text-sm font-semibold tabular-nums">+ {gap === null ? (+ <span className="text-xs font-normal text-muted-foreground">—</span>+ ) : metric === 'position' ? (+ gap.toFixed(1)+ ) : (+ formatNumber(Math.round(gap))+ )}+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>++ <div className="flex flex-wrap items-center gap-4 px-6 pb-4 text-xs text-muted-foreground">+ <span className="inline-flex items-center gap-1.5">+ {metric === 'position' ? t('late') : t('low')}+ <span aria-hidden className="inline-flex overflow-hidden rounded border">+ {HEAT_SHADES.map((shade) => (+ <span key={shade} className={cn('h-2.5 w-4', shade)} />+ ))}+ </span>+ {metric === 'position' ? t('first') : t('high')}+ </span>+ <span>{t('gapTip')}</span>+ <span>{t('legend')}</span>+ </div>+ </div>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex 684633fe1..cb216c821 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -157,7 +157,7 @@ import {} from '@/config/prompt-options';import { DateRangeFilter } from '@/components/filters/date-range-filter';import { getBrandFilterOptions } from '@/lib/actions/tracking';-import { formatRegionDisplay, isValidLocation, locationCode } from '@/lib/region';+import { formatRegionDisplay, isValidLocation, locationCode, regionLabel } from '@/lib/region';import { SuggestionsTab } from './_suggestions-tab';import { CONTACT_SALES_URL, PLANS } from '@/config/plans';import { getPromptUsage, isPromptLimitReached } from '@/lib/prompt-usage';@@ -199,8 +199,20 @@ import {} from './prompt-sort';import { BulkActionBar } from './_bulk-action-bar';import { ColumnsPanel } from './_columns-panel';+import { LocationMatrix, clearLocationMatrixCache, loadLocationMatrix } from './_location-matrix';import { getPromptTableViews, type PromptTableViews } from '@/lib/actions/prompt-table-views';-import { effectiveView, visibleColumns, type PromptColumnId } from '@/lib/prompt-table-columns';+import {+ effectiveView,+ parseLocationColumn,+ visibleColumns,+ type PromptColumnId,+} from '@/lib/prompt-table-columns';+import {+ matrixLocations,+ metricValue,+ type PromptLocationMatrix,+} from '@/lib/prompt-location-matrix';+import { readUrlChoice } from '@/lib/url-state';import { promptsTableState } from './table-state';import { formatCompactNumber, formatDate, formatNumber } from '@/lib/format';import {@@ -1556,8 +1568,10 @@ export default function PromptsPage() {}, [loadData, promptDataWanted]);// After prompts are added, paused, resumed, deleted or retargeted: reload- // the table and the usage cards together.+ // the table and the usage cards together, and read the locations' figures+ // (PROMPT-015b) anew.const reloadAfterChange = useCallback(() => {+ clearLocationMatrixCache();setUsageVersion((v) => v + 1);return loadData();}, [loadData]);@@ -2908,6 +2922,53 @@ function AllPromptsTab({const tableViews =columnViews?.brandId === activeBrandId ? columnViews.views : { mine: null, brand: null };const columns = visibleColumns(effectiveView(tableViews.mine, tableViews.brand));+ const tLocations = useTranslations('prompts.locations');+ const tMetrics = useTranslations('prompts.locations.metrics');+ // Table, or the Locations view (PROMPT-015b), kept in the URL (?layout=locations).+ const [layout, setLayout] = useState<'table' | 'locations'>('table');+ useEffect(() => {+ setLayout(readUrlChoice('layout', ['table', 'locations'] as const, 'table'));+ }, []);+ const prefetchLocations = () => {+ const regions = matrixLocations(filtered);+ if (layout === 'table' && regions.length) {+ loadLocationMatrix(activeBrandId, positionsWindow, regions).catch(() => {});+ }+ };+ const changeLayout = (next: 'table' | 'locations') => {+ setLayout(next);+ const params = new URLSearchParams(window.location.search);+ if (next === 'table') params.delete('layout');+ else params.set('layout', next);+ const query = params.toString();+ window.history.replaceState(null, '', `${window.location.pathname}${query ? `?${query}` : ''}`);+ };+ // The locations the prompts track, for the Locations view and location columns.+ const trackedLocations = useMemo(() => matrixLocations(allRows), [allRows]);+ // Location columns in the Table view read their figures, once per location shown.+ const columnRegions = [+ ...new Set(columns.map((id) => parseLocationColumn(id)?.region).filter(Boolean)),+ ] as string[];+ const columnMatrixKey = `${activeBrandId}:${positionsWindow.from}:${positionsWindow.to ?? ''}:${columnRegions.join(',')}`;+ const [columnMatrix, setColumnMatrix] = useState<{+ key: string;+ matrix: PromptLocationMatrix;+ } | null>(null);+ useEffect(() => {+ if (layout !== 'table' || !columnRegions.length) return;+ let cancelled = false;+ loadLocationMatrix(activeBrandId, positionsWindow, columnRegions)+ .then((matrix) => {+ if (!cancelled) setColumnMatrix({ key: columnMatrixKey, matrix });+ })+ .catch((err) => console.error('Failed to read the location columns:', err));+ return () => {+ cancelled = true;+ };+ // `columnRegions` and the window are in the key.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [layout, columnMatrixKey]);+ const locationMatrix = columnMatrix?.key === columnMatrixKey ? columnMatrix.matrix : null;// Rows deleted from the row menu or the bulk bar, hidden at once and// deleted for real after the Undo window (PROMPT-006). There is no soft// delete for prompts — a delete drops their history — so the delay is the@@ -3319,8 +3380,15 @@ function AllPromptsTab({if (!loading && positionsId && !openPositions) setPositionsId(null);// The panel opens on the table's window; changing it there only moves the panel.+ // A Locations view cell opens the panel on its location (PROMPT-015b).+ const [panelRegion, setPanelRegion] = useState<string | null>(null);const openPositionsPanel = useCallback(- (promptId: string, tab: 'platforms' | 'improve' = 'platforms') => {+ (+ promptId: string,+ tab: 'platforms' | 'improve' = 'platforms',+ region: string | null = null,+ ) => {+ setPanelRegion(region);setPositionsTab(tab);setPositionsRange(panelRangeFromTable(positionsPreset, positionsWindow, viewerTimeZone()));setPositionsId(promptId);@@ -3754,7 +3822,32 @@ function AllPromptsTab({</span>)}</div>- <div className="flex items-center gap-2">+ <div className="flex flex-wrap items-center gap-2">+ <div+ role="group"+ aria-label={tLocations('view')}+ className="inline-flex gap-0.5 rounded-full bg-muted p-0.5"+ >+ {(['table', 'locations'] as const).map((l) => (+ <button+ key={l}+ type="button"+ aria-pressed={layout === l}+ onClick={() => changeLayout(l)}+ // Read ahead, so the Locations view opens on its data.+ onPointerEnter={l === 'locations' ? prefetchLocations : undefined}+ onFocus={l === 'locations' ? prefetchLocations : undefined}+ className={cn(+ 'h-7 rounded-full px-3 text-xs transition-colors',+ layout === l+ ? 'bg-background font-medium text-foreground shadow-sm'+ : 'text-muted-foreground hover:text-foreground',+ )}+ >+ {tLocations(l)}+ </button>+ ))}+ </div><Selectvalue={statusFilter}onValueChange={(v) => onStatusFilterChange((v as PromptStatusFilter | null) ?? 'all')}@@ -3817,13 +3910,16 @@ function AllPromptsTab({className="pl-8 h-8 text-xs"/></div>- <ColumnsPanel- brandId={activeBrandId}- brandName={brandName}- canManage={canManage}- views={tableViews}- onViewsChange={(views) => setColumnViews({ brandId: activeBrandId, views })}- />+ {layout === 'table' && (+ <ColumnsPanel+ brandId={activeBrandId}+ brandName={brandName}+ canManage={canManage}+ views={tableViews}+ onViewsChange={(views) => setColumnViews({ brandId: activeBrandId, views })}+ locations={trackedLocations}+ />+ )}</div></div></CardHeader>@@ -3859,292 +3955,333 @@ function AllPromptsTab({onClear={() => setSelectedIds(new Set())}/>)}- <Table stickyHeader stickyFirstColumn>- {latenessOrder && (- <TableCaption className="sr-only">{tPerformance('order')}</TableCaption>- )}- <TableHeader>- <TableRow>- <TableHead className="pl-6">- {onEditPrompt ? (- <div className="flex items-center gap-3">- <Checkbox- checked={allSelected(pageIds, selectedIds)}- onCheckedChange={() => setSelectedIds(toggleAll(pageIds, selectedIds))}- aria-label="Select every prompt on this page"- />- Prompt- </div>- ) : (- 'Prompt'- )}- </TableHead>- {columns.map((id) => headCells[id])}- {onEditPrompt && (- <TableHead className="text-right pr-6 w-[60px]">- <span className="sr-only">Actions</span>- </TableHead>- )}- </TableRow>- </TableHeader>- <TableBody>- {pageRows.map((p) => {- const vol = volumeByPromptId.get(p.id);- const vis = visibility[p.id];- const status = promptStatus(p, now);- const cells: Record<PromptColumnId, React.ReactNode> = {- topic: (- <TableCell key="topic">- {p.category?.trim() ? (- <ClampedText- handle={fullText}- text={p.category}- render={- <span className="text-xs text-muted-foreground truncate inline-block max-w-[140px] align-middle" />- }+ {layout === 'locations' ? (+ <LocationMatrix+ brandId={activeBrandId}+ rows={filtered}+ pageRows={pageRows}+ window={positionsWindow}+ onOpenCell={(promptId, region) => openPositionsPanel(promptId, 'platforms', region)}+ onTrack={onEditPrompt ? (prompt) => onEditPrompt(prompt) : undefined}+ />+ ) : (+ <Table stickyHeader stickyFirstColumn>+ {latenessOrder && (+ <TableCaption className="sr-only">{tPerformance('order')}</TableCaption>+ )}+ <TableHeader>+ <TableRow>+ <TableHead className="pl-6">+ {onEditPrompt ? (+ <div className="flex items-center gap-3">+ <Checkbox+ checked={allSelected(pageIds, selectedIds)}+ onCheckedChange={() => setSelectedIds(toggleAll(pageIds, selectedIds))}+ aria-label="Select every prompt on this page"/>- ) : (- <span className="text-xs text-muted-foreground inline-block align-middle">- —+ Prompt+ </div>+ ) : (+ 'Prompt'+ )}+ </TableHead>+ {columns.map((id) => {+ const loc = parseLocationColumn(id);+ return loc ? (+ <TableHead key={id} className="bg-muted/40 text-right">+ <span className="block text-xs font-medium">{tMetrics(loc.metric)}</span>+ <span className="block text-[11px] font-normal text-muted-foreground">+ {regionLabel(loc.region)}</span>- )}- </TableCell>- ),- status: (- <TableCell key="status" className="text-center">- <Badge- variant="outline"- className={cn('text-xs', STATUS_BADGE[status])}- title={status === 'new' ? tStatus('newHint') : undefined}- >- {tStatus(status)}- </Badge>- </TableCell>- ),- work: (- <TableCell key="work" className="text-center">- <div className="inline-flex flex-col items-center gap-0.5">- <WorkStatusBadge- status={statusOf(p)}- onChange={- onEditPrompt- ? guard((s: PromptWorkStatus | null) => handleStatusChange(p, s), {- action: tActions('setWorkStatus'),- })- : undefined- }- />- {p.targetUrlCount > 0 && (- <span- className={cn(- 'text-[10px] tabular-nums',- p.citedUrlCount > 0- ? 'text-emerald-600 dark:text-emerald-400'- : 'text-muted-foreground',- )}- title={`${p.citedUrlCount} of ${p.targetUrlCount} target URLs cited in AI answers`}- >- {p.citedUrlCount}/{p.targetUrlCount} cited+ </TableHead>+ ) : (+ headCells[id as PromptColumnId]+ );+ })}+ {onEditPrompt && (+ <TableHead className="text-right pr-6 w-[60px]">+ <span className="sr-only">Actions</span>+ </TableHead>+ )}+ </TableRow>+ </TableHeader>+ <TableBody>+ {pageRows.map((p) => {+ const vol = volumeByPromptId.get(p.id);+ const vis = visibility[p.id];+ const status = promptStatus(p, now);+ const cells: Record<PromptColumnId, React.ReactNode> = {+ topic: (+ <TableCell key="topic">+ {p.category?.trim() ? (+ <ClampedText+ handle={fullText}+ text={p.category}+ render={+ <span className="text-xs text-muted-foreground truncate inline-block max-w-[140px] align-middle" />+ }+ />+ ) : (+ <span className="text-xs text-muted-foreground inline-block align-middle">+ —</span>)}- </div>- </TableCell>- ),- visibility: (- <TableCell key="visibility" className="text-right">- {vis ? (- <div- className="inline-flex items-center gap-2 justify-end min-w-[110px]"- title={`Mentioned in ${vis.mentionAnswers} of ${vis.runs} answers (${rangeLabel}) · cited in ${vis.citationAnswers}${- vis.positionFactor !== null- ? ` · position factor ${vis.positionFactor.toFixed(2)}`- : ''- } · coverage ${vis.visibilityRate}% (${vis.visibleRuns}/${vis.runs} runs)`}+ </TableCell>+ ),+ status: (+ <TableCell key="status" className="text-center">+ <Badge+ variant="outline"+ className={cn('text-xs', STATUS_BADGE[status])}+ title={status === 'new' ? tStatus('newHint') : undefined}>- <span- className={cn(- 'text-sm font-semibold tabular-nums',- visibilityColorClass(vis.score ?? 0),- )}- >- {vis.score ?? 0}- </span>- <div className="h-1.5 w-16 rounded-full bg-muted overflow-hidden">- <div+ {tStatus(status)}+ </Badge>+ </TableCell>+ ),+ work: (+ <TableCell key="work" className="text-center">+ <div className="inline-flex flex-col items-center gap-0.5">+ <WorkStatusBadge+ status={statusOf(p)}+ onChange={+ onEditPrompt+ ? guard((s: PromptWorkStatus | null) => handleStatusChange(p, s), {+ action: tActions('setWorkStatus'),+ })+ : undefined+ }+ />+ {p.targetUrlCount > 0 && (+ <spanclassName={cn(- 'h-full rounded-full',- visibilityBarClass(vis.score ?? 0),+ 'text-[10px] tabular-nums',+ p.citedUrlCount > 0+ ? 'text-emerald-600 dark:text-emerald-400'+ : 'text-muted-foreground',)}- style={{- width: `${Math.min(100, Math.max(0, vis.score ?? 0))}%`,- }}- />- </div>- </div>- ) : (- <span className="text-xs text-muted-foreground">—</span>- )}- </TableCell>- ),- mentions: (- <TableCell key="mentions" className="text-right tabular-nums text-sm">- {vis ? (- formatNumber(vis.totalMentions)- ) : (- <span className="text-xs text-muted-foreground">—</span>- )}- </TableCell>- ),- citations: (- <TableCell key="citations" className="text-right tabular-nums text-sm">- {vis ? (- formatNumber(vis.totalCitations)- ) : (- <span className="text-xs text-muted-foreground">—</span>- )}- </TableCell>- ),- positions: (- <TableCell key="positions" className="pl-8">- {/* Fixed widths so the value, dots and See line up on every row. */}- <div className="inline-flex items-center gap-2">- <div className="w-[5.5rem] whitespace-nowrap">- <PositionValue cell={positions[p.id]} vis={vis} />- </div>- <div className="w-6">- {/* Whenever it has answers: a prompt never named is the one to open. */}- {opensPositionsPanel(vis) && (- <Button- type="button"- size="icon-xs"- variant="outline"- aria-label={`View positions for ${p.text}`}- title="See positions"- onClick={() => openPositionsPanel(p.id)}+ title={`${p.citedUrlCount} of ${p.targetUrlCount} target URLs cited in AI answers`}>- <BarChart3 />- </Button>+ {p.citedUrlCount}/{p.targetUrlCount} cited+ </span>)}</div>- </div>- </TableCell>- ),- volume: (- <TableCell key="volume" className="text-right">- {vol ? (- <EstimateRange- estimate={estimateByPromptId.get(p.id)!}- handle={volumeNote}- className="text-sm font-semibold"- />- ) : (- <span className="text-xs text-muted-foreground">—</span>- )}- </TableCell>- ),- competition: (- <TableCell key="competition" className="text-center">- <div className="flex justify-center">- <CompetitionBars- index={vol?.competitionIndex ?? null}- label={vol?.competition ?? null}- />- </div>- </TableCell>- ),- runs: (- <TableCell key="runs" className="text-right tabular-nums text-sm">- {vis ? (- formatNumber(vis.runs)- ) : (- <span className="text-xs text-muted-foreground">—</span>- )}- </TableCell>- ),- added: (- <TableCell- key="added"- className="text-right text-xs whitespace-nowrap text-muted-foreground"- title={new Date(p.createdAt).toLocaleString('en-US', {- dateStyle: 'medium',- timeStyle: 'short',- })}- >- {formatDate(p.createdAt)}- </TableCell>- ),- lastRun: (- <TableCell key="lastRun" className="text-right text-xs text-muted-foreground">- {formatRelative(vis?.lastRunAt, tCommon)}- </TableCell>- ),- };- return (- <TableRow key={p.id} className="hover:bg-muted/50">- <TableCell className="pl-6 font-medium text-sm max-w-[320px]">- <div className="flex items-start gap-3">- {onEditPrompt && (- <Checkbox- className="mt-0.5"- checked={selectedIds.has(p.id)}- onCheckedChange={(v) => toggleRow(p.id, v === true)}- aria-label={`Select ${p.text}`}+ </TableCell>+ ),+ visibility: (+ <TableCell key="visibility" className="text-right">+ {vis ? (+ <div+ className="inline-flex items-center gap-2 justify-end min-w-[110px]"+ title={`Mentioned in ${vis.mentionAnswers} of ${vis.runs} answers (${rangeLabel}) · cited in ${vis.citationAnswers}${+ vis.positionFactor !== null+ ? ` · position factor ${vis.positionFactor.toFixed(2)}`+ : ''+ } · coverage ${vis.visibilityRate}% (${vis.visibleRuns}/${vis.runs} runs)`}+ >+ <span+ className={cn(+ 'text-sm font-semibold tabular-nums',+ visibilityColorClass(vis.score ?? 0),+ )}+ >+ {vis.score ?? 0}+ </span>+ <div className="h-1.5 w-16 rounded-full bg-muted overflow-hidden">+ <div+ className={cn(+ 'h-full rounded-full',+ visibilityBarClass(vis.score ?? 0),+ )}+ style={{+ width: `${Math.min(100, Math.max(0, vis.score ?? 0))}%`,+ }}+ />+ </div>+ </div>+ ) : (+ <span className="text-xs text-muted-foreground">—</span>+ )}+ </TableCell>+ ),+ mentions: (+ <TableCell key="mentions" className="text-right tabular-nums text-sm">+ {vis ? (+ formatNumber(vis.totalMentions)+ ) : (+ <span className="text-xs text-muted-foreground">—</span>+ )}+ </TableCell>+ ),+ citations: (+ <TableCell key="citations" className="text-right tabular-nums text-sm">+ {vis ? (+ formatNumber(vis.totalCitations)+ ) : (+ <span className="text-xs text-muted-foreground">—</span>+ )}+ </TableCell>+ ),+ positions: (+ <TableCell key="positions" className="pl-8">+ {/* Fixed widths so the value, dots and See line up on every row. */}+ <div className="inline-flex items-center gap-2">+ <div className="w-[5.5rem] whitespace-nowrap">+ <PositionValue cell={positions[p.id]} vis={vis} />+ </div>+ <div className="w-6">+ {/* Whenever it has answers: a prompt never named is the one to open. */}+ {opensPositionsPanel(vis) && (+ <Button+ type="button"+ size="icon-xs"+ variant="outline"+ aria-label={`View positions for ${p.text}`}+ title="See positions"+ onClick={() => openPositionsPanel(p.id)}+ >+ <BarChart3 />+ </Button>+ )}+ </div>+ </div>+ </TableCell>+ ),+ volume: (+ <TableCell key="volume" className="text-right">+ {vol ? (+ <EstimateRange+ estimate={estimateByPromptId.get(p.id)!}+ handle={volumeNote}+ className="text-sm font-semibold"/>+ ) : (+ <span className="text-xs text-muted-foreground">—</span>)}- <ClampedText- handle={fullText}- text={p.text}- render={- <Link- href={`/dashboard/prompts/${p.id}`}- className="line-clamp-2 transition-colors hover:text-primary hover:underline"+ </TableCell>+ ),+ competition: (+ <TableCell key="competition" className="text-center">+ <div className="flex justify-center">+ <CompetitionBars+ index={vol?.competitionIndex ?? null}+ label={vol?.competition ?? null}+ />+ </div>+ </TableCell>+ ),+ runs: (+ <TableCell key="runs" className="text-right tabular-nums text-sm">+ {vis ? (+ formatNumber(vis.runs)+ ) : (+ <span className="text-xs text-muted-foreground">—</span>+ )}+ </TableCell>+ ),+ added: (+ <TableCell+ key="added"+ className="text-right text-xs whitespace-nowrap text-muted-foreground"+ title={new Date(p.createdAt).toLocaleString('en-US', {+ dateStyle: 'medium',+ timeStyle: 'short',+ })}+ >+ {formatDate(p.createdAt)}+ </TableCell>+ ),+ lastRun: (+ <TableCell key="lastRun" className="text-right text-xs text-muted-foreground">+ {formatRelative(vis?.lastRunAt, tCommon)}+ </TableCell>+ ),+ };+ return (+ <TableRow key={p.id} className="hover:bg-muted/50">+ <TableCell className="pl-6 font-medium text-sm max-w-[320px]">+ <div className="flex items-start gap-3">+ {onEditPrompt && (+ <Checkbox+ className="mt-0.5"+ checked={selectedIds.has(p.id)}+ onCheckedChange={(v) => toggleRow(p.id, v === true)}+ aria-label={`Select ${p.text}`}/>- }- />- </div>- </TableCell>- {columns.map((id) => cells[id])}- {onEditPrompt && (- <TableCell className="text-right pr-6">- <RowActionsMenu- prompt={p}- brandId={activeBrandId}- onEdit={() => onEditPrompt(p)}- onToggleActive={guard(() => void toggleActive(p), {- action: tActions(p.isActive ? 'pausePrompts' : 'resumePrompts'),- })}- onImprove={() => openPositionsPanel(p.id, 'improve')}- onSuggestContent={guard(() => void suggestContent(p), {- action: tActions('suggestContent'),- })}- onOpenSuggestion={openOpportunity}- suggesting={suggestingIds.has(p.id)}- noPlan={contentNoPlan}- suggestDisabledReason={- suggestDisabledReason ??- (bulkSuggesting ? 'Wait for the selected prompts' : null)- }- onCreateContent={guard(- () =>- setContentPreset({- kind: 'prompt',- id: p.id,- text: p.text,- method: 'create',- }),- { action: tActions('createContent') },)}- onDelete={guard(() => setConfirmDelete([p]), {- action: tActions('deletePrompts'),- })}- />+ <ClampedText+ handle={fullText}+ text={p.text}+ render={+ <Link+ href={`/dashboard/prompts/${p.id}`}+ className="line-clamp-2 transition-colors hover:text-primary hover:underline"+ />+ }+ />+ </div></TableCell>- )}- </TableRow>- );- })}- </TableBody>- </Table>+ {columns.map((id) => {+ const loc = parseLocationColumn(id);+ if (!loc) return cells[id as PromptColumnId];+ const value = metricValue(locationMatrix?.[p.id]?.[loc.region], loc.metric);+ return (+ <TableCell+ key={id}+ className="bg-muted/20 text-right text-sm font-semibold tabular-nums"+ >+ {value === null ? (+ <span className="text-xs font-normal text-muted-foreground">—</span>+ ) : loc.metric === 'position' ? (+ `#${value.toFixed(1)}`+ ) : (+ formatNumber(Math.round(value))+ )}+ </TableCell>+ );+ })}+ {onEditPrompt && (+ <TableCell className="text-right pr-6">+ <RowActionsMenu+ prompt={p}+ brandId={activeBrandId}+ onEdit={() => onEditPrompt(p)}+ onToggleActive={guard(() => void toggleActive(p), {+ action: tActions(p.isActive ? 'pausePrompts' : 'resumePrompts'),+ })}+ onImprove={() => openPositionsPanel(p.id, 'improve')}+ onSuggestContent={guard(() => void suggestContent(p), {+ action: tActions('suggestContent'),+ })}+ onOpenSuggestion={openOpportunity}+ suggesting={suggestingIds.has(p.id)}+ noPlan={contentNoPlan}+ suggestDisabledReason={+ suggestDisabledReason ??+ (bulkSuggesting ? 'Wait for the selected prompts' : null)+ }+ onCreateContent={guard(+ () =>+ setContentPreset({+ kind: 'prompt',+ id: p.id,+ text: p.text,+ method: 'create',+ }),+ { action: tActions('createContent') },+ )}+ onDelete={guard(() => setConfirmDelete([p]), {+ action: tActions('deletePrompts'),+ })}+ />+ </TableCell>+ )}+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ )}<ClampedTextTooltip handle={fullText} /><EstimateNoteTooltip handle={volumeNote} /><TablePager@@ -4192,7 +4329,7 @@ function AllPromptsTab({range={positionsRange}window={panelWindow}onRangeChange={setPositionsRange}- region={regionFilter}+ region={panelRegion ?? regionFilter}initialTab={positionsTab}// Escape and a click outside belong to Start while it is open over the// panel: they close Start, and the panel stays.diff --git a/web/src/lib/actions/prompt-table-views.ts b/web/src/lib/actions/prompt-table-views.tsindex 6edcdb164..87ad8bdc9 100644--- a/web/src/lib/actions/prompt-table-views.ts+++ b/web/src/lib/actions/prompt-table-views.ts@@ -3,7 +3,9 @@import { z } from 'zod';import { createClient } from '@/lib/supabase/server';import {+ MAX_LOCATION_COLUMNS,PROMPT_COLUMNS,+ isLocationColumn,readColumnsView,type PromptColumnsView,} from '@/lib/prompt-table-columns';@@ -15,9 +17,11 @@ import {* Failures come back as a value: production masks a thrown error's message.*/+const columnId = z.union([z.enum(PROMPT_COLUMNS), z.string().refine(isLocationColumn)]);+const MAX_IDS = PROMPT_COLUMNS.length + MAX_LOCATION_COLUMNS;const viewSchema = z.object({- order: z.array(z.enum(PROMPT_COLUMNS)).max(PROMPT_COLUMNS.length),- hidden: z.array(z.enum(PROMPT_COLUMNS)).max(PROMPT_COLUMNS.length),+ order: z.array(columnId).max(MAX_IDS),+ hidden: z.array(columnId).max(MAX_IDS),});export interface PromptTableViews {@@ -75,7 +79,7 @@ export async function savePromptTableView({brand_id: brandId,user_id: scope === 'brand' ? null : user.id,- columns: parsed.data,+ columns: { order: [...parsed.data.order], hidden: [...parsed.data.hidden] },updated_by: user.id,updated_at: new Date().toISOString(),},diff --git a/web/src/lib/actions/prompt.test.ts b/web/src/lib/actions/prompt.test.tsindex d73fcc9a0..77e46d801 100644--- a/web/src/lib/actions/prompt.test.ts+++ b/web/src/lib/actions/prompt.test.ts@@ -1,7 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { PLANS, type Plan } from '@/config/plans';import { getPromptVolumes, type VolumeQuota } from '@/lib/actions/volumes';-import { getPromptVisibilitySummaries } from '@/lib/actions/tracking';+import { getPromptVisibilitySummaries, type PromptVisibilitySummary } from '@/lib/actions/tracking';/*** setPromptActive meters resuming like adding (00128): only active prompts@@ -26,6 +26,16 @@ let positionsNull = false;let jsonRpcMissing = false;/** The position RPC calls, and whether any asked for a slice. */let positionCalls: { fn: string; ranged: boolean }[] = [];+/** When set, each heavy read takes a moment, counted while it runs. */+let slowReads: { running: number; most: number } | null = null;+const slowRead = async <T>(read: () => T | Promise<T>): Promise<T> => {+ if (!slowReads) return read();+ const reads = slowReads;+ reads.most = Math.max(reads.most, ++reads.running);+ await new Promise((resolve) => setTimeout(resolve, 2));+ reads.running--;+ return read();+};vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }));vi.mock('@/lib/actions/volumes', () => ({ getPromptVolumes: vi.fn() }));@@ -68,7 +78,10 @@ vi.mock('@/lib/supabase/server', () => ({call.ranged = true;return chain;},- then: (resolve: (value: unknown) => unknown) => resolve(result()),+ then: (resolve: (value: unknown) => unknown) =>+ fn === 'prompt_position_summaries_json'+ ? slowRead(result).then(resolve)+ : resolve(result()),};return chain;},@@ -106,7 +119,8 @@ vi.mock('@/lib/supabase/server', () => ({})),}));-const { getPromptsPageData, setPromptActive, updatePromptLocations } = await import('./prompt');+const { getPromptLocationMatrix, getPromptsPageData, setPromptActive, updatePromptLocations } =+ await import('./prompt');const capped = (maxPrompts: number): Plan => ({...PLANS.starter,@@ -368,3 +382,89 @@ describe('getPromptsPageData', () => {);});});++describe('getPromptLocationMatrix (PROMPT-015b)', () => {+ const BRAND = '11111111-1111-1111-1111-111111111111';+ beforeEach(() => {+ plan = capped(50);+ positionData = [+ {+ prompt_id: 'p1',+ platform: 'chatgpt-web',+ runs: 4,+ mention_answers: 4,+ position_sum: 10,+ position_count: 4,+ entity_sum: 20,+ entity_count: 4,+ },+ ];+ positionsError = null;+ previousPositionData = null;+ positionsNull = false;+ jsonRpcMissing = false;+ vi.mocked(getPromptVisibilitySummaries).mockImplementation(+ async (_brand, opts): Promise<Record<string, PromptVisibilitySummary>> =>+ opts?.region === 'TR'+ ? {+ p1: {+ score: 35,+ totalMentions: 9,+ totalCitations: 2,+ runs: 6,+ } as PromptVisibilitySummary,+ }+ : {},+ );+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("reads each location as the table reads one, and keys the prompt's figures by it", async () => {+ const matrix = await getPromptLocationMatrix(BRAND, {+ from: '2026-10-21T00:00:00Z',+ regions: ['TR', 'US', 'TR', 'not a code'],+ });+ expect(vi.mocked(getPromptVisibilitySummaries).mock.calls.map(([, o]) => o?.region)).toEqual([+ 'TR',+ 'US',+ ]);+ expect(matrix).toEqual({+ p1: { TR: { score: 35, mentions: 9, citations: 2, position: 2.5, runs: 6 } },+ });+ await expect(getPromptLocationMatrix('nope', { regions: ['TR'] })).rejects.toThrow('invalid');+ });++ it('runs at most three of its heavy reads at once, however many locations', async () => {+ slowReads = { running: 0, most: 0 };+ positionCalls = [];+ vi.mocked(getPromptVisibilitySummaries).mockClear();+ const summaries = vi.mocked(getPromptVisibilitySummaries).getMockImplementation()!;+ vi.mocked(getPromptVisibilitySummaries).mockImplementation((brand, opts) =>+ slowRead(() => summaries(brand, opts)),+ );+ const regions = ['TR', 'US', 'DE', 'FR', 'GB', 'ES', 'IT', 'NL', 'JP', 'BR', 'CA', 'AU'];+ try {+ const matrix = await getPromptLocationMatrix(BRAND, {+ from: '2026-10-21T00:00:00Z',+ regions,+ });+ expect(vi.mocked(getPromptVisibilitySummaries)).toHaveBeenCalledTimes(12);+ expect(positionCalls.filter((c) => c.fn === 'prompt_position_summaries_json')).toHaveLength(+ 12,+ );+ expect(slowReads.most).toBe(3);+ expect(matrix.p1.TR).toEqual({+ score: 35,+ mentions: 9,+ citations: 2,+ position: 2.5,+ runs: 6,+ });+ } finally {+ slowReads = null;+ }+ });+});diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.tsindex 3fa730d05..b994a869d 100644--- a/web/src/lib/actions/prompt.ts+++ b/web/src/lib/actions/prompt.ts@@ -1,5 +1,6 @@'use server';+import { z } from 'zod';import { createClient } from '@/lib/supabase/server';import { revalidatePath } from 'next/cache';import type { PromptSet, Prompt, AIPlatform, PromptVolume } from '@/types';@@ -14,6 +15,12 @@ import {import { ALL_MODELS, ALL_SCRAPERS, DEFAULT_PROMPT_RANGE_DAYS } from '@/config/prompt-options';import { PROMPT_DELETE_BATCH } from '@/lib/prompt-bulk-actions';import { isValidLocation, locationCode } from '@/lib/region';+import { createLimiter } from '@/lib/limiter';+import {+ MATRIX_READS_AT_ONCE,+ MATRIX_REGIONS,+ type PromptLocationCell,+} from '@/lib/prompt-location-matrix';import type { Plan, PlanId } from '@/config/plans';import { getPromptVolumes, type VolumeQuota } from '@/lib/actions/volumes';import {@@ -1146,24 +1153,86 @@ async function getPositionRows(window: { from: string; to?: string },region?: string,): Promise<PositionRows> {+ const before = previousWindow(window);+ const [included, current, previous] = await Promise.all([+ includedPositionPlatforms(brandId),+ positionSums(brandId, window, region),+ positionSums(brandId, before, region),+ ]);+ if (!included) return noPositionRows();+ return { included, current, previous };+}++/** The engines the org's plan includes, as the Positions panel counts them; null without a brand. */+async function includedPositionPlatforms(+ brandId: string,+): Promise<{ id: string; label: string }[] | null> {const supabase = await createClient();const { data: brand } = await supabase.from('brands').select('organization_id').eq('id', brandId).maybeSingle();- if (!brand?.organization_id) return noPositionRows();+ if (!brand?.organization_id) return null;+ const plan = await getOrgPlan(brand.organization_id as string);+ return POSITION_PLATFORMS.filter((p) => platformAccess(plan, p.id).state === 'included').map(+ (p) => ({ id: p.id as string, label: p.label as string }),+ );+}- const before = previousWindow(window);- const [plan, current, previous] = await Promise.all([- getOrgPlan(brand.organization_id as string),- positionSums(brandId, window, region),- positionSums(brandId, before, region),+/**+ * Each tracked prompt's figures in each of `regions` (PROMPT-015b): the+ * same reads the table uses for one location, once per location, side by+ * side, so a location's column equals the table filtered to it. Keyed by+ * prompt id, then location code; a prompt with no answers in a location+ * has no cell there.+ */+export async function getPromptLocationMatrix(+ brandId: string,+ opts: { days?: number; from?: string; to?: string; regions: string[] },+): Promise<Record<string, Record<string, PromptLocationCell>>> {+ const regions = [...new Set(opts.regions.filter(isValidLocation))].slice(0, MATRIX_REGIONS);+ if (!z.guid().safeParse(brandId).success) throw new Error('invalid');+ const days = opts.days ?? DEFAULT_PROMPT_RANGE_DAYS;+ const window = {+ from: opts.from ?? new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString(),+ to: opts.to,+ };+ // One round of reads, but at most MATRIX_READS_AT_ONCE of the heavy ones+ // (two per location) at a time: twelve locations at once squeezed the+ // database.+ const limit = createLimiter(MATRIX_READS_AT_ONCE);+ const [platforms, reads] = await Promise.all([+ includedPositionPlatforms(brandId),+ Promise.all(+ regions.map((region) =>+ Promise.all([+ limit(() =>+ getPromptVisibilitySummaries(brandId, { days, from: opts.from, to: opts.to, region }),+ ),+ limit(() => positionSums(brandId, window, region)).catch((err) => {+ console.error('[prompts] location position sums failed:', err);+ return new Map<string, PlatformPositionRow[]>();+ }),+ ]),+ ),+ ),]);- const included = POSITION_PLATFORMS.filter(- (p) => platformAccess(plan, p.id).state === 'included',- ).map((p) => ({ id: p.id as string, label: p.label as string }));- return { included, current, previous };+ const included = platforms ?? [];+ const cells: Record<string, Record<string, PromptLocationCell>> = {};+ regions.forEach((region, i) => {+ const [visibility, positions] = reads[i];+ for (const [promptId, vis] of Object.entries(visibility)) {+ (cells[promptId] ??= {})[region] = {+ score: vis.score,+ mentions: vis.totalMentions,+ citations: vis.totalCitations,+ position: buildPositionCell(positions.get(promptId) ?? [], [], included).avg,+ runs: vis.runs,+ };+ }+ });+ return cells;}/** A prompt and platform's sums, as prompt_position_summaries_json (00153) returns them. */diff --git a/web/src/lib/insights-topics.ts b/web/src/lib/insights-topics.tsindex 4449ccf23..3cf3c0ee6 100644--- a/web/src/lib/insights-topics.ts+++ b/web/src/lib/insights-topics.ts@@ -119,6 +119,20 @@ export function topicHeatmap(topics: TopicCompetitors[], columns: string[]): Hea);}+/**+ * Cell shades, light to dark: soft theme-relative tints, so they read in+ * both themes and a full table doesn't turn into dark blocks. The text keeps+ * its color on every shade. Also the Tracked Prompts Locations view's+ * (PROMPT-015b), by heatShade's index.+ */+export const HEAT_SHADES = [+ 'bg-muted/40 text-muted-foreground',+ 'bg-foreground/[0.06] text-foreground',+ 'bg-foreground/[0.12] text-foreground',+ 'bg-foreground/[0.2] text-foreground',+ 'bg-foreground/[0.32] text-foreground',+] as const;+/*** A cell's shade, light to dark, by where its score sits between the lowest* and highest non-zero score in view. The map compares, so its tones spreaddiff --git a/web/src/lib/limiter.test.ts b/web/src/lib/limiter.test.tsnew file mode 100644index 000000000..caa35fcfe--- /dev/null+++ b/web/src/lib/limiter.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from 'vitest';+import { createLimiter } from './limiter';++/** createLimiter: at most `max` tasks at once, in the order they came. */++const tick = () => new Promise<void>((resolve) => setTimeout(resolve, 0));++describe('createLimiter', () => {+ it('runs at most three at once, in order, and starts the next as one ends', async () => {+ const run = createLimiter(3);+ let running = 0;+ let most = 0;+ const started: number[] = [];+ const ends: (() => void)[] = [];+ const results = Array.from({ length: 7 }, (_, i) =>+ run(async () => {+ started.push(i);+ most = Math.max(most, ++running);+ await new Promise<void>((resolve) => ends.push(resolve));+ running--;+ return i;+ }),+ );+ await tick();+ expect(started).toEqual([0, 1, 2]);+ ends[1]();+ await tick();+ expect(started).toEqual([0, 1, 2, 3]);+ // A task arriving now waits behind those already waiting.+ const late = run(async () => {+ started.push(99);+ return 99;+ });+ for (let i = 0; i < 20 && started.length < 9; i++) {+ ends.forEach((end) => end());+ await tick();+ }+ expect(await Promise.all(results)).toEqual([0, 1, 2, 3, 4, 5, 6]);+ expect(await late).toBe(99);+ expect(started.indexOf(99)).toBe(7);+ expect(most).toBe(3);+ });++ it("frees a failed task's place", async () => {+ const run = createLimiter(1);+ await expect(run(async () => Promise.reject(new Error('down')))).rejects.toThrow('down');+ await expect(+ run(() => {+ throw new Error('at once');+ }),+ ).rejects.toThrow('at once');+ expect(await run(async () => 'next')).toBe('next');+ });+});diff --git a/web/src/lib/limiter.ts b/web/src/lib/limiter.tsnew file mode 100644index 000000000..b261857cf--- /dev/null+++ b/web/src/lib/limiter.ts@@ -0,0 +1,21 @@+/**+ * Runs the tasks handed to it at most `max` at a time, in the order they+ * came: heavy reads that would otherwise all start at once. A task waiting+ * for a place takes the one a finished task leaves, so a task arriving in+ * between can't jump the line.+ */+export function createLimiter(max: number) {+ let running = 0;+ const waiting: (() => void)[] = [];+ return async function run<T>(task: () => Promise<T>): Promise<T> {+ if (running < max) running++;+ else await new Promise<void>((resolve) => waiting.push(resolve));+ try {+ return await task();+ } finally {+ const next = waiting.shift();+ if (next) next();+ else running--;+ }+ };+}diff --git a/web/src/lib/prompt-location-matrix.test.ts b/web/src/lib/prompt-location-matrix.test.tsnew file mode 100644index 000000000..cc047ae56--- /dev/null+++ b/web/src/lib/prompt-location-matrix.test.ts@@ -0,0 +1,95 @@+import { describe, expect, it } from 'vitest';+import {+ cellShade,+ locationAverages,+ matrixInsights,+ matrixLocations,+ metricValue,+ rowGap,+ type PromptLocationCell,+ type PromptLocationMatrix,+} from './prompt-location-matrix';++/** The Tracked Prompts Locations view (PROMPT-015b). */++const cell = (+ score: number | null,+ over: Partial<PromptLocationCell> = {},+): PromptLocationCell => ({+ score,+ mentions: score === null ? 0 : Math.round(score / 2),+ citations: 1,+ position: score ? 3.5 : null,+ runs: score === null ? 0 : 7,+ ...over,+});++const matrix: PromptLocationMatrix = {+ p1: { TR: cell(35), 'TR~istanbul': cell(41), US: cell(62) },+ p2: { TR: cell(26), 'TR~istanbul': cell(47), US: cell(20) },+ p3: { US: cell(70) },+};+const prompts = [+ { id: 'p1', text: 'best specialty coffee subscription', regions: ['US', 'TR', 'TR~istanbul'] },+ { id: 'p2', text: 'same day coffee delivery near me', regions: ['US', 'TR', 'TR~istanbul'] },+ { id: 'p3', text: 'single origin vs blend coffee', regions: ['US'] },+];+const regions = ['US', 'TR', 'TR~istanbul'];++describe('metricValue', () => {+ it("reads the metric, and nothing where there are no answers or it's never named", () => {+ expect(metricValue(matrix.p1.US, 'visibility')).toBe(62);+ expect(metricValue(matrix.p1.US, 'mentions')).toBe(31);+ expect(metricValue(matrix.p1.US, 'position')).toBe(3.5);+ expect(metricValue(cell(0, { position: null }), 'position')).toBeNull();+ expect(metricValue(undefined, 'visibility')).toBeNull();+ expect(metricValue(cell(null), 'visibility')).toBeNull();+ });+});++describe('matrixLocations', () => {+ it('shows the locations the prompts track, the most tracked first', () => {+ expect(matrixLocations(prompts)).toEqual(['US', 'TR', 'TR~istanbul']);+ expect(matrixLocations([{ regions: [] }])).toEqual([]);+ });+});++describe('cellShade', () => {+ it('spreads the tones over the values in view; for position, earlier is darker', () => {+ const inView = [20, 35, 62, 70];+ expect(cellShade(70, inView, 'visibility')).toBe(4);+ expect(cellShade(20, inView, 'visibility')).toBe(1);+ expect(cellShade(null, inView, 'visibility')).toBe(0);+ expect(cellShade(0, inView, 'visibility')).toBe(0);+ expect(cellShade(1.5, [1.5, 6], 'position')).toBe(4);+ expect(cellShade(6, [1.5, 6], 'position')).toBe(1);+ });+});++describe('rowGap and locationAverages', () => {+ it('reads the gap between the best and worst location, and each location’s average', () => {+ expect(rowGap([35, 41, 62])).toBe(27);+ expect(rowGap([35, null])).toBeNull();+ expect(locationAverages(matrix, ['p1', 'p2', 'p3'], regions, 'visibility')).toEqual([+ 51, 31, 44,+ ]);+ });+});++describe('matrixInsights', () => {+ it('names the weakest and strongest location and the widest prompt, on visibility', () => {+ expect(matrixInsights(matrix, prompts, regions)).toEqual({+ weakest: { region: 'TR', average: 31, untracked: 1 },+ strongest: { region: 'US', average: 51, tracked: 3 },+ widest: {+ promptId: 'p1',+ text: 'best specialty coffee subscription',+ low: 35,+ lowAt: 'TR',+ high: 62,+ highAt: 'US',+ },+ overall: 43,+ });+ });+});diff --git a/web/src/lib/prompt-location-matrix.ts b/web/src/lib/prompt-location-matrix.tsnew file mode 100644index 000000000..783f6ec68--- /dev/null+++ b/web/src/lib/prompt-location-matrix.ts@@ -0,0 +1,172 @@+import { heatShade } from '@/lib/insights-topics';++/**+ * The Tracked Prompts Locations view (PROMPT-015b): each tracked prompt in+ * each location the brand tracks, side by side, for one metric at a time.+ * The figures are the table's own, read once per location+ * (getPromptLocationMatrix); this module shapes them.+ */++export type LocationMetric = 'visibility' | 'position' | 'mentions' | 'citations';+export const LOCATION_METRICS: readonly LocationMetric[] = [+ 'visibility',+ 'position',+ 'mentions',+ 'citations',+];++/** One prompt in one location. */+export interface PromptLocationCell {+ /** AI Visibility Score, 0–100; null without answers. */+ score: number | null;+ mentions: number;+ citations: number;+ /** Average position the brand is named at; null when never named. */+ position: number | null;+ runs: number;+}++/** By prompt id, then location code. */+export type PromptLocationMatrix = Record<string, Record<string, PromptLocationCell>>;++/** Locations read at most in one go: each is its own read. */+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;++/** A cell's value for the metric; null without answers there (or, for position, never named). */+export function metricValue(+ cell: PromptLocationCell | undefined,+ metric: LocationMetric,+): number | null {+ if (!cell || cell.runs === 0) return null;+ if (metric === 'visibility') return cell.score;+ if (metric === 'mentions') return cell.mentions;+ if (metric === 'citations') return cell.citations;+ return cell.position;+}++/**+ * The locations the view shows: those the prompts track, the most tracked+ * first, then by code, at most MATRIX_REGIONS.+ */+export function matrixLocations(prompts: readonly { regions: readonly string[] }[]): string[] {+ const counts = new Map<string, number>();+ for (const p of prompts) {+ for (const r of new Set(p.regions)) counts.set(r, (counts.get(r) ?? 0) + 1);+ }+ return [...counts]+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))+ .slice(0, MATRIX_REGIONS)+ .map(([r]) => r);+}++/**+ * A value's shade, 0 (lightest) to 4, among the values in view, as Brand+ * Visibility's Topics vs competitors shades its map (heatShade). For+ * position, being named earlier is darker; never named stays lightest.+ */+export function cellShade(+ value: number | null,+ inView: readonly number[],+ metric: LocationMetric,+): 0 | 1 | 2 | 3 | 4 {+ if (value === null || value <= 0) return 0;+ const shown = inView.filter((v) => v > 0);+ if (!shown.length) return 0;+ const low = Math.min(...shown);+ const high = Math.max(...shown);+ return metric === 'position'+ ? heatShade(high + low - value, low, high)+ : heatShade(value, low, high);+}++/** Best minus worst location for a prompt; null with fewer than two values. */+export function rowGap(values: readonly (number | null)[]): number | null {+ const known = values.filter((v): v is number => v !== null);+ if (known.length < 2) return null;+ return Math.round((Math.max(...known) - Math.min(...known)) * 10) / 10;+}++/** The metric's average per location, over the prompts with a value there. */+export function locationAverages(+ matrix: PromptLocationMatrix,+ promptIds: readonly string[],+ regions: readonly string[],+ metric: LocationMetric,+): (number | null)[] {+ return regions.map((region) => {+ const values = promptIds+ .map((id) => metricValue(matrix[id]?.[region], metric))+ .filter((v): v is number => v !== null);+ if (!values.length) return null;+ const avg = values.reduce((a, b) => a + b, 0) / values.length;+ return metric === 'position' ? Math.round(avg * 10) / 10 : Math.round(avg);+ });+}++export interface MatrixInsights {+ /** By average visibility, with the prompts not tracked there. */+ weakest: { region: string; average: number; untracked: number } | null;+ strongest: { region: string; average: number; tracked: number } | null;+ /** The prompt whose visibility differs most between locations. */+ widest: {+ promptId: string;+ text: string;+ low: number;+ lowAt: string;+ high: number;+ highAt: string;+ } | null;+ /** Visibility across every location, for the weakest's comparison. */+ overall: number | null;+}++/** The three cards above the view, on visibility whatever the metric shown. */+export function matrixInsights(+ matrix: PromptLocationMatrix,+ prompts: readonly { id: string; text: string; regions: readonly string[] }[],+ regions: readonly string[],+): MatrixInsights {+ const ids = prompts.map((p) => p.id);+ const averages = locationAverages(matrix, ids, regions, 'visibility');+ const ranked = regions+ .map((region, i) => ({ region, average: averages[i] }))+ .filter((r): r is { region: string; average: number } => r.average !== null);+ const sorted = [...ranked].sort((a, b) => a.average - b.average);+ const all = prompts.flatMap((p) =>+ regions+ .map((r) => metricValue(matrix[p.id]?.[r], 'visibility'))+ .filter((v): v is number => v !== null),+ );+ let widest: MatrixInsights['widest'] = null;+ let widestGap = -1;+ for (const p of prompts) {+ const values = regions.map((r) => metricValue(matrix[p.id]?.[r], 'visibility'));+ const gap = rowGap(values);+ if (gap === null || gap <= widestGap) continue;+ widestGap = gap;+ const known = values.map((v, i) => ({ v, r: regions[i] })).filter((x) => x.v !== null);+ const lo = known.reduce((a, b) => (b.v! < a.v! ? b : a));+ const hi = known.reduce((a, b) => (b.v! > a.v! ? b : a));+ widest = {+ promptId: p.id,+ text: p.text,+ low: Math.round(lo.v!),+ lowAt: lo.r,+ high: Math.round(hi.v!),+ highAt: hi.r,+ };+ }+ const tracking = (region: string) => prompts.filter((p) => p.regions.includes(region)).length;+ const weakest = sorted[0];+ const strongest = sorted.at(-1);+ return {+ weakest: weakest ? { ...weakest, untracked: prompts.length - tracking(weakest.region) } : null,+ strongest:+ strongest && sorted.length > 1 ? { ...strongest, tracked: tracking(strongest.region) } : null,+ widest,+ overall: all.length ? Math.round(all.reduce((a, b) => a + b, 0) / all.length) : null,+ };+}diff --git a/web/src/lib/prompt-table-columns.test.ts b/web/src/lib/prompt-table-columns.test.tsindex 9547c2bc3..ba796ca5c 100644--- a/web/src/lib/prompt-table-columns.test.ts+++ b/web/src/lib/prompt-table-columns.test.ts@@ -1,7 +1,11 @@import { describe, expect, it } from 'vitest';import {DEFAULT_COLUMNS_VIEW,+ MAX_LOCATION_COLUMNS,PROMPT_COLUMNS,+ addLocationColumn,+ parseLocationColumn,+ removeColumn,effectiveView,moveColumn,readColumnsView,@@ -69,3 +73,27 @@ describe('a view', () => {expect(effectiveView(null, null)).toBe(DEFAULT_COLUMNS_VIEW);});});++describe('location columns (PROMPT-015b)', () => {+ it('adds a metric in a location at the end, once, and takes it out', () => {+ const added = addLocationColumn(DEFAULT_COLUMNS_VIEW, 'visibility', 'TR');+ expect(added.order.at(-1)).toBe('loc:visibility:TR');+ expect(addLocationColumn(added, 'visibility', 'TR').order).toEqual(added.order);+ expect(parseLocationColumn('loc:position:US-CA')).toEqual({+ metric: 'position',+ region: 'US-CA',+ });+ expect(parseLocationColumn('volume')).toBeNull();+ expect(removeColumn(added, 'loc:visibility:TR')).toEqual(DEFAULT_COLUMNS_VIEW);+ });++ it(`keeps saved ones, ${MAX_LOCATION_COLUMNS} at most, and drops malformed ones`, () => {+ const many = Array.from({ length: 10 }, (_, i) => `loc:mentions:R${i}`);+ const view = readColumnsView({+ order: [...PROMPT_COLUMNS, ...many, 'loc:nope:TR'],+ hidden: [],+ });+ expect(view?.order.filter((id) => id.startsWith('loc:'))).toHaveLength(MAX_LOCATION_COLUMNS);+ expect(view?.order).not.toContain('loc:nope:TR');+ });+});diff --git a/web/src/lib/prompt-table-columns.ts b/web/src/lib/prompt-table-columns.tsindex b7e10bf0a..7e448325d 100644--- a/web/src/lib/prompt-table-columns.ts+++ b/web/src/lib/prompt-table-columns.ts@@ -1,3 +1,5 @@+import type { LocationMetric } from '@/lib/prompt-location-matrix';+/*** The Tracked Prompts table's columns a person can show, hide and order* (PROMPT-015a). Prompt and the row's menu always show. A saved view is@@ -23,15 +25,40 @@ export const PROMPT_COLUMNS = [export type PromptColumnId = (typeof PROMPT_COLUMNS)[number];+/** A metric in one location, as a column (PROMPT-015b): `loc:<metric>:<location code>`. */+export type LocationColumnId = `loc:${LocationMetric}:${string}`;++export type TableColumnId = PromptColumnId | LocationColumnId;+export interface PromptColumnsView {- order: PromptColumnId[];- hidden: PromptColumnId[];+ order: TableColumnId[];+ hidden: TableColumnId[];+}++/** Location columns a view holds at most. */+export const MAX_LOCATION_COLUMNS = 8;++const LOCATION_COLUMN = /^loc:(visibility|position|mentions|citations):([A-Za-z0-9~_-]{2,64})$/;++export function locationColumn(metric: LocationMetric, region: string): LocationColumnId {+ return `loc:${metric}:${region}`;+}++/** A location column's metric and location; null for any other column. */+export function parseLocationColumn(id: string): { metric: LocationMetric; region: string } | null {+ const match = LOCATION_COLUMN.exec(id);+ return match ? { metric: match[1] as LocationMetric, region: match[2] } : null;+}++export function isLocationColumn(id: string): id is LocationColumnId {+ return LOCATION_COLUMN.test(id);}export const DEFAULT_COLUMNS_VIEW: PromptColumnsView = { order: [...PROMPT_COLUMNS], hidden: [] };const KNOWN = new Set<string>(PROMPT_COLUMNS);-const isColumn = (id: unknown): id is PromptColumnId => typeof id === 'string' && KNOWN.has(id);+const isColumn = (id: unknown): id is TableColumnId =>+ typeof id === 'string' && (KNOWN.has(id) || isLocationColumn(id));/*** A saved view, as the table reads it: ids it doesn't know are dropped, and@@ -42,7 +69,17 @@ export function readColumnsView(raw: unknown): PromptColumnsView | null {if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;const { order, hidden } = raw as { order?: unknown; hidden?: unknown };if (!Array.isArray(order)) return null;- const kept = [...new Set(order.filter(isColumn))];+ const locations = order.filter(+ (id): id is LocationColumnId => typeof id === 'string' && isLocationColumn(id),+ );+ const kept: TableColumnId[] = [+ ...new Set(+ order.filter(+ (id) =>+ isColumn(id) && (!isLocationColumn(id) || locations.indexOf(id) < MAX_LOCATION_COLUMNS),+ ),+ ),+ ] as TableColumnId[];for (const [i, id] of PROMPT_COLUMNS.entries()) {if (kept.includes(id)) continue;const before = PROMPT_COLUMNS.slice(0, i).findLast((prev) => kept.includes(prev));@@ -50,19 +87,21 @@ export function readColumnsView(raw: unknown): PromptColumnsView | null {}return {order: kept,- hidden: Array.isArray(hidden) ? [...new Set(hidden.filter(isColumn))] : [],+ hidden: Array.isArray(hidden)+ ? [...new Set(hidden.filter((id): id is TableColumnId => isColumn(id) && kept.includes(id)))]+ : [],};}/** The columns shown, in order. */-export function visibleColumns(view: PromptColumnsView): PromptColumnId[] {+export function visibleColumns(view: PromptColumnsView): TableColumnId[] {const hidden = new Set(view.hidden);return view.order.filter((id) => !hidden.has(id));}export function toggleColumn(view: PromptColumnsView,- id: PromptColumnId,+ id: TableColumnId,shown: boolean,): PromptColumnsView {const hidden = view.hidden.filter((h) => h !== id);@@ -72,8 +111,8 @@ export function toggleColumn(/** Moves a column to `to`'s place (a drop), or one step up or down. */export function moveColumn(view: PromptColumnsView,- id: PromptColumnId,- to: PromptColumnId | -1 | 1,+ id: TableColumnId,+ to: TableColumnId | -1 | 1,): PromptColumnsView {const order = view.order.filter((c) => c !== id);const from = view.order.indexOf(id);@@ -88,6 +127,23 @@ export function moveColumn(return { ...view, order };}+/** Adds a location column at the end, shown; the same one twice stays once. */+export function addLocationColumn(+ view: PromptColumnsView,+ metric: LocationMetric,+ region: string,+): PromptColumnsView {+ const id = locationColumn(metric, region);+ if (view.order.includes(id)) return toggleColumn(view, id, true);+ if (view.order.filter(isLocationColumn).length >= MAX_LOCATION_COLUMNS) return view;+ return { order: [...view.order, id], hidden: view.hidden };+}++/** Takes a location column out of the view. */+export function removeColumn(view: PromptColumnsView, id: LocationColumnId): PromptColumnsView {+ return { order: view.order.filter((c) => c !== id), hidden: view.hidden.filter((c) => c !== id) };+}+export function sameView(a: PromptColumnsView, b: PromptColumnsView): boolean {return (a.order.join() === b.order.join() && [...a.hidden].sort().join() === [...b.hidden].sort().join()