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(web): return invite/accept errors as values instead of throwing (#566)
jorge arambula3182b694f5de
diff --git a/web/src/components/settings/team-section.tsx b/web/src/components/settings/team-section.tsxindex 8e10d055b..ea79fbe1d 100644--- a/web/src/components/settings/team-section.tsx+++ b/web/src/components/settings/team-section.tsx@@ -433,10 +433,14 @@ function InviteDialog({ canInvite, onInvited }: { canInvite: boolean; onInvited:}setSubmitting(true);try {- const { inviteLink: link, emailSent: sent } = await inviteMember(email.trim(), role);- setInviteLink(link);- setEmailSent(sent);- toast.success(sent ? 'Invitation sent' : 'Invite created — share the link');+ const result = await inviteMember(email.trim(), role);+ if ('error' in result) {+ toast.error(result.error);+ return;+ }+ setInviteLink(result.inviteLink);+ setEmailSent(result.emailSent);+ toast.success(result.emailSent ? 'Invitation sent' : 'Invite created — share the link');onInvited();} catch (error) {toast.error(error instanceof Error ? error.message : 'Failed to send invitation');diff --git a/web/src/components/team/accept-invitation-card.tsx b/web/src/components/team/accept-invitation-card.tsxindex 51ae1e808..189e4bdd4 100644--- a/web/src/components/team/accept-invitation-card.tsx+++ b/web/src/components/team/accept-invitation-card.tsx@@ -47,9 +47,11 @@ export function AcceptInvitationCard({const [confirmPassword, setConfirmPassword] = useState('');const [isAccepting, setIsAccepting] = useState(false);const [isSwitching, setIsSwitching] = useState(false);+ const [acceptError, setAcceptError] = useState<string | null>(null);async function handleAccept(e: React.FormEvent<HTMLFormElement>) {e.preventDefault();+ setAcceptError(null);if (password.length < 8) {toast.error('Password must be at least 8 characters');@@ -77,7 +79,16 @@ export function AcceptInvitationCard({throw new Error(updateErr.message);}- await acceptInvitation(token);+ const result = await acceptInvitation(token);+ if ('error' in result) {+ // Inline beats a toast here — this is the message that tells the+ // user what to do next (e.g. which account to sign in with), and a+ // toast that auto-dismisses would take that instruction with it.+ setAcceptError(result.error);+ setIsAccepting(false);+ return;+ }+toast.success(`Welcome to ${organizationName}!`);router.push('/dashboard');router.refresh();@@ -142,6 +153,7 @@ export function AcceptInvitationCard({</div>) : (<form onSubmit={handleAccept} className="mt-6 space-y-4">+ {acceptError && <p className="text-sm text-destructive">{acceptError}</p>}<div className="space-y-2"><Label htmlFor="invite-fullname">Full name</Label><Inputdiff --git a/web/src/lib/actions/team.ts b/web/src/lib/actions/team.tsindex 33c28936c..1b470c3ee 100644--- a/web/src/lib/actions/team.ts+++ b/web/src/lib/actions/team.ts@@ -156,12 +156,21 @@ export async function listInvitations(): Promise<TeamInvitation[]> {}));}-export async function inviteMember(email: string, role: TeamRole) {+export type InviteMemberResult = { inviteLink: string; emailSent: boolean } | { error: string };++/**+ * User-facing failures (bad email, existing member, duplicate pending invite,+ * insert errors) come back as a VALUE: production masks every error thrown+ * from a server action, so the actionable message (e.g. "A pending invitation+ * already exists for this email") would otherwise reach users as the+ * meaningless digest string (#550).+ */+export async function inviteMember(email: string, role: TeamRole): Promise<InviteMemberResult> {const { user, profile } = await requireAdmin();const normalizedEmail = email.trim().toLowerCase();if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalizedEmail)) {- throw new Error('Invalid email address');+ return { error: 'Invalid email address' };}const [{ count: memberCount }, { count: inviteCount }] = await Promise.all([@@ -195,7 +204,7 @@ export async function inviteMember(email: string, role: TeamRole) {.eq('id', matched.id).maybeSingle();if (matchedProfile?.organization_id === profile.organization_id) {- throw new Error('This user is already a member of your team');+ return { error: 'This user is already a member of your team' };}}}@@ -236,9 +245,9 @@ export async function inviteMember(email: string, role: TeamRole) {if (insertError) {if (insertError.code === '23505') {- throw new Error('A pending invitation already exists for this email');+ return { error: 'A pending invitation already exists for this email' };}- throw new Error(insertError.message);+ return { error: insertError.message };}// inviteUserByEmail only emails BRAND-NEW addresses — it errors for an email@@ -264,7 +273,7 @@ export async function inviteMember(email: string, role: TeamRole) {}revalidatePath('/dashboard/settings');- return { invitation, inviteLink: shareLink, emailSent };+ return { inviteLink: shareLink, emailSent };}export async function revokeInvitation(invitationId: string) {@@ -352,11 +361,15 @@ export async function removeMember(userId: string) {revalidatePath('/dashboard/settings');}-export interface AcceptInvitationResult {- organizationId: string;- role: TeamRole;-}+export type AcceptInvitationResult = { organizationId: string; role: TeamRole } | { error: string };+/**+ * User-facing failures (stale/invalid token, expired invite, wrong signed-in+ * account) come back as a VALUE: production masks every error thrown from a+ * server action, so the most actionable message in this flow — telling the+ * user which email to sign in with — would otherwise reach them as the+ * meaningless digest string (#550).+ */export async function acceptInvitation(token: string): Promise<AcceptInvitationResult> {const supabase = await createClient();const {@@ -371,22 +384,22 @@ export async function acceptInvitation(token: string): Promise<AcceptInvitationR.eq('token', token).maybeSingle();- if (error || !invitation) throw new Error('Invitation not found');+ if (error || !invitation) return { error: 'Invitation not found' };if (invitation.status !== 'pending') {- throw new Error('This invitation is no longer valid');+ return { error: 'This invitation is no longer valid' };}const expiresAt = new Date(invitation.expires_at as string);if (expiresAt.getTime() < Date.now()) {await supabaseAdmin.from('invitations').update({ status: 'expired' }).eq('id', invitation.id);- throw new Error('This invitation has expired');+ return { error: 'This invitation has expired' };}const inviteEmail = (invitation.email as string).toLowerCase();const userEmail = user.email?.toLowerCase() ?? '';if (inviteEmail !== userEmail) {- throw new Error(`This invitation was sent to ${inviteEmail}. Please sign in with that email.`);+ return { error: `This invitation was sent to ${inviteEmail}. Please sign in with that email.` };}const { error: profileErr } = await supabaseAdmin@@ -398,7 +411,7 @@ export async function acceptInvitation(token: string): Promise<AcceptInvitationR}).eq('id', user.id);- if (profileErr) throw new Error(profileErr.message);+ if (profileErr) return { error: profileErr.message };await supabaseAdmin.from('invitations')