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(content): say why creating content failed, never a bare "Unauthorized" (#1355)

Cihan3e08669fee0b
diff --git a/server/src/lib/access.js b/server/src/lib/access.js
index af7a3188b..66d7e67ac 100644
--- a/server/src/lib/access.js
+++ b/server/src/lib/access.js
@@ -20,12 +20,20 @@
import supabaseAdmin from '../config/supabase.js';
import { getOrgIdForUser } from './plan-guard.js';
-function accessError(message, status) {
+function accessError(message, status, code) {
const err = new Error(message);
err.status = status;
+ if (code) err.code = code;
return err;
}
+/**
+ * A resource of another organization: said in plain words, as a toast or an
+ * MCP client shows it. 403, never 401, which means a bad or expired session.
+ */
+export const NOT_IN_WORKSPACE = "This brand isn't in your workspace";
+const notInWorkspace = () => accessError(NOT_IN_WORKSPACE, 403, 'not_in_workspace');
+
/**
* Assert that `brandId` belongs to the caller's organization.
* @returns {Promise<{ brand: object, orgId: string|null }>}
@@ -43,7 +51,7 @@ export async function assertBrandAccess(brandId, userId) {
const orgId = await getOrgIdForUser(userId);
if (orgId !== brand.organization_id) {
- throw accessError('Unauthorized', 403);
+ throw notInWorkspace();
}
return { brand, orgId };
@@ -76,7 +84,7 @@ export async function assertOpportunitiesAccess(ids, userId) {
const orgByBrand = new Map((brands || []).map((b) => [b.id, b.organization_id]));
const allOwned = opps.every((o) => orgByBrand.get(o.brand_id) === userOrg);
if (!allOwned) {
- throw accessError('Unauthorized', 403);
+ throw notInWorkspace();
}
return opps;
@@ -122,7 +130,7 @@ export async function assertPromptAccess(promptIds, userId) {
const allOwned = rows.every((r) => r.prompt_sets?.brands?.organization_id === userOrg);
if (!allOwned) {
- throw accessError('Unauthorized', 403);
+ throw notInWorkspace();
}
return rows;
diff --git a/server/src/lib/access.test.js b/server/src/lib/access.test.js
new file mode 100644
index 000000000..dafacb659
--- /dev/null
+++ b/server/src/lib/access.test.js
@@ -0,0 +1,46 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// The brand and the caller's organization, as the database answers them.
+const state = vi.hoisted(() => ({ brand: null, orgId: null }));
+
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ from: () => {
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ single: async () => ({ data: state.brand, error: null }),
+ };
+ return chain;
+ },
+ },
+}));
+vi.mock('./plan-guard.js', () => ({ getOrgIdForUser: async () => state.orgId }));
+
+const { assertBrandAccess, NOT_IN_WORKSPACE } = await import('./access.js');
+
+beforeEach(() => {
+ state.brand = { id: 'b1', organization_id: 'org-1' };
+ state.orgId = 'org-1';
+});
+
+describe('assertBrandAccess', () => {
+ it('lets a brand of the caller’s organization through', async () => {
+ await expect(assertBrandAccess('b1', 'u1')).resolves.toMatchObject({ orgId: 'org-1' });
+ });
+
+ // BUG-001: a bare "Unauthorized" read as a session problem, with no reason.
+ it('says in plain words that another organization’s brand isn’t in the workspace, as a 403', async () => {
+ state.orgId = 'org-2';
+ await expect(assertBrandAccess('b1', 'u1')).rejects.toMatchObject({
+ message: NOT_IN_WORKSPACE,
+ status: 403,
+ code: 'not_in_workspace',
+ });
+ });
+
+ it('says a brand that is gone is not found', async () => {
+ state.brand = null;
+ await expect(assertBrandAccess('b1', 'u1')).rejects.toMatchObject({ status: 404 });
+ });
+});
diff --git a/server/src/routes/content.js b/server/src/routes/content.js
index 415d8d4d6..9ee28ff6d 100644
--- a/server/src/routes/content.js
+++ b/server/src/routes/content.js
@@ -21,6 +21,7 @@ import {
assertOpportunitiesAccess,
assertOpportunityAccess,
assertPromptAccess,
+ NOT_IN_WORKSPACE,
} from '../lib/access.js';
import { loadClusters } from '../lib/prompt-clusters.js';
import { sendToActionCenter } from '../lib/action-center/from-opportunity.js';
@@ -134,7 +135,7 @@ router.post('/generate', requireFeature('content_optimization'), async (req, res
.single();
if (!profile || profile.organization_id !== brand.organization_id) {
- return res.status(403).json({ error: 'Unauthorized' });
+ return res.status(403).json({ error: NOT_IN_WORKSPACE, code: 'not_in_workspace' });
}
const job = await createJob({
@@ -231,7 +232,9 @@ router.post('/opportunities/generate', requireFeature('content_optimization'), a
message: error.message,
});
}
- if (error.status) return res.status(error.status).json({ error: error.message });
+ if (error.status) {
+ return res.status(error.status).json({ error: error.message, code: error.code });
+ }
req.log.error({ err: error }, 'on-demand opportunity generation error');
return res.status(500).json({ error: 'Failed to start generation' });
}
@@ -315,7 +318,9 @@ router.post('/:id/alternative', requireFeature('content_optimization'), async (r
message: error.message,
});
}
- if (error.status) return res.status(error.status).json({ error: error.message });
+ if (error.status) {
+ return res.status(error.status).json({ error: error.message, code: error.code });
+ }
req.log.error({ err: error }, 'alternative opportunity error');
return res.status(500).json({ error: 'Failed to start generation' });
}
@@ -337,7 +342,9 @@ router.get(
const existingId = await openOpportunityForPrompt(prompt.prompt_sets.brand_id, promptId);
return res.json({ existingId });
} catch (error) {
- if (error.status) return res.status(error.status).json({ error: error.message });
+ if (error.status) {
+ return res.status(error.status).json({ error: error.message, code: error.code });
+ }
req.log.error({ err: error }, 'prompt content suggestion lookup error');
return res.status(500).json({ error: 'Failed to look up the suggestion' });
}
@@ -404,7 +411,9 @@ router.post(
message: error.message,
});
}
- if (error.status) return res.status(error.status).json({ error: error.message });
+ if (error.status) {
+ return res.status(error.status).json({ error: error.message, code: error.code });
+ }
req.log.error({ err: error }, 'prompt content suggestion error');
return res.status(500).json({ error: 'Failed to start generation' });
}
@@ -1530,7 +1539,7 @@ router.post('/:id/brief', async (req, res) => {
const userOrgId = await getOrgIdForUser(req.user.id);
if (!brand || !userOrgId || userOrgId !== brand.organization_id) {
- return res.status(403).json({ error: 'Unauthorized' });
+ return res.status(403).json({ error: NOT_IN_WORKSPACE, code: 'not_in_workspace' });
}
const result = await generateBriefForOpportunity(id, { model });
diff --git a/web/messages/en.json b/web/messages/en.json
index 94eb54262..97aabb439 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -1,4 +1,17 @@
{
+ "apiFailure": {
+ "session": "Your session expired. Sign in again.",
+ "workspace": "This brand isn't in your workspace. Switch to one of your brands.",
+ "not_found": "This no longer exists. Reload the page and start again.",
+ "plan": "Your plan doesn't include this. Upgrade to use it.",
+ "limit": "You've used this month's allowance. Upgrade, or wait until it resets.",
+ "busy": "Too many requests. Wait a minute and try again.",
+ "failed": "Something went wrong. Try again.",
+ "signIn": "Sign in",
+ "yourBrands": "Your brands",
+ "reload": "Reload",
+ "upgrade": "Upgrade"
+ },
"common": {
"loading": "Loading...",
"error": "Something went wrong.",
@@ -4337,7 +4350,7 @@
"dismissAllConfirm": "{count, plural, one {This will dismiss # opportunity.} other {This will dismiss # opportunities.}} This can't be undone.",
"deleteAll": "Delete",
"deleteAllTitle": "Delete opportunities?",
- "deleteAllConfirm": "{count, plural, one {This permanently deletes # opportunity.} other {This permanently deletes # opportunities.}} Dismissing instead keeps them out of your way without removing them.",
+ "deleteAllConfirm": "{count, plural, one {This permanently deletes # opportunity.} other {This permanently deletes # opportunities.}} It doesn't give back this month's opportunity allowance. Dismissing instead keeps them out of your way without removing them.",
"deleteAllBriefWarning": "{count, plural, one {# of them has a generated brief, which is deleted too and does not return your monthly brief allowance.} other {# of them have generated briefs, which are deleted too and do not return your monthly brief allowance.}}",
"deletedToast": "{count, plural, one {Deleted # opportunity} other {Deleted # opportunities}}"
},
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
index f97a0dbd5..52cfb02e2 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx
@@ -2,6 +2,7 @@
import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { useLocale, useTranslations } from 'next-intl';
+import { useFailureToast } from '@/hooks/use-failure-toast';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
@@ -340,6 +341,7 @@ interface PromptFilterItem {
export default function ContentPage() {
const t = useTranslations('content');
+ const failureToast = useFailureToast();
const assetTypeLabel = useAssetTypeLabel();
const tCommon = useTranslations('common');
const locale = useLocale();
@@ -824,11 +826,14 @@ export default function ContentPage() {
}).catch((err: unknown) => ({
ok: false as const,
error: err instanceof Error ? err.message : t('generateError'),
+ failure: 'failed' as const,
quotaExhausted: false,
periodEnd: null,
}));
if (!result.ok) {
- toast.error(result.quotaExhausted ? t('newLimitReached') : result.error);
+ // The reason in plain words, never the server's bare string (BUG-001).
+ if (result.quotaExhausted) toast.error(t('newLimitReached'));
+ else failureToast(result.failure);
setUsageVersion((v) => v + 1);
return false;
}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx
index b53cc7e4e..149fc1ed7 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx
@@ -2,6 +2,7 @@
import { useMemo, useState } from 'react';
import { useFormatter, useLocale, useTranslations } from 'next-intl';
+import { useFailureToast } from '@/hooks/use-failure-toast';
import { ArrowRight, Loader2, MessageCircle, Tag } from 'lucide-react';
import { toast } from 'sonner';
import { Link, useRouter } from '@/i18n/navigation';
@@ -67,6 +68,7 @@ export function Opportunities({
className?: string;
}) {
const t = useTranslations('insights.opportunities');
+ const failureToast = useFailureToast();
const format = useFormatter();
const f = numberFormat(useLocale());
const router = useRouter();
@@ -156,10 +158,8 @@ export function Opportunities({
idempotencyKey: crypto.randomUUID(),
});
if (!started.ok) {
- toast.error(started.quotaExhausted ? t('contentLimit') : started.error, {
- id: toastId,
- description,
- });
+ if (started.quotaExhausted) toast.error(t('contentLimit'), { id: toastId, description });
+ else failureToast(started.failure, { id: toastId, description });
return;
}
const outcome = await waitForContentJob(started.jobId, {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx
index 7ef437db1..7e5ac5840 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx
@@ -332,6 +332,40 @@ describe('MentionsListTab', () => {
);
});
+ it('says why a content suggestion failed, in plain words', async () => {
+ listMentions.mockResolvedValue(list());
+ getMentionResponse.mockResolvedValue({ response: 'Acme Coffee.', citations: [] });
+ suggestContentForPrompt.mockResolvedValue({
+ ok: false,
+ error: 'Unauthorized',
+ failure: 'workspace',
+ });
+ render(tab());
+ await settle();
+ await act(async () => {
+ (container.querySelector('tbody tr[tabindex]') as HTMLElement).click();
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ const drawer = document.body.querySelector('[role="dialog"]') as HTMLElement;
+ await act(async () => {
+ (
+ [...drawer.querySelectorAll('button')].find(
+ (b) => b.textContent === 'Suggest content',
+ ) as HTMLElement
+ ).click();
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ // Not the raw "Unauthorized": the reason, and what to do about it.
+ expect(toast.error).toHaveBeenCalledWith(
+ "This brand isn't in your workspace. Switch to one of your brands.",
+ expect.objectContaining({
+ id: 'toast-1',
+ description: 'Best espresso beans?',
+ action: expect.objectContaining({ label: 'Your brands' }),
+ }),
+ );
+ });
+
it("shows an answer's last correction, and lets a manager correct it", async () => {
listMentions.mockResolvedValue(list());
getMentionResponse.mockResolvedValue({
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_use-mention-actions.ts b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_use-mention-actions.ts
index 3fca58408..2976c9c29 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_use-mention-actions.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_use-mention-actions.ts
@@ -3,6 +3,7 @@
import { useCallback, useState } from 'react';
import { useTranslations } from 'next-intl';
import { toast } from 'sonner';
+import { useFailureToast } from '@/hooks/use-failure-toast';
import { useRouter } from '@/i18n/navigation';
import { getGenerationJobStatus, suggestContentForPrompt } from '@/lib/actions/content';
import { sendMentionsToActionCenter } from '@/lib/actions/mentions';
@@ -21,6 +22,7 @@ const SUGGEST_CALLS = { start: suggestContentForPrompt, getStatus: getGeneration
export function useMentionActions(brandId: string) {
const t = useTranslations('mentions.actions');
const router = useRouter();
+ const failureToast = useFailureToast();
const [sending, setSending] = useState(false);
const [suggesting, setSuggesting] = useState<string | null>(null);
@@ -103,6 +105,11 @@ export function useMentionActions(brandId: string) {
});
break;
case 'failed':
+ // A reason the API gave, in plain words (BUG-001); else what went wrong.
+ if (outcome.failure && outcome.failure !== 'failed') {
+ failureToast(outcome.failure, { id: toastId, description: row.promptText });
+ break;
+ }
toast.error(t('suggestFailed'), {
id: toastId,
description: outcome.message ?? undefined,
@@ -116,7 +123,7 @@ export function useMentionActions(brandId: string) {
break;
}
},
- [router, t],
+ [failureToast, router, t],
);
return { send, sending, suggest, suggesting };
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index bba693083..85aa9af10 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -3,6 +3,7 @@
import { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import { createPortal } from 'react-dom';
import { useFormatter, useNow, useTranslations } from 'next-intl';
+import { useFailureToast } from '@/hooks/use-failure-toast';
import { useSearchParams } from 'next/navigation';
import { Link, usePathname, useRouter } from '@/i18n/navigation';
import { PROMPTS_BASE, sectionFor, sectionFromPath } from '@/lib/prompts-routes';
@@ -2825,6 +2826,7 @@ function AllPromptsTab({
onChanged: () => void;
}) {
const tCommon = useTranslations('common');
+ const failureToast = useFailureToast();
const tPrompts = useTranslations('prompts');
// One tooltip for every prompt and topic the table cuts short.
const fullText = useMemo(() => createClampedTextHandle(), []);
@@ -3133,6 +3135,11 @@ function AllPromptsTab({
});
break;
case 'failed':
+ // A reason the API gave, in plain words (BUG-001); else what went wrong.
+ if (outcome.failure && outcome.failure !== 'failed') {
+ failureToast(outcome.failure, { id: toastId, description: prompt.text });
+ break;
+ }
toast.error("Couldn't write a content suggestion", {
id: toastId,
description: [outcome.message, quotaUntouched].filter(Boolean).join(' ') || undefined,
@@ -3146,7 +3153,7 @@ function AllPromptsTab({
break;
}
},
- [hasOpportunityLimit, markSuggesting, openOpportunity],
+ [failureToast, hasOpportunityLimit, markSuggesting, openOpportunity],
);
// Bulk "Suggest content": one prompt after another (runInTurn), so a
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.ts b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.ts
index 7c71f0079..600700a2e 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_use-page-actions.ts
@@ -2,6 +2,7 @@
import { useCallback, useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
+import { useFailureToast } from '@/hooks/use-failure-toast';
import { toast } from 'sonner';
import { useRouter } from '@/i18n/navigation';
import { getAuditQuota, runAuditsBulk, type AuditQuota } from '@/lib/actions/audits';
@@ -28,6 +29,7 @@ const SUGGEST_CALLS = { start: generateOpportunitiesOnDemand, getStatus: getGene
*/
export function usePageActions(brandId: string, dateWindow: TrafficDateWindow) {
const t = useTranslations('traffic.pageList.actions');
+ const failureToast = useFailureToast();
const router = useRouter();
const [sending, setSending] = useState(false);
const [auditing, setAuditing] = useState(false);
@@ -168,6 +170,11 @@ export function usePageActions(brandId: string, dateWindow: TrafficDateWindow) {
});
break;
default:
+ // A reason the API gave, in plain words (BUG-001); else what went wrong.
+ if (outcome.failure && outcome.failure !== 'failed') {
+ failureToast(outcome.failure, { id: toastId });
+ break;
+ }
toast.error(t('suggestFailed'), {
id: toastId,
description: outcome.message ?? undefined,
@@ -177,7 +184,7 @@ export function usePageActions(brandId: string, dateWindow: TrafficDateWindow) {
setSuggesting(null);
}
},
- [brandId, router, t],
+ [brandId, failureToast, router, t],
);
return { send, sending, auditMany, auditing, quota, suggestContent, suggesting };
diff --git a/web/src/components/content/opportunity-detail.tsx b/web/src/components/content/opportunity-detail.tsx
index 3eca28083..3f0d10d1e 100644
--- a/web/src/components/content/opportunity-detail.tsx
+++ b/web/src/components/content/opportunity-detail.tsx
@@ -2,6 +2,7 @@
import { useState, useEffect } from 'react';
import { useLocale, useTranslations } from 'next-intl';
+import { useFailureToast } from '@/hooks/use-failure-toast';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
@@ -149,6 +150,7 @@ export function OpportunityDetail({
onPrioritized?: (id: string) => void;
}) {
const t = useTranslations('content');
+ const failureToast = useFailureToast();
const assetTypeLabel = useAssetTypeLabel();
const locale = useLocale();
@@ -318,11 +320,15 @@ export function OpportunityDetail({
}).catch((err: unknown) => ({
ok: false as const,
error: err instanceof Error ? err.message : t('alternative.failed'),
+ failure: 'failed' as const,
quotaExhausted: false,
noCluster: false,
}));
if (!result.ok) {
- toast.error(result.quotaExhausted ? t('newLimitReached') : result.error);
+ // No cluster says what to do itself; anything else in plain words (BUG-001).
+ if (result.quotaExhausted) toast.error(t('newLimitReached'));
+ else if (result.noCluster) toast.error(result.error);
+ else failureToast(result.failure);
return false;
}
toast(t('alternative.started'));
diff --git a/web/src/hooks/use-failure-toast.test.tsx b/web/src/hooks/use-failure-toast.test.tsx
new file mode 100644
index 000000000..3569c5053
--- /dev/null
+++ b/web/src/hooks/use-failure-toast.test.tsx
@@ -0,0 +1,65 @@
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { describe, expect, it, vi } from 'vitest';
+import messages from '../../messages/en.json';
+import type { ApiFailure } from '@/lib/api-failure';
+import { useFailureToast } from './use-failure-toast';
+
+const toast = vi.hoisted(() => ({ error: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
+const push = vi.fn();
+vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push }) }));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+/** Shows the failure's toast once, and returns what toast.error got. */
+function show(failure: ApiFailure, options?: { id?: string; description?: string }) {
+ toast.error.mockReset();
+ push.mockReset();
+ function Probe() {
+ const failureToast = useFailureToast();
+ failureToast(failure, options);
+ return null;
+ }
+ const root = createRoot(document.createElement('div'));
+ act(() =>
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <Probe />
+ </NextIntlClientProvider>,
+ ),
+ );
+ act(() => root.unmount());
+ return toast.error.mock.calls[0] as [string, { action?: { label: string; onClick: () => void } }];
+}
+
+describe('useFailureToast (BUG-001)', () => {
+ it('says another workspace’s brand plainly, and offers the member’s brands', () => {
+ const [message, options] = show('workspace');
+ expect(message).toBe("This brand isn't in your workspace. Switch to one of your brands.");
+ expect(options.action?.label).toBe('Your brands');
+ options.action?.onClick();
+ expect(push).toHaveBeenCalledWith('/dashboard/brands');
+ });
+
+ it('asks to sign in again for an expired session, and to upgrade for a limit', () => {
+ expect(show('session')[1].action?.label).toBe('Sign in');
+ const [message, options] = show('limit', { id: 't1' });
+ expect(message).toBe("You've used this month's allowance. Upgrade, or wait until it resets.");
+ expect(options).toMatchObject({ id: 't1', action: { label: 'Upgrade' } });
+ });
+
+ it('asks to wait a minute for a rate limit, with nothing to click', () => {
+ const [message, options] = show('busy');
+ expect(message).toBe('Too many requests. Wait a minute and try again.');
+ expect(options.action).toBeUndefined();
+ });
+
+ it('offers nothing to click for a plain failure', () => {
+ const [message, options] = show('failed');
+ expect(message).toBe('Something went wrong. Try again.');
+ expect(options.action).toBeUndefined();
+ });
+});
diff --git a/web/src/hooks/use-failure-toast.ts b/web/src/hooks/use-failure-toast.ts
new file mode 100644
index 000000000..17108459a
--- /dev/null
+++ b/web/src/hooks/use-failure-toast.ts
@@ -0,0 +1,41 @@
+'use client';
+
+import { useCallback } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { useRouter } from '@/i18n/navigation';
+import type { ApiFailure } from '@/lib/api-failure';
+
+/**
+ * A failed call as a toast (BUG-001): the reason in plain words and the one
+ * thing to do about it — sign in again, switch brand, reload, or upgrade.
+ */
+export function useFailureToast() {
+ const t = useTranslations('apiFailure');
+ const router = useRouter();
+ return useCallback(
+ (failure: ApiFailure, options: { id?: string | number; description?: string } = {}) => {
+ const action = (() => {
+ switch (failure) {
+ case 'session':
+ return { label: t('signIn'), onClick: () => router.push('/sign-in') };
+ case 'workspace':
+ return { label: t('yourBrands'), onClick: () => router.push('/dashboard/brands') };
+ case 'not_found':
+ return { label: t('reload'), onClick: () => window.location.reload() };
+ case 'plan':
+ case 'limit':
+ return {
+ label: t('upgrade'),
+ onClick: () => router.push('/dashboard/settings/billing'),
+ };
+ case 'busy':
+ case 'failed':
+ return undefined;
+ }
+ })();
+ toast.error(t(failure), { ...options, ...(action ? { action } : {}) });
+ },
+ [t, router],
+ );
+}
diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.ts
index 6b58482d1..a53ee295e 100644
--- a/web/src/lib/actions/content.ts
+++ b/web/src/lib/actions/content.ts
@@ -3,19 +3,32 @@
import { createClient } from '@/lib/supabase/server';
import type { ContentBrief, ContentOpportunity, OpportunityBasket, WebhookConfig } from '@/types';
import { API_BASE_URL } from '@/config/api';
+import { apiFailure, type ApiFailure } from '@/lib/api-failure';
import type { ContentUsage } from '@/lib/content-usage';
const AEO_SERVER_URL = API_BASE_URL;
async function getSession() {
+ const session = await sessionOrNull();
+ if (!session) throw new Error('Not authenticated');
+ return session;
+}
+
+async function sessionOrNull() {
const supabase = await createClient();
const {
data: { session },
} = await supabase.auth.getSession();
- if (!session) throw new Error('Not authenticated');
return session;
}
+/**
+ * No session, for the calls whose errors come back as values: the toast then
+ * offers Sign in (BUG-001). Thrown, the reason wouldn't reach the browser, as
+ * Next.js hides a server action's error message in production.
+ */
+const NO_SESSION = { ok: false as const, error: 'Not authenticated', failure: 'session' as const };
+
/** What a "+ New" request asks for (CONTENT-003). */
export interface OnDemandRequest {
brandId: string;
@@ -31,13 +44,21 @@ export interface OnDemandRequest {
export type OnDemandResult =
| { ok: true; jobId: string; count: number }
- | { ok: false; error: string; quotaExhausted?: boolean; periodEnd?: string | null };
+ | {
+ ok: false;
+ error: string;
+ /** Why, for the toast to say in plain words (BUG-001). */
+ failure: ApiFailure;
+ quotaExhausted?: boolean;
+ periodEnd?: string | null;
+ };
/** Starts generating opportunities now ("+ New"); errors come back as values. */
export async function generateOpportunitiesOnDemand(
request: OnDemandRequest,
): Promise<OnDemandResult> {
- const session = await getSession();
+ const session = await sessionOrNull();
+ if (!session) return NO_SESSION;
const res = await fetch(`${AEO_SERVER_URL}/api/content/opportunities/generate`, {
method: 'POST',
@@ -53,6 +74,7 @@ export async function generateOpportunitiesOnDemand(
return {
ok: false,
error: body.message || body.error || `Server error: ${res.status}`,
+ failure: apiFailure(res.status, body),
quotaExhausted: body.error === 'quota_exhausted',
periodEnd: body.periodEnd ?? null,
};
@@ -623,7 +645,13 @@ export async function saveWebhookConfig(
export type AlternativeResult =
| { ok: true; jobId: string }
- | { ok: false; error: string; quotaExhausted?: boolean; noCluster?: boolean };
+ | {
+ ok: false;
+ error: string;
+ failure: ApiFailure;
+ quotaExhausted?: boolean;
+ noCluster?: boolean;
+ };
/**
* "Another angle" (CONTENT-006): starts generating one more opportunity for
@@ -633,7 +661,8 @@ export async function suggestAlternative(
id: string,
{ direction, idempotencyKey }: { direction?: string | null; idempotencyKey: string },
): Promise<AlternativeResult> {
- const session = await getSession();
+ const session = await sessionOrNull();
+ if (!session) return NO_SESSION;
const res = await fetch(`${AEO_SERVER_URL}/api/content/${id}/alternative`, {
method: 'POST',
@@ -649,6 +678,7 @@ export async function suggestAlternative(
return {
ok: false,
error: body.message || body.error || `Server error: ${res.status}`,
+ failure: apiFailure(res.status, body),
quotaExhausted: body.error === 'quota_exhausted',
noCluster: body.error === 'no_cluster',
};
@@ -659,7 +689,7 @@ export async function suggestAlternative(
export type PromptSuggestionResult =
| { ok: true; jobId: string }
| { ok: true; existingId: string }
- | { ok: false; error: string; quotaExhausted?: boolean };
+ | { ok: false; error: string; failure: ApiFailure; quotaExhausted?: boolean };
/**
* "Suggest content" from the prompts table (PROMPT-006): one content
@@ -670,7 +700,8 @@ export async function suggestContentForPrompt(
promptId: string,
idempotencyKey: string,
): Promise<PromptSuggestionResult> {
- const session = await getSession();
+ const session = await sessionOrNull();
+ if (!session) return NO_SESSION;
const res = await fetch(`${AEO_SERVER_URL}/api/content/prompts/${promptId}/suggest`, {
method: 'POST',
@@ -686,6 +717,7 @@ export async function suggestContentForPrompt(
return {
ok: false,
error: body.message || body.error || `Server error: ${res.status}`,
+ failure: apiFailure(res.status, body),
quotaExhausted: body.error === 'quota_exhausted',
};
}
diff --git a/web/src/lib/api-failure.test.ts b/web/src/lib/api-failure.test.ts
new file mode 100644
index 000000000..93ea38c93
--- /dev/null
+++ b/web/src/lib/api-failure.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest';
+import { apiFailure } from './api-failure';
+
+describe('apiFailure', () => {
+ it('reads a bad or expired session from 401 only', () => {
+ // middleware/index.js answers with a message.
+ expect(apiFailure(401, { message: 'Unauthorized API Request' })).toBe('session');
+ // The old bare "Unauthorized" was another workspace's brand, not the session.
+ expect(apiFailure(403, { error: 'Unauthorized' })).toBe('workspace');
+ });
+
+ it('tells a used-up allowance from a plan without the feature', () => {
+ expect(apiFailure(429, { error: 'quota_exhausted' })).toBe('limit');
+ expect(apiFailure(403, { error: 'plan_limit' })).toBe('plan');
+ expect(apiFailure(402, { error: 'no_subscription' })).toBe('plan');
+ });
+
+ it('reads a rate limit as busy, never as an allowance to upgrade', () => {
+ // server/src/middleware/rate-limiter.js: a message, no error.
+ const limiter = { success: false, message: 'Too many requests, please try again later.' };
+ expect(apiFailure(429, limiter)).toBe('busy');
+ // A monthly budget used up (plan-guard's PlanLimitError) is an allowance.
+ expect(apiFailure(429, { error: 'plan_limit' })).toBe('limit');
+ // Any other 429 is a plain failure.
+ expect(apiFailure(429, { error: 'something_else' })).toBe('failed');
+ });
+
+ it("reads another workspace's brand from the server's code, and nothing else", () => {
+ expect(
+ apiFailure(403, { error: "This brand isn't in your workspace", code: 'not_in_workspace' }),
+ ).toBe('workspace');
+ // Before the server deploy, its bare 403.
+ expect(apiFailure(403, { error: 'Unauthorized' })).toBe('workspace');
+ // Any other 403 is no workspace, and no plan.
+ expect(apiFailure(403, { error: 'Only admins can do this' })).toBe('failed');
+ });
+
+ it("doesn't take an account without an organization for a plan to upgrade", () => {
+ // plan-guard's 400 carries plan_limit too.
+ expect(apiFailure(400, { error: 'plan_limit' })).toBe('failed');
+ });
+
+ it('reads something gone as not found, and anything else as a failure', () => {
+ expect(apiFailure(404, { error: 'Opportunity not found' })).toBe('not_found');
+ expect(apiFailure(500, {})).toBe('failed');
+ expect(apiFailure(502)).toBe('failed');
+ });
+});
diff --git a/web/src/lib/api-failure.ts b/web/src/lib/api-failure.ts
new file mode 100644
index 000000000..0c5428a14
--- /dev/null
+++ b/web/src/lib/api-failure.ts
@@ -0,0 +1,41 @@
+/**
+ * Why a call to the API failed, read from its status and body (BUG-001), so a
+ * toast or an MCP client can say it in plain words with one thing to do. A
+ * bare "Unauthorized" read as a session problem when the brand was another
+ * workspace's: 401 is a bad or expired session only.
+ */
+export const API_FAILURES = [
+ 'session',
+ 'workspace',
+ 'not_found',
+ 'plan',
+ 'limit',
+ 'busy',
+ 'failed',
+] as const;
+export type ApiFailure = (typeof API_FAILURES)[number];
+
+/**
+ * Read from the server's own codes, not the status alone: a 403 is another
+ * workspace's brand only when the server says so, and a 429 is a used-up
+ * allowance only with quota_exhausted or plan_limit. Anything not
+ * recognised is a plain failure rather than a wrong reason with a wrong
+ * thing to do.
+ */
+export function apiFailure(status: number, body: Record<string, unknown> = {}): ApiFailure {
+ if (status === 401) return 'session';
+ if (body.error === 'quota_exhausted') return 'limit';
+ // A monthly budget used up: plan-guard's PlanLimitError answers 429 with plan_limit.
+ if (status === 429 && body.error === 'plan_limit') return 'limit';
+ // The rate limiter, whose body carries a message and no error: wait a minute, not upgrade.
+ if (status === 429 && body.error === undefined) return 'busy';
+ // A missing subscription (402), or a plan without the feature: requireFeature's
+ // 403 with plan_limit. Not plan-guard's 400 for an account with no organization.
+ if (status === 402 || (status === 403 && body.error === 'plan_limit')) return 'plan';
+ // The server's code since BUG-001; its bare "Unauthorized" 403 before then.
+ if (body.code === 'not_in_workspace' || (status === 403 && body.error === 'Unauthorized')) {
+ return 'workspace';
+ }
+ if (status === 404) return 'not_found';
+ return 'failed';
+}
diff --git a/web/src/lib/content-job.test.ts b/web/src/lib/content-job.test.ts
index f7307b50e..2292cce80 100644
--- a/web/src/lib/content-job.test.ts
+++ b/web/src/lib/content-job.test.ts
@@ -4,6 +4,7 @@
* Following a content job until it completes, fails or we stop waiting.
*/
+import type { ApiFailure } from './api-failure';
import { describe, expect, test } from 'vitest';
import type { GenerationJobStatus, OnDemandRequest } from '@/lib/actions/content';
import { suggestForPage, suggestForPrompt, waitForContentJob } from './content-job';
@@ -104,7 +105,12 @@ describe('suggestForPrompt', () => {
test('tells a used-up quota from nothing to write yet', async () => {
expect(
- await run(async () => ({ ok: false, error: 'Monthly limit', quotaExhausted: true })),
+ await run(async () => ({
+ ok: false,
+ error: 'Monthly limit',
+ failure: 'limit',
+ quotaExhausted: true,
+ })),
).toEqual({ kind: 'limited' });
expect(
await run(
@@ -121,9 +127,13 @@ describe('suggestForPrompt', () => {
});
test('turns a refusal, a failed job or a throw into failed', async () => {
- expect(await run(async () => ({ ok: false, error: 'Prompt not found' }))).toEqual({
+ // With the reason the API gave, for the toast to say in plain words (BUG-001).
+ expect(
+ await run(async () => ({ ok: false, error: 'Prompt not found', failure: 'not_found' })),
+ ).toEqual({
kind: 'failed',
message: 'Prompt not found',
+ failure: 'not_found',
});
expect(
await run(
@@ -145,7 +155,7 @@ describe('suggestForPage (AT-006 part B3)', () => {
r: OnDemandRequest,
) => Promise<
| { ok: true; jobId: string; count: number }
- | { ok: false; error: string; quotaExhausted?: boolean }
+ | { ok: false; error: string; failure: ApiFailure; quotaExhausted?: boolean }
>,
result: GenerationJobStatus['result'],
) =>
@@ -183,12 +193,19 @@ describe('suggestForPage (AT-006 part B3)', () => {
test("says when the month's suggestions are used up, before or during the run", async () => {
expect(
- await run(async () => ({ ok: false, error: 'used up', quotaExhausted: true }), null),
+ await run(
+ async () => ({ ok: false, error: 'used up', failure: 'limit', quotaExhausted: true }),
+ null,
+ ),
).toEqual({ kind: 'limited' });
expect(await run(started, { generated: 0, limited: true })).toEqual({ kind: 'limited' });
- expect(await run(async () => ({ ok: false, error: 'nope' }), null)).toEqual({
+ // Another workspace's brand: the reason travels for a plain toast (BUG-001).
+ expect(
+ await run(async () => ({ ok: false, error: 'nope', failure: 'workspace' }), null),
+ ).toEqual({
kind: 'failed',
message: 'nope',
+ failure: 'workspace',
});
});
});
diff --git a/web/src/lib/content-job.ts b/web/src/lib/content-job.ts
index a7a11fc3d..ca514c172 100644
--- a/web/src/lib/content-job.ts
+++ b/web/src/lib/content-job.ts
@@ -5,6 +5,7 @@
* server.
*/
+import type { ApiFailure } from '@/lib/api-failure';
import type {
GenerationJobStatus,
OnDemandRequest,
@@ -58,7 +59,8 @@ export type PromptSuggestionOutcome =
| { kind: 'limited' }
/** Nothing to write from yet: the prompt isn't grouped or has no answers. */
| { kind: 'nothing' }
- | { kind: 'failed'; message: string | null }
+ /** `failure` says why when the API answered, for the toast (BUG-001). */
+ | { kind: 'failed'; message: string | null; failure?: ApiFailure }
/** Still being written when we stopped waiting. */
| { kind: 'timeout' };
@@ -88,7 +90,7 @@ export async function suggestForPrompt(
if (!started.ok) {
return started.quotaExhausted
? { kind: 'limited' }
- : { kind: 'failed', message: started.error };
+ : { kind: 'failed', message: started.error, failure: started.failure };
}
if ('existingId' in started) return { kind: 'existing', opportunityId: started.existingId };
@@ -141,7 +143,7 @@ export async function suggestForPage(
if (!started.ok) {
return started.quotaExhausted
? { kind: 'limited' }
- : { kind: 'failed', message: started.error };
+ : { kind: 'failed', message: started.error, failure: started.failure };
}
const outcome = await waitForContentJob(started.jobId, { getStatus, ...waiting });
diff --git a/web/src/stores/use-brand-store.test.ts b/web/src/stores/use-brand-store.test.ts
new file mode 100644
index 000000000..2a78eceab
--- /dev/null
+++ b/web/src/stores/use-brand-store.test.ts
@@ -0,0 +1,39 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+import type { Brand } from '@/types';
+
+// An in-memory localStorage for the store to persist to: the test environment has none.
+const memory = new Map<string, string>();
+Object.defineProperty(window, 'localStorage', {
+ configurable: true,
+ value: {
+ getItem: (key: string) => memory.get(key) ?? null,
+ setItem: (key: string, value: string) => memory.set(key, String(value)),
+ removeItem: (key: string) => memory.delete(key),
+ clear: () => memory.clear(),
+ },
+});
+const { useBrandStore } = await import('./use-brand-store');
+
+const brand = (id: string) => ({ id, name: id }) as unknown as Brand;
+
+beforeEach(() => {
+ useBrandStore.setState({ brands: [], activeBrandId: null });
+});
+
+describe('the brand store', () => {
+ it('keeps the brand chosen last time while it is still one of the member’s', () => {
+ useBrandStore.setState({ activeBrandId: 'b2' });
+ useBrandStore.getState().setBrands([brand('b1'), brand('b2')]);
+ expect(useBrandStore.getState().activeBrandId).toBe('b2');
+ });
+
+ // BUG-001: a brand deleted, or another workspace's, answered every call with 404 or 403.
+ it('drops a brand that is no longer the member’s for their first one', () => {
+ useBrandStore.setState({ activeBrandId: 'gone' });
+ useBrandStore.getState().setBrands([brand('b1'), brand('b2')]);
+ expect(useBrandStore.getState().activeBrandId).toBe('b1');
+
+ useBrandStore.getState().setBrands([]);
+ expect(useBrandStore.getState().activeBrandId).toBeNull();
+ });
+});
diff --git a/web/src/stores/use-brand-store.ts b/web/src/stores/use-brand-store.ts
index 020a6a8dc..b0820e9e9 100644
--- a/web/src/stores/use-brand-store.ts
+++ b/web/src/stores/use-brand-store.ts
@@ -19,10 +19,16 @@ export const useBrandStore = create<BrandStore>()(
brands: [],
activeBrandId: null,
+ // The brand kept from the last visit only while it is still one of the
+ // member's: a brand deleted, or another workspace's (an account
+ // switched in this browser), sent with every call answers 404 or 403
+ // (BUG-001).
setBrands: (brands) =>
set({
brands,
- activeBrandId: brands.length > 0 ? (get().activeBrandId ?? brands[0].id) : null,
+ activeBrandId: brands.some((b) => b.id === get().activeBrandId)
+ ? get().activeBrandId
+ : (brands[0]?.id ?? null),
}),
addBrand: (brand) =>