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
perf(topics): read a topic's latest runs lean on the topic page (#1150)
Cihan1450f1552da3
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/topics/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/topics/[id]/page.tsxindex 29d001854..e0dc931fe 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/topics/[id]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/topics/[id]/page.tsx@@ -10,7 +10,7 @@ import {type VisibilityTrendPoint,type ShareOfVoiceData,type CompetitorComparisonData,- type PromptResultWithText,+ type TopicRecentRun,} from '@/lib/actions/tracking';import type { Topic } from '@/types';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';@@ -154,7 +154,7 @@ export default function TopicDetailPage({ params }: { params: Promise<{ id: striconst [trend, setTrend] = useState<VisibilityTrendPoint[]>([]);const [sov, setSov] = useState<ShareOfVoiceData | null>(null);const [competitors, setCompetitors] = useState<CompetitorComparisonData | null>(null);- const [results, setResults] = useState<PromptResultWithText[]>([]);+ const [results, setResults] = useState<TopicRecentRun[]>([]);const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);diff --git a/web/src/lib/actions/tracking.test.ts b/web/src/lib/actions/tracking.test.tsindex ea181e65a..2a24738f9 100644--- a/web/src/lib/actions/tracking.test.ts+++ b/web/src/lib/actions/tracking.test.ts@@ -29,17 +29,31 @@ let promptResultRead: { data: unknown; error: { message: string } | null } = {error: null,};+// List reads: the rows each table answers (none by default), and every+// query's calls in order.+let listRows: Record<string, unknown[]> = {};+let listQueries: { table: string; calls: unknown[][] }[] = [];+function fakeQueryBuilder(table: string) {+ const query = { table, calls: [] as unknown[][] };+ listQueries.push(query);+ const record =+ (method: string) =>+ (...args: unknown[]) => {+ query.calls.push([method, ...args]);+ return builder;+ };const builder = {- select: () => builder,- eq: () => builder,- neq: () => builder,+ select: record('select'),+ eq: record('eq'),+ neq: record('neq'),maybeSingle: async () => promptResultRead,- in: () => builder,- order: () => builder,- range: () => builder,- // Awaiting a list query yields no rows.- then: (resolve: (v: unknown) => unknown) => resolve({ data: [], error: null, count: 0 }),+ in: record('in'),+ order: record('order'),+ range: record('range'),+ limit: record('limit'),+ then: (resolve: (v: unknown) => unknown) =>+ resolve({ data: listRows[table] ?? [], error: null, count: 0 }),single: async () => {if (table === 'prompt_results') return { data: promptResultRow, error: null };if (table === 'prompts') {@@ -220,9 +234,44 @@ describe('getInsightsSummary', () => {describe('topic-filtered reads (00164)', () => {beforeEach(() => {rpcCalls = [];+ listQueries = [];});afterEach(() => {rpcByName = false;+ listRows = {};+ });++ it("reads the topic's latest runs lean: each run's prompt and visibility, no count", async () => {+ rpcByName = true;+ listRows = {+ prompts: [+ { id: 'p1', text: 'Best espresso machine under $500?' },+ { id: 'p2', text: 'Cheapest burr grinder?' },+ ],+ prompt_results: [+ { prompt_id: 'p2', visibility_score: 40 },+ { prompt_id: 'p1', visibility_score: 80 },+ ],+ };+ const { getTopicDetail } = await import('./tracking');++ const detail = await getTopicDetail('brand-id', 'topic-1');++ expect(detail.results).toEqual([+ { promptId: 'p2', promptText: 'Cheapest burr grinder?', visibilityScore: 40 },+ { promptId: 'p1', promptText: 'Best espresso machine under $500?', visibilityScore: 80 },+ ]);+ // Not every column, and no count of every answer the topic ever had.+ const runs = listQueries.filter((q) => q.table === 'prompt_results');+ expect(runs).toHaveLength(1);+ expect(runs[0].calls).toEqual([+ ['select', 'prompt_id, visibility_score'],+ ['eq', 'brand_id', 'brand-id'],+ ['neq', 'platform', 'chatgpt-shopping'],+ ['in', 'prompt_id', ['p1', 'p2']],+ ['order', 'created_at', { ascending: false }],+ ['limit', 50],+ ]);});it('serves the topic detail page from the daily rollups, every call scoped to the topic', async () => {diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.tsindex 7a192996f..3a6432cab 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -3653,7 +3653,56 @@ export interface TopicDetailData {trend: VisibilityTrendPoint[];sov: ShareOfVoiceData;competitors: CompetitorComparisonData;- results: PromptResultWithText[];+ results: TopicRecentRun[];+}++/** One of a topic's latest runs, as its best and worst prompts read them. */+export interface TopicRecentRun {+ promptId: string;+ promptText: string;+ visibilityScore: number;+}++/**+ * A topic's latest runs for the topic page's best and worst prompts: each+ * run's prompt and visibility, nothing else. It went through+ * getPromptResults, which read every column of the 50 rows — answers,+ * citations, competitors, searches — and counted every answer the topic has+ * ever had (`count: 'exact'`, under RLS) for a total the page never showed:+ * the one raw read over prompt_results left once the rest moved to the+ * rollups (00164). Here: the topic's prompts with their text, then the runs.+ */+async function getTopicRecentRuns(+ brandId: string,+ topicId: string,+ limit: number,+): Promise<TopicRecentRun[]> {+ const supabase = await dbClient();+ const { data: prompts, error: promptsError } = await supabase+ .from('prompts')+ .select('id, text')+ .eq('topic_id', topicId);+ if (promptsError) throw new Error(promptsError.message);+ const texts = new Map(+ ((prompts ?? []) as { id: string; text: string }[]).map((p) => [p.id, p.text]),+ );+ if (texts.size === 0) return [];++ // #155 — as every Insights read: chatgpt-shopping answers aren't comparable.+ const { data: runs, error } = await supabase+ .from('prompt_results')+ .select('prompt_id, visibility_score')+ .eq('brand_id', brandId)+ .neq('platform', 'chatgpt-shopping')+ .in('prompt_id', [...texts.keys()])+ .order('created_at', { ascending: false })+ .limit(limit);+ if (error) throw new Error(error.message);+ return ((runs ?? []) as { prompt_id: string; visibility_score: number }[]).map((run) => ({+ promptId: run.prompt_id,+ promptText: texts.get(run.prompt_id) ?? '',+ visibilityScore: Number(run.visibility_score ?? 0),+ }));}/**@@ -3686,7 +3735,7 @@ export async function getTopicDetail(brandId: string, topicId: string): Promise<getVisibilityRateTrend(brandId, { topicId, days: allTime }),getShareOfVoiceData(brandId, { topicId, days: allTime }),getCompetitorComparison(brandId, { topicId, days: allTime }),- getPromptResults(brandId, { topicId, limit: 50 }),+ getTopicRecentRuns(brandId, topicId, 50),]);if (!topic) throw new Error('Topic not found');@@ -3707,5 +3756,5 @@ export async function getTopicDetail(brandId: string, topicId: string): Promise<};});- return { topic, summary, trend, sov, competitors, results: results.results };+ return { topic, summary, trend, sov, competitors, results };}