Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

💄 style(auth): show change-email errors inline with next steps (#23638)

YuTengjing263d9059c73e
diff --git a/locales/en-US/auth.json b/locales/en-US/auth.json
index f728b3c4927..b9a7bec1f04 100644
--- a/locales/en-US/auth.json
+++ b/locales/en-US/auth.json
@@ -347,10 +347,13 @@
"profile.cancel": "Cancel",
"profile.changePassword": "Reset password",
"profile.email": "Email Address",
+ "profile.emailChangeFailed": "Could not update your email. Check your network connection and try again.",
"profile.emailChangeSuccess": "Verification email sent. Please check your new email inbox.",
- "profile.emailInUse": "This email is already used by another account. Please use a different email.",
+ "profile.emailChangeTooMany": "Too many email change attempts. Please wait a while and try again.",
+ "profile.emailInUseHint": "{{email}} is already used by another account. Enter a different email, or if that account is also yours, sign in to it and change its email first, then come back and try again.",
"profile.emailInvalid": "Please enter a valid email address",
"profile.emailPlaceholder": "[email protected]",
+ "profile.emailSameAsCurrent": "This is already your current email. Enter a different address.",
"profile.fullName": "Fullname",
"profile.interests": "Interests",
"profile.password": "Password",
diff --git a/locales/zh-CN/auth.json b/locales/zh-CN/auth.json
index 76d081b6b97..83c4c855bd9 100644
--- a/locales/zh-CN/auth.json
+++ b/locales/zh-CN/auth.json
@@ -347,10 +347,13 @@
"profile.cancel": "取消",
"profile.changePassword": "重置密码",
"profile.email": "邮箱",
+ "profile.emailChangeFailed": "邮箱修改失败,请检查网络连接后重试。",
"profile.emailChangeSuccess": "验证邮件已发送,请查收新邮箱。",
- "profile.emailInUse": "该邮箱已被其他账号使用,请换一个邮箱。",
+ "profile.emailChangeTooMany": "修改邮箱的次数过多,请稍后再试。",
+ "profile.emailInUseHint": "{{email}} 已被另一个账号使用。请换一个邮箱;如果那个账号也是你的,请先登录它把邮箱改掉,再回到这里修改。",
"profile.emailInvalid": "请输入有效的邮箱地址",
"profile.emailPlaceholder": "[email protected]",
+ "profile.emailSameAsCurrent": "这已经是你当前的邮箱,请输入一个新地址。",
"profile.fullName": "全名",
"profile.interests": "兴趣领域",
"profile.password": "密码",
diff --git a/packages/locales/src/default/auth.ts b/packages/locales/src/default/auth.ts
index 7d4e4a7a26a..1430389999a 100644
--- a/packages/locales/src/default/auth.ts
+++ b/packages/locales/src/default/auth.ts
@@ -387,8 +387,13 @@ export default {
'profile.changePassword': 'Reset password',
'profile.email': 'Email Address',
'profile.emailChangeSuccess': 'Verification email sent. Please check your new email inbox.',
- 'profile.emailInUse':
- 'This email is already used by another account. Please use a different email.',
+ 'profile.emailChangeFailed':
+ 'Could not update your email. Check your network connection and try again.',
+ 'profile.emailChangeTooMany':
+ 'Too many email change attempts. Please wait a while and try again.',
+ 'profile.emailSameAsCurrent': 'This is already your current email. Enter a different address.',
+ 'profile.emailInUseHint':
+ '{{email}} is already used by another account. Enter a different email, or if that account is also yours, sign in to it and change its email first, then come back and try again.',
'profile.emailInvalid': 'Please enter a valid email address',
'profile.emailPlaceholder': '[email protected]',
'profile.fullName': 'Fullname',
diff --git a/src/features/Settings/profile/features/EmailRow.test.tsx b/src/features/Settings/profile/features/EmailRow.test.tsx
new file mode 100644
index 00000000000..eb657f8a5c3
--- /dev/null
+++ b/src/features/Settings/profile/features/EmailRow.test.tsx
@@ -0,0 +1,144 @@
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { CHANGE_EMAIL_IN_USE_CODE } from '@/libs/better-auth/constants';
+
+import EmailRow from './EmailRow';
+
+const mocks = vi.hoisted(() => ({
+ changeEmail: vi.fn(),
+ toastError: vi.fn(),
+ toastSuccess: vi.fn(),
+}));
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ isDesktop: false,
+}));
+
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ toast: { error: mocks.toastError, success: mocks.toastSuccess },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: { email?: string }) =>
+ options?.email ? `${key}:${options.email}` : key,
+ }),
+}));
+
+vi.mock('@/libs/better-auth/auth-client', () => ({ changeEmail: mocks.changeEmail }));
+
+vi.mock('@/hooks/useAppOrigin', () => ({ useAppOrigin: () => 'https://app.example.com' }));
+
+vi.mock('@/services/electron/system', () => ({ electronSystemService: {} }));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({ user: { email: '[email protected]' } }),
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ userProfileSelectors: {
+ email: (state: { user?: { email?: string } }) => state.user?.email,
+ },
+}));
+
+vi.mock('./ProfileRow', () => ({
+ default: ({ action, children }: { action?: ReactNode; children?: ReactNode }) => (
+ <div>
+ {children}
+ {action}
+ </div>
+ ),
+}));
+
+const submitEmail = async (value: string) => {
+ const user = userEvent.setup();
+ render(<EmailRow />);
+ await user.click(screen.getByText('profile.updateEmail'));
+ await user.type(screen.getByPlaceholderText('profile.emailPlaceholder'), value);
+ await user.click(screen.getByText('profile.save'));
+ return user;
+};
+
+describe('EmailRow', () => {
+ beforeEach(() => {
+ mocks.changeEmail.mockReset();
+ mocks.toastError.mockReset();
+ mocks.toastSuccess.mockReset();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it('shows next steps under the input, not a toast, when the email belongs to another account', async () => {
+ mocks.changeEmail.mockResolvedValue({
+ error: { code: CHANGE_EMAIL_IN_USE_CODE, message: 'in use' },
+ });
+
+ const user = await submitEmail('[email protected]');
+
+ expect(await screen.findByText('profile.emailInUseHint:[email protected]')).toBeInTheDocument();
+ expect(screen.getByPlaceholderText('profile.emailPlaceholder')).toHaveAttribute(
+ 'aria-invalid',
+ 'true',
+ );
+ expect(mocks.toastError).not.toHaveBeenCalled();
+
+ // Editing the address clears the stale error
+ await user.type(screen.getByPlaceholderText('profile.emailPlaceholder'), 'x');
+ expect(screen.queryByText('profile.emailInUseHint:[email protected]')).not.toBeInTheDocument();
+ });
+
+ it('shows an actionable inline error when the request fails', async () => {
+ mocks.changeEmail.mockRejectedValue(new Error('network'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await submitEmail('[email protected]');
+
+ expect(await screen.findByText('profile.emailChangeFailed')).toBeInTheDocument();
+ expect(mocks.toastError).not.toHaveBeenCalled();
+ });
+
+ it('shows friendly copy instead of the raw server message for other errors', async () => {
+ mocks.changeEmail.mockResolvedValue({
+ error: { message: "Verification email isn't enabled", status: 400 },
+ });
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await submitEmail('[email protected]');
+
+ expect(await screen.findByText('profile.emailChangeFailed')).toBeInTheDocument();
+ expect(screen.queryByText("Verification email isn't enabled")).not.toBeInTheDocument();
+ });
+
+ it('tells the user to wait when change-email is rate limited', async () => {
+ mocks.changeEmail.mockResolvedValue({
+ error: { code: 'TOO_MANY_CHANGE_EMAIL_REQUESTS', message: 'Too many', status: 429 },
+ });
+
+ await submitEmail('[email protected]');
+
+ expect(await screen.findByText('profile.emailChangeTooMany')).toBeInTheDocument();
+ });
+
+ it('rejects the current email inline without calling the API', async () => {
+ await submitEmail('[email protected]');
+
+ expect(await screen.findByText('profile.emailSameAsCurrent')).toBeInTheDocument();
+ expect(mocks.changeEmail).not.toHaveBeenCalled();
+ });
+
+ it('shows the invalid-format error inline without calling the API', async () => {
+ await submitEmail('not-an-email');
+
+ await waitFor(() => expect(screen.getByText('profile.emailInvalid')).toBeInTheDocument());
+ expect(mocks.changeEmail).not.toHaveBeenCalled();
+ expect(mocks.toastError).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Settings/profile/features/EmailRow.tsx b/src/features/Settings/profile/features/EmailRow.tsx
index fd4f4e163e9..81edee0f9bf 100644
--- a/src/features/Settings/profile/features/EmailRow.tsx
+++ b/src/features/Settings/profile/features/EmailRow.tsx
@@ -13,7 +13,6 @@ import { CHANGE_EMAIL_IN_USE_CODE } from '@/libs/better-auth/constants';
import { electronSystemService } from '@/services/electron/system';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
-import { saveToast } from '@/store/utils/saveToast';
import ProfileRow from './ProfileRow';
@@ -25,16 +24,20 @@ const EmailRow = () => {
const [isEditing, setIsEditing] = useState(false);
const [editValue, setEditValue] = useState('');
const [saving, setSaving] = useState(false);
+ /** Shown under the input instead of a toast so the guidance stays visible while the user fixes it */
+ const [error, setError] = useState('');
const appOrigin = useAppOrigin();
const handleStartEdit = () => {
setEditValue('');
+ setError('');
setIsEditing(true);
};
const handleCancel = () => {
setIsEditing(false);
setEditValue('');
+ setError('');
};
const handleSave = useCallback(async () => {
@@ -42,30 +45,43 @@ const EmailRow = () => {
if (!trimmed) return;
if (!EMAIL_REGEX.test(trimmed)) {
- toast.error(t('profile.emailInvalid'));
+ setError(t('profile.emailInvalid'));
+ return;
+ }
+
+ // Better Auth rejects this with an untranslated "Email is the same" and no error code
+ if (trimmed.toLowerCase() === email?.toLowerCase()) {
+ setError(t('profile.emailSameAsCurrent'));
return;
}
try {
setSaving(true);
+ setError('');
const res = await changeEmail({ callbackURL: '/settings/profile', newEmail: trimmed });
if (res.error) {
if (res.error.code === CHANGE_EMAIL_IN_USE_CODE) {
- toast.error(t('profile.emailInUse'));
+ setError(t('profile.emailInUseHint', { email: trimmed }));
return;
}
- toast.error(res.error.message ?? res.error.statusText ?? t('profile.saveError'));
+ if (res.error.status === 429) {
+ setError(t('profile.emailChangeTooMany'));
+ return;
+ }
+ // Server messages are untranslated and technical; keep them in the console only
+ console.error('Failed to change email:', res.error);
+ setError(t('profile.emailChangeFailed'));
return;
}
setIsEditing(false);
toast.success(t('profile.emailChangeSuccess'));
} catch (err) {
console.error('Failed to change email:', err);
- saveToast(err, { retry: () => void handleSave(), title: t('profile.saveError') });
+ setError(t('profile.emailChangeFailed'));
} finally {
setSaving(false);
}
- }, [editValue, t]);
+ }, [editValue, email, t]);
// Desktop OIDC and Better Auth sessions are not bridged, so change-email can only
// be completed on the web app.
@@ -115,19 +131,31 @@ const EmailRow = () => {
}
>
{isEditing ? (
- <Input
- autoFocus
- autoComplete="email"
- inputMode="email"
- placeholder={t('profile.emailPlaceholder')}
- size="small"
- style={{ flex: 1, minWidth: 0, width: '100%' }}
- type="email"
- value={editValue}
- variant="filled"
- onChange={(e) => setEditValue(e.target.value)}
- onPressEnter={handleSave}
- />
+ <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>
+ <Input
+ autoFocus
+ aria-invalid={!!error}
+ autoComplete="email"
+ data-invalid={error ? '' : undefined}
+ inputMode="email"
+ placeholder={t('profile.emailPlaceholder')}
+ size="small"
+ style={{ flex: 1, minWidth: 0, width: '100%' }}
+ type="email"
+ value={editValue}
+ variant="filled"
+ onPressEnter={handleSave}
+ onChange={(e) => {
+ setEditValue(e.target.value);
+ setError('');
+ }}
+ />
+ {error && (
+ <Text fontSize={12} role="alert" type="danger">
+ {error}
+ </Text>
+ )}
+ </Flexbox>
) : (
<Text>{email || '--'}</Text>
)}