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): show average position and trend in the Positions column (#1017)
Cihan78886c72e35c
diff --git a/server/src/lib/prompt-improve.js b/server/src/lib/prompt-improve.jsindex 53e52522d..719e14cae 100644--- a/server/src/lib/prompt-improve.js+++ b/server/src/lib/prompt-improve.js@@ -55,6 +55,8 @@ const EXCERPT_CHARS = 1200;* Below this share of runs mentioning the brand, the platform counts as not* mentioned: a brand in 8 of 120 answers is mostly missing there, and needs* coverage advice, not positioning advice, however high those 8 ranked.+ * Mirrored in web/src/lib/prompt-improve.ts for the Tracked Prompts Positions+ * column — keep the two in sync.*/export const MIN_MENTION_RATE = 0.5;diff --git a/supabase/migrations/00123_prompt_position_summaries.sql b/supabase/migrations/00123_prompt_position_summaries.sqlnew file mode 100644index 000000000..e63d72c1c--- /dev/null+++ b/supabase/migrations/00123_prompt_position_summaries.sql@@ -0,0 +1,69 @@+-- Per-prompt, per-platform position aggregates for the Tracked Prompts table+-- (PROMPT-007): the Positions column's average position, its trend against+-- the previous period, and a dot per platform.+--+-- One GROUP BY in Postgres, like prompt_visibility_summaries (00025/00072),+-- rather than pulling every answer of every prompt into the page. The web+-- adds the sums up over the plan-included platforms, which keeps the average+-- the same as the Positions panel's: the mean mention position over the+-- answers that mention the brand.+--+-- Sums and counts rather than averages, so platforms can be combined without+-- weighting errors. chatgpt-shopping is excluded like every analytical+-- surface (#155); p_region scopes to one tracked location (#691).++create or replace function public.prompt_position_summaries(+ p_brand_id uuid,+ p_date_from timestamptz default null,+ p_date_to timestamptz default null,+ p_region text default null+)+returns table (+ prompt_id uuid,+ platform text,+ runs bigint,+ mention_answers bigint,+ -- Over answers that mention the brand and store a position.+ position_sum double precision,+ position_count bigint,+ -- How many brands those answers named, for Early / Mid / Late.+ entity_sum double precision,+ entity_count bigint+)+language sql+stable+security invoker+set search_path = public+as $$+ select pr.prompt_id,+ pr.platform,+ count(*)::bigint as runs,+ count(*) filter (where pr.mention_count > 0)::bigint as mention_answers,+ coalesce(sum(pr.mention_position) filter (+ where pr.mention_count > 0 and pr.mention_position > 0), 0)::double precision+ as position_sum,+ count(*) filter (+ where pr.mention_count > 0 and pr.mention_position > 0)::bigint as position_count,+ coalesce(sum(pr.mentioned_entity_count) filter (+ where pr.mention_count > 0 and pr.mention_position > 0+ and pr.mentioned_entity_count > 0), 0)::double precision as entity_sum,+ count(*) filter (+ where pr.mention_count > 0 and pr.mention_position > 0+ and pr.mentioned_entity_count > 0)::bigint as entity_count+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.prompt_id is not null+ and pr.platform <> 'chatgpt-shopping'+ and (p_date_from is null or pr.created_at >= p_date_from)+ and (p_date_to is null or pr.created_at <= p_date_to)+ and (p_region is null or pr.region = p_region)+ group by pr.prompt_id, pr.platform+$$;++grant execute on function+ public.prompt_position_summaries(uuid, timestamptz, timestamptz, text)+ to authenticated;++comment on function+ public.prompt_position_summaries(uuid, timestamptz, timestamptz, text) is+ 'Per-prompt, per-platform mention position sums for the Tracked Prompts Positions column (PROMPT-007). Sums, not averages, so platforms combine exactly.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 45e7cbbe0..8b0f4d966 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -14411,6 +14411,79 @@ grant execute on function public.import_prompts(uuid, uuid, integer, jsonb) to acomment on function public.import_prompts(uuid, uuid, integer, jsonb) is'Bulk-inserts prompts [{idx, text, category, topic_id, platforms, models, regions}] in order under a per-organization advisory lock, stopping before the org would exceed p_max_locations tracked locations (-1 = unlimited). Returns the (idx, id) of each inserted row. PROMPT-005.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00123_prompt_position_summaries.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Per-prompt, per-platform position aggregates for the Tracked Prompts table+-- (PROMPT-007): the Positions column's average position, its trend against+-- the previous period, and a dot per platform.+--+-- One GROUP BY in Postgres, like prompt_visibility_summaries (00025/00072),+-- rather than pulling every answer of every prompt into the page. The web+-- adds the sums up over the plan-included platforms, which keeps the average+-- the same as the Positions panel's: the mean mention position over the+-- answers that mention the brand.+--+-- Sums and counts rather than averages, so platforms can be combined without+-- weighting errors. chatgpt-shopping is excluded like every analytical+-- surface (#155); p_region scopes to one tracked location (#691).++create or replace function public.prompt_position_summaries(+ p_brand_id uuid,+ p_date_from timestamptz default null,+ p_date_to timestamptz default null,+ p_region text default null+)+returns table (+ prompt_id uuid,+ platform text,+ runs bigint,+ mention_answers bigint,+ -- Over answers that mention the brand and store a position.+ position_sum double precision,+ position_count bigint,+ -- How many brands those answers named, for Early / Mid / Late.+ entity_sum double precision,+ entity_count bigint+)+language sql+stable+security invoker+set search_path = public+as $$+ select pr.prompt_id,+ pr.platform,+ count(*)::bigint as runs,+ count(*) filter (where pr.mention_count > 0)::bigint as mention_answers,+ coalesce(sum(pr.mention_position) filter (+ where pr.mention_count > 0 and pr.mention_position > 0), 0)::double precision+ as position_sum,+ count(*) filter (+ where pr.mention_count > 0 and pr.mention_position > 0)::bigint as position_count,+ coalesce(sum(pr.mentioned_entity_count) filter (+ where pr.mention_count > 0 and pr.mention_position > 0+ and pr.mentioned_entity_count > 0), 0)::double precision as entity_sum,+ count(*) filter (+ where pr.mention_count > 0 and pr.mention_position > 0+ and pr.mentioned_entity_count > 0)::bigint as entity_count+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.prompt_id is not null+ and pr.platform <> 'chatgpt-shopping'+ and (p_date_from is null or pr.created_at >= p_date_from)+ and (p_date_to is null or pr.created_at <= p_date_to)+ and (p_region is null or pr.region = p_region)+ group by pr.prompt_id, pr.platform+$$;++grant execute on function+ public.prompt_position_summaries(uuid, timestamptz, timestamptz, text)+ to authenticated;++comment on function+ public.prompt_position_summaries(uuid, timestamptz, timestamptz, text) is+ 'Per-prompt, per-platform mention position sums for the Tracked Prompts Positions column (PROMPT-007). Sums, not averages, so platforms combine exactly.';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00125_opportunity_usage.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex 30ea2c884..036cf3fd9 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -75,6 +75,8 @@ import {X,ListChecks,Sparkles,+ ArrowUp,+ ArrowDown,ExternalLink,MoreHorizontal,Pause,@@ -82,6 +84,12 @@ import {Lightbulb,} from 'lucide-react';import { cn } from '@/lib/utils';+import type {+ PlatformDot,+ PlatformDotState,+ PromptPositionCell,+} from '@/lib/prompt-position-summary';+import { mentionRateLabel } from '@/lib/prompt-improve';import { useBrandStore } from '@/stores/use-brand-store';import {startPromptVolumeAnalysis,@@ -202,12 +210,20 @@ function ColHead({// ─── Sortable column header (All Prompts) ─────────────────────────────────────-type AllPromptsSortKey = 'visibility' | 'mentions' | 'citations' | 'volume' | 'runs' | 'lastRun';+type AllPromptsSortKey =+ | 'visibility'+ | 'mentions'+ | 'citations'+ | 'position'+ | 'volume'+ | 'runs'+ | 'lastRun';const ALL_PROMPTS_SORT_KEYS: AllPromptsSortKey[] = ['visibility','mentions','citations',+ 'position','volume','runs','lastRun',@@ -1271,6 +1287,7 @@ export default function PromptsPage() {const [volumes, setVolumes] = useState<PromptVolume[]>([]);const [allPrompts, setAllPrompts] = useState<Prompt[]>([]);const [visibility, setVisibility] = useState<Record<string, PromptVisibilitySummary>>({});+ const [positions, setPositions] = useState<Record<string, PromptPositionCell>>({});const [loading, setLoading] = useState(true);const [analyzing, setAnalyzing] = useState(false);const [analysisProgress, setAnalysisProgress] = useState<{@@ -1410,6 +1427,7 @@ export default function PromptsPage() {setVolumes([]);setAllPrompts([]);setVisibility({});+ setPositions({});setLoading(false);return;}@@ -1432,6 +1450,7 @@ export default function PromptsPage() {const prompts = page.promptSets.flatMap((ps) => ps.prompts);setAllPrompts(prompts);setVisibility(page.visibility);+ setPositions(page.positions);if (page.volumesDegraded) {toast.warning('Volume data is temporarily unavailable — showing prompts without it.');}@@ -1961,6 +1980,7 @@ export default function PromptsPage() {activeBrandId={activeBrandId}volumeByPromptId={volumeByPromptId}visibility={visibility}+ positions={positions}rangeLabel={rangeLabel}positionsWindow={positionsWindow}positionsPreset={range ? rangePreset : '30d'}@@ -2356,6 +2376,50 @@ export default function PromptsPage() {);}+// ─── Positions cell (All Prompts) ─────────────────────────────────────────────++/**+ * Average position with its trend against the previous period; hovering it+ * lists each platform, which is what the "Late or missing" filter reads.+ */+function PositionValue({ cell }: { cell: PromptPositionCell | undefined }) {+ if (!cell || cell.avg === null) {+ return <span className="text-xs text-muted-foreground">—</span>;+ }+ const delta = cell.delta;+ const breakdown = cell.dots.map((d) => `${d.label}: ${dotDetail(d)}`).join('\n');+ return (+ <span className="inline-flex items-center gap-1 tabular-nums" title={breakdown}>+ <span className="text-sm font-semibold">#{cell.avg.toFixed(1)}</span>+ {delta !== null && delta !== 0 && (+ <span+ className={cn(+ 'inline-flex items-center text-[10px] font-medium',+ delta > 0 ? 'text-emerald-600 dark:text-emerald-400' : 'text-red-600 dark:text-red-400',+ )}+ >+ {delta > 0 ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />}+ {Math.abs(delta).toFixed(1)}+ </span>+ )}+ </span>+ );+}++const DOT_LABEL: Record<PlatformDotState, string> = {+ early: 'named early',+ late: 'named further down',+ mentioned: 'mentioned, position unknown',+ missing: 'not mentioned',+ no_runs: 'no runs',+};++/** Like the Improve tab, "not mentioned" says how often it was. */+function dotDetail(d: PlatformDot): string {+ if (d.state === 'missing') return `${DOT_LABEL.missing} · ${mentionRateLabel(d)}`;+ return `${DOT_LABEL[d.state]}${d.avg !== null ? ` (#${d.avg.toFixed(1)})` : ''}`;+}+/** How long a row deleted from its menu can be restored (PROMPT-006). */const DELETE_UNDO_MS = 10_000;@@ -2474,6 +2538,7 @@ function AllPromptsTab({activeBrandId,volumeByPromptId,visibility,+ positions,rangeLabel,positionsWindow,positionsPreset,@@ -2488,6 +2553,8 @@ function AllPromptsTab({activeBrandId: string;volumeByPromptId: Map<string, PromptVolume>;visibility: Record<string, PromptVisibilitySummary>;+ /** The Positions column per prompt id. */+ positions: Record<string, PromptPositionCell>;/** Selected window, so the column tooltips describe the data on screen. */rangeLabel: string;/** Bounds the table's columns were computed over, for the Positions panel. */@@ -2715,6 +2782,8 @@ function AllPromptsTab({);const [search, setSearch] = useState('');const [workFilter, setWorkFilter] = useState<'all' | 'none' | PromptWorkStatus>('all');+ // Quick filter: prompts late or missing on at least one engine.+ const [lateOnly, setLateOnly] = useState(false);// Optimistic per-row status overrides — the prompts prop belongs to the// parent's load cycle; a full reload for a one-column change would flash// the whole table.@@ -2804,7 +2873,15 @@ function AllPromptsTab({const handleSort = useCallback((key: AllPromptsSortKey) => {const params = new URLSearchParams(Array.from(searchParams.entries()));- const nextDir: SortDir = activeSort === key && dir === 'desc' ? 'asc' : 'desc';+ // Position is best when lowest, so it starts at asc (#1 first).+ const nextDir: SortDir =+ activeSort === key+ ? dir === 'desc'+ ? 'asc'+ : 'desc'+ : key === 'position'+ ? 'asc'+ : 'desc';params.set('tab', 'all');params.set('sort', key);params.set('dir', nextDir);@@ -2826,6 +2903,7 @@ function AllPromptsTab({workFilter === 'none' ? statusOf(p) === null : statusOf(p) === workFilter,);}+ if (lateOnly) list = list.filter((p) => positions[p.id]?.lateOrMissing);const valueOf = (p: Prompt): number | null => {const vis = visibility[p.id];@@ -2837,6 +2915,8 @@ function AllPromptsTab({return vis ? vis.totalMentions : null;case 'citations':return vis ? vis.totalCitations : null;+ case 'position':+ return positions[p.id]?.avg ?? null;case 'volume':return vol ? vol.estAiVolume : null;case 'runs':@@ -2847,13 +2927,24 @@ function AllPromptsTab({};return list.sort((a, b) => compareNullsLast(valueOf(a), valueOf(b), dir));- }, [prompts, search, workFilter, statusOf, activeSort, dir, visibility, volumeByPromptId]);+ }, [+ prompts,+ search,+ workFilter,+ lateOnly,+ statusOf,+ activeSort,+ dir,+ visibility,+ positions,+ volumeByPromptId,+ ]);// Pagination for the main prompt list. resetKey encodes every variable that// changes the visible row set (search text, sort column, sort direction, work// status filter) so usePagination jumps back to page 0 automatically when// any filter or sort changes — satisfying the issue's acceptance criteria.- const promptsResetKey = `${search}::${workFilter}::${activeSort}::${dir}`;+ const promptsResetKey = `${search}::${workFilter}::${lateOnly}::${activeSort}::${dir}`;const promptsPager = usePagination(filtered.length, promptsResetKey);if (loading) {@@ -2929,6 +3020,17 @@ function AllPromptsTab({<SelectItem value="none">No status</SelectItem></SelectContent></Select>+ <Button+ type="button"+ size="sm"+ variant={lateOnly ? 'default' : 'outline'}+ className="h-8 text-xs"+ aria-pressed={lateOnly}+ title="Prompts named late, or not at all, on at least one AI platform"+ onClick={() => setLateOnly((v) => !v)}+ >+ Late or missing+ </Button><div className="relative w-60"><Search className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground" /><Input@@ -2984,12 +3086,16 @@ function AllPromptsTab({>Citations</SortableHead>- <ColHead- className="text-center"- tooltip={`Where the brand was mentioned and cited, per AI platform, over the ${rangeLabel}. Available when the prompt has a mention or citation in that window.`}+ <SortableHead+ className="pl-8"+ tooltip={`Average position the brand is named at in AI answers over the ${rangeLabel}, with the change against the previous period of the same length. Hover a value for each platform; the chart button opens the details.`}+ sortKey="position"+ activeSort={activeSort}+ dir={dir}+ onSort={handleSort}>Positions- </ColHead>+ </SortableHead><SortableHeadclassName="text-right"tooltip="Estimated monthly AI prompt volume, from keyword analysis. Empty until analysed."@@ -3134,21 +3240,27 @@ function AllPromptsTab({<span className="text-xs text-muted-foreground">—</span>)}</TableCell>- <TableCell className="text-center">- {vis && (vis.mentionAnswers > 0 || vis.citationAnswers > 0) ? (- <Button- type="button"- size="xs"- variant="outline"- aria-label={`View positions for ${p.text}`}- onClick={() => openPositionsPanel(p.id)}- >- <BarChart3 />- See- </Button>- ) : (- <span className="text-xs text-muted-foreground">—</span>- )}+ <TableCell 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]} />+ </div>+ <div className="w-6">+ {vis && (vis.mentionAnswers > 0 || vis.citationAnswers > 0) && (+ <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><TableCell className="text-right">{vol ? (diff --git a/web/src/lib/actions/prompt.test.ts b/web/src/lib/actions/prompt.test.tsindex 0a49273e6..cf2497b8d 100644--- a/web/src/lib/actions/prompt.test.ts+++ b/web/src/lib/actions/prompt.test.ts@@ -1,5 +1,7 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+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';/*** setPromptActive meters resuming like adding (00128): only active prompts@@ -13,6 +15,9 @@ let usedLocations = 0;let usageFails = false;let plan: Plan;let writes: unknown[] = [];+let promptSetRows: Record<string, unknown>[] = [];+let positionData: Record<string, unknown>[] = [];+let positionsError: string | null = null;vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }));vi.mock('@/lib/actions/volumes', () => ({ getPromptVolumes: vi.fn() }));@@ -24,13 +29,24 @@ vi.mock('@/lib/guards/plan-guard', () => ({vi.mock('@/lib/supabase/server', () => ({createClient: vi.fn(async () => ({- rpc: async () =>- usageFails+ rpc: async (fn: string) => {+ if (fn === 'prompt_position_summaries') {+ return positionsError+ ? { data: null, error: { message: positionsError } }+ : { data: positionData, error: null };+ }+ return usageFails? { data: null, error: { message: 'rpc failed' } }- : { data: [{ brand_id: 'b1', locations: usedLocations }], error: null },- from: () => ({+ : { data: [{ brand_id: 'b1', locations: usedLocations }], error: null };+ },+ from: (table: string) => ({select: () => ({eq: () => ({+ order: async () =>+ table === 'prompt_sets'+ ? { data: promptSetRows, error: null }+ : { data: null, error: { message: `unexpected ${table}` } },+ maybeSingle: async () => ({ data: { organization_id: 'org-1' }, error: null }),single: async () =>promptRow? {@@ -57,7 +73,7 @@ vi.mock('@/lib/supabase/server', () => ({})),}));-const { setPromptActive, updatePromptLocations } = await import('./prompt');+const { getPromptsPageData, setPromptActive, updatePromptLocations } = await import('./prompt');const capped = (maxPrompts: number): Plan => ({...PLANS.starter,@@ -168,3 +184,73 @@ describe('updatePromptLocations on paused prompts', () => {expect(writes).toEqual([]);});});++describe('getPromptsPageData', () => {+ beforeEach(() => {+ plan = capped(50);+ promptRow = null;+ promptSetRows = [+ {+ id: 'ps1',+ brand_id: 'b1',+ name: 'Prompts',+ created_at: '2026-10-01T00:00:00.000Z',+ updated_at: '2026-10-01T00:00:00.000Z',+ prompts: [+ {+ id: 'p1',+ prompt_set_id: 'ps1',+ text: 'best crm for startups',+ platforms: ['chatgpt-web'],+ regions: ['US'],+ models: [],+ is_active: true,+ prompt_target_urls: [],+ created_at: '2026-10-01T00:00:00.000Z',+ },+ ],+ },+ ];+ positionData = [+ {+ prompt_id: 'p1',+ platform: 'chatgpt-web',+ runs: 4,+ mention_answers: 4,+ position_sum: 8,+ position_count: 4,+ entity_sum: 20,+ entity_count: 4,+ },+ ];+ positionsError = null;+ vi.mocked(getPromptVolumes).mockResolvedValue({ volumes: [], quota: {} as VolumeQuota });+ vi.mocked(getPromptVisibilitySummaries).mockResolvedValue({});+ // The location quota fails here (no brand row), which the page also absorbs.+ vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('fills the Positions column from the position summaries', async () => {+ const page = await getPromptsPageData('b1');++ expect(page.positions.p1.avg).toBe(2);+ expect(page.positions.p1.dots.map((d) => d.id)).toEqual(['chatgpt-web']);+ });++ it('shows — in the Positions column when the position query fails, instead of failing the page', async () => {+ positionsError = 'canceling statement due to statement timeout';++ const page = await getPromptsPageData('b1');++ expect(page.promptSets[0].prompts.map((p) => p.id)).toEqual(['p1']);+ expect(page.positions.p1).toEqual({ avg: null, delta: null, dots: [], lateOrMissing: false });+ expect(console.error).toHaveBeenCalledWith(+ expect.stringContaining('position summaries'),+ expect.any(Error),+ );+ });+});diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.tsindex 56daaa51b..473070a48 100644--- a/web/src/lib/actions/prompt.ts+++ b/web/src/lib/actions/prompt.ts@@ -20,6 +20,13 @@ import {getPromptVisibilitySummaries,type PromptVisibilitySummary,} from '@/lib/actions/tracking';+import { POSITION_PLATFORMS, platformAccess } from '@/lib/prompt-positions';+import {+ buildPositionCell,+ previousWindow,+ type PlatformPositionRow,+ type PromptPositionCell,+} from '@/lib/prompt-position-summary';function filterByPlan(plan: Plan, platforms: string[], models: string[]) {const allowedScrapers = plan.limits.allowedScrapers@@ -920,6 +927,8 @@ export async function deletePromptSet(id: string): Promise<void> {export interface PromptsPageData {promptSets: PromptSet[];visibility: Record<string, PromptVisibilitySummary>;+ /** The Positions column per prompt id (PROMPT-007). */+ positions: Record<string, PromptPositionCell>;volumes: PromptVolume[];quota: VolumeQuota | null;/** True when the volumes upstream failed/timed out — the table still renders. */@@ -950,7 +959,11 @@ export async function getPromptsPageData(// no date dimension, so neither changes with the selected range or the// selected location.const days = opts?.days ?? DEFAULT_PROMPT_RANGE_DAYS;- const [promptSets, visibility, volumesResult, locationQuota] = await Promise.all([+ const window = {+ from: opts?.from ?? new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString(),+ to: opts?.to,+ };+ const [promptSets, visibility, positionRows, volumesResult, locationQuota] = await Promise.all([getPromptSets(brandId),getPromptVisibilitySummaries(brandId, {days,@@ -958,6 +971,13 @@ export async function getPromptsPageData(to: opts?.to,region: opts?.region,}),+ // The Positions column scans every answer in the window and the one+ // before it. A timeout, or the web deploying before 00123 is applied,+ // shows — in that column instead of failing the table.+ getPositionRows(brandId, window, opts?.region).catch((err) => {+ console.error('[prompts] position summaries fetch failed, rendering without them:', err);+ return noPositionRows();+ }),getPromptVolumes(brandId).then((r) => ({ volumes: r.volumes, quota: r.quota ?? null, degraded: false }),(err) => {@@ -973,9 +993,26 @@ export async function getPromptsPageData(}),]);+ const positions: Record<string, PromptPositionCell> = {};+ for (const prompt of promptSets.flatMap((ps) => ps.prompts)) {+ const current = positionRows.current.get(prompt.id) ?? [];+ // A dot for every included engine the prompt tracks, plus any it has+ // answers from in the window, so the dots and the average agree.+ const platforms = positionRows.included.filter(+ (p) =>+ prompt.platforms.includes(p.id as AIPlatform) || current.some((r) => r.platform === p.id),+ );+ positions[prompt.id] = buildPositionCell(+ current,+ positionRows.previous.get(prompt.id) ?? [],+ platforms,+ );+ }+return {promptSets,visibility,+ positions,volumes: volumesResult.volumes,quota: volumesResult.quota,volumesDegraded: volumesResult.degraded,@@ -983,6 +1020,78 @@ export async function getPromptsPageData(};}+interface PositionRows {+ included: { id: string; label: string }[];+ current: Map<string, PlatformPositionRow[]>;+ previous: Map<string, PlatformPositionRow[]>;+}++/** No position data: every prompt's Positions cell reads —. */+function noPositionRows(): PositionRows {+ return { included: [], current: new Map(), previous: new Map() };+}++/**+ * Per-prompt, per-engine position sums for the Positions column: the window+ * on screen and the period of the same length just before it, for the trend.+ * Only engines the org's plan includes count, as in the Positions panel.+ */+async function getPositionRows(+ brandId: string,+ window: { from: string; to?: string },+ region?: string,+): Promise<PositionRows> {+ const supabase = await createClient();+ const { data: brand } = await supabase+ .from('brands')+ .select('organization_id')+ .eq('id', brandId)+ .maybeSingle();+ if (!brand?.organization_id) return noPositionRows();++ 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),+ ]);+ 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 };+}++async function positionSums(+ brandId: string,+ window: { from: string; to?: string },+ region?: string,+): Promise<Map<string, PlatformPositionRow[]>> {+ const supabase = await createClient();+ const { data, error } = await supabase.rpc('prompt_position_summaries', {+ p_brand_id: brandId,+ p_date_from: window.from,+ p_date_to: window.to ?? undefined,+ p_region: region ?? undefined,+ });+ if (error) throw new Error(error.message);++ const byPrompt = new Map<string, PlatformPositionRow[]>();+ for (const row of data ?? []) {+ const list = byPrompt.get(row.prompt_id) ?? [];+ list.push({+ platform: row.platform,+ runs: Number(row.runs ?? 0),+ mentionAnswers: Number(row.mention_answers ?? 0),+ positionSum: Number(row.position_sum ?? 0),+ positionCount: Number(row.position_count ?? 0),+ entitySum: Number(row.entity_sum ?? 0),+ entityCount: Number(row.entity_count ?? 0),+ });+ byPrompt.set(row.prompt_id, list);+ }+ return byPrompt;+}+/** How many prompts the brand tracks — the count beside Tracked Prompts in the sidebar (PROMPT-001). */export async function getTrackedPromptCount(brandId: string): Promise<number> {const supabase = await createClient();diff --git a/web/src/lib/prompt-improve.ts b/web/src/lib/prompt-improve.tsindex e733ebfe6..d69ed6d9c 100644--- a/web/src/lib/prompt-improve.ts+++ b/web/src/lib/prompt-improve.ts@@ -117,6 +117,15 @@ export const STATE_ORDER: ImproveState[] = ['no_runs',];+/**+ * Below this share of runs mentioning the brand, a platform counts as not+ * mentioned, however high those few ranked. The Tracked Prompts Positions+ * column applies it too, so its "missing" matches this tab's "Not mentioned".+ * Mirrors MIN_MENTION_RATE in server/src/lib/prompt-improve.js — keep the two+ * in sync.+ */+export const MIN_MENTION_RATE = 0.5;+/** "mentioned in 8 of 120 runs": why a platform's state is what it is. */export function mentionRateLabel(p: Pick<ImprovePlatform, 'runs' | 'mentionedRuns'>): string {return `mentioned in ${p.mentionedRuns} of ${p.runs} run${p.runs === 1 ? '' : 's'}`;diff --git a/web/src/lib/prompt-position-summary.test.ts b/web/src/lib/prompt-position-summary.test.tsnew file mode 100644index 000000000..fd0899357--- /dev/null+++ b/web/src/lib/prompt-position-summary.test.ts@@ -0,0 +1,161 @@+/**+ * prompt-position-summary.test.ts (PROMPT-007)+ *+ * Tests the Tracked Prompts Positions cell: the average the panel shows, the+ * trend against the previous period, and the per-platform dots.+ */++import { describe, expect, test } from 'vitest';+import {+ buildPositionCell,+ previousWindow,+ type PlatformPositionRow,+} from './prompt-position-summary';++const row = (platform: string, over: Partial<PlatformPositionRow> = {}): PlatformPositionRow => ({+ platform,+ runs: 4,+ mentionAnswers: 4,+ positionSum: 4,+ positionCount: 4,+ entitySum: 20,+ entityCount: 4,+ ...over,+});++const platforms = [+ { id: 'chatgpt-web', label: 'ChatGPT' },+ { id: 'perplexity-web', label: 'Perplexity' },+ { id: 'gemini-web', label: 'Gemini' },+ { id: 'google-aio', label: 'Google AI Overviews' },+];++describe('buildPositionCell', () => {+ test('averages positions over mentioning answers across platforms, like the panel', () => {+ const cell = buildPositionCell(+ [+ row('chatgpt-web', { positionSum: 2, positionCount: 2 }), // #1, #1+ row('perplexity-web', { positionSum: 8, positionCount: 2 }), // #4, #4+ ],+ [],+ platforms,+ );+ expect(cell.avg).toBe(2.5);+ expect(cell.delta).toBeNull();+ });++ test('ignores platforms outside the plan-included list', () => {+ const cell = buildPositionCell(+ [+ row('chatgpt-web', { positionSum: 1, positionCount: 1 }),+ row('grok-web', { positionSum: 9, positionCount: 1 }),+ ],+ [],+ platforms,+ );+ expect(cell.avg).toBe(1);+ expect(cell.dots.map((d) => d.id)).not.toContain('grok-web');+ });++ test('delta is previous minus current: positive when the brand moved up', () => {+ const better = buildPositionCell(+ [row('chatgpt-web', { positionSum: 3, positionCount: 2 })], // #1.5+ [row('chatgpt-web', { positionSum: 4, positionCount: 2 })], // #2.0+ platforms,+ );+ expect(better.delta).toBe(0.5);+ const worse = buildPositionCell(+ [row('chatgpt-web', { positionSum: 6, positionCount: 2 })],+ [row('chatgpt-web', { positionSum: 4, positionCount: 2 })],+ platforms,+ );+ expect(worse.delta).toBe(-1);+ });++ test('a dot per platform: early, late, mentioned without position, missing, no runs', () => {+ const cell = buildPositionCell(+ [+ row('chatgpt-web', { positionSum: 1, positionCount: 1, entitySum: 5, entityCount: 1 }),+ row('perplexity-web', { positionSum: 5, positionCount: 1, entitySum: 5, entityCount: 1 }),+ row('gemini-web', { positionSum: 0, positionCount: 0 }),+ row('google-aio', { mentionAnswers: 0, positionSum: 0, positionCount: 0 }),+ ],+ [],+ [...platforms, { id: 'copilot-web', label: 'Microsoft Copilot' }],+ );+ expect(cell.dots.map((d) => [d.id, d.state])).toEqual([+ ['chatgpt-web', 'early'],+ ['perplexity-web', 'late'],+ ['gemini-web', 'mentioned'],+ ['google-aio', 'missing'],+ ['copilot-web', 'no_runs'],+ ]);+ expect(cell.lateOrMissing).toBe(true);+ });++ test('mentioned in under half the runs is missing, like the Improve tab, however high it ranked', () => {+ // #1 in 8 of 120 answers: the Improve tab calls this "Not mentioned".+ const cell = buildPositionCell(+ [+ row('chatgpt-web', {+ runs: 120,+ mentionAnswers: 8,+ positionSum: 8,+ positionCount: 8,+ entitySum: 40,+ entityCount: 8,+ }),+ ],+ [],+ platforms.slice(0, 1),+ );+ expect(cell.dots).toEqual([+ {+ id: 'chatgpt-web',+ label: 'ChatGPT',+ state: 'missing',+ avg: null,+ runs: 120,+ mentionedRuns: 8,+ },+ ]);+ expect(cell.lateOrMissing).toBe(true);+ // The average stays the Positions panel's.+ expect(cell.avg).toBe(1);+ });++ test('mentioned in exactly half the runs counts as mentioned', () => {+ const cell = buildPositionCell(+ [row('chatgpt-web', { runs: 4, mentionAnswers: 2, positionSum: 2, positionCount: 2 })],+ [],+ platforms.slice(0, 1),+ );+ expect(cell.dots[0].state).toBe('early');+ expect(cell.lateOrMissing).toBe(false);+ });++ test('not late or missing when every tracked platform is early or has no runs', () => {+ const cell = buildPositionCell(+ [row('chatgpt-web', { positionSum: 1, positionCount: 1 })],+ [],+ platforms.slice(0, 2),+ );+ expect(cell.lateOrMissing).toBe(false);+ });+});++describe('previousWindow', () => {+ test('is the same length, ending where the window starts', () => {+ expect(+ previousWindow({ from: '2026-10-08T00:00:00.000Z', to: '2026-10-15T00:00:00.000Z' }),+ ).toEqual({ from: '2026-10-01T00:00:00.000Z', to: '2026-10-08T00:00:00.000Z' });+ });++ test('an open window ends now', () => {+ const now = Date.parse('2026-10-13T00:00:00.000Z');+ expect(previousWindow({ from: '2026-10-06T00:00:00.000Z' }, now)).toEqual({+ from: '2026-09-29T00:00:00.000Z',+ to: '2026-10-06T00:00:00.000Z',+ });+ });+});diff --git a/web/src/lib/prompt-position-summary.ts b/web/src/lib/prompt-position-summary.tsnew file mode 100644index 000000000..1c8f4f28a--- /dev/null+++ b/web/src/lib/prompt-position-summary.ts@@ -0,0 +1,119 @@+/**+ * The Tracked Prompts table's Positions cell (PROMPT-007): average mention+ * position over the selected range, its change against the previous period of+ * the same length, and one dot per platform.+ *+ * Pure on purpose: the server action loads per-platform sums+ * (prompt_position_summaries, 00123) and this turns them into the cell. The+ * average is the Positions panel's: the mean mention position over the+ * answers that mention the brand, on the plan-included platforms.+ */++import { positionTone } from '@/lib/position-tone';+import { MIN_MENTION_RATE } from '@/lib/prompt-improve';++/** One platform's sums for one prompt over a window. */+export interface PlatformPositionRow {+ platform: string;+ runs: number;+ mentionAnswers: number;+ positionSum: number;+ positionCount: number;+ entitySum: number;+ entityCount: number;+}++/**+ * - early mentioned, in the first third of the brands named+ * - late mentioned, but further down+ * - mentioned mentioned, with no stored position+ * - missing mentioned in fewer than half the runs, or never: the Improve+ * tab's "Not mentioned" (MIN_MENTION_RATE)+ * - no_runs nothing tracked in the window+ */+export type PlatformDotState = 'early' | 'late' | 'mentioned' | 'missing' | 'no_runs';++export interface PlatformDot {+ id: string;+ label: string;+ state: PlatformDotState;+ /** The platform's average position; null when not mentioned or unknown. */+ avg: number | null;+ runs: number;+ /** Runs that mention the brand, for "mentioned in 8 of 120 runs". */+ mentionedRuns: number;+}++export interface PromptPositionCell {+ /** Average mention position over the window; null when never ranked. */+ avg: number | null;+ /** Previous period's average minus this one: positive means it moved up. */+ delta: number | null;+ dots: PlatformDot[];+ /** Late or missing on at least one platform — the "work queue" filter. */+ lateOrMissing: boolean;+}++const round1 = (n: number) => Math.round(n * 10) / 10;++function average(rows: PlatformPositionRow[]): number | null {+ const sum = rows.reduce((a, r) => a + r.positionSum, 0);+ const count = rows.reduce((a, r) => a + r.positionCount, 0);+ return count > 0 ? round1(sum / count) : null;+}++function dotState(row: PlatformPositionRow | undefined): PlatformDotState {+ if (!row || row.runs === 0) return 'no_runs';+ // Same rule as the Improve tab: #1 in 8 of 120 answers is mostly missing.+ if (row.mentionAnswers < row.runs * MIN_MENTION_RATE) return 'missing';+ if (row.positionCount === 0) return 'mentioned';+ const rank = row.positionSum / row.positionCount;+ const total = row.entityCount > 0 ? row.entitySum / row.entityCount : rank;+ return positionTone(rank, Math.max(total, rank)) === 'Early' ? 'early' : 'late';+}++/**+ * The cell for one prompt. `platforms` are the ones the prompt tracks that+ * the plan includes, in display order; rows for any other platform are+ * ignored, so the average matches the panel's.+ */+export function buildPositionCell(+ current: PlatformPositionRow[],+ previous: PlatformPositionRow[],+ platforms: { id: string; label: string }[],+): PromptPositionCell {+ const ids = new Set(platforms.map((p) => p.id));+ const now = current.filter((r) => ids.has(r.platform));+ const before = previous.filter((r) => ids.has(r.platform));+ const avg = average(now);+ const prev = average(before);+ const dots = platforms.map((p) => {+ const row = now.find((r) => r.platform === p.id);+ const state = dotState(row);+ return {+ id: p.id,+ label: p.label,+ state,+ avg:+ row && state !== 'missing' && row.positionCount > 0+ ? round1(row.positionSum / row.positionCount)+ : null,+ runs: row?.runs ?? 0,+ mentionedRuns: row?.mentionAnswers ?? 0,+ };+ });+ return {+ avg,+ delta: avg !== null && prev !== null ? round1(prev - avg) : null,+ dots,+ lateOrMissing: dots.some((d) => d.state === 'late' || d.state === 'missing'),+ };+}++/** The previous period of the same length, ending where this one starts. */+export function previousWindow(window: { from: string; to?: string }, now = Date.now()) {+ const from = Date.parse(window.from);+ const to = window.to ? Date.parse(window.to) : now;+ const span = Math.max(0, to - from);+ return { from: new Date(from - span).toISOString(), to: new Date(from).toISOString() };+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 9e66d8895..5dfef5d4a 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -3125,6 +3125,24 @@ export type Database = {}Returns: Json}+ prompt_position_summaries: {+ Args: {+ p_brand_id: string+ p_date_from?: string+ p_date_to?: string+ p_region?: string+ }+ Returns: {+ entity_count: number+ entity_sum: number+ mention_answers: number+ platform: string+ position_count: number+ position_sum: number+ prompt_id: string+ runs: number+ }[]+ }prompt_visibility_summaries: {Args: {p_brand_id: string