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
fix(prompts): say a failed read failed, never "No prompts yet" (#1324)
Cihanc66906ff870a
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 2282e84bc..ec118e5a1 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -5039,6 +5039,8 @@}},"prompts": {+ "loadError": "Couldn't load your prompts.",+ "visibilityDegraded": "Visibility figures are temporarily unavailable — showing prompts without them.","positions": {"answers": "{count, plural, one {# answer} other {# answers}}","answersInPeriod": "{count, plural, one {# answer} other {# answers}} in this period",@@ -5445,7 +5447,7 @@},"perception": {"sectionLabel": "Perception",- "loadError": "Couldn't load the perception figures. Try again in a moment.",+ "loadError": "Couldn't load the perception figures.","unavailable": "Perception isn't available yet. It appears once the mentions data has been prepared.","pickDates": "Choose a start or end date to see the perception figures.","noMentions": "AI didn't name {brand} in the tracked responses of this period.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.test.tsxindex 483aa464e..ec874453e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.test.tsx@@ -242,9 +242,7 @@ describe('MentionsPerceptionTab', () => {await act(async () => {await vi.advanceTimersByTimeAsync(250);});- expect(container.textContent).toBe(- "Couldn't load the perception figures. Try again in a moment.",- );+ expect(container.textContent).toBe("Couldn't load the perception figures.Try again");render(<MentionsPerceptionTab@@ -257,6 +255,30 @@ describe('MentionsPerceptionTab', () => {expect(container.querySelector('[aria-hidden]')).not.toBeNull();});+ it('reads the same filters again on Try again, with the skeleton meanwhile', async () => {+ vi.useFakeTimers();+ getMentionsPerception+ .mockRejectedValueOnce(new Error('timeout'))+ .mockResolvedValueOnce(perception);+ render(+ <MentionsPerceptionTab brandId="b1" brand="Ansvisor" filters={DEFAULT_MENTIONS_FILTERS} />,+ );+ await act(async () => {+ await vi.advanceTimersByTimeAsync(250);+ });+ const retry = [...container.querySelectorAll('button')].find(+ (b) => b.textContent === 'Try again',+ )!;+ await act(async () => retry.click());+ expect(container.querySelector('[aria-hidden]')).not.toBeNull();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(250);+ });+ expect(getMentionsPerception).toHaveBeenCalledTimes(2);+ expect(getMentionsPerception.mock.calls[1]).toEqual(getMentionsPerception.mock.calls[0]);+ expect(container.textContent).toContain('What AI associates with Ansvisor');+ });+it('asks for dates on a custom range without any', () => {render(<MentionsPerceptionTabdiff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.tsxindex 62c76ea8a..289246b64 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.tsx@@ -2,6 +2,8 @@import { useEffect, useMemo, useState } from 'react';import { useTranslations } from 'next-intl';+import { RotateCw } from 'lucide-react';+import { Button } from '@/components/ui/button';import { Card, CardContent } from '@/components/ui/card';import { Skeleton } from '@/components/ui/skeleton';import { getMentionsPerception } from '@/lib/actions/mentions';@@ -44,9 +46,12 @@ export function MentionsPerceptionTab({filters: MentionsFilters;}) {const t = useTranslations('mentions.perception');+ const common = useTranslations('common');const query = useMemo(() => mentionsQuery(filters), [filters]);const key = query ? JSON.stringify([brandId, query]) : null;const [loaded, setLoaded] = useState<Loaded | null>(null);+ // Try again reads the same filters once more.+ const [attempt, setAttempt] = useState(0);useEffect(() => {if (!key || !query) return;@@ -64,12 +69,30 @@ export function MentionsPerceptionTab({cancelled = true;clearTimeout(timer);};- }, [brandId, key, query]);+ }, [brandId, key, query, attempt]);if (!query) return <Message>{t('pickDates')}</Message>;if (!loaded || loaded.brandId !== brandId) return <PerceptionSkeleton />;if (loaded.status === 'error') {- return loaded.key === key ? <Message>{t('loadError')}</Message> : <PerceptionSkeleton />;+ return loaded.key === key ? (+ <Message>+ <p>{t('loadError')}</p>+ <Button+ className="mt-4 gap-2"+ size="sm"+ variant="outline"+ onClick={() => {+ setLoaded(null);+ setAttempt((n) => n + 1);+ }}+ >+ <RotateCw className="h-4 w-4" />+ {common('retry')}+ </Button>+ </Message>+ ) : (+ <PerceptionSkeleton />+ );}if (!loaded.perception) return <Message>{t('unavailable')}</Message>;diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex ad89f1894..30755fc3f 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -100,6 +100,7 @@ import {Pause,Play,Lightbulb,+ RotateCw,} from 'lucide-react';import { cn } from '@/lib/utils';import {@@ -188,6 +189,7 @@ import {type SortDir,} from './prompt-sort';import { BulkActionBar } from './_bulk-action-bar';+import { promptsTableState } from './table-state';import { formatCompactNumber, formatDate, formatNumber } from '@/lib/format';import { usePagination, TablePager } from '@/components/table-pager';import { PromptPositionsSheet } from '@/components/prompts/prompt-positions-sheet';@@ -1263,6 +1265,8 @@ export default function PromptsPage() {const [visibility, setVisibility] = useState<Record<string, PromptVisibilitySummary>>({});const [positions, setPositions] = useState<Record<string, PromptPositionCell>>({});const [loading, setLoading] = useState(true);+ // The last read failed: the table says so, rather than that there are no prompts.+ const [loadFailed, setLoadFailed] = useState(false);const [analyzing, setAnalyzing] = useState(false);const [analysisProgress, setAnalysisProgress] = useState<{done: number;@@ -1282,6 +1286,7 @@ export default function PromptsPage() {const activeBrandId = useBrandStore((s) => s.activeBrandId);const tCommon = useTranslations('common');const tNav = useTranslations('nav');+ const tPrompts = useTranslations('prompts');const activeBrand = useBrandStore((s) => s.brands.find((brand) => brand.id === s.activeBrandId) ?? null,);@@ -1467,6 +1472,7 @@ export default function PromptsPage() {}setLoading(true);+ setLoadFailed(false);try {// One consolidated server action: Next.js queues client-fired server// actions sequentially, so the old three separate calls cost their@@ -1487,15 +1493,17 @@ export default function PromptsPage() {if (page.volumesDegraded) {toast.warning('Volume data is temporarily unavailable — showing prompts without it.');}+ if (page.visibilityDegraded) toast.warning(tPrompts('visibilityDegraded'));} catch (err) {if (isCancelled?.()) return;console.error('Failed to load prompt data:', err);+ setLoadFailed(true);toast.error('Failed to load prompt data');} finally {if (!isCancelled?.()) setLoading(false);}},- [activeBrandId, range, regionFilter],+ [activeBrandId, range, regionFilter, tPrompts],);useEffect(() => {@@ -2045,6 +2053,8 @@ export default function PromptsPage() {)}<AllPromptsTabloading={loading}+ failed={loadFailed}+ onRetry={() => void loadData()}prompts={allPrompts}activeBrandId={activeBrandId}volumeByPromptId={volumeByPromptId}@@ -2662,6 +2672,8 @@ const WORK_FILTER_LABELS: Record<string, string> = {function AllPromptsTab({loading,+ failed,+ onRetry,prompts: allRows,activeBrandId,volumeByPromptId,@@ -2678,6 +2690,9 @@ function AllPromptsTab({onChanged,}: {loading: boolean;+ /** The last read failed: say so and offer to read again, never "No prompts yet". */+ failed: boolean;+ onRetry: () => void;prompts: Prompt[];activeBrandId: string;volumeByPromptId: Map<string, PromptVolume>;@@ -2702,6 +2717,7 @@ function AllPromptsTab({onChanged: () => void;}) {const tCommon = useTranslations('common');+ const tPrompts = useTranslations('prompts');// One tooltip for every prompt and topic the table cuts short.const fullText = useMemo(() => createClampedTextHandle(), []);const tUsage = useTranslations('prompts.usage');@@ -3331,7 +3347,8 @@ function AllPromptsTab({});}, []);- if (loading) {+ const state = promptsTableState({ loading, failed, rows: prompts.length });+ if (state === 'loading') {return (<div className="flex items-center justify-center py-10"><Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />@@ -3339,7 +3356,22 @@ function AllPromptsTab({);}- if (prompts.length === 0) {+ if (state === 'failed') {+ return (+ <Card>+ <CardContent className="py-14 text-center text-sm">+ <AlertCircle className="mx-auto h-9 w-9 text-destructive/60" />+ <p className="mt-2 font-medium">{tPrompts('loadError')}</p>+ <Button className="mt-4 gap-2" size="sm" variant="outline" onClick={onRetry}>+ <RotateCw className="h-4 w-4" />+ {tCommon('retry')}+ </Button>+ </CardContent>+ </Card>+ );+ }++ if (state === 'empty') {return (<Card><CardContent className="flex flex-col items-center justify-center py-16 gap-4">diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/table-state.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/prompts/table-state.test.tsnew file mode 100644index 000000000..3e0f9892e--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/table-state.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';+import { promptsTableState } from './table-state';++describe('promptsTableState', () => {+ it('waits while the prompts are read', () => {+ expect(promptsTableState({ loading: true, failed: false, rows: 0 })).toBe('loading');+ expect(promptsTableState({ loading: true, failed: true, rows: 4 })).toBe('loading');+ });++ it('says a read failed instead of "No prompts yet"', () => {+ expect(promptsTableState({ loading: false, failed: true, rows: 0 })).toBe('failed');+ });++ it('keeps the rows on screen when a re-read fails', () => {+ expect(promptsTableState({ loading: false, failed: true, rows: 4 })).toBe('rows');+ });++ it('is empty only when a read succeeded with no prompts', () => {+ expect(promptsTableState({ loading: false, failed: false, rows: 0 })).toBe('empty');+ expect(promptsTableState({ loading: false, failed: false, rows: 2 })).toBe('rows');+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/table-state.ts b/web/src/app/[locale]/(dashboard)/dashboard/prompts/table-state.tsnew file mode 100644index 000000000..9dc23139f--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/table-state.ts@@ -0,0 +1,21 @@+/**+ * What the Prompts table shows. A read that failed with nothing on screen+ * says so and offers to read again: it is never "No prompts yet", which+ * would tell a brand with prompts to add its first one. A failed re-read+ * keeps the rows already shown.+ */+export type PromptsTableState = 'loading' | 'failed' | 'empty' | 'rows';++export function promptsTableState({+ loading,+ failed,+ rows,+}: {+ loading: boolean;+ failed: boolean;+ rows: number;+}): PromptsTableState {+ if (loading) return 'loading';+ if (rows > 0) return 'rows';+ return failed ? 'failed' : 'empty';+}diff --git a/web/src/lib/actions/prompt.test.ts b/web/src/lib/actions/prompt.test.tsindex 656a01eb2..d73fcc9a0 100644--- a/web/src/lib/actions/prompt.test.ts+++ b/web/src/lib/actions/prompt.test.ts@@ -350,4 +350,21 @@ describe('getPromptsPageData', () => {expect.any(Error),);});++ it('shows the prompts without their visibility when that read times out, and says so', async () => {+ vi.mocked(getPromptVisibilitySummaries).mockRejectedValue(+ new Error('canceling statement due to statement timeout'),+ );++ const page = await getPromptsPageData('b1');++ expect(page.promptSets[0].prompts.map((p) => p.id)).toEqual(['p1']);+ expect(page.visibility).toEqual({});+ expect(page.visibilityDegraded).toBe(true);+ expect(page.volumesDegraded).toBe(false);+ expect(console.error).toHaveBeenCalledWith(+ expect.stringContaining('visibility summaries'),+ expect.any(Error),+ );+ });});diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.tsindex 4233d6004..60f77a9fb 100644--- a/web/src/lib/actions/prompt.ts+++ b/web/src/lib/actions/prompt.ts@@ -1020,6 +1020,8 @@ export interface PromptsPageData {quota: VolumeQuota | null;/** True when the volumes upstream failed/timed out — the table still renders. */volumesDegraded: boolean;+ /** True when the visibility summaries failed/timed out — their columns read —. */+ visibilityDegraded: boolean;}/**@@ -1052,12 +1054,21 @@ export async function getPromptsPageData(// GET /api/prompts/usage, which reads counters instead of counting prompts.const [promptSets, visibility, positionRows, volumesResult] = await Promise.all([getPromptSets(brandId),+ // The visibility columns scan the window's answers too: a timeout shows —+ // in them, with a note, rather than blanking the table as if the brand+ // had no prompts.getPromptVisibilitySummaries(brandId, {days,from: opts?.from,to: opts?.to,region: opts?.region,- }),+ }).then(+ (summaries) => ({ summaries, degraded: false }),+ (err) => {+ console.error('[prompts] visibility summaries fetch failed, rendering without them:', err);+ return { summaries: {} as Record<string, PromptVisibilitySummary>, degraded: true };+ },+ ),// The Positions column scans every answer in the window and the one// before it. A timeout shows — in that column instead of failing the// table; the web deploying before 00153 falls back to 00123's rows.@@ -1092,11 +1103,12 @@ export async function getPromptsPageData(return {promptSets,- visibility,+ visibility: visibility.summaries,positions,volumes: volumesResult.volumes,quota: volumesResult.quota,volumesDegraded: volumesResult.degraded,+ visibilityDegraded: visibility.degraded,};}