Skip to content

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.

fix(prompts): return a failed suggestions read as a value, retry it once, and say what went wrong (#1777)

Cihanfaec3461d2e9
diff --git a/web/messages/en.json b/web/messages/en.json
index 55b304f5e..97102e35c 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -7635,6 +7635,9 @@
"presenceRate": "Presence Rate",
"gaps": "Content Gaps",
"suggestions": {
+ "loadFailed": "Couldn't load suggestions",
+ "loadUnavailable": "Ansvisor isn't answering right now. Try again in a moment.",
+ "retry": "Retry",
"measuredSuggestionsKept": "Search Console and Analytics suggestions were kept — dismiss them individually to hide them for 30 days.",
"catalog": {
"badge": "Your catalog",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx
index 4c5042633..c0b071476 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx
@@ -67,7 +67,9 @@ const openUpgrade = vi.fn();
async function render(count: number, planId: 'starter' | 'growth' = 'starter') {
actions.getPromptSuggestions.mockResolvedValue({
+ ok: true,
suggestions: Array.from({ length: count }, (_, i) => suggestion(i + 1)),
+ stale: false,
});
await act(async () => {
root.render(
@@ -245,7 +247,9 @@ describe('SuggestionsCard — Add All', () => {
describe('SuggestionsCard — estimated volume', () => {
it("shows an AI's guess as a grey range, never a bare number", async () => {
actions.getPromptSuggestions.mockResolvedValue({
+ ok: true,
suggestions: [{ ...suggestion(1), estVolume: 1200 }],
+ stale: false,
});
await act(async () => {
root.render(
@@ -375,7 +379,11 @@ describe('SuggestionsCard — shopping questions from the catalog (ECOM-003)', (
async function show(search = '') {
window.history.replaceState(null, '', `/dashboard/prompts${search}`);
- actions.getPromptSuggestions.mockResolvedValue({ suggestions: [suggestion(1), fromCatalog] });
+ actions.getPromptSuggestions.mockResolvedValue({
+ ok: true,
+ suggestions: [suggestion(1), fromCatalog],
+ stale: false,
+ });
await act(async () => {
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
@@ -403,3 +411,83 @@ describe('SuggestionsCard — shopping questions from the catalog (ECOM-003)', (
expect(container.textContent).toContain('Shopping');
});
});
+
+describe('SuggestionsCard — a failed read', () => {
+ async function mount() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <SuggestionsCard brandId="b1" onAccepted={onAccepted} sourceStates={null} />
+ </NextIntlClientProvider>,
+ );
+ });
+ }
+ const retryButton = () =>
+ [...container.querySelectorAll('button')].find((b) => b.textContent === 'Retry');
+
+ afterEach(() => vi.useRealTimers());
+
+ it('tries once more by itself when the API did not answer, and lists what comes back', async () => {
+ vi.useFakeTimers();
+ actions.getPromptSuggestions
+ .mockResolvedValueOnce({ ok: false, failure: 'failed', retryable: true })
+ .mockResolvedValueOnce({ ok: true, suggestions: [suggestion(1)], stale: false });
+ await mount();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1500);
+ });
+ expect(actions.getPromptSuggestions).toHaveBeenCalledTimes(2);
+ expect(rows()).toHaveLength(1);
+ expect(container.textContent).not.toContain("Couldn't load suggestions");
+ });
+
+ it("says the API is not answering in plain words, never React's hidden message, and Retry reads again", async () => {
+ vi.useFakeTimers();
+ actions.getPromptSuggestions.mockResolvedValue({
+ ok: false,
+ failure: 'failed',
+ retryable: true,
+ });
+ await mount();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1500);
+ });
+ expect(actions.getPromptSuggestions).toHaveBeenCalledTimes(2);
+ expect(container.textContent).toContain("Couldn't load suggestions");
+ expect(container.textContent).toContain("Ansvisor isn't answering right now.");
+ expect(container.textContent).not.toContain('Minified React error');
+
+ actions.getPromptSuggestions.mockResolvedValue({
+ ok: true,
+ suggestions: [suggestion(1), suggestion(2)],
+ stale: false,
+ });
+ await act(async () => {
+ retryButton()!.click();
+ });
+ expect(rows()).toHaveLength(2);
+ });
+
+ it('says why when trying again would not help, without retrying by itself', async () => {
+ actions.getPromptSuggestions.mockResolvedValue({
+ ok: false,
+ failure: 'workspace',
+ retryable: false,
+ });
+ await mount();
+ expect(actions.getPromptSuggestions).toHaveBeenCalledTimes(1);
+ expect(container.textContent).toContain("This brand isn't in your workspace.");
+ expect(retryButton()).toBeDefined();
+ });
+
+ it('reads a server action that threw on its way as no answer', async () => {
+ vi.useFakeTimers();
+ actions.getPromptSuggestions.mockRejectedValue(new Error('Minified React error #441'));
+ await mount();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1500);
+ });
+ expect(container.textContent).toContain("Ansvisor isn't answering right now.");
+ expect(container.textContent).not.toContain('Minified React error');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
index 56531b131..c1659867c 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
@@ -66,6 +66,8 @@ import {
import type { SuggestionSourceStates } from '@/lib/actions/integrations';
import { useUpgradeGate } from '@/components/providers/upgrade-gate';
import { useUserRole } from '@/hooks/use-user-role';
+import { readWithOneRetry, type ReadFailure } from '@/lib/api-failure';
+import { SuggestionsLoadError } from './_suggestions-load-error';
/**
* Analytics evidence, in the customer's own numbers (#705). A blind spot is
@@ -329,7 +331,7 @@ export function SuggestionsCard({
const [suggestions, setSuggestions] = useState<PromptSuggestion[]>([]);
const [loading, setLoading] = useState(false);
const [loaded, setLoaded] = useState(false);
- const [error, setError] = useState<string | null>(null);
+ const [error, setError] = useState<ReadFailure | null>(null);
const [refreshing, setRefreshing] = useState(false);
const [pendingId, setPendingId] = useState<string | null>(null);
const [sourceFilter, setSourceFilter] = useState<SourceFilter>('all');
@@ -347,17 +349,15 @@ export function SuggestionsCard({
const load = useCallback(async () => {
setLoading(true);
setError(null);
- try {
- const { suggestions: s } = await getPromptSuggestions(brandId);
- setSuggestions(s);
+ // Once more by itself when the API didn't answer, as while it restarts.
+ const read = await readWithOneRetry(() => getPromptSuggestions(brandId));
+ if (read.ok) {
+ setSuggestions(read.suggestions);
setLoaded(true);
- } catch (err) {
- console.error('Failed to load suggestions:', err);
- setError(err instanceof Error ? err.message : 'Failed to load suggestions');
- toast.error('Failed to load suggestions');
- } finally {
- setLoading(false);
+ } else {
+ setError(read);
}
+ setLoading(false);
}, [brandId]);
useEffect(() => {
@@ -717,15 +717,7 @@ export function SuggestionsCard({
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : error ? (
- <div className="flex flex-col items-center justify-center py-10 text-center">
- <AlertTriangle className="h-8 w-8 text-destructive/60 mb-2" />
- <p className="text-sm font-medium mb-1">Couldn&apos;t load suggestions</p>
- <p className="text-xs text-muted-foreground mb-3 max-w-sm">{error}</p>
- <Button onClick={load} disabled={loading} size="sm" variant="outline" className="gap-2">
- <RefreshCw className="h-3.5 w-3.5" />
- Retry
- </Button>
- </div>
+ <SuggestionsLoadError failure={error} onRetry={load} />
) : suggestions.length === 0 ? (
<div className="flex flex-col items-center justify-center py-10 text-center">
<Sparkles className="h-8 w-8 text-muted-foreground/40 mb-2" />
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-load-error.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-load-error.tsx
new file mode 100644
index 000000000..32f310e5e
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-load-error.tsx
@@ -0,0 +1,35 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { AlertTriangle, RefreshCw } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import type { ReadFailure } from '@/lib/api-failure';
+
+/**
+ * A suggestions card's failed read, in plain words, with Retry: an API that
+ * isn't answering says so, anything else says why as the failure toasts do.
+ * Never the thrown message, which production hides behind React's #441.
+ */
+export function SuggestionsLoadError({
+ failure,
+ onRetry,
+}: {
+ failure: ReadFailure;
+ onRetry: () => void;
+}) {
+ const t = useTranslations('prompts.suggestions');
+ const tFailure = useTranslations('apiFailure');
+ return (
+ <div className="flex flex-col items-center justify-center py-10 text-center">
+ <AlertTriangle className="h-8 w-8 text-destructive/60 mb-2" />
+ <p className="text-sm font-medium mb-1">{t('loadFailed')}</p>
+ <p className="text-xs text-muted-foreground mb-3 max-w-sm">
+ {failure.retryable ? t('loadUnavailable') : tFailure(failure.failure)}
+ </p>
+ <Button onClick={onRetry} size="sm" variant="outline" className="gap-2">
+ <RefreshCw className="h-3.5 w-3.5" />
+ {t('retry')}
+ </Button>
+ </div>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.test.tsx
index 3fb06789b..d8c305358 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.test.tsx
@@ -45,9 +45,10 @@ afterEach(() => {
});
async function render(canManage: boolean, ideas: { id: string; name: string }[] = []) {
- actions.getTopicSuggestions.mockResolvedValue(
- ideas.map((idea) => ({ ...idea, brand_id: 'b1', status: 'new', reason: null })),
- );
+ actions.getTopicSuggestions.mockResolvedValue({
+ ok: true,
+ suggestions: ideas.map((idea) => ({ ...idea, brand_id: 'b1', status: 'new', reason: null })),
+ });
await act(async () => {
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.tsx
index b0811cbe6..e1767d168 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topic-suggestions-card.tsx
@@ -14,7 +14,6 @@ import {
Info,
ChevronDown,
ChevronRight,
- AlertTriangle,
} from 'lucide-react';
import { toast } from 'sonner';
import {
@@ -25,6 +24,8 @@ import {
type TopicSuggestion,
} from '@/lib/actions/topic-suggestions';
import { useUpgradeGate } from '@/components/providers/upgrade-gate';
+import { readWithOneRetry, type ReadFailure } from '@/lib/api-failure';
+import { SuggestionsLoadError } from './_suggestions-load-error';
interface Props {
brandId: string;
@@ -40,7 +41,7 @@ export function TopicSuggestionsCard({ brandId, canManage, onAccepted }: Props)
const [suggestions, setSuggestions] = useState<TopicSuggestion[]>([]);
const [loading, setLoading] = useState(false);
const [loaded, setLoaded] = useState(false);
- const [error, setError] = useState<string | null>(null);
+ const [error, setError] = useState<ReadFailure | null>(null);
const [refreshing, setRefreshing] = useState(false);
const [pendingId, setPendingId] = useState<string | null>(null);
// Collapsed by default so the card is a one-line strip and the leaderboard
@@ -84,17 +85,15 @@ export function TopicSuggestionsCard({ brandId, canManage, onAccepted }: Props)
const load = useCallback(async () => {
setLoading(true);
setError(null);
- try {
- const s = await getTopicSuggestions(brandId);
- setSuggestions(s);
+ // Once more by itself when the API didn't answer, as while it restarts.
+ const read = await readWithOneRetry(() => getTopicSuggestions(brandId));
+ if (read.ok) {
+ setSuggestions(read.suggestions);
setLoaded(true);
- } catch (err) {
- console.error('Failed to load topic suggestions:', err);
- setError(err instanceof Error ? err.message : 'Failed to load topic suggestions');
- toast.error('Failed to load topic suggestions');
- } finally {
- setLoading(false);
+ } else {
+ setError(read);
}
+ setLoading(false);
}, [brandId]);
// Fetch ONLY once the card is actually expanded — never on page load. The
@@ -225,21 +224,7 @@ export function TopicSuggestionsCard({ brandId, canManage, onAccepted }: Props)
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : error ? (
- <div className="flex flex-col items-center justify-center py-10 text-center">
- <AlertTriangle className="h-8 w-8 text-destructive/60 mb-2" />
- <p className="text-sm font-medium mb-1">Couldn&apos;t load suggestions</p>
- <p className="text-xs text-muted-foreground mb-3 max-w-sm">{error}</p>
- <Button
- onClick={load}
- disabled={loading}
- size="sm"
- variant="outline"
- className="gap-2"
- >
- <RefreshCw className="h-3.5 w-3.5" />
- Retry
- </Button>
- </div>
+ <SuggestionsLoadError failure={error} onRetry={load} />
) : suggestions.length === 0 ? (
<div className="flex flex-col items-center justify-center py-10 text-center">
<Sparkles className="h-8 w-8 text-muted-foreground/40 mb-2" />
diff --git a/web/src/lib/actions/prompt-suggestions.test.ts b/web/src/lib/actions/prompt-suggestions.test.ts
index b4f6109b9..2456d16fe 100644
--- a/web/src/lib/actions/prompt-suggestions.test.ts
+++ b/web/src/lib/actions/prompt-suggestions.test.ts
@@ -97,7 +97,8 @@ vi.mock('@/lib/actions/prompt-workflow', () => ({
const fetchMock = vi.fn(async () => new Response('{}', { status: 200 }));
vi.stubGlobal('fetch', fetchMock);
-const { trackPagePrompts, trackSuggestions } = await import('./prompt-suggestions');
+const { getPromptSuggestions, trackPagePrompts, trackSuggestions } =
+ await import('./prompt-suggestions');
beforeEach(() => {
slotsLeft = Infinity;
@@ -224,3 +225,56 @@ describe('trackPagePrompts (AT-006 part B2)', () => {
expect(removedTopics).toEqual(['topic-1']);
});
});
+
+/**
+ * getPromptSuggestions: its failures come back as values, as production
+ * hides a thrown server action's message behind React's #441.
+ */
+describe('getPromptSuggestions', () => {
+ const json = (body: unknown, status = 200) =>
+ new Response(JSON.stringify(body), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+
+ it('returns the open suggestions', async () => {
+ fetchMock.mockResolvedValueOnce(
+ json({
+ suggestions: [{ id: 's1', brand_id: 'b1', suggested_text: 'Best GEO tools?' }],
+ stale: false,
+ }),
+ );
+ const read = await getPromptSuggestions('b1');
+ expect(read).toMatchObject({ ok: true, stale: false });
+ expect(read.ok && read.suggestions.map((x) => x.suggestedText)).toEqual(['Best GEO tools?']);
+ });
+
+ it('marks a proxy that says the API is down as worth retrying', async () => {
+ fetchMock.mockResolvedValueOnce(new Response('<html>Bad Gateway</html>', { status: 502 }));
+ expect(await getPromptSuggestions('b1')).toEqual({
+ ok: false,
+ failure: 'failed',
+ retryable: true,
+ });
+ });
+
+ it('returns no answer, never throws, when the request fails or times out', async () => {
+ fetchMock.mockRejectedValueOnce(new DOMException('The operation timed out.', 'TimeoutError'));
+ expect(await getPromptSuggestions('b1')).toEqual({
+ ok: false,
+ failure: 'failed',
+ retryable: true,
+ });
+ });
+
+ it("says why when trying again wouldn't help", async () => {
+ fetchMock.mockResolvedValueOnce(
+ json({ error: "This brand isn't in your workspace", code: 'not_in_workspace' }, 403),
+ );
+ expect(await getPromptSuggestions('b1')).toEqual({
+ ok: false,
+ failure: 'workspace',
+ retryable: false,
+ });
+ });
+});
diff --git a/web/src/lib/actions/prompt-suggestions.ts b/web/src/lib/actions/prompt-suggestions.ts
index 128195315..54daf8930 100644
--- a/web/src/lib/actions/prompt-suggestions.ts
+++ b/web/src/lib/actions/prompt-suggestions.ts
@@ -9,6 +9,7 @@ import { API_BASE_URL } from '@/config/api';
// live in a plain module (every runtime export here must be a server action).
import type { PromptSuggestionSource, SuggestionSourceData } from '@/lib/prompt-suggestion-source';
import { assertWritable } from '@/lib/subscription-guard';
+import { NO_ANSWER, responseFailure, type ReadFailure } from '@/lib/api-failure';
const AEO_SERVER_URL = API_BASE_URL;
@@ -72,29 +73,43 @@ async function getSession() {
return session;
}
-export async function getPromptSuggestions(
- brandId: string,
-): Promise<{ suggestions: PromptSuggestion[]; stale: boolean }> {
- const session = await getSession();
- const res = await fetch(`${AEO_SERVER_URL}/api/prompts/suggestions/${brandId}`, {
- headers: { Authorization: `Bearer ${session.access_token}` },
- cache: 'no-store',
- // Read-only cache lookup — a hung upstream must not pin the suggestions
- // card (and the serialized server-action queue behind it) indefinitely.
- signal: AbortSignal.timeout(15_000),
- });
- if (!res.ok) {
- const body = await res.json().catch(() => ({}));
- throw new Error(body.error || `Server error: ${res.status}`);
+export type PromptSuggestionsRead =
+ | { ok: true; suggestions: PromptSuggestion[]; stale: boolean }
+ | ReadFailure;
+
+/**
+ * The brand's open suggestions. A failure comes back as a value, never
+ * thrown: production hides a thrown message (React's #441), and an API that
+ * didn't answer is marked retryable for the card's one automatic retry.
+ */
+export async function getPromptSuggestions(brandId: string): Promise<PromptSuggestionsRead> {
+ const supabase = await createClient();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
+ if (!session) return { ok: false, failure: 'session', retryable: false };
+ try {
+ const res = await fetch(`${AEO_SERVER_URL}/api/prompts/suggestions/${brandId}`, {
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ cache: 'no-store',
+ // Read-only cache lookup — a hung upstream must not pin the suggestions
+ // card (and the serialized server-action queue behind it) indefinitely.
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (!res.ok) return await responseFailure(res);
+ const data = (await res.json()) as {
+ suggestions: SuggestionRow[];
+ stale: boolean;
+ };
+ return {
+ ok: true,
+ suggestions: data.suggestions.map(mapRow),
+ stale: data.stale,
+ };
+ } catch {
+ // No answer, or one cut off: a dropped connection or the timeout.
+ return NO_ANSWER;
}
- const data = (await res.json()) as {
- suggestions: SuggestionRow[];
- stale: boolean;
- };
- return {
- suggestions: data.suggestions.map(mapRow),
- stale: data.stale,
- };
}
export async function refreshPromptSuggestions(brandId: string): Promise<PromptSuggestion[]> {
diff --git a/web/src/lib/actions/topic-suggestions.ts b/web/src/lib/actions/topic-suggestions.ts
index f6ccef3e7..fba4e5232 100644
--- a/web/src/lib/actions/topic-suggestions.ts
+++ b/web/src/lib/actions/topic-suggestions.ts
@@ -5,6 +5,7 @@ import { createClient } from '@/lib/supabase/server';
import { createTopic } from '@/lib/actions/topic';
import { TOPIC_NAME_CHARS } from '@/lib/topic-names';
import { API_BASE_URL } from '@/config/api';
+import { NO_ANSWER, responseFailure, type ReadFailure } from '@/lib/api-failure';
const AEO_SERVER_URL = API_BASE_URL;
@@ -49,21 +50,34 @@ async function getSession() {
return session;
}
-export async function getTopicSuggestions(brandId: string): Promise<TopicSuggestion[]> {
- const session = await getSession();
- const res = await fetch(`${AEO_SERVER_URL}/api/topics/suggestions/${brandId}`, {
- headers: { Authorization: `Bearer ${session.access_token}` },
- cache: 'no-store',
- // Read-only lookup — a hung upstream must not pin the suggestions card
- // (and the serialized server-action queue behind it) indefinitely.
- signal: AbortSignal.timeout(15_000),
- });
- if (!res.ok) {
- const body = await res.json().catch(() => ({}));
- throw new Error(body.error || `Server error: ${res.status}`);
+export type TopicSuggestionsRead = { ok: true; suggestions: TopicSuggestion[] } | ReadFailure;
+
+/**
+ * The brand's open topic suggestions. A failure comes back as a value, never
+ * thrown: production hides a thrown message (React's #441), and an API that
+ * didn't answer is marked retryable for the card's one automatic retry.
+ */
+export async function getTopicSuggestions(brandId: string): Promise<TopicSuggestionsRead> {
+ const supabase = await createClient();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
+ if (!session) return { ok: false, failure: 'session', retryable: false };
+ try {
+ const res = await fetch(`${AEO_SERVER_URL}/api/topics/suggestions/${brandId}`, {
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ cache: 'no-store',
+ // Read-only lookup — a hung upstream must not pin the suggestions card
+ // (and the serialized server-action queue behind it) indefinitely.
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (!res.ok) return await responseFailure(res);
+ const data = (await res.json()) as { suggestions: SuggestionRow[] };
+ return { ok: true, suggestions: data.suggestions.map(mapRow) };
+ } catch {
+ // No answer, or one cut off: a dropped connection or the timeout.
+ return NO_ANSWER;
}
- const data = (await res.json()) as { suggestions: SuggestionRow[] };
- return data.suggestions.map(mapRow);
}
export async function refreshTopicSuggestions(brandId: string): Promise<TopicSuggestion[]> {
diff --git a/web/src/lib/actions/tracking-insights-cache.test.ts b/web/src/lib/actions/tracking-insights-cache.test.ts
index a76c72031..91ca8cc65 100644
--- a/web/src/lib/actions/tracking-insights-cache.test.ts
+++ b/web/src/lib/actions/tracking-insights-cache.test.ts
@@ -106,7 +106,7 @@ vi.mock('@/lib/guards/plan-guard', () => ({
vi.mock('@/lib/prompt-locations', () => ({ getOrgLocationUsage: async () => ({ total: 2 }) }));
vi.mock('@/lib/actions/volumes', () => ({ getPromptVolumes: async () => ({ volumes: [] }) }));
vi.mock('@/lib/actions/prompt-suggestions', () => ({
- getPromptSuggestions: async () => ({ suggestions: [] }),
+ getPromptSuggestions: async () => ({ ok: true, suggestions: [], stale: true }),
}));
// unstable_cache as Next runs it: a result is stored once its function
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index b69bf8f1c..622b341b5 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -666,7 +666,9 @@ const TRACKED_TOPIC_ROWS = 1000;
*/
async function getInsightsOpportunities(brandId: string): Promise<InsightsOpportunities> {
try {
- const { suggestions } = await getPromptSuggestions(brandId);
+ const read = await getPromptSuggestions(brandId);
+ if (!read.ok) return { suggestions: [], trackedTopicIds: [], contentUsage: null };
+ const { suggestions } = read;
const topicIds = [...new Set(suggestions.flatMap((s) => (s.topicId ? [s.topicId] : [])))];
const readTrackedTopics = async (): Promise<string[] | null> => {
if (topicIds.length === 0) return [];
diff --git a/web/src/lib/api-failure.test.ts b/web/src/lib/api-failure.test.ts
index 62bddd766..5c9bdd89b 100644
--- a/web/src/lib/api-failure.test.ts
+++ b/web/src/lib/api-failure.test.ts
@@ -1,5 +1,12 @@
-import { describe, expect, it } from 'vitest';
-import { apiFailure, isSubscriptionInactive } from './api-failure';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ NO_ANSWER,
+ apiFailure,
+ isSubscriptionInactive,
+ isTransientStatus,
+ readWithOneRetry,
+ responseFailure,
+} from './api-failure';
describe('apiFailure', () => {
it('reads a bad or expired session from 401 only', () => {
@@ -83,3 +90,56 @@ describe('isSubscriptionInactive', () => {
expect(isSubscriptionInactive(undefined)).toBe(false);
});
});
+
+describe('a read whose failure comes back as a value', () => {
+ afterEach(() => vi.useRealTimers());
+
+ it('takes the proxy saying the API is down as transient, and nothing else', () => {
+ expect([502, 503, 504].every(isTransientStatus)).toBe(true);
+ expect([400, 401, 403, 404, 429, 500].some(isTransientStatus)).toBe(false);
+ });
+
+ it('reads a failed response, also one whose body is not JSON', async () => {
+ expect(await responseFailure(new Response('Bad Gateway', { status: 502 }))).toEqual({
+ ok: false,
+ failure: 'failed',
+ retryable: true,
+ });
+ expect(
+ await responseFailure(
+ new Response(JSON.stringify({ message: 'Unauthorized API Request' }), { status: 401 }),
+ ),
+ ).toEqual({ ok: false, failure: 'session', retryable: false });
+ });
+
+ it('tries once more after the delay when trying again may help', async () => {
+ vi.useFakeTimers();
+ const read = vi
+ .fn()
+ .mockResolvedValueOnce(NO_ANSWER)
+ .mockResolvedValueOnce({ ok: true, value: 1 });
+ const result = readWithOneRetry(read, 1500);
+ await vi.advanceTimersByTimeAsync(1499);
+ expect(read).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(await result).toEqual({ ok: true, value: 1 });
+ expect(read).toHaveBeenCalledTimes(2);
+ });
+
+ it('tries only once more, and not at all when it would not help', async () => {
+ const down = vi.fn().mockResolvedValue(NO_ANSWER);
+ expect(await readWithOneRetry(down, 0)).toEqual(NO_ANSWER);
+ expect(down).toHaveBeenCalledTimes(2);
+
+ const refused = { ok: false as const, failure: 'workspace' as const, retryable: false };
+ const notMine = vi.fn().mockResolvedValue(refused);
+ expect(await readWithOneRetry(notMine, 0)).toEqual(refused);
+ expect(notMine).toHaveBeenCalledTimes(1);
+ });
+
+ it('reads a server action that threw on its way as no answer', async () => {
+ const read = vi.fn().mockRejectedValue(new Error('Minified React error #441'));
+ expect(await readWithOneRetry(read, 0)).toEqual(NO_ANSWER);
+ expect(read).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/web/src/lib/api-failure.ts b/web/src/lib/api-failure.ts
index 5c95c9e81..bf3ba81f5 100644
--- a/web/src/lib/api-failure.ts
+++ b/web/src/lib/api-failure.ts
@@ -45,6 +45,59 @@ export function apiFailure(status: number, body: Record<string, unknown> = {}):
return 'failed';
}
+/**
+ * A read's failure, returned rather than thrown: Next.js hides a server
+ * action's thrown message in production, so the card showed React's
+ * "Minified React error #441" instead of what went wrong. `retryable` when
+ * trying again may help: the API didn't answer (a dropped connection, the
+ * read's timeout) or the proxy in front of it said it was down, as while it
+ * restarts on a deploy.
+ */
+export interface ReadFailure {
+ ok: false;
+ failure: ApiFailure;
+ retryable: boolean;
+}
+
+/** The proxy's answers while the API is down or restarting. */
+export function isTransientStatus(status: number): boolean {
+ return status === 502 || status === 503 || status === 504;
+}
+
+/** The API didn't answer: a network error, or the read's timeout. */
+export const NO_ANSWER: ReadFailure = { ok: false, failure: 'failed', retryable: true };
+
+/** A response that isn't ok, as a ReadFailure. */
+export async function responseFailure(res: Response): Promise<ReadFailure> {
+ const body = await res.json().catch(() => ({}));
+ return {
+ ok: false,
+ failure: apiFailure(res.status, body),
+ retryable: isTransientStatus(res.status),
+ };
+}
+
+/** How long a card waits before its one automatic retry. */
+export const READ_RETRY_DELAY_MS = 1500;
+
+/**
+ * Runs `read`, and once more after `delayMs` when it failed in a way trying
+ * again may fix. A server action that throws on its way (the request to
+ * Next itself failed) is NO_ANSWER too. Called in the browser, so the wait
+ * never holds Next's serialized server-action queue.
+ */
+export async function readWithOneRetry<R extends { ok: true } | ReadFailure>(
+ read: () => Promise<R>,
+ delayMs = READ_RETRY_DELAY_MS,
+): Promise<R | ReadFailure> {
+ const attempt = () => read().catch((): ReadFailure => NO_ANSWER);
+ const first = await attempt();
+ const result: { ok: true } | ReadFailure = first;
+ if (result.ok || !result.retryable) return first;
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
+ return attempt();
+}
+
/**
* Whether a response body is the server's subscription_inactive (a read-only
* workspace), also when it comes as text: the AI SDK's chat transport throws