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): surface savePromptSet failures instead of the masked digest error (#536)
Gökhan Geyik16385e5debf2
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsxindex f4e566c5d..672c9a24e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx@@ -236,7 +236,7 @@ export default function PromptsPage() {let targetSetId = promptSets[0]?.id;if (!targetSetId) {- const newSet = await savePromptSet({+ const result = await savePromptSet({brandId,name: 'Prompts',prompts: activePrompts.map((p) => ({@@ -246,7 +246,11 @@ export default function PromptsPage() {models: defaultModels,})),});- targetSetId = newSet.id;+ if ('error' in result) {+ toast.error(result.error);+ return;+ }+ targetSetId = result.promptSet.id;} else {await Promise.all(activePrompts.map((p) =>@@ -291,11 +295,15 @@ export default function PromptsPage() {...promptData,});} else {- await savePromptSet({+ const result = await savePromptSet({brandId,name: `Prompts`,prompts: [promptData],});+ if ('error' in result) {+ toast.error(result.error);+ return;+ }}setManualText('');diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsxindex 99188001c..c0416a5ef 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx@@ -6,7 +6,7 @@ import { createClient } from '@/lib/supabase/client';import { createBrand, updateBrand } from '@/lib/actions/brand';import { syncDomains } from '@/lib/actions/brand-domain';import { createTopics } from '@/lib/actions/topic';-import { savePromptSet } from '@/lib/actions/prompt';+import { getPromptCapacity, savePromptSet } from '@/lib/actions/prompt';import { addCompetitor } from '@/lib/actions/competitor';import { triggerTrackingCheck } from '@/lib/actions/tracking';import { usePlanContext } from '@/components/providers/plan-provider';@@ -262,6 +262,11 @@ export default function NewBrandPage() {// Step 4const [topicPrompts, setTopicPrompts] = useState<TopicPromptsData[]>([]);const [loadingPrompts, setLoadingPrompts] = useState(false);+ const [promptCapacity, setPromptCapacity] = useState<{+ maxPrompts: number;+ used: number;+ } | null>(null);+ const [saveError, setSaveError] = useState<string | null>(null);// Step 5interface CompetitorItem {@@ -315,6 +320,17 @@ export default function NewBrandPage() {// eslint-disable-next-line react-hooks/exhaustive-deps}, [step]);+ // Know the plan's prompt cap while reviewing, so the step can warn and+ // disable Continue instead of failing the save afterwards.+ useEffect(() => {+ if (step === 4 && createdBrand && !promptCapacity) {+ getPromptCapacity(createdBrand.id)+ .then(setPromptCapacity)+ .catch(() => {});+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [step, createdBrand]);+// Load current plan from org on mountuseEffect(() => {async function loadPlan() {@@ -545,6 +561,7 @@ export default function NewBrandPage() {const handleSavePromptsAndContinue = async () => {if (!createdBrand) return;setIsLoading(true);+ setSaveError(null);try {const allPrompts = topicPrompts.flatMap((tp) =>tp.prompts.map((text) => ({@@ -557,21 +574,31 @@ export default function NewBrandPage() {);if (allPrompts.length === 0) {- toast.error('Add at least one prompt before continuing');+ setSaveError('Add at least one prompt before continuing.');setIsLoading(false);return;}- await savePromptSet({+ const result = await savePromptSet({brandId: createdBrand.id,name: 'Brand Setup Prompts',prompts: allPrompts,});+ if ('error' in result) {+ // No technical toasts on this step: actionable failures (plan limit)+ // show verbatim inline, anything else gets a friendly retry message.+ setSaveError(+ result.code === 'plan_limit'+ ? result.error+ : "We couldn't save your prompts — please try again.",+ );+ return;+ }setStep(5);fetchCompetitorSuggestions();- } catch (err) {- toast.error(err instanceof Error ? err.message : 'Failed to save prompts');+ } catch {+ setSaveError("We couldn't save your prompts — please try again.");} finally {setIsLoading(false);}@@ -700,6 +727,13 @@ export default function NewBrandPage() {};const totalPrompts = topicPrompts.reduce((sum, tp) => sum + tp.prompts.length, 0);+ // Prompts this brand may save before hitting the org's plan cap (null =+ // unknown or unlimited); over that, Continue is disabled with an inline hint.+ const promptLimit =+ promptCapacity && promptCapacity.maxPrompts !== -1+ ? Math.max(0, promptCapacity.maxPrompts - promptCapacity.used)+ : null;+ const excessPrompts = promptLimit !== null ? Math.max(0, totalPrompts - promptLimit) : 0;// ── Step 1: Brand Info ──@@ -1035,7 +1069,7 @@ export default function NewBrandPage() {</div><ButtononClick={handleSavePromptsAndContinue}- disabled={isLoading || totalPrompts === 0}+ disabled={isLoading || totalPrompts === 0 || excessPrompts > 0}>{isLoading ? (<>@@ -1048,6 +1082,19 @@ export default function NewBrandPage() {</Button></div>+ {excessPrompts > 0 && (+ <div className="mb-4 rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm">+ Your plan includes up to {promptLimit} prompts for this brand — remove {excessPrompts}{' '}+ to continue.+ </div>+ )}++ {saveError && excessPrompts === 0 && (+ <div className="mb-4 rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm">+ {saveError}+ </div>+ )}+<div className="mb-4"><p className="text-sm font-medium">Your Prompt List</p><p className="text-xs text-muted-foreground">{totalPrompts} prompts total</p>diff --git a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsxindex 52a5ad218..13364f7db 100644--- a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx+++ b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx@@ -5,7 +5,7 @@ import { useRouter } from '@/i18n/navigation';import { createClient } from '@/lib/supabase/client';import { createBrand } from '@/lib/actions/brand';import { createTopics, getTopics } from '@/lib/actions/topic';-import { savePromptSet } from '@/lib/actions/prompt';+import { getPromptCapacity, savePromptSet } from '@/lib/actions/prompt';import { triggerTrackingCheck } from '@/lib/actions/tracking';import { addCompetitor, getCompetitors } from '@/lib/actions/competitor';import { getFaviconUrl } from '@/lib/favicon';@@ -273,6 +273,11 @@ export default function OnboardingPage() {const [topicPrompts, setTopicPrompts] = useState<TopicPromptsData[]>([]);const [loadingPrompts, setLoadingPrompts] = useState(false);const [promptGenError, setPromptGenError] = useState(false);+ const [promptCapacity, setPromptCapacity] = useState<{+ maxPrompts: number;+ used: number;+ } | null>(null);+ const [saveError, setSaveError] = useState<string | null>(null);// Step 5interface CompetitorItem {@@ -338,6 +343,17 @@ export default function OnboardingPage() {// eslint-disable-next-line react-hooks/exhaustive-deps}, [step, initialLoading]);+ // Know the plan's prompt cap while reviewing, so the step can warn and+ // disable Continue instead of failing the save afterwards.+ useEffect(() => {+ if (step === 4 && createdBrand && !promptCapacity) {+ getPromptCapacity(createdBrand.id)+ .then(setPromptCapacity)+ .catch(() => {});+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [step, createdBrand]);+// Resume logic: check existing state on mountuseEffect(() => {async function checkResume() {@@ -704,6 +720,7 @@ export default function OnboardingPage() {const handleSavePromptsAndContinue = async () => {if (!createdBrand) return;setIsLoading(true);+ setSaveError(null);try {const allPrompts = topicPrompts.flatMap((tp) =>tp.prompts.map((text) => ({@@ -716,16 +733,26 @@ export default function OnboardingPage() {);if (allPrompts.length === 0) {- toast.error('Add at least one prompt before continuing');+ setSaveError('Add at least one prompt before continuing.');setIsLoading(false);return;}- await savePromptSet({+ const result = await savePromptSet({brandId: createdBrand.id,name: 'Onboarding Prompts',prompts: allPrompts,});+ if ('error' in result) {+ // No technical toasts on this step: actionable failures (plan limit)+ // show verbatim inline, anything else gets a friendly retry message.+ setSaveError(+ result.code === 'plan_limit'+ ? result.error+ : "We couldn't save your prompts — please try again.",+ );+ return;+ }track('onboarding_prompts_saved', { count: allPrompts.length });track('onboarding_step_completed', {step: 4,@@ -736,8 +763,8 @@ export default function OnboardingPage() {setStep(5);fetchCompetitorSuggestions();- } catch (err) {- toast.error(err instanceof Error ? err.message : 'Failed to save prompts');+ } catch {+ setSaveError("We couldn't save your prompts — please try again.");} finally {setIsLoading(false);}@@ -934,6 +961,13 @@ export default function OnboardingPage() {};const totalPrompts = topicPrompts.reduce((sum, tp) => sum + tp.prompts.length, 0);+ // Prompts this brand may save before hitting the org's plan cap (null =+ // unknown or unlimited); over that, Continue is disabled with an inline hint.+ const promptLimit =+ promptCapacity && promptCapacity.maxPrompts !== -1+ ? Math.max(0, promptCapacity.maxPrompts - promptCapacity.used)+ : null;+ const excessPrompts = promptLimit !== null ? Math.max(0, totalPrompts - promptLimit) : 0;// ── Loading state ──@@ -1291,7 +1325,7 @@ export default function OnboardingPage() {</div><ButtononClick={handleSavePromptsAndContinue}- disabled={isLoading || totalPrompts === 0}+ disabled={isLoading || totalPrompts === 0 || excessPrompts > 0}>{isLoading ? (<>@@ -1311,6 +1345,18 @@ export default function OnboardingPage() {</div>)}+ {excessPrompts > 0 && (+ <div className="mb-4 rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm">+ Your plan includes up to {promptLimit} prompts — remove {excessPrompts} to continue.+ </div>+ )}++ {saveError && excessPrompts === 0 && (+ <div className="mb-4 rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm">+ {saveError}+ </div>+ )}+<div className="mb-4"><p className="text-sm font-medium">Your Prompt List</p><p className="text-xs text-muted-foreground">{totalPrompts} prompts total</p>diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.tsindex a94cf0960..80113d1c3 100644--- a/web/src/lib/actions/prompt.ts+++ b/web/src/lib/actions/prompt.ts@@ -151,7 +151,39 @@ interface SavePromptSetInput {}[];}-export async function savePromptSet(input: SavePromptSetInput): Promise<PromptSet> {+export type SavePromptSetResult = { promptSet: PromptSet } | { error: string; code?: 'plan_limit' };++/**+ * How many prompts a brand's save may total before hitting the org's plan cap.+ * `used` counts prompts on the org's OTHER brands only — savePromptSet+ * replaces this brand's own set, so its current prompts don't count against a+ * re-save. Lets the setup wizards gate the review step inline (counter ++ * disabled Continue) instead of failing the save after the fact.+ */+export async function getPromptCapacity(+ brandId: string,+): Promise<{ maxPrompts: number; used: number }> {+ const supabase = await createClient();+ const { organizationId: orgId } = await getBrandContext(supabase, brandId);+ const plan = await getOrgPlan(orgId);+ const totalOrgPrompts = await getOrgPromptCount(supabase, orgId);+ const { count: brandPromptCount } = await supabase+ .from('prompts')+ .select('id, prompt_sets!inner(brand_id)', { count: 'exact', head: true })+ .eq('prompt_sets.brand_id', brandId);+ return {+ maxPrompts: plan.limits.maxPrompts,+ used: totalOrgPrompts - (brandPromptCount ?? 0),+ };+}++/**+ * User-facing failures (plan limit, empty platform selection, DB errors) come+ * back as a VALUE: production masks every error thrown from a server action,+ * so a thrown PlanLimitError would reach users as the meaningless digest+ * message (#427).+ */+export async function savePromptSet(input: SavePromptSetInput): Promise<SavePromptSetResult> {const supabase = await createClient();const { organizationId: orgId, region: brandRegion } = await getBrandContext(@@ -170,7 +202,19 @@ export async function savePromptSet(input: SavePromptSetInput): Promise<PromptSe.eq('prompt_sets.brand_id', input.brandId);const otherPrompts = totalOrgPrompts - (brandPromptCount ?? 0);- await enforceLimit(orgId, 'maxPrompts', otherPrompts + input.prompts.length - 1);++ // Inclusive cap: saving exactly maxPrompts is allowed; only reject when the+ // resulting total would exceed it. Spell out the counts so the user knows+ // exactly how many prompts to remove (onboarding generates 5 per topic, so+ // hitting the cap there is a normal, recoverable state).+ const maxPrompts = plan.limits.maxPrompts;+ const requestedTotal = otherPrompts + input.prompts.length;+ if (maxPrompts !== -1 && requestedTotal > maxPrompts) {+ return {+ code: 'plan_limit',+ error: `Your ${plan.name} plan allows up to ${maxPrompts} tracked prompts and this would save ${requestedTotal}. Remove ${requestedTotal - maxPrompts} prompt${requestedTotal - maxPrompts === 1 ? '' : 's'} to continue, or upgrade your plan.`,+ };+ }// Delete existing prompt sets for this brand to avoid duplicates// (e.g. user navigated back during onboarding and re-submitted)@@ -196,7 +240,7 @@ export async function savePromptSet(input: SavePromptSetInput): Promise<PromptSe.single();if (setError || !set) {- throw new Error(setError?.message ?? 'Failed to create prompt set');+ return { error: setError?.message ?? 'Failed to create prompt set' };}// Insert prompts@@ -221,36 +265,37 @@ export async function savePromptSet(input: SavePromptSetInput): Promise<PromptSe}),);+ const rows = [];+ for (const p of input.prompts) {+ const filtered = filterByPlan(plan, p.platforms, p.models ?? []);+ const platforms = stripShoppingWhenDisabled(filtered.platforms, shoppingEnabled);+ if (platforms.length === 0 && filtered.models.length === 0) {+ return { error: 'At least one platform or model must be selected for each prompt.' };+ }+ rows.push({+ prompt_set_id: set.id,+ text: p.text,+ category: p.category || null,+ topic_id: (p.category && topicIdMap.get(p.category)) || null,+ platforms,+ regions: [brandRegion],+ models: filtered.models,+ is_active: p.isActive ?? true,+ });+ }+const { data: prompts, error: promptError } = await supabase.from('prompts')- .insert(- input.prompts.map((p) => {- const filtered = filterByPlan(plan, p.platforms, p.models ?? []);- const platforms = stripShoppingWhenDisabled(filtered.platforms, shoppingEnabled);- if (platforms.length === 0 && filtered.models.length === 0) {- throw new Error('At least one platform or model must be selected for each prompt.');- }- return {- prompt_set_id: set.id,- text: p.text,- category: p.category || null,- topic_id: (p.category && topicIdMap.get(p.category)) || null,- platforms,- regions: [brandRegion],- models: filtered.models,- is_active: p.isActive ?? true,- };- }),- )+ .insert(rows).select();- if (promptError) throw new Error(promptError.message);+ if (promptError) return { error: promptError.message };insertedPrompts = (prompts as Record<string, unknown>[]) ?? [];}revalidatePath('/dashboard/brands');- return mapPromptSetRow(set as Record<string, unknown>, insertedPrompts);+ return { promptSet: mapPromptSetRow(set as Record<string, unknown>, insertedPrompts) };}export async function updatePrompt(