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): let Clear All dismiss every suggestion listed, after saying what it will hide (#1793)
Cihan312a6ae9904b
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 820740c73..44e2e2cfb 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -8081,7 +8081,15 @@"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.",+ "clearAllConfirm": {+ "title": "Clear all suggestions?",+ "body": "{count, plural, one {# suggestion} other {# suggestions}} listed will be dismissed.",+ "measured": "{count, plural, one {# of them comes} other {# of them come}} from Search Console or Analytics: once dismissed, {count, plural, one {it stays} other {they stay}} hidden for 30 days.",+ "confirm": "Clear all",+ "cancel": "Cancel"+ },+ "clearAllPartial": "{count, plural, one {# suggestion} other {# suggestions}} couldn't be dismissed. Try again.",+ "clearAllFailed": "Couldn't clear the suggestions. Try again.","catalog": {"badge": "Your catalog","tooltip": "A shopping question from your catalog's “{category}” category, with {products, plural, one {# product} other {# products}}.",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.tsxindex c0b071476..6bbb931b7 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@@ -18,6 +18,7 @@ const actions = vi.hoisted(() => ({refreshPromptSuggestions: vi.fn(),acceptSuggestion: vi.fn(),dismissSuggestion: vi.fn(),+ dismissSuggestions: vi.fn(),trackSuggestions: vi.fn(),}));vi.mock('@/lib/actions/prompt-suggestions', () => actions);@@ -244,6 +245,88 @@ describe('SuggestionsCard — Add All', () => {});});+describe('SuggestionsCard — Clear All', () => {+ // Suggestions from Search Console and Analytics stay hidden for 30 days once dismissed.+ const measured = (n: number, source: 'gsc' | 'ga'): PromptSuggestion => ({+ ...suggestion(n),+ source,+ });++ async function renderList(list: PromptSuggestion[]) {+ actions.getPromptSuggestions.mockResolvedValue({ ok: true, suggestions: list, stale: false });+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <UpgradeDialogContext.Provider+ value={{ isLocked, reason: 'ended', adminName: null, openUpgrade }}+ >+ <SuggestionsCard brandId="b1" onAccepted={onAccepted} sourceStates={null} />+ </UpgradeDialogContext.Provider>+ </NextIntlClientProvider>,+ );+ });+ }+ const button = (label: string, root: ParentNode = container) =>+ [...root.querySelectorAll('button')].find((b) => b.textContent === label);+ const dialog = () => document.body.querySelector('[role="dialog"]');+ async function click(target: HTMLButtonElement | undefined) {+ await act(async () => {+ target!.click();+ });+ }++ it('asks first, with how many it dismisses and how many come from Search Console or Analytics', async () => {+ await renderList([suggestion(1), measured(2, 'gsc'), suggestion(3), measured(4, 'ga')]);+ await click(button('Clear All'));+ expect(dialog()?.textContent).toContain('4 suggestions listed will be dismissed.');+ expect(dialog()?.textContent).toContain(+ '2 of them come from Search Console or Analytics: once dismissed, they stay hidden for 30 days.',+ );+ expect(actions.dismissSuggestions).not.toHaveBeenCalled();+ });++ it('changes nothing when cancelled', async () => {+ await renderList([measured(1, 'gsc'), suggestion(2)]);+ await click(button('Clear All'));+ await click(button('Cancel', dialog()!));+ expect(actions.dismissSuggestions).not.toHaveBeenCalled();+ expect(rows()).toHaveLength(2);+ expect(toast.info).not.toHaveBeenCalled();+ });++ it('clears a list of only Search Console and Analytics suggestions once confirmed', async () => {+ actions.dismissSuggestions.mockResolvedValue({ ok: true, dismissed: ['s1', 's2'], failed: [] });+ await renderList([measured(1, 'gsc'), measured(2, 'ga')]);+ await click(button('Clear All'));+ expect(dialog()?.textContent).toContain('2 suggestions listed will be dismissed.');+ expect(dialog()?.textContent).toContain('2 of them come from Search Console or Analytics');+ await click(button('Clear all', dialog()!));+ expect(actions.dismissSuggestions).toHaveBeenCalledWith(['s1', 's2']);+ expect(rows()).toHaveLength(0);+ expect(toast.error).not.toHaveBeenCalled();+ });++ it("says nothing of Search Console when none is listed, and brings back what couldn't be dismissed", async () => {+ actions.dismissSuggestions.mockResolvedValue({ ok: true, dismissed: ['s1'], failed: ['s2'] });+ await renderList([suggestion(1), suggestion(2)]);+ await click(button('Clear All'));+ expect(dialog()?.textContent).not.toContain('Search Console');+ await click(button('Clear all', dialog()!));+ expect([...rows()].map((r) => r.textContent).join()).toContain('Prompt 2');+ expect(rows()).toHaveLength(1);+ expect(toast.error).toHaveBeenCalledWith("1 suggestion couldn't be dismissed. Try again.");+ });++ it('puts every one back when the dismiss could not run', async () => {+ actions.dismissSuggestions.mockResolvedValue({ ok: false, failure: 'failed' });+ await renderList([suggestion(1), measured(2, 'gsc')]);+ await click(button('Clear All'));+ await click(button('Clear all', dialog()!));+ expect(rows()).toHaveLength(2);+ expect(toast.error).toHaveBeenCalledWith("Couldn't clear the suggestions. Try again.");+ });+});+describe('SuggestionsCard — estimated volume', () => {it("shows an AI's guess as a grey range, never a bare number", async () => {actions.getPromptSuggestions.mockResolvedValue({diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsxindex c1659867c..300b87189 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx@@ -50,6 +50,7 @@ import {refreshPromptSuggestions,acceptSuggestion,dismissSuggestion,+ dismissSuggestions,trackSuggestions,type PromptSuggestion,} from '@/lib/actions/prompt-suggestions';@@ -68,6 +69,14 @@ 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';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';/*** Analytics evidence, in the customer's own numbers (#705). A blind spot is@@ -341,6 +350,9 @@ export function SuggestionsCard({}, []);const [search, setSearch] = useState('');const [clearing, setClearing] = useState(false);+ // Clear All asks first: how many it dismisses, and how many of them come+ // from Search Console or Analytics (hidden for 30 days once dismissed).+ const [confirmClear, setConfirmClear] = useState(false);const [adding, setAdding] = useState(false);// What Add All left behind when the plan's prompt limit stopped it.const [limitNote, setLimitNote] = useState<{ added: number; left: number } | null>(null);@@ -425,30 +437,33 @@ export function SuggestionsCard({);/**- * Dismiss only generated rows on screen. Search Console and Analytics rows- * carry a 30-day cooldown, so bulk clear keeps them visible unless the user- * explicitly dismisses each one.+ * Dismiss every suggestion listed, after the confirmation: each one as+ * one by one would, so Search Console and Analytics ones stay hidden for+ * 30 days. They leave the list at once; the ones that couldn't be+ * dismissed come back.*/- const handleClearAll = () => {- const preserved = visible.filter(isMeasuredSuggestion);- const doomed = visible.filter((s) => !isMeasuredSuggestion(s));- if (preserved.length > 0) {- toast.info(t('measuredSuggestionsKept'));- }+ const handleClearAll = async () => {+ setConfirmClear(false);+ const doomed = visible;if (doomed.length === 0) return;setClearing(true);const ids = new Set(doomed.map((d) => d.id));setSuggestions((prev) => prev.filter((x) => !ids.has(x.id)));- Promise.allSettled(doomed.map((d) => dismissSuggestion(d.id)))- .then((results) => {- const failed = results.filter((r) => r.status === 'rejected').length;- if (failed > 0) {- toast.error(`${failed} suggestion${failed === 1 ? '' : 's'} could not be dismissed`);- load();- }- })- .finally(() => setClearing(false));+ try {+ const result = await dismissSuggestions([...ids]);+ if (!result.ok) {+ setSuggestions((prev) => [...prev, ...doomed]);+ toast.error(t('clearAllFailed'));+ } else if (result.failed.length > 0) {+ const failed = new Set(result.failed);+ setSuggestions((prev) => [...prev, ...doomed.filter((d) => failed.has(d.id))]);+ toast.error(t('clearAllPartial', { count: failed.size }));+ }+ } finally {+ setClearing(false);+ }};+ const measuredToClear = visible.filter(isMeasuredSuggestion).length;/*** Track every suggestion on screen, in batches trackSuggestions takes. Each@@ -615,7 +630,9 @@ export function SuggestionsCard({{canDismiss && (<Button- onClick={guard(handleClearAll, { action: tActions('dismissSuggestions') })}+ onClick={guard(() => setConfirmClear(true), {+ action: tActions('dismissSuggestions'),+ })}disabled={clearing || adding || visible.length === 0}size="sm"variant="outline"@@ -634,6 +651,27 @@ export function SuggestionsCard({)}</div></CardHeader>+ <Dialog open={confirmClear} onOpenChange={setConfirmClear}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('clearAllConfirm.title')}</DialogTitle>+ <DialogDescription>+ {t('clearAllConfirm.body', { count: visible.length })}+ </DialogDescription>+ </DialogHeader>+ {measuredToClear > 0 && (+ <p className="text-sm text-muted-foreground">+ {t('clearAllConfirm.measured', { count: measuredToClear })}+ </p>+ )}+ <DialogFooter>+ <Button variant="outline" onClick={() => setConfirmClear(false)}>+ {t('clearAllConfirm.cancel')}+ </Button>+ <Button onClick={() => void handleClearAll()}>{t('clearAllConfirm.confirm')}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog><CardContent>{limitNote && (<divdiff --git a/web/src/lib/actions/prompt-suggestions.test.ts b/web/src/lib/actions/prompt-suggestions.test.tsindex 2456d16fe..762f75b40 100644--- a/web/src/lib/actions/prompt-suggestions.test.ts+++ b/web/src/lib/actions/prompt-suggestions.test.ts@@ -97,7 +97,7 @@ vi.mock('@/lib/actions/prompt-workflow', () => ({const fetchMock = vi.fn(async () => new Response('{}', { status: 200 }));vi.stubGlobal('fetch', fetchMock);-const { getPromptSuggestions, trackPagePrompts, trackSuggestions } =+const { dismissSuggestions, getPromptSuggestions, trackPagePrompts, trackSuggestions } =await import('./prompt-suggestions');beforeEach(() => {@@ -278,3 +278,33 @@ describe('getPromptSuggestions', () => {});});});++describe('dismissSuggestions', () => {+ it('dismisses each one through the route one by one uses, a few at a time', async () => {+ const ids = Array.from({ length: 12 }, (_, i) => `s${i + 1}`);+ expect(await dismissSuggestions([...ids, 's1'])).toEqual({+ ok: true,+ dismissed: ids,+ failed: [],+ });+ expect(fetchMock).toHaveBeenCalledTimes(12);+ expect(fetchMock).toHaveBeenCalledWith(+ 'http://server/api/prompts/suggestions/s1/dismiss',+ expect.objectContaining({ method: 'POST', headers: { Authorization: 'Bearer t' } }),+ );+ });++ it('lists the ones that could not be dismissed, and never throws', async () => {+ fetchMock.mockImplementation((async (url: string) => {+ if (url.includes('/s2/')) return new Response('{}', { status: 403 });+ if (url.includes('/s3/')) throw new Error('network down');+ return new Response('{}', { status: 200 });+ }) as never);+ expect(await dismissSuggestions(['s1', 's2', 's3'])).toEqual({+ ok: true,+ dismissed: ['s1'],+ failed: ['s2', 's3'],+ });+ fetchMock.mockImplementation(async () => new Response('{}', { status: 200 }));+ });+});diff --git a/web/src/lib/actions/prompt-suggestions.ts b/web/src/lib/actions/prompt-suggestions.tsindex aaa3a91eb..8ab0fa62b 100644--- a/web/src/lib/actions/prompt-suggestions.ts+++ b/web/src/lib/actions/prompt-suggestions.ts@@ -139,6 +139,48 @@ export async function dismissSuggestion(suggestionId: string): Promise<{ successreturn res.json();}+/** Suggestions one dismiss round sends at once. */+const DISMISS_BATCH = 10;++export type DismissSuggestionsResult =+ | { ok: true; dismissed: string[]; failed: string[] }+ | { ok: false; failure: 'failed' };++/**+ * Dismisses several suggestions, each through the same route as one by one+ * (so a Search Console or Analytics one stays hidden for 30 days, as when+ * dismissed alone), a few at a time. Never throws (#1777): what couldn't be+ * dismissed is listed, and a call that couldn't start is `failed`.+ */+export async function dismissSuggestions(+ suggestionIds: string[],+): Promise<DismissSuggestionsResult> {+ try {+ const session = await getSession();+ const ids = [...new Set(suggestionIds.filter((id) => typeof id === 'string' && id))];+ const dismissed: string[] = [];+ const failed: string[] = [];+ for (let i = 0; i < ids.length; i += DISMISS_BATCH) {+ await Promise.all(+ ids.slice(i, i + DISMISS_BATCH).map(async (id) => {+ try {+ const res = await fetch(+ `${AEO_SERVER_URL}/api/prompts/suggestions/${encodeURIComponent(id)}/dismiss`,+ { method: 'POST', headers: { Authorization: `Bearer ${session.access_token}` } },+ );+ (res.ok ? dismissed : failed).push(id);+ } catch {+ failed.push(id);+ }+ }),+ );+ }+ return { ok: true, dismissed, failed };+ } catch {+ return { ok: false, failure: 'failed' };+ }+}+export type AcceptSuggestionResult = { promptId: string } | { error: string; code?: 'plan_limit' };type ServerClient = Awaited<ReturnType<typeof createClient>>;