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): collapse 6 serialized topic-detail server actions into one (#338)
Gökhan Geyika9387d2a4793
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/page.tsxindex 0549cd41a..b26b15d13 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/topics/[id]/page.tsx@@ -4,18 +4,13 @@ import { useCallback, useEffect, useRef, useState, use } from 'react';import { Link, useRouter } from '@/i18n/navigation';import { useBrandStore } from '@/stores/use-brand-store';import {- getInsightsSummary,- getVisibilityTrend,- getShareOfVoiceData,- getCompetitorComparison,- getPromptResults,+ getTopicDetail,type InsightsSummary,type VisibilityTrendPoint,type ShareOfVoiceData,type CompetitorComparisonData,type PromptResultWithText,} from '@/lib/actions/tracking';-import { getTopics } from '@/lib/actions/topic';import type { Topic } from '@/types';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { Badge } from '@/components/ui/badge';@@ -161,20 +156,16 @@ export default function TopicDetailPage({ params }: { params: Promise<{ id: striif (!activeBrandId || !topicId) return;setLoading(true);try {- const [topics, summ, tr, sv, cmp, res] = await Promise.all([- getTopics(activeBrandId),- getInsightsSummary(activeBrandId, { topicId }),- getVisibilityTrend(activeBrandId, { topicId }),- getShareOfVoiceData(activeBrandId, { topicId }),- getCompetitorComparison(activeBrandId, { topicId }),- getPromptResults(activeBrandId, { topicId, limit: 50 }),- ]);- setTopic(topics.find((t) => t.id === topicId) ?? null);- setSummary(summ);- setTrend(tr);- setSov(sv);- setCompetitors(cmp);- setResults(res.results);+ // One server action (#312): Next.js runs server actions sequentially, so+ // the old six-call Promise.all paid the sum of all six. This is one round+ // trip whose body runs the work in a real server-side Promise.all.+ const detail = await getTopicDetail(activeBrandId, topicId);+ setTopic(detail.topic);+ setSummary(detail.summary);+ setTrend(detail.trend);+ setSov(detail.sov);+ setCompetitors(detail.competitors);+ setResults(detail.results);} catch (err) {console.error('Failed to load topic detail', err);} finally {diff --git a/web/src/lib/actions/topic.ts b/web/src/lib/actions/topic.tsindex 167dde9e9..01613dbd9 100644--- a/web/src/lib/actions/topic.ts+++ b/web/src/lib/actions/topic.ts@@ -45,6 +45,28 @@ export async function getTopics(brandId: string): Promise<Topic[]> {return (data ?? []).map((r) => mapTopicRow(r as Record<string, unknown>));}+/**+ * Fetch a single active topic by id, scoped to the brand. Returns null when the+ * topic doesn't exist, isn't this brand's, or is inactive — the detail page+ * renders "not found". The `is_active = true` filter mirrors getTopics(), which+ * the page used before (via .find() over the active list), so inactive topics+ * stay hidden. Cheaper than fetching the whole list just to read one name.+ */+export async function getTopicById(brandId: string, topicId: string): Promise<Topic | null> {+ const supabase = await createClient();++ const { data, error } = await supabase+ .from('topics')+ .select('id, brand_id, name, is_active, created_at')+ .eq('brand_id', brandId)+ .eq('id', topicId)+ .eq('is_active', true)+ .maybeSingle();++ if (error) throw new Error(error.message);+ return data ? mapTopicRow(data as Record<string, unknown>) : null;+}+export async function createTopic(brandId: string, name: string): Promise<Topic> {const supabase = await createClient();diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.tsindex 140747549..fdb04a960 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -2,8 +2,16 @@import { createClient } from '@/lib/supabase/server';import { expandDateToEndOfDay } from '@/lib/dates';-import type { PromptResult, AIPlatform, Sentiment, Citation, CompetitorMention } from '@/types';+import type {+ PromptResult,+ AIPlatform,+ Sentiment,+ Citation,+ CompetitorMention,+ Topic,+} from '@/types';import { API_BASE_URL } from '@/config/api';+import { getTopicById } from '@/lib/actions/topic';/** Round to one decimal place (keeps sub-1 averages visible instead of flooring to 0). */function roundTo1(n: number): number {@@ -1994,3 +2002,39 @@ function formatTotalMagnitude(const sign = deltaPct < 0 ? '−' : '+';return `${core} (${sign}${Math.abs(deltaPct)}%)`;}++// ─── Topic detail bundle (#312) ───────────────────────────────────────────++export interface TopicDetailData {+ topic: Topic | null;+ summary: InsightsSummary;+ trend: VisibilityTrendPoint[];+ sov: ShareOfVoiceData;+ competitors: CompetitorComparisonData;+ results: PromptResultWithText[];+}++/**+ * One server action for the whole topic detail page (#312).+ *+ * The page previously fired six separate server-action calls from the client.+ * Next.js runs server actions **sequentially** (each is its own queued POST),+ * so that cost was roughly the sum of all six, not the slowest. Collapsing them+ * into one action means a single round trip whose body runs the work in a real+ * server-side `Promise.all` (genuinely parallel). The topic is fetched by id+ * instead of pulling the whole topics list just to read one name.+ *+ * Output is identical to the old per-call results — this is a perf refactor.+ */+export async function getTopicDetail(brandId: string, topicId: string): Promise<TopicDetailData> {+ const [topic, summary, trend, sov, competitors, results] = await Promise.all([+ getTopicById(brandId, topicId),+ getInsightsSummary(brandId, { topicId }),+ getVisibilityTrend(brandId, { topicId }),+ getShareOfVoiceData(brandId, { topicId }),+ getCompetitorComparison(brandId, { topicId }),+ getPromptResults(brandId, { topicId, limit: 50 }),+ ]);++ return { topic, summary, trend, sov, competitors, results: results.results };+}