🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(auth): confirm agreement before continuing (#17190)
YuTengjingfa7da885e5e0
diff --git a/locales/en-US/auth.json b/locales/en-US/auth.jsonindex 597df50b741..e65f0d86915 100644--- a/locales/en-US/auth.json+++ b/locales/en-US/auth.json@@ -1,4 +1,8 @@{+ "agreement.checkbox": "I have read and agree to the <terms>Terms and Conditions</terms> and <privacy>Privacy Policy</privacy>",+ "agreement.confirm.content": "By selecting \"Agree and continue\", you confirm that you have read and agree to the <terms>Terms and Conditions</terms> and <privacy>Privacy Policy</privacy>.",+ "agreement.confirm.ok": "Agree and continue",+ "agreement.confirm.title": "Terms and Privacy Policy","apikey.display.autoGenerated": "Auto-generated","apikey.display.copy": "Copy","apikey.display.copyError": "Copy failed",diff --git a/locales/zh-CN/auth.json b/locales/zh-CN/auth.jsonindex ef65c4a1b09..f913741c474 100644--- a/locales/zh-CN/auth.json+++ b/locales/zh-CN/auth.json@@ -1,4 +1,8 @@{+ "agreement.checkbox": "我已阅读并同意<terms>服务条款</terms>与<privacy>隐私政策</privacy>",+ "agreement.confirm.content": "点击“同意并继续”即表示你已阅读并同意<terms>服务条款</terms>与<privacy>隐私政策</privacy>。",+ "agreement.confirm.ok": "同意并继续",+ "agreement.confirm.title": "确认服务条款与隐私政策","apikey.display.autoGenerated": "自动生成","apikey.display.copy": "复制","apikey.display.copyError": "复制失败,请再试一次",diff --git a/packages/locales/src/default/auth.ts b/packages/locales/src/default/auth.tsindex e576c82444b..01d90a54c78 100644--- a/packages/locales/src/default/auth.ts+++ b/packages/locales/src/default/auth.ts@@ -1,4 +1,10 @@export default {+ 'agreement.checkbox':+ 'I have read and agree to the <terms>Terms and Conditions</terms> and <privacy>Privacy Policy</privacy>',+ 'agreement.confirm.content':+ 'By selecting "Agree and continue", you confirm that you have read and agree to the <terms>Terms and Conditions</terms> and <privacy>Privacy Policy</privacy>.',+ 'agreement.confirm.ok': 'Agree and continue',+ 'agreement.confirm.title': 'Terms and Privacy Policy','apikey.display.autoGenerated': 'Auto-generated','apikey.display.copy': 'Copy','apikey.display.copyError': 'Copy failed',diff --git a/plugins/vite/sharedRendererConfig.test.ts b/plugins/vite/sharedRendererConfig.test.tsindex 8f3eafaacb5..b62a009a397 100644--- a/plugins/vite/sharedRendererConfig.test.ts+++ b/plugins/vite/sharedRendererConfig.test.ts@@ -1,6 +1,14 @@import { describe, expect, it } from 'vitest';-import { __testing, sharedModulePreload } from './sharedRendererConfig';+import { __testing, sharedModulePreload, sharedOptimizeDeps } from './sharedRendererConfig';++describe('sharedOptimizeDeps', () => {+ it('pre-bundles the root and base-ui entrypoints together', () => {+ expect(sharedOptimizeDeps.include).toEqual(+ expect.arrayContaining(['@lobehub/ui', '@lobehub/ui/base-ui']),+ );+ });+});describe('sharedModulePreload', () => {it('keeps vendor modulepreload dependencies while excluding i18n chunks', () => {diff --git a/plugins/vite/sharedRendererConfig.ts b/plugins/vite/sharedRendererConfig.tsindex a60c669ced9..6911e24f01a 100644--- a/plugins/vite/sharedRendererConfig.ts+++ b/plugins/vite/sharedRendererConfig.ts@@ -260,6 +260,7 @@ export const sharedOptimizeDeps = {'antd','@ant-design/icons','@lobehub/ui',+ '@lobehub/ui/base-ui','@lobehub/ui > @emotion/react','antd-style','zustand',diff --git a/src/features/Auth/SignIn/SignInEmailStep.tsx b/src/features/Auth/SignIn/SignInEmailStep.tsxindex 9b136768227..d307c3e14da 100644--- a/src/features/Auth/SignIn/SignInEmailStep.tsx+++ b/src/features/Auth/SignIn/SignInEmailStep.tsx@@ -10,7 +10,7 @@ import { useTranslation } from 'react-i18next';import AuthIcons from '@/components/AuthIcons';import AuthCard from '@/features/AuthCard';-import { AuthAgreement } from '@/features/AuthShell';+import { AuthAgreement, useAuthAgreement } from '@/features/AuthShell';const styles = createStaticStyles(({ css, cssVar }) => ({inlineLink: css`@@ -63,6 +63,7 @@ export const SignInEmailStep = ({onSocialSignIn,}: SignInEmailStepProps) => {const { t } = useTranslation('auth');+ const { agreementChecked, continueWithAgreement, setAgreementChecked } = useAuthAgreement();const emailInputRef = useRef<InputRef>(null);useEffect(() => {@@ -100,7 +101,11 @@ export const SignInEmailStep = ({key={provider}loading={socialLoading === provider}size="large"- onClick={() => onSocialSignIn(provider)}+ onClick={() =>+ continueWithAgreement(() => {+ onSocialSignIn(provider);+ })+ }>{getProviderLabel(provider)}</Button>@@ -132,7 +137,11 @@ export const SignInEmailStep = ({<Formform={form}layout="vertical"- onFinish={(values) => onCheckUser(values as { email: string })}+ onFinish={(values) =>+ continueWithAgreement(() => {+ void onCheckUser(values as { email: string });+ })+ }><Form.Itemname="email"@@ -160,6 +169,7 @@ export const SignInEmailStep = ({style={{ padding: 6 }}/></Form.Item>+ <AuthAgreement checked={agreementChecked} onChange={setAgreementChecked} /><Button block htmlType="submit" loading={loading} size="large" type="primary">{t('betterAuth.signin.nextStep')}</Button>@@ -209,7 +219,7 @@ export const SignInEmailStep = ({</a></Text>)}- <AuthAgreement />+ {!showEmailForm && <AuthAgreement />}{showEmailForm && (<Text align={'center'} fontSize={13} style={{ marginTop: 16 }} type={'secondary'}>{t('betterAuth.signin.noAccount')}{' '}diff --git a/src/features/Auth/SignUp/BetterAuthSignUpForm.tsx b/src/features/Auth/SignUp/BetterAuthSignUpForm.tsxindex 0c07b2c1302..aed10afa204 100644--- a/src/features/Auth/SignUp/BetterAuthSignUpForm.tsx+++ b/src/features/Auth/SignUp/BetterAuthSignUpForm.tsx@@ -10,7 +10,7 @@ import { useTranslation } from 'react-i18next';import { Link, useNavigate, useSearchParams } from 'react-router';import { AuthCard } from '@/features/AuthCard';-import { AuthAgreement } from '@/features/AuthShell';+import { AuthAgreement, useAuthAgreement } from '@/features/AuthShell';import { trackLoginOrSignupClicked } from '@/features/User/UserLoginOrSignup/trackLoginOrSignupClicked';import { useSignUp } from './useSignUp';@@ -21,6 +21,7 @@ const BetterAuthSignUpForm = () => {const { t } = useTranslation('auth');const navigate = useNavigate();const [searchParams] = useSearchParams();+ const { agreementChecked, continueWithAgreement, setAgreementChecked } = useAuthAgreement();const emailInputRef = useRef<InputRef>(null);const passwordInputRef = useRef<InputRef>(null);@@ -54,7 +55,15 @@ const BetterAuthSignUpForm = () => {return (<AuthCard footer={footer} title={t('betterAuth.signup.cardTitle', { appName: BRANDING_NAME })}>- <Form form={form} layout="vertical" onFinish={onSubmit}>+ <Form+ form={form}+ layout="vertical"+ onFinish={(values) =>+ continueWithAgreement(() => {+ void onSubmit(values);+ })+ }+ ><Form.Itemname="email"rules={[@@ -143,13 +152,13 @@ const BetterAuthSignUpForm = () => {{businessElement}+ <AuthAgreement checked={agreementChecked} onChange={setAgreementChecked} /><Form.Item><Button block htmlType="submit" loading={loading} size="large" type="primary">{t('betterAuth.signup.submit')}</Button></Form.Item></Form>- <AuthAgreement /></AuthCard>);};diff --git a/src/features/AuthShell/AuthAgreement.test.tsx b/src/features/AuthShell/AuthAgreement.test.tsxnew file mode 100644index 00000000000..13a5e509971--- /dev/null+++ b/src/features/AuthShell/AuthAgreement.test.tsx@@ -0,0 +1,162 @@+import * as BaseUI from '@lobehub/ui/base-ui';+import { act, fireEvent, render, renderHook, screen } from '@testing-library/react';+import { Form } from 'antd';+import type { ReactElement } from 'react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { SignInEmailStep } from '@/features/Auth/SignIn/SignInEmailStep';++import AuthAgreement, { useAuthAgreement } from './AuthAgreement';+import AuthFooterLinks from './AuthFooterLinks';++interface TransMockProps {+ components?: Record<string, ReactElement>;+ i18nKey: string;+}++vi.mock('react-i18next', async (importOriginal) => ({+ ...(await importOriginal()),+ Trans: ({ components, i18nKey }: TransMockProps) => (+ <>+ {i18nKey}+ {components?.terms}+ {components?.privacy}+ </>+ ),+}));++afterEach(() => {+ vi.restoreAllMocks();+});++const expectLinksToOpenInNewTabs = () => {+ const links = screen.getAllByRole('link');++ expect(links).toHaveLength(2);+ for (const link of links) {+ expect(link.getAttribute('target')).toBe('_blank');+ expect(link.getAttribute('rel')).toBe('noopener noreferrer');+ }+};++describe('AuthAgreement', () => {+ it('should keep the passive agreement visible and open its links in new tabs', () => {+ render(<AuthAgreement />);++ expect(screen.queryByRole('checkbox')).toBeNull();+ expect(screen.getByText('footer.agreement')).toBeTruthy();+ expectLinksToOpenInNewTabs();+ });++ it('should use the active agreement copy with the checkbox', () => {+ render(<AuthAgreement checked={false} onChange={vi.fn()} />);++ expect(screen.getByRole('checkbox')).toBeTruthy();+ expect(screen.getByText('agreement.checkbox')).toBeTruthy();+ expectLinksToOpenInNewTabs();+ });+});++describe('SignInEmailStep', () => {+ it('should confirm the agreement before social sign-in', async () => {+ let confirmAgreement: (() => Promise<void>) | (() => void) | undefined;+ vi.spyOn(BaseUI, 'confirmModal').mockImplementation(({ onOk }) => {+ confirmAgreement = onOk;+ return { close: vi.fn(), destroy: vi.fn() };+ });+ const onSocialSignIn = vi.fn();++ const TestSignInEmailStep = () => {+ const [form] = Form.useForm<{ email: string }>();++ return (+ <SignInEmailStep+ disableEmailPassword+ serverConfigInit+ form={form}+ isSocialOnly={false}+ loading={false}+ oAuthSSOProviders={['google']}+ socialLoading={null}+ onCheckUser={vi.fn(async () => {})}+ onGoToSignup={vi.fn()}+ onResetEmail={vi.fn()}+ onSetPassword={vi.fn()}+ onSocialSignIn={onSocialSignIn}+ />+ );+ };++ render(<TestSignInEmailStep />);+ fireEvent.click(screen.getByRole('button', { name: /Google/ }));++ expect(BaseUI.confirmModal).toHaveBeenCalledOnce();+ expect(onSocialSignIn).not.toHaveBeenCalled();++ await act(async () => {+ await confirmAgreement?.();+ });++ expect(onSocialSignIn).toHaveBeenCalledWith('google');+ });+});++describe('AuthFooterLinks', () => {+ it('should open its links in new tabs', () => {+ render(<AuthFooterLinks />);++ expectLinksToOpenInNewTabs();+ });+});++describe('useAuthAgreement', () => {+ it('should keep the agreement unchecked when confirmation is cancelled', () => {+ const requestConfirmation = vi.fn();+ const continueAction = vi.fn();+ const { result } = renderHook(() => useAuthAgreement(requestConfirmation));++ act(() => {+ result.current.continueWithAgreement(continueAction);+ });++ expect(result.current.agreementChecked).toBe(false);+ expect(requestConfirmation).toHaveBeenCalledOnce();+ expect(continueAction).not.toHaveBeenCalled();+ });++ it('should check the agreement and reuse consent after confirmation', () => {+ const requestConfirmation = vi.fn((onConfirm: () => void) => onConfirm());+ const continueAction = vi.fn();+ const { result } = renderHook(() => useAuthAgreement(requestConfirmation));++ act(() => {+ result.current.continueWithAgreement(continueAction);+ });++ expect(result.current.agreementChecked).toBe(true);++ act(() => {+ result.current.continueWithAgreement(continueAction);+ });++ expect(requestConfirmation).toHaveBeenCalledOnce();+ expect(continueAction).toHaveBeenCalledTimes(2);+ });++ it('should skip confirmation when the agreement is checked manually', () => {+ const requestConfirmation = vi.fn();+ const continueAction = vi.fn();+ const { result } = renderHook(() => useAuthAgreement(requestConfirmation));++ act(() => {+ result.current.setAgreementChecked(true);+ });++ act(() => {+ result.current.continueWithAgreement(continueAction);+ });++ expect(requestConfirmation).not.toHaveBeenCalled();+ expect(continueAction).toHaveBeenCalledOnce();+ });+});diff --git a/src/features/AuthShell/AuthAgreement.tsx b/src/features/AuthShell/AuthAgreement.tsxindex 90eb3e67f35..084a805fc3a 100644--- a/src/features/AuthShell/AuthAgreement.tsx+++ b/src/features/AuthShell/AuthAgreement.tsx@@ -1,38 +1,132 @@'use client';import { Text } from '@lobehub/ui';-import { type CSSProperties, memo } from 'react';+import { Checkbox, confirmModal } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import { memo, useCallback, useState } from 'react';import { Trans, useTranslation } from 'react-i18next';import { PRIVACY_URL, TERMS_URL } from '@/const/url';-const linkStyle: CSSProperties = {- color: 'inherit',- cursor: 'pointer',- textDecoration: 'underline',+const styles = createStaticStyles(({ css, cssVar }) => ({+ link: css`+ cursor: pointer;+ color: inherit;+ text-decoration: underline;++ &:active,+ &:focus,+ &:hover,+ &:visited {+ text-decoration: underline;+ }++ &:visited {+ color: ${cssVar.colorLinkActive};+ }+ `,+}));++type AuthAgreementProps =+ | {+ checked: boolean;+ onChange: (checked: boolean) => void;+ }+ | {+ checked?: undefined;+ onChange?: undefined;+ };++interface AgreementTextProps {+ i18nKey: 'agreement.checkbox' | 'agreement.confirm.content' | 'footer.agreement';+}++type ContinueWithAgreement = () => void;+type RequestAgreementConfirmation = (onConfirm: ContinueWithAgreement) => void;++const AgreementText = memo<AgreementTextProps>(({ i18nKey }) => {+ const { t: translate } = useTranslation('auth');++ return (+ <Trans+ i18nKey={i18nKey}+ ns={'auth'}+ components={{+ privacy: (+ <a className={styles.link} href={PRIVACY_URL} rel="noopener noreferrer" target="_blank">+ {translate('footer.privacy')}+ </a>+ ),+ terms: (+ <a className={styles.link} href={TERMS_URL} rel="noopener noreferrer" target="_blank">+ {translate('footer.terms')}+ </a>+ ),+ }}+ />+ );+});++export const useAuthAgreement = (requestConfirmation?: RequestAgreementConfirmation) => {+ const { t } = useTranslation(['auth', 'common']);+ const [agreementChecked, setAgreementChecked] = useState(false);++ const showConfirmation = useCallback(+ (onConfirm: ContinueWithAgreement) => {+ if (requestConfirmation) {+ requestConfirmation(onConfirm);+ return;+ }++ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: <AgreementText i18nKey={'agreement.confirm.content'} />,+ okText: t('agreement.confirm.ok', { ns: 'auth' }),+ onOk: onConfirm,+ title: t('agreement.confirm.title', { ns: 'auth' }),+ });+ },+ [requestConfirmation, t],+ );++ const continueWithAgreement = useCallback(+ (continueAction: ContinueWithAgreement) => {+ if (agreementChecked) {+ continueAction();+ return;+ }++ showConfirmation(() => {+ setAgreementChecked(true);+ continueAction();+ });+ },+ [agreementChecked, showConfirmation],+ );++ return { agreementChecked, continueWithAgreement, setAgreementChecked };};-const AuthAgreement = memo(() => {- const { t } = useTranslation('auth');+const AuthAgreement = memo<AuthAgreementProps>(({ checked, onChange }) => {+ if (checked === undefined || onChange === undefined) {+ return (+ <Text fontSize={13} style={{ display: 'block', marginBlockStart: 8 }} type={'secondary'}>+ <AgreementText i18nKey={'footer.agreement'} />+ </Text>+ );+ }+return (- <Text fontSize={13} style={{ display: 'block', marginBlockStart: 8 }} type={'secondary'}>- <Trans- i18nKey={'footer.agreement'}- ns={'auth'}- components={{- privacy: (- <a href={PRIVACY_URL} style={linkStyle}>- {t('footer.privacy')}- </a>- ),- terms: (- <a href={TERMS_URL} style={linkStyle}>- {t('footer.terms')}- </a>- ),- }}- />- </Text>+ <Checkbox+ checked={checked}+ size={16}+ style={{ alignItems: 'flex-start', marginBlockEnd: 12, width: '100%' }}+ styles={{ checkbox: { marginBlockStart: 2 } }}+ textProps={{ fontSize: 13, type: 'secondary' }}+ onChange={onChange}+ >+ <AgreementText i18nKey={'agreement.checkbox'} />+ </Checkbox>);});diff --git a/src/features/AuthShell/AuthFooterLinks.tsx b/src/features/AuthShell/AuthFooterLinks.tsxindex 68b192573bd..a499c261bb1 100644--- a/src/features/AuthShell/AuthFooterLinks.tsx+++ b/src/features/AuthShell/AuthFooterLinks.tsx@@ -1,25 +1,32 @@'use client';import { Text } from '@lobehub/ui';-import { type CSSProperties, memo } from 'react';+import { createStaticStyles } from 'antd-style';+import { memo } from 'react';import { useTranslation } from 'react-i18next';import { PRIVACY_URL, TERMS_URL } from '@/const/url';-const linkStyle: CSSProperties = {- color: 'inherit',- cursor: 'pointer',-};+const styles = createStaticStyles(({ css, cssVar }) => ({+ link: css`+ cursor: pointer;+ color: inherit;++ &:visited {+ color: ${cssVar.colorLinkActive};+ }+ `,+}));const AuthFooterLinks = memo(() => {const { t } = useTranslation('auth');return (<Text align={'center'} fontSize={13} type={'secondary'}>- <a href={TERMS_URL} style={linkStyle}>+ <a className={styles.link} href={TERMS_URL} rel="noopener noreferrer" target="_blank">{t('footer.terms')}</a><span style={{ marginInline: 8 }}>·</span>- <a href={PRIVACY_URL} style={linkStyle}>+ <a className={styles.link} href={PRIVACY_URL} rel="noopener noreferrer" target="_blank">{t('footer.privacy')}</a></Text>diff --git a/src/features/AuthShell/AuthShell.tsx b/src/features/AuthShell/AuthShell.tsxindex e826878979e..828f8bc1aea 100644--- a/src/features/AuthShell/AuthShell.tsx+++ b/src/features/AuthShell/AuthShell.tsx@@ -1,5 +1,6 @@'use client';+import { ModalHost } from '@lobehub/ui/base-ui';import { memo, type PropsWithChildren } from 'react';import BusinessAuthProvider from '@/business/client/BusinessAuthProvider';@@ -35,6 +36,7 @@ const AuthShell = memo<PropsWithChildren>(({ children }) => {</BusinessAuthProvider></LobeAnalyticsProviderWrapper></AuthServerConfigProvider>+ <ModalHost /></AuthThemeLite></AuthLocale>);diff --git a/src/features/AuthShell/AuthThemeLite.tsx b/src/features/AuthShell/AuthThemeLite.tsxindex cfda333a7ea..4b3d75b78ad 100644--- a/src/features/AuthShell/AuthThemeLite.tsx+++ b/src/features/AuthShell/AuthThemeLite.tsx@@ -4,6 +4,7 @@ import 'antd/dist/reset.css';import { ConfigProvider, ThemeProvider } from '@lobehub/ui';import { App } from 'antd';+import { domMax, LazyMotion } from 'motion/react';import * as m from 'motion/react-m';import { type PropsWithChildren } from 'react';import { memo } from 'react';@@ -43,7 +44,7 @@ const AuthThemeLite = memo<AuthThemeLiteProps>(({ children, globalCDN }) => {proxy: globalCDN ? 'unpkg' : undefined,}}>- {children}+ <LazyMotion features={domMax}>{children}</LazyMotion></ConfigProvider></App></ThemeProvider>diff --git a/src/features/AuthShell/index.ts b/src/features/AuthShell/index.tsindex 4bc06716f0c..0f99602951b 100644--- a/src/features/AuthShell/index.ts+++ b/src/features/AuthShell/index.ts@@ -1,4 +1,4 @@-export { default as AuthAgreement } from './AuthAgreement';+export { default as AuthAgreement, useAuthAgreement } from './AuthAgreement';export { default as AuthContainer } from './AuthContainer';export { AuthServerConfigProvider, useAuthServerConfigStore } from './AuthServerConfigProvider';export { default } from './AuthShell';