🤯 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
♻️ refactor: report action failures through toast instead of inline blocks (#17782)
Inneie305870bc0cf
diff --git a/locales/en-US/auth.json b/locales/en-US/auth.jsonindex eb9b6615611..69ff87d602f 100644--- a/locales/en-US/auth.json+++ b/locales/en-US/auth.json@@ -115,6 +115,7 @@"betterAuth.signin.passwordPlaceholder": "Enter your password","betterAuth.signin.passwordStep.subtitle": "Enter your password to continue","betterAuth.signin.passwordStep.title": "Enter your password",+ "betterAuth.signin.sessionExpired": "Your session has expired. Sign in again to continue.","betterAuth.signin.setPassword": "set a password","betterAuth.signin.signupLink": "Sign up now","betterAuth.signin.socialError": "Social sign in failed, please try again",@@ -229,6 +230,7 @@"profile.authorizations.revoke.title": "Revoke authorization for {{name}}?","profile.authorizations.title": "Manage Authorizations","profile.avatar": "Avatar",+ "profile.avatarUploadError": "Avatar could not be updated","profile.cancel": "Cancel","profile.changePassword": "Reset password","profile.email": "Email Address",@@ -239,8 +241,9 @@"profile.interests": "Interests","profile.password": "Password","profile.resetPasswordError": "Failed to send password reset link",- "profile.resetPasswordSent": "Password reset link sent, please check your email",+ "profile.resetPasswordSent": "Reset link sent to {{email}}","profile.save": "Save",+ "profile.saveError": "Changes could not be saved","profile.setPassword": "Set password","profile.sso.link.button": "Connect Account","profile.sso.link.success": "Account linked successfully",diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 928417f9895..d274b3414a8 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1416,6 +1416,8 @@"upload.clientMode.fileNotSupported": "File uploads are not supported in browser mode; only images are allowed.","upload.clientMode.visionNotSupported": "The current model does not support visual recognition. Please switch to a different model to use this feature.","upload.preview.prepareTasks": "Preparing chunks...",+ "upload.preview.status.cancelled": "Upload cancelled",+ "upload.preview.status.error": "Upload failed","upload.preview.status.pending": "Preparing to upload...","upload.preview.status.processing": "Processing file...","upload.validation.unsupportedFileType": "Unsupported file type: {{files}}. Supported images: JPG, PNG, GIF, WebP. Supported documents include PDF, Word, Excel, PowerPoint, Markdown, text, CSV, JSON, and code files.",diff --git a/locales/en-US/common.json b/locales/en-US/common.jsonindex 159e3b89f0b..bf0a1bfc2bd 100644--- a/locales/en-US/common.json+++ b/locales/en-US/common.json@@ -304,6 +304,8 @@"import": "Import","importData": "Import Data","importModal.error.desc": "Sorry, an error occurred during the data import process. Please try importing again, or <1>submit a request</1>, and we will help you troubleshoot the issue as soon as possible.",+ "importModal.error.invalidConfig": "This configuration file could not be read",+ "importModal.error.selectAnotherFile": "Choose another file","importModal.error.title": "Data Import Failed","importModal.finish.onlySettings": "System settings imported successfully","importModal.finish.start": "Start using",diff --git a/locales/en-US/file.json b/locales/en-US/file.jsonindex f8fa9eecd83..f9ab6b168c2 100644--- a/locales/en-US/file.json+++ b/locales/en-US/file.json@@ -248,6 +248,7 @@"uploadDock.body.item.pending": "Preparing to upload...","uploadDock.body.item.processing": "Processing file...","uploadDock.body.item.restTime": "Remaining {{time}}",+ "uploadDock.body.item.retry": "Retry upload","uploadDock.fileQueueInfo": "Uploading the first {{count}} files, {{remaining}} remaining in queue","uploadDock.header.cancelAll": "Cancel all","uploadDock.totalCount": "Total {{count}} items",diff --git a/locales/en-US/subscription.json b/locales/en-US/subscription.jsonindex a5ad68bc2e3..4f307fd72db 100644--- a/locales/en-US/subscription.json+++ b/locales/en-US/subscription.json@@ -449,6 +449,7 @@"plans.plan.ultimate.desc": "For heavy users who need complex AI conversations","plans.plan.ultimate.title": "Ultimate","plans.restoreSubscription": "Restore Subscription",+ "plans.restoreSubscriptionError": "Could not restore your subscription","plans.restoreSubscriptionSuccess": "Subscription has been restored","plans.storage.title": "Data Storage","plans.subscribe": "Subscribe",diff --git a/locales/zh-CN/auth.json b/locales/zh-CN/auth.jsonindex d5d476dc44a..6bda6ba747b 100644--- a/locales/zh-CN/auth.json+++ b/locales/zh-CN/auth.json@@ -115,6 +115,7 @@"betterAuth.signin.passwordPlaceholder": "请输入密码","betterAuth.signin.passwordStep.subtitle": "请输入密码以继续","betterAuth.signin.passwordStep.title": "请输入密码",+ "betterAuth.signin.sessionExpired": "登录已过期,请重新登录以继续","betterAuth.signin.setPassword": "设置密码","betterAuth.signin.signupLink": "创建账号","betterAuth.signin.socialError": "登录遇到了问题,请重试",@@ -229,6 +230,7 @@"profile.authorizations.revoke.title": "取消授权「{{name}}」?","profile.authorizations.title": "管理授权","profile.avatar": "头像",+ "profile.avatarUploadError": "头像更新失败","profile.cancel": "取消","profile.changePassword": "重置密码","profile.email": "邮箱",@@ -239,8 +241,9 @@"profile.interests": "兴趣领域","profile.password": "密码","profile.resetPasswordError": "发送失败,请稍后重试",- "profile.resetPasswordSent": "已发送重置链接,请查收邮箱",+ "profile.resetPasswordSent": "重置链接已发送至 {{email}}","profile.save": "保存",+ "profile.saveError": "修改保存失败","profile.setPassword": "设置密码","profile.sso.link.button": "关联账户","profile.sso.link.success": "账户已关联",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex a76a085d520..4b94dfb7e1d 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1416,6 +1416,8 @@"upload.clientMode.fileNotSupported": "浏览器模式暂不支持上传文件。仅支持图片","upload.clientMode.visionNotSupported": "当前模型不支持视觉识别。请切换模型后使用","upload.preview.prepareTasks": "正在准备分块…",+ "upload.preview.status.cancelled": "已取消上传",+ "upload.preview.status.error": "上传失败","upload.preview.status.pending": "准备上传…","upload.preview.status.processing": "文件处理中…","upload.validation.unsupportedFileType": "不支持的文件类型:{{files}}。支持的图片格式:JPG、PNG、GIF、WebP。支持的文档包括PDF、Word、Excel、PowerPoint、Markdown、文本、CSV、JSON和代码文件。",diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.jsonindex 6b3d2c75589..f8565b7e920 100644--- a/locales/zh-CN/common.json+++ b/locales/zh-CN/common.json@@ -304,6 +304,8 @@"import": "导入","importData": "导入数据","importModal.error.desc": "数据导入时遇到问题。请尝试重新导入,或 <1>提交问题</1>,我们会第一时间帮你排查",+ "importModal.error.invalidConfig": "无法读取该配置文件",+ "importModal.error.selectAnotherFile": "重新选择文件","importModal.error.title": "数据导入遇到问题","importModal.finish.onlySettings": "系统设置导入成功","importModal.finish.start": "开始使用",diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.jsonindex 8ce92755be0..74df49f4268 100644--- a/locales/zh-CN/file.json+++ b/locales/zh-CN/file.json@@ -248,6 +248,7 @@"uploadDock.body.item.pending": "准备上传…","uploadDock.body.item.processing": "文件处理中…","uploadDock.body.item.restTime": "剩余 {{time}}",+ "uploadDock.body.item.retry": "重新上传","uploadDock.fileQueueInfo": "正在上传前 {{count}} 个文件,剩余 {{remaining}} 个文件将排队上传","uploadDock.header.cancelAll": "全部取消","uploadDock.totalCount": "共 {{count}} 项",diff --git a/locales/zh-CN/subscription.json b/locales/zh-CN/subscription.jsonindex 664c179ed7e..276ce844b5a 100644--- a/locales/zh-CN/subscription.json+++ b/locales/zh-CN/subscription.json@@ -449,6 +449,7 @@"plans.plan.ultimate.desc": "适合需要复杂 AI 对话的重度用户","plans.plan.ultimate.title": "专业版","plans.restoreSubscription": "恢复订阅",+ "plans.restoreSubscriptionError": "订阅恢复失败","plans.restoreSubscriptionSuccess": "订阅已恢复","plans.storage.title": "数据存储","plans.subscribe": "订阅",diff --git a/packages/locales/src/default/auth.ts b/packages/locales/src/default/auth.tsindex 2197fc399b3..efbcc18d853 100644--- a/packages/locales/src/default/auth.ts+++ b/packages/locales/src/default/auth.ts@@ -127,6 +127,7 @@ export default {'betterAuth.signin.passwordStep.subtitle': 'Enter your password to continue','betterAuth.signin.passwordStep.title': 'Enter your password','betterAuth.signin.setPassword': 'set a password',+ 'betterAuth.signin.sessionExpired': 'Your session has expired. Sign in again to continue.','betterAuth.signin.signupLink': 'Sign up now','betterAuth.signin.socialError': 'Social sign in failed, please try again','betterAuth.signin.socialOnlyHint':@@ -247,6 +248,7 @@ export default {'profile.authorizations.revoke.title': 'Revoke authorization for {{name}}?','profile.authorizations.title': 'Manage Authorizations','profile.avatar': 'Avatar',+ 'profile.avatarUploadError': 'Avatar could not be updated','profile.cancel': 'Cancel','profile.changePassword': 'Reset password','profile.email': 'Email Address',@@ -257,8 +259,9 @@ export default {'profile.interests': 'Interests','profile.password': 'Password','profile.resetPasswordError': 'Failed to send password reset link',- 'profile.resetPasswordSent': 'Password reset link sent, please check your email',+ 'profile.resetPasswordSent': 'Reset link sent to {{email}}','profile.save': 'Save',+ 'profile.saveError': 'Changes could not be saved','profile.setPassword': 'Set password','profile.sso.link.button': 'Connect Account','profile.sso.link.success': 'Account linked successfully',diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 8adb1a48d25..8f4b8391e1a 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1615,6 +1615,8 @@ export default {'upload.clientMode.visionNotSupported':'The current model does not support visual recognition. Please switch to a different model to use this feature.','upload.preview.prepareTasks': 'Preparing chunks...',+ 'upload.preview.status.cancelled': 'Upload cancelled',+ 'upload.preview.status.error': 'Upload failed','upload.preview.status.pending': 'Preparing to upload...','upload.preview.status.processing': 'Processing file...','upload.validation.unsupportedFileType':diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.tsindex 6ef7b976e4b..20b44128e6e 100644--- a/packages/locales/src/default/common.ts+++ b/packages/locales/src/default/common.ts@@ -385,6 +385,8 @@ export default {'importData': 'Import Data','importModal.error.desc':'Sorry, an error occurred during the data import process. Please try importing again, or <1>submit a request</1>, and we will help you troubleshoot the issue as soon as possible.',+ 'importModal.error.invalidConfig': 'This configuration file could not be read',+ 'importModal.error.selectAnotherFile': 'Choose another file','importModal.error.title': 'Data Import Failed','importModal.finish.onlySettings': 'System settings imported successfully','importModal.finish.start': 'Start using',diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.tsindex ef641d48c36..320f2f58f0d 100644--- a/packages/locales/src/default/file.ts+++ b/packages/locales/src/default/file.ts@@ -291,6 +291,7 @@ export default {'uploadDock.body.item.pending': 'Preparing to upload...','uploadDock.body.item.processing': 'Processing file...','uploadDock.body.item.restTime': 'Remaining {{time}}',+ 'uploadDock.body.item.retry': 'Retry upload','uploadDock.fileQueueInfo':'Uploading the first {{count}} files, {{remaining}} remaining in queue','uploadDock.totalCount': 'Total {{count}} items',diff --git a/packages/locales/src/default/subscription.ts b/packages/locales/src/default/subscription.tsindex af8d832d27f..2aa718442bd 100644--- a/packages/locales/src/default/subscription.ts+++ b/packages/locales/src/default/subscription.ts@@ -451,6 +451,7 @@ export default {'plans.cancelDowngrade': 'Cancel Scheduled Downgrade','plans.cancelDowngradeSuccess': 'Scheduled downgrade has been cancelled','plans.restoreSubscription': 'Restore Subscription',+ 'plans.restoreSubscriptionError': 'Could not restore your subscription','plans.restoreSubscriptionSuccess': 'Subscription has been restored','plans.pendingDowngrade': 'Pending Downgrade','plans.embeddingStorage.embeddings': 'entries',diff --git a/packages/trpc/src/client/lambda.ts b/packages/trpc/src/client/lambda.tsindex 6c8f84757e3..112ebbcfe04 100644--- a/packages/trpc/src/client/lambda.ts+++ b/packages/trpc/src/client/lambda.ts@@ -75,11 +75,14 @@ const errorHandlingLink: TRPCLink<LambdaRouter> = () => {// If user is still marked as signed in but got 401,// session is invalid - clear client state firstif (isSignedIn) {- await logout();+ const params = new URLSearchParams({ callbackUrl: location.toString() });+ params.set('reason', 'sessionExpired');+ await logout({ redirectTo: `/signin?${params.toString()}` });+ } else {+ const { loginRequired } =+ await import('@/components/Error/loginRequiredNotification');+ loginRequired.redirect({ reason: 'sessionExpired' });}- const { loginRequired } =- await import('@/components/Error/loginRequiredNotification');- loginRequired.redirect();}}}diff --git a/packages/types/src/files/upload.ts b/packages/types/src/files/upload.tsindex 37603fcaf11..94cf07fc45e 100644--- a/packages/types/src/files/upload.ts+++ b/packages/types/src/files/upload.ts@@ -15,12 +15,7 @@ export interface FileUploadState {}export type FileUploadStatus =- | 'pending'- | 'uploading'- | 'processing'- | 'success'- | 'error'- | 'cancelled';+ 'pending' | 'uploading' | 'processing' | 'success' | 'error' | 'cancelled';export type FileProcessStatus = 'pending' | 'chunking' | 'embedding' | 'success' | 'error';@@ -32,10 +27,16 @@ export interface UploadFileItem {* AbortController to cancel the upload*/abortController?: AbortController;+ /** Agent that owns the draft upload, used to retry in the same conversation context. */+ agentId?: string;/*** base64 data, it will use in other data*/base64Url?: string;+ /** Human-readable reason retained on the originating upload surface. */+ error?: string;+ /** Stable business reason used to render an in-context remedy action. */+ errorCode?: string;file: File;/*** the file url after upload,it will be s3 url@@ -43,6 +44,8 @@ export interface UploadFileItem {*/fileUrl?: string;id: string;+ knowledgeBaseId?: string;+ parentId?: string;/*** blob url for local preview* it will use in the file preview before send the message@@ -58,6 +61,7 @@ export interface UploadFileItem {status: FileUploadStatus;tasks?: FileParsingTask;uploadState?: FileUploadState;+ visibility?: 'private' | 'public';}export const FileMetadataSchema = z.object({diff --git a/src/business/client/features/FileUploadErrorActions/index.tsx b/src/business/client/features/FileUploadErrorActions/index.tsxnew file mode 100644index 00000000000..2452b919b8d--- /dev/null+++ b/src/business/client/features/FileUploadErrorActions/index.tsx@@ -0,0 +1,8 @@+import { memo } from 'react';++interface FileUploadErrorActionsProps {+ code?: string;+ compact?: boolean;+}++export const FileUploadErrorActions = memo<FileUploadErrorActionsProps>(() => null);diff --git a/src/business/client/handleFileUploadError.ts b/src/business/client/handleFileUploadError.tsindex f8659fe1479..3581ee16b94 100644--- a/src/business/client/handleFileUploadError.ts+++ b/src/business/client/handleFileUploadError.ts@@ -1,5 +1,10 @@+export interface FileUploadErrorDetails {+ code?: string;+ description: string;+}+export interface HandleFileUploadErrorOptions {- onUploadBlocked?: () => void;+ onUploadBlocked?: (details: FileUploadErrorDetails) => void;}export const handleFileUploadError = (_error: unknown, _options?: HandleFileUploadErrorOptions) =>diff --git a/src/components/Error/Description.tsx b/src/components/Error/Description.tsxdeleted file mode 100644index 8e6a08311d8..00000000000--- a/src/components/Error/Description.tsx+++ /dev/null@@ -1,31 +0,0 @@-'use client';--import { Flexbox, Highlighter, Icon } from '@lobehub/ui';-import { ChevronDown, ChevronUp } from 'lucide-react';-import { memo, useState } from 'react';-import { useTranslation } from 'react-i18next';--const Description = memo<{ message: string; status: number }>(({ message, status }) => {- const { t } = useTranslation('error');- const [show, setShow] = useState(false);- return (- <Flexbox gap={8}>- {t(`response.${status}` as any)}- <Flexbox- horizontal- gap={4}- style={{ cursor: 'pointer', fontSize: 12 }}- onClick={() => {- setShow(!show);- }}- >- {t('fetchError.detail')} <Icon icon={show ? ChevronUp : ChevronDown} />- </Flexbox>- <Highlighter language={'text'} style={{ display: show ? undefined : 'none', maxHeight: 80 }}>- {message}- </Highlighter>- </Flexbox>- );-});--export default Description;diff --git a/src/components/Error/RedirectLogin.tsx b/src/components/Error/RedirectLogin.tsxdeleted file mode 100644index 69689b72199..00000000000--- a/src/components/Error/RedirectLogin.tsx+++ /dev/null@@ -1,18 +0,0 @@-import { useTimeout } from 'ahooks';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { useUserStore } from '@/store/user';--const RedirectLogin = memo<{ timeout: number }>(({ timeout = 2000 }) => {- const signIn = useUserStore((s) => s.openLogin);- const { t } = useTranslation('error');-- useTimeout(() => {- signIn();- }, timeout);-- return <div style={{ cursor: 'pointer', fontSize: 12 }}>{t('loginRequired.desc')}</div>;-});--export default RedirectLogin;diff --git a/src/components/Error/fetchErrorNotification.tsx b/src/components/Error/fetchErrorNotification.tsxdeleted file mode 100644index 95919108f14..00000000000--- a/src/components/Error/fetchErrorNotification.tsx+++ /dev/null@@ -1,17 +0,0 @@-import { FluentEmoji } from '@lobehub/ui';-import { t } from 'i18next';--import { notification } from '@/components/AntdStaticMethods';--import Description from './Description';--export const fetchErrorNotification = {- error: ({ status, errorMessage }: { errorMessage: string; status: number }) => {- notification.error({- description: <Description message={errorMessage} status={status} />,- icon: <FluentEmoji emoji={'🤧'} size={24} />,- message: t('fetchError.title', { ns: 'error' }),- type: 'error',- });- },-};diff --git a/src/components/Error/loginRequiredNotification.tsx b/src/components/Error/loginRequiredNotification.tsxindex 305cd63c70c..6f5dc00d91d 100644--- a/src/components/Error/loginRequiredNotification.tsx+++ b/src/components/Error/loginRequiredNotification.tsx@@ -1,19 +1,7 @@-import { FluentEmoji } from '@lobehub/ui';-import { t } from 'i18next';--import { notification } from '@/components/AntdStaticMethods';--import RedirectLogin from './RedirectLogin';+import { getUserStoreState } from '@/store/user/store';export const loginRequired = {- redirect: ({ timeout = 2000 }: { timeout?: number } = {}) => {- notification.error({- description: <RedirectLogin timeout={timeout} />,- duration: timeout / 1000,- icon: <FluentEmoji emoji={'🫡'} size={24} />,- message: t('loginRequired.title', { ns: 'error' }),- showProgress: true,- type: 'warning',- });+ redirect: ({ reason }: { reason?: 'sessionExpired' } = {}) => {+ void getUserStoreState().openLogin(reason);},};diff --git a/src/features/Auth/SignIn/SignInEmailStep.tsx b/src/features/Auth/SignIn/SignInEmailStep.tsxindex 5634e7a98af..9d8747813d6 100644--- a/src/features/Auth/SignIn/SignInEmailStep.tsx+++ b/src/features/Auth/SignIn/SignInEmailStep.tsx@@ -49,6 +49,7 @@ export interface SignInEmailStepProps {onSetPassword: () => void;onSocialSignIn: (provider: string) => void;serverConfigInit: boolean;+ sessionExpired?: boolean;socialLoading: string | null;}@@ -60,6 +61,7 @@ export const SignInEmailStep = ({loading,oAuthSSOProviders,serverConfigInit,+ sessionExpired,socialLoading,onCheckUser,onGoToSignup,@@ -96,6 +98,15 @@ export const SignInEmailStep = ({return (<AuthCard title={t('signin.subtitle', { appName: BRANDING_NAME })}>+ {sessionExpired && (+ <Alert+ showIcon+ message={t('betterAuth.signin.sessionExpired')}+ style={{ marginBlockEnd: 12 }}+ type="warning"+ variant="filled"+ />+ )}{serverConfigInit && oAuthSSOProviders.length > 0 && (<Flexbox gap={12}>{oAuthSSOProviders.map((provider) => {diff --git a/src/features/Auth/SignIn/index.tsx b/src/features/Auth/SignIn/index.tsxindex aeea5302758..3ce78346f2f 100644--- a/src/features/Auth/SignIn/index.tsx+++ b/src/features/Auth/SignIn/index.tsx@@ -23,6 +23,7 @@ const SignIn = () => {loading,oAuthSSOProviders,sending,+ sessionExpired,sentInfo,serverConfigInit,socialLoading,@@ -62,6 +63,7 @@ const SignIn = () => {loading={loading}oAuthSSOProviders={oAuthSSOProviders}serverConfigInit={serverConfigInit}+ sessionExpired={sessionExpired}socialLoading={socialLoading}onCheckUser={handleCheckUser}onGoToSignup={handleGoToSignup}diff --git a/src/features/Auth/SignIn/useSignIn.test.ts b/src/features/Auth/SignIn/useSignIn.test.tsindex 2f2dd53bc65..c6705ea81f9 100644--- a/src/features/Auth/SignIn/useSignIn.test.ts+++ b/src/features/Auth/SignIn/useSignIn.test.ts@@ -485,7 +485,7 @@ describe('useSignIn', () => {describe('handleForgotPassword', () => {it('should call requestPasswordReset and land on the email-sent state', async () => {- mockRequestPasswordReset.mockResolvedValue(undefined);+ mockRequestPasswordReset.mockResolvedValue({ data: { status: true }, error: null });mockFetch.mockResolvedValueOnce({json: async () => ({ exists: true, hasPassword: true }),@@ -524,6 +524,35 @@ describe('useSignIn', () => {expect(result.current.step).toBe('email');});+ // The better-auth client resolves with `{ data, error }` rather than+ // throwing, so a rejected-promise test alone leaves the failure branch+ // unreachable and a failed send lands on the "email sent" screen.+ it('should show error and stay put when the client resolves with an error', async () => {+ mockRequestPasswordReset.mockResolvedValue({+ data: null,+ error: { message: 'Email provider rejected the request', status: 503 },+ });++ mockFetch.mockResolvedValueOnce({+ json: async () => ({ exists: true, hasPassword: true }),+ ok: true,+ });++ const { result } = renderHook(() => useSignIn());++ await act(async () => {+ await result.current.handleCheckUser({ email: '[email protected]' });+ });++ await act(async () => {+ await result.current.handleForgotPassword();+ });++ expect(mockMessageError).toHaveBeenCalled();+ expect(result.current.step).toBe('password');+ expect(result.current.sentInfo).toBeNull();+ });+it('should show error on failure', async () => {mockRequestPasswordReset.mockRejectedValue(new Error('fail'));@@ -572,7 +601,7 @@ describe('useSignIn', () => {describe('handleResendEmail', () => {it('should resend the password reset email and confirm', async () => {- mockRequestPasswordReset.mockResolvedValue(undefined);+ mockRequestPasswordReset.mockResolvedValue({ data: { status: true }, error: null });mockFetch.mockResolvedValueOnce({json: async () => ({ exists: true, hasPassword: true }),ok: true,@@ -601,7 +630,7 @@ describe('useSignIn', () => {describe('handleBackFromSent', () => {it('should return to the email entry (not the password step) after a reset email', async () => {- mockRequestPasswordReset.mockResolvedValue(undefined);+ mockRequestPasswordReset.mockResolvedValue({ data: { status: true }, error: null });mockFetch.mockResolvedValueOnce({json: async () => ({ exists: true, hasPassword: true }),ok: true,diff --git a/src/features/Auth/SignIn/useSignIn.ts b/src/features/Auth/SignIn/useSignIn.tsindex 5c3f65a8607..d6b344fbcd9 100644--- a/src/features/Auth/SignIn/useSignIn.ts+++ b/src/features/Auth/SignIn/useSignIn.ts@@ -40,6 +40,7 @@ export const useSignIn = () => {const { t } = useTranslation('auth');const navigate = useNavigate();const [searchParams] = useSearchParams();+ const sessionExpired = searchParams.get('reason') === 'sessionExpired';const enableMagicLink = useAuthServerConfigStore((s) => s.serverConfig.enableMagicLink || false);const disableEmailPassword = useAuthServerConfigStore((s) => s.serverConfig.disableEmailPassword || false,@@ -324,10 +325,13 @@ export const useSignIn = () => {if (sending) return false;setSending(true);try {- await requestPasswordReset({+ // The better-auth client resolves with `{ data, error }` instead of+ // throwing, so a failed send would otherwise land on the "email sent" screen.+ const { error } = await requestPasswordReset({email: targetEmail,redirectTo: `/reset-password?email=${encodeURIComponent(targetEmail)}`,});+ if (error) throw error;return true;} catch {toast.error(t('betterAuth.signin.forgotPasswordError'));@@ -387,6 +391,7 @@ export const useSignIn = () => {loading,oAuthSSOProviders: sortedProviders,sending,+ sessionExpired,sentInfo,serverConfigInit: enableBusinessFeatures ? true : serverConfigInit,socialLoading,diff --git a/src/features/ChatInput/Desktop/FilePreview/FileItem/index.tsx b/src/features/ChatInput/Desktop/FilePreview/FileItem/index.tsxindex 56ff1c54a62..00fb88df6f5 100644--- a/src/features/ChatInput/Desktop/FilePreview/FileItem/index.tsx+++ b/src/features/ChatInput/Desktop/FilePreview/FileItem/index.tsx@@ -1,9 +1,10 @@import { ActionIcon, Block, Center, Flexbox, Text } from '@lobehub/ui';import { createStaticStyles, cssVar } from 'antd-style';-import { Trash2Icon } from 'lucide-react';+import { RotateCwIcon, Trash2Icon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';+import { FileUploadErrorActions } from '@/business/client/features/FileUploadErrorActions';import { useFileStore } from '@/store/file';import { type UploadFileItem } from '@/types/files/upload';@@ -47,9 +48,12 @@ const styles = createStaticStyles(({ css }) => ({type FileItemProps = UploadFileItem;const FileItem = memo<FileItemProps>((props) => {- const { file, uploadState, status, id, tasks } = props;+ const { error, errorCode, file, uploadState, status, id, tasks } = props;const { t } = useTranslation(['chat', 'common']);- const [removeChatUploadFile] = useFileStore((s) => [s.removeChatUploadFile]);+ const [removeChatUploadFile, retryChatUploadFile] = useFileStore((s) => [+ s.removeChatUploadFile,+ s.retryChatUploadFile,+ ]);return (<Block horizontal align={'center'} className={styles.container} variant={'outlined'}>@@ -65,16 +69,34 @@ const FileItem = memo<FileItemProps>((props) => {>{file.name}</Text>- <UploadDetail size={file.size} status={status} tasks={tasks} uploadState={uploadState} />+ <UploadDetail+ error={error}+ size={file.size}+ status={status}+ tasks={tasks}+ uploadState={uploadState}+ /></Flexbox>- <Flexbox className={styles.actions}>+ <Flexbox horizontal className={styles.actions}>+ {status === 'error' && errorCode ? (+ <FileUploadErrorActions compact code={errorCode} />+ ) : status === 'error' ? (+ <ActionIcon+ icon={RotateCwIcon}+ size={'small'}+ title={t('retry', { ns: 'common' })}+ onClick={() => {+ void retryChatUploadFile(id);+ }}+ />+ ) : null}<ActionIconcolor={'red'}icon={Trash2Icon}size={'small'}title={t('delete', { ns: 'common' })}onClick={() => {- removeChatUploadFile(id);+ void removeChatUploadFile(id);}}/></Flexbox>diff --git a/src/features/ChatInput/Mobile/FilePreview/FileItem/File.tsx b/src/features/ChatInput/Mobile/FilePreview/FileItem/File.tsxindex ec463cac29e..6342ed5c5b2 100644--- a/src/features/ChatInput/Mobile/FilePreview/FileItem/File.tsx+++ b/src/features/ChatInput/Mobile/FilePreview/FileItem/File.tsx@@ -1,13 +1,19 @@import { ActionIcon, Flexbox, Text } from '@lobehub/ui';import { createStaticStyles, cssVar } from 'antd-style';-import { Trash } from 'lucide-react';+import { RotateCw, Trash } from 'lucide-react';import { memo } from 'react';+import { FileUploadErrorActions } from '@/business/client/features/FileUploadErrorActions';import FileIcon from '@/components/FileIcon';import UploadDetail from '@/features/ChatInput/components/UploadDetail';import { type UploadFileItem } from '@/types/files';const styles = createStaticStyles(({ css }) => ({+ actions: css`+ position: absolute;+ inset-block-start: 0;+ inset-inline-end: 0;+ `,container: css`cursor: pointer;@@ -25,12 +31,7 @@ const styles = createStaticStyles(({ css }) => ({background: ${cssVar.colorFillTertiary};`,deleteButton: css`- position: absolute;- inset-block-start: 0;- inset-inline-end: 0;-color: #fff;-background: ${cssVar.colorBgMask};&:hover {@@ -41,27 +42,52 @@ const styles = createStaticStyles(({ css }) => ({interface FileItemProps extends UploadFileItem {onRemove?: () => void;+ onRetry?: () => void;}-const FileItem = memo<FileItemProps>(({ id, onRemove, file, status, uploadState, tasks }) => {- return (- <Flexbox horizontal align={'center'} className={styles.container} gap={12} key={id}>- <FileIcon fileName={file.name} fileType={file.type} />- <Flexbox style={{ overflow: 'hidden' }}>- <Text ellipsis>{file.name}</Text>- <UploadDetail size={file.size} status={status} tasks={tasks} uploadState={uploadState} />+const FileItem = memo<FileItemProps>(+ ({ error, errorCode, id, onRemove, onRetry, file, status, uploadState, tasks }) => {+ return (+ <Flexbox horizontal align={'center'} className={styles.container} gap={12} key={id}>+ <FileIcon fileName={file.name} fileType={file.type} />+ <Flexbox style={{ overflow: 'hidden' }}>+ <Text ellipsis>{file.name}</Text>+ <UploadDetail+ error={error}+ size={file.size}+ status={status}+ tasks={tasks}+ uploadState={uploadState}+ />+ </Flexbox>+ <Flexbox horizontal className={styles.actions}>+ {status === 'error' && errorCode ? (+ <FileUploadErrorActions compact code={errorCode} />+ ) : status === 'error' ? (+ <ActionIcon+ glass+ className={styles.deleteButton}+ icon={RotateCw}+ size={'small'}+ onClick={(e) => {+ e.stopPropagation();+ onRetry?.();+ }}+ />+ ) : null}+ <ActionIcon+ glass+ className={styles.deleteButton}+ icon={Trash}+ size={'small'}+ onClick={(e) => {+ e.stopPropagation();+ onRemove?.();+ }}+ />+ </Flexbox></Flexbox>- <ActionIcon- glass- className={styles.deleteButton}- icon={Trash}- size={'small'}- onClick={(e) => {- e.stopPropagation();- onRemove?.();- }}- />- </Flexbox>- );-});+ );+ },+);export default FileItem;diff --git a/src/features/ChatInput/Mobile/FilePreview/FileItem/Image.tsx b/src/features/ChatInput/Mobile/FilePreview/FileItem/Image.tsxindex 676d070f145..c32f9c9afda 100644--- a/src/features/ChatInput/Mobile/FilePreview/FileItem/Image.tsx+++ b/src/features/ChatInput/Mobile/FilePreview/FileItem/Image.tsx@@ -1,8 +1,10 @@-import { ActionIcon, Image } from '@lobehub/ui';+import { ActionIcon, Flexbox, Image } from '@lobehub/ui';import { createStaticStyles, cssVar, cx } from 'antd-style';-import { Trash } from 'lucide-react';+import { RotateCw, Trash } from 'lucide-react';import { memo } from 'react';+import { FileUploadErrorActions } from '@/business/client/features/FileUploadErrorActions';+import { MIN_IMAGE_SIZE } from './style';const styles = createStaticStyles(({ css }) => ({@@ -27,39 +29,60 @@ const styles = createStaticStyles(({ css }) => ({interface FileItemProps {alt?: string;+ error?: boolean;+ errorCode?: string;loading?: boolean;onRemove?: () => void;+ onRetry?: () => void;src?: string;}-const FileItem = memo<FileItemProps>(({ alt, onRemove, src, loading }) => {- const IMAGE_SIZE = MIN_IMAGE_SIZE;+const FileItem = memo<FileItemProps>(+ ({ alt, error, errorCode, onRemove, onRetry, src, loading }) => {+ const IMAGE_SIZE = MIN_IMAGE_SIZE;- return (- <Image- alwaysShowActions- alt={alt || ''}- classNames={{ wrapper: cx(styles.image, styles.editableImage) }}- height={64}- isLoading={loading}- objectFit={'cover'}- size={IMAGE_SIZE}- src={src}- width={64}- actions={- <ActionIcon- glass- className={styles.deleteButton}- icon={Trash}- size={'small'}- onClick={(e) => {- e.stopPropagation();- onRemove?.();- }}- />- }- />- );-});+ return (+ <Image+ alwaysShowActions+ alt={alt || ''}+ classNames={{ wrapper: cx(styles.image, styles.editableImage) }}+ height={64}+ isLoading={loading}+ objectFit={'cover'}+ size={IMAGE_SIZE}+ src={src}+ width={64}+ actions={+ <Flexbox horizontal>+ {error && errorCode ? (+ <FileUploadErrorActions compact code={errorCode} />+ ) : error ? (+ <ActionIcon+ glass+ className={styles.deleteButton}+ icon={RotateCw}+ size={'small'}+ onClick={(e) => {+ e.stopPropagation();+ onRetry?.();+ }}+ />+ ) : null}+ <ActionIcon+ glass+ className={styles.deleteButton}+ icon={Trash}+ size={'small'}+ onClick={(e) => {+ e.stopPropagation();+ onRemove?.();+ }}+ />+ </Flexbox>+ }+ />+ );+ },+);export default FileItem;diff --git a/src/features/ChatInput/Mobile/FilePreview/FileItem/index.tsx b/src/features/ChatInput/Mobile/FilePreview/FileItem/index.tsxindex 15fddc6592b..f2f0c53e4b9 100644--- a/src/features/ChatInput/Mobile/FilePreview/FileItem/index.tsx+++ b/src/features/ChatInput/Mobile/FilePreview/FileItem/index.tsx@@ -18,23 +18,39 @@ interface FileItemProps extends UploadFileItem {}const FileItem = memo<FileItemProps>((props) => {- const { file, id, previewUrl, status } = props;- const [removeFile] = useFileStore((s) => [s.removeChatUploadFile]);+ const { errorCode, file, id, previewUrl, status } = props;+ const [removeFile, retryFile] = useFileStore((s) => [+ s.removeChatUploadFile,+ s.retryChatUploadFile,+ ]);if (file.type.startsWith('image')) {return (<Imagealt={file.name}+ error={status === 'error'}+ errorCode={errorCode}loading={status === 'pending'}src={previewUrl}onRemove={() => {removeFile(id);}}+ onRetry={() => {+ void retryFile(id);+ }}/>);}- return <File onRemove={() => removeFile(id)} {...props} />;+ return (+ <File+ {...props}+ onRemove={() => removeFile(id)}+ onRetry={() => {+ void retryFile(id);+ }}+ />+ );});export default FileItem;diff --git a/src/features/ChatInput/components/UploadDetail/UploadStatus.tsx b/src/features/ChatInput/components/UploadDetail/UploadStatus.tsxindex b5492d932a0..852ec0c2924 100644--- a/src/features/ChatInput/components/UploadDetail/UploadStatus.tsx+++ b/src/features/ChatInput/components/UploadDetail/UploadStatus.tsx@@ -2,7 +2,7 @@ import { CheckCircleFilled } from '@ant-design/icons';import { Flexbox, Icon, Text } from '@lobehub/ui';import { Progress } from 'antd';import { cssVar } from 'antd-style';-import { Loader2Icon } from 'lucide-react';+import { CircleAlertIcon, Loader2Icon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -10,12 +10,13 @@ import { type FileUploadState, type FileUploadStatus } from '@/types/files/uploaimport { formatSize } from '@/utils/format';interface UploadStateProps {+ error?: string;size: number;status: FileUploadStatus;uploadState?: FileUploadState;}-const UploadStatus = memo<UploadStateProps>(({ status, size, uploadState }) => {+const UploadStatus = memo<UploadStateProps>(({ error, status, size, uploadState }) => {const { t } = useTranslation('chat');switch (status) {@@ -63,6 +64,28 @@ const UploadStatus = memo<UploadStateProps>(({ status, size, uploadState }) => {</Flexbox>);}++ case 'error': {+ return (+ <Flexbox horizontal align={'center'} gap={4} style={{ minWidth: 0 }}>+ <Icon icon={CircleAlertIcon} size={12} style={{ color: cssVar.colorError }} />+ <Text+ ellipsis={{ tooltip: error }}+ style={{ color: cssVar.colorError, fontSize: 12, maxWidth: 110 }}+ >+ {error || t('upload.preview.status.error')}+ </Text>+ </Flexbox>+ );+ }++ case 'cancelled': {+ return (+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {t('upload.preview.status.cancelled')}+ </Text>+ );+ }}});diff --git a/src/features/ChatInput/components/UploadDetail/index.tsx b/src/features/ChatInput/components/UploadDetail/index.tsxindex 843a2aa0047..671481776ff 100644--- a/src/features/ChatInput/components/UploadDetail/index.tsx+++ b/src/features/ChatInput/components/UploadDetail/index.tsx@@ -19,18 +19,19 @@ const styles = createStaticStyles(({ css }) => ({}));interface UploadDetailProps {+ error?: string;size: number;status: FileUploadStatus;tasks?: FileParsingTask;uploadState?: FileUploadState;}-const UploadDetail = memo<UploadDetailProps>(({ uploadState, status, size, tasks }) => {+const UploadDetail = memo<UploadDetailProps>(({ error, uploadState, status, size, tasks }) => {const { t } = useTranslation('chat');return (<Flexbox horizontal align={'center'} gap={8} height={22}>- <UploadStatus size={size} status={status} uploadState={uploadState} />+ <UploadStatus error={error} size={size} status={status} uploadState={uploadState} />{!!tasks && Object.keys(tasks).length === 0 ? (<Text style={{ fontSize: 12 }} type={'secondary'}>{t('upload.preview.prepareTasks')}diff --git a/src/features/DataImporter/config.test.ts b/src/features/DataImporter/config.test.tsnew file mode 100644index 00000000000..d4dad265a86--- /dev/null+++ b/src/features/DataImporter/config.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest';++import { parseConfigFile } from './config';++describe('parseConfigFile', () => {+ it('returns parsed data for valid JSON', async () => {+ const file = new File(['{"version":1}'], 'backup.json', { type: 'application/json' });++ await expect(parseConfigFile(file)).resolves.toEqual({+ data: { version: 1 },+ success: true,+ });+ });++ it('returns a validation error instead of showing global feedback', async () => {+ const file = new File(['{"version":'], 'broken.json', { type: 'application/json' });++ const result = await parseConfigFile(file);++ expect(result.success).toBe(false);+ if (!result.success) expect(result.error).toBeTruthy();+ });+});diff --git a/src/features/DataImporter/config.ts b/src/features/DataImporter/config.tsindex f6518aab5b9..141cb535349 100644--- a/src/features/DataImporter/config.ts+++ b/src/features/DataImporter/config.ts@@ -1,21 +1,18 @@-import { t } from 'i18next';--import { notification } from '@/components/AntdStaticMethods';import { type ImportPgDataStructure } from '@/types/export';-export const parseConfigFile = async (file: File): Promise<ImportPgDataStructure | undefined> => {+export type ConfigFileParseResult =+ { data: ImportPgDataStructure; success: true } | { error: string; success: false };++export const parseConfigFile = async (file: File): Promise<ConfigFileParseResult> => {const text = await file.text();try {- return JSON.parse(text);+ return { data: JSON.parse(text), success: true };} catch (error) {console.error(error);- notification.error({- description: t('import.importConfigFile.description', {- ns: 'error',- reason: (error as any).message,- }),- message: t('import.importConfigFile.title', { ns: 'error' }),- });+ return {+ error: error instanceof Error ? error.message : String(error),+ success: false,+ };}};diff --git a/src/features/DataImporter/index.tsx b/src/features/DataImporter/index.tsxindex 5d2e22356d6..408031ad20a 100644--- a/src/features/DataImporter/index.tsx+++ b/src/features/DataImporter/index.tsx@@ -3,11 +3,12 @@import { type ErrorShape, type ImportFileUploadState } from '@lobechat/types';import { ImportStage } from '@lobechat/types';import { Center } from '@lobehub/ui';+import { Button, toast } from '@lobehub/ui/base-ui';import { Upload } from 'antd';import { createStaticStyles, cx } from 'antd-style';import { ImportIcon } from 'lucide-react';import { type ReactNode } from 'react';-import React, { memo, useMemo, useState } from 'react';+import React, { memo, useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import DataStyleModal from '@/components/DataStyleModal';@@ -70,6 +71,28 @@ const DataImporter = memo<DataImporterProps>(({ children, onFinishImport }) => {const [importResults, setImportResults] = useState<ImportResults | undefined>();const [showImportModal, setShowImportModal] = useState(false);const [importPgData, setImportPgData] = useState<ImportPgDataStructure | undefined>(undefined);+ const [hasConfigError, setHasConfigError] = useState(false);++ // Keeps the import modal in place on a bad file so the retry stays one click+ // away; the reason itself is transient and belongs to the toast.+ const handleBeforeUpload = useCallback(+ async (file: File) => {+ const result = await parseConfigFile(file);++ if (!result.success) {+ setHasConfigError(true);+ toast.error({ description: result.error, title: t('importModal.error.invalidConfig') });+ return false;+ }++ setHasConfigError(false);+ setImportPgData(result.data);+ setShowImportModal(true);++ return false;+ },+ [t],+ );const dataSource = useMemo(() => {if (!importResults) return;@@ -91,14 +114,14 @@ const DataImporter = memo<DataImporterProps>(({ children, onFinishImport }) => {const isFinished = importState === ImportStage.Success || importState === ImportStage.Error;- const closeModal = () => {+ const closeModal = useCallback(() => {setImportState(ImportStage.Finished);setImportResults(undefined);setImportError(undefined);setUploadingState(undefined);onFinishImport?.();- };+ }, [onFinishImport]);const content = useMemo(() => {switch (importState) {@@ -151,32 +174,44 @@ const DataImporter = memo<DataImporterProps>(({ children, onFinishImport }) => {return undefined;}}- }, [importState, fileUploadingState]);+ }, [closeModal, dataSource, duration, fileUploadingState, importError, importState, t]);return (<><DataStyleModalicon={ImportIcon}- open={importState !== ImportStage.Start && importState !== ImportStage.Finished}title={t('importModal.title')}width={isFinished ? 600 : 400}+ open={+ hasConfigError ||+ (importState !== ImportStage.Start && importState !== ImportStage.Finished)+ }+ onOpenChange={(open) => {+ if (!open) setHasConfigError(false);+ }}>- {content}+ {hasConfigError ? (+ <Center gap={24} padding={40}>+ <Upload+ accept={'application/json'}+ beforeUpload={handleBeforeUpload}+ className={cx(styles.wrapper)}+ maxCount={1}+ showUploadList={false}+ >+ <Button>{t('importModal.error.selectAnotherFile')}</Button>+ </Upload>+ </Center>+ ) : (+ content+ )}</DataStyleModal><Uploadaccept={'application/json'}+ beforeUpload={handleBeforeUpload}className={cx(styles.wrapper)}maxCount={1}showUploadList={false}- beforeUpload={async (file) => {- const config = await parseConfigFile(file);- if (!config) return false;-- setImportPgData(config);- setShowImportModal(true);-- return false;- }}>{/* a very hackable solution: add a pseudo before to have a large hot zone */}<div className={cx(styles.children)}>{children}</div>diff --git a/src/features/PluginTag/PluginStatus.tsx b/src/features/PluginTag/PluginStatus.tsxindex 97cd8430380..71be44fcb9b 100644--- a/src/features/PluginTag/PluginStatus.tsx+++ b/src/features/PluginTag/PluginStatus.tsx@@ -1,4 +1,4 @@-import { ActionIcon, Flexbox, Tag } from '@lobehub/ui';+import { ActionIcon, Flexbox, Tag, Text } from '@lobehub/ui';import { Button } from '@lobehub/ui/base-ui';import { Badge } from 'antd';import isEqual from 'fast-deep-equal';@@ -18,8 +18,9 @@ interface PluginStatusProps {}const PluginStatus = memo<PluginStatusProps>(({ title, id, deprecated }) => {const { t } = useTranslation();- const [status, isCustom, reinstallCustomPlugin] = useToolStore((s) => [+ const [status, installError, isCustom, reinstallCustomPlugin] = useToolStore((s) => [toolSelectors.getManifestLoadingStatus(id)(s),+ toolSelectors.getPluginInstallError(id)(s),customPluginSelectors.isCustomPlugin(id)(s),s.reinstallCustomPlugin,]);@@ -51,7 +52,7 @@ const PluginStatus = memo<PluginStatusProps>(({ title, id, deprecated }) => {return <Badge status={'success'} />;}}- }, [status]);+ }, [id, reinstallCustomPlugin, status, t]);const tag =// Deprecated tag@@ -67,10 +68,21 @@ const PluginStatus = memo<PluginStatusProps>(({ title, id, deprecated }) => {) : null;return (- <Flexbox horizontal gap={12} justify={'space-between'}>- <Flexbox horizontal align={'center'} gap={8}>- {title || id}- {tag}+ <Flexbox horizontal align={'flex-start'} gap={12} justify={'space-between'}>+ <Flexbox gap={2}>+ <Flexbox horizontal align={'center'} gap={8}>+ {title || id}+ {tag}+ </Flexbox>+ {installError ? (+ <Text fontSize={12} type={'danger'}>+ {t(`error.${installError.message}`, {+ defaultValue: installError.cause,+ error: installError.cause,+ ns: 'plugin',+ })}+ </Text>+ ) : null}</Flexbox>{deprecated ? (diff --git a/src/features/ResourceManager/components/UploadDock/Item.tsx b/src/features/ResourceManager/components/UploadDock/Item.tsxindex dc011357137..0c0256684d7 100644--- a/src/features/ResourceManager/components/UploadDock/Item.tsx+++ b/src/features/ResourceManager/components/UploadDock/Item.tsx@@ -1,10 +1,11 @@import { ActionIcon, Flexbox, Text } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';-import { XIcon } from 'lucide-react';+import { RotateCwIcon, XIcon } from 'lucide-react';import { type ReactNode } from 'react';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';+import { FileUploadErrorActions } from '@/business/client/features/FileUploadErrorActions';import FileIcon from '@/components/FileIcon';import { useFileStore } from '@/store/file';import { type UploadFileItem } from '@/types/files/upload';@@ -45,10 +46,11 @@ const styles = createStaticStyles(({ css, cssVar }) => {type UploadItemProps = UploadFileItem;-const UploadItem = memo<UploadItemProps>(({ id, file, status, uploadState }) => {+const UploadItem = memo<UploadItemProps>(({ error, errorCode, id, file, status, uploadState }) => {const { t } = useTranslation('file');const { type, name, size } = file;const cancelUpload = useFileStore((s) => s.cancelUpload);+ const retryDockUpload = useFileStore((s) => s.retryDockUpload);const desc: ReactNode = useMemo(() => {switch (status) {@@ -95,9 +97,12 @@ const UploadItem = memo<UploadItemProps>(({ id, file, status, uploadState }) =>}case 'error': {return (- <Text style={{ fontSize: 12 }} type={'danger'}>- {formatSize(size)} · {t('uploadDock.body.item.error')}- </Text>+ <Flexbox gap={6}>+ <Text style={{ fontSize: 12 }} type={'danger'}>+ {error || `${formatSize(size)} · ${t('uploadDock.body.item.error')}`}+ </Text>+ {errorCode ? <FileUploadErrorActions code={errorCode} /> : null}+ </Flexbox>);}case 'cancelled': {@@ -111,7 +116,7 @@ const UploadItem = memo<UploadItemProps>(({ id, file, status, uploadState }) =>return '';}}- }, [status, uploadState, size, t]);+ }, [error, errorCode, status, uploadState, size, t]);return (<Flexbox@@ -142,6 +147,17 @@ const UploadItem = memo<UploadItemProps>(({ id, file, status, uploadState }) =>/>)}+ {status === 'error' && !errorCode ? (+ <ActionIcon+ icon={RotateCwIcon}+ size="small"+ title={t('uploadDock.body.item.retry')}+ onClick={() => {+ void retryDockUpload(id);+ }}+ />+ ) : null}+{status === 'uploading' && !!uploadState && (<divclassName={styles.progress}diff --git a/src/features/ResourceManager/components/UploadDock/index.tsx b/src/features/ResourceManager/components/UploadDock/index.tsxindex 0d77bdda3c1..ed3dedfe69d 100644--- a/src/features/ResourceManager/components/UploadDock/index.tsx+++ b/src/features/ResourceManager/components/UploadDock/index.tsx@@ -104,7 +104,7 @@ const UploadDock = memo(() => {const autoDismissTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);useEffect(() => {- if (isUploading || overviewUploadingStatus === 'pending') {+ if (overviewUploadingStatus !== 'success') {if (autoDismissTimerRef.current) {clearTimeout(autoDismissTimerRef.current);}@@ -121,7 +121,7 @@ const UploadDock = memo(() => {clearTimeout(autoDismissTimerRef.current);}};- }, [isUploading, overviewUploadingStatus, fileList, dispatchDockFileList]);+ }, [overviewUploadingStatus, fileList, dispatchDockFileList]);if (count === 0 || !show) return;diff --git a/src/routes/(main)/(create)/image/features/PromptInput/index.tsx b/src/routes/(main)/(create)/image/features/PromptInput/index.tsxindex 6f16de5a4b9..c31da05cfb1 100644--- a/src/routes/(main)/(create)/image/features/PromptInput/index.tsx+++ b/src/routes/(main)/(create)/image/features/PromptInput/index.tsx@@ -193,7 +193,7 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {if (!canCreate) return;if (!isLogin) {- loginRequired.redirect({ timeout: 2000 });+ loginRequired.redirect();return;}diff --git a/src/routes/(main)/(create)/video/features/PromptInput/index.tsx b/src/routes/(main)/(create)/video/features/PromptInput/index.tsxindex 9919caf41f0..44cddb6c17f 100644--- a/src/routes/(main)/(create)/video/features/PromptInput/index.tsx+++ b/src/routes/(main)/(create)/video/features/PromptInput/index.tsx@@ -354,7 +354,7 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {if (!canCreate) return;if (!isLogin) {- loginRequired.redirect({ timeout: 2000 });+ loginRequired.redirect();return;}diff --git a/src/routes/(main)/settings/profile/features/AvatarRow.tsx b/src/routes/(main)/settings/profile/features/AvatarRow.tsxindex a95e7c6da9f..a2a426a3ff1 100644--- a/src/routes/(main)/settings/profile/features/AvatarRow.tsx+++ b/src/routes/(main)/settings/profile/features/AvatarRow.tsx@@ -4,13 +4,13 @@ import { Icon } from '@lobehub/ui';import { Upload } from 'antd';import { createStaticStyles, cssVar } from 'antd-style';import { Loader2Icon, PencilIcon } from 'lucide-react';-import { useMemo, useState } from 'react';+import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { fetchErrorNotification } from '@/components/Error/fetchErrorNotification';import UserAvatar from '@/features/User/UserAvatar';import { useUserStore } from '@/store/user';import { authSelectors } from '@/store/user/selectors';+import { saveToast } from '@/store/utils/saveToast';import { imageToBase64 } from '@/utils/imageToBase64';import { createUploadImageHandler } from '@/utils/uploadFIle';@@ -53,35 +53,35 @@ const AvatarRow = () => {const updateAvatar = useUserStore((s) => s.updateAvatar);const [uploading, setUploading] = useState(false);- const handleUploadAvatar = useMemo(- () =>- createUploadImageHandler(async (avatar) => {- try {- setUploading(true);- const img = new Image();- img.src = avatar;-- await new Promise((resolve, reject) => {- img.addEventListener('load', resolve);- img.addEventListener('error', reject);- });-- const webpBase64 = imageToBase64({ img, size: 256 });- await updateAvatar(webpBase64);- setUploading(false);- } catch (error) {- console.error('Failed to upload avatar:', error);- setUploading(false);-- fetchErrorNotification.error({- errorMessage: error instanceof Error ? error.message : String(error),- status: 500,- });- }- }),- [updateAvatar],+ const saveAvatar = useCallback(+ async (avatar: string) => {+ try {+ setUploading(true);+ const img = new Image();+ img.src = avatar;++ await new Promise((resolve, reject) => {+ img.addEventListener('load', resolve);+ img.addEventListener('error', reject);+ });++ const webpBase64 = imageToBase64({ img, size: 256 });+ await updateAvatar(webpBase64);+ } catch (error) {+ console.error('Failed to upload avatar:', error);+ saveToast(error, {+ retry: () => void saveAvatar(avatar),+ title: t('profile.avatarUploadError'),+ });+ } finally {+ setUploading(false);+ }+ },+ [updateAvatar, t],);+ const handleUploadAvatar = useMemo(() => createUploadImageHandler(saveAvatar), [saveAvatar]);+const canUpload = isLogin;const avatarContent = canUpload ? (diff --git a/src/routes/(main)/settings/profile/features/FullNameRow.tsx b/src/routes/(main)/settings/profile/features/FullNameRow.tsxindex 879eca8629e..e28ed6262c4 100644--- a/src/routes/(main)/settings/profile/features/FullNameRow.tsx+++ b/src/routes/(main)/settings/profile/features/FullNameRow.tsx@@ -3,12 +3,12 @@import { Flexbox, Icon, Input } from '@lobehub/ui';import { type InputRef } from 'antd';import { Loader2Icon } from 'lucide-react';-import { useCallback, useRef, useState } from 'react';+import { useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { fetchErrorNotification } from '@/components/Error/fetchErrorNotification';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';+import { saveToast } from '@/store/utils/saveToast';import ProfileRow from './ProfileRow';@@ -19,7 +19,7 @@ const FullNameRow = () => {const [saving, setSaving] = useState(false);const inputRef = useRef<InputRef>(null);- const handleSave = useCallback(async () => {+ const handleSave = async () => {const value = inputRef.current?.input?.value?.trim();if (!value || value === fullName) return;@@ -28,14 +28,11 @@ const FullNameRow = () => {await updateFullName(value);} catch (error) {console.error('Failed to update fullName:', error);- fetchErrorNotification.error({- errorMessage: error instanceof Error ? error.message : String(error),- status: 500,- });+ saveToast(error, { retry: () => void handleSave(), title: t('profile.saveError') });} finally {setSaving(false);}- }, [fullName, updateFullName]);+ };return (<ProfileRow anchor={'profile-full-name'} label={t('profile.fullName')}>diff --git a/src/routes/(main)/settings/profile/features/InterestsRow.test.tsx b/src/routes/(main)/settings/profile/features/InterestsRow.test.tsxindex 108091b830b..56254f1d90c 100644--- a/src/routes/(main)/settings/profile/features/InterestsRow.test.tsx+++ b/src/routes/(main)/settings/profile/features/InterestsRow.test.tsx@@ -7,6 +7,7 @@ import InterestsRow from './InterestsRow';const mocks = vi.hoisted(() => ({interests: [] as string[],+ saveToast: vi.fn(),updateInterests: vi.fn(),}));@@ -32,7 +33,14 @@ vi.mock('react-i18next', () => ({useTranslation: (namespace: string) => ({t: (key: string) => {if (namespace === 'auth') {- return ({ 'profile.interests': 'Interests' } as Record<string, string>)[key] ?? key;+ return (+ (+ {+ 'profile.interests': 'Interests',+ 'profile.saveError': 'Could not save interests',+ } as Record<string, string>+ )[key] ?? key+ );}return (@@ -48,10 +56,8 @@ vi.mock('react-i18next', () => ({}),}));-vi.mock('@/components/Error/fetchErrorNotification', () => ({- fetchErrorNotification: {- error: vi.fn(),- },+vi.mock('@/store/utils/saveToast', () => ({+ saveToast: mocks.saveToast,}));vi.mock('@/store/user', () => ({@@ -76,6 +82,7 @@ vi.mock('./ProfileRow', () => ({beforeEach(() => {mocks.interests = [];+ mocks.saveToast.mockReset();mocks.updateInterests.mockReset();mocks.updateInterests.mockResolvedValue(undefined);});@@ -109,4 +116,37 @@ describe('InterestsRow', () => {expect(mocks.updateInterests).toHaveBeenCalledWith(['自定义']);});});++ it('reports a failed save through the shared save toast without touching the row layout', async () => {+ const user = userEvent.setup();+ const failure = new Error('network detail');+ mocks.updateInterests.mockRejectedValueOnce(failure);++ render(<InterestsRow />);++ await user.click(screen.getByRole('button', { name: '编程与开发' }));++ await waitFor(() => {+ expect(mocks.saveToast).toHaveBeenCalledWith(failure, {+ retry: expect.any(Function),+ title: 'Could not save interests',+ });+ });+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ });++ it('retries the same payload from the toast action', async () => {+ const user = userEvent.setup();+ mocks.updateInterests.mockRejectedValueOnce(new Error('network detail'));++ render(<InterestsRow />);++ await user.click(screen.getByRole('button', { name: '编程与开发' }));++ await waitFor(() => expect(mocks.saveToast).toHaveBeenCalled());++ await mocks.saveToast.mock.calls[0][1].retry();++ expect(mocks.updateInterests).toHaveBeenNthCalledWith(2, ['coding']);+ });});diff --git a/src/routes/(main)/settings/profile/features/InterestsRow.tsx b/src/routes/(main)/settings/profile/features/InterestsRow.tsxindex 200e81afc59..945732f7f69 100644--- a/src/routes/(main)/settings/profile/features/InterestsRow.tsx+++ b/src/routes/(main)/settings/profile/features/InterestsRow.tsx@@ -8,10 +8,10 @@ import { BriefcaseIcon } from 'lucide-react';import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { fetchErrorNotification } from '@/components/Error/fetchErrorNotification';import { INTEREST_AREAS } from '@/routes/onboarding/config';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';+import { saveToast } from '@/store/utils/saveToast';import ProfileRow from './ProfileRow';@@ -30,13 +30,13 @@ const InterestsRow = () => {await updateInterests(updated);} catch (error) {console.error('Failed to update interests:', error);- fetchErrorNotification.error({- errorMessage: error instanceof Error ? error.message : String(error),- status: 500,+ saveToast(error, {+ retry: () => void saveInterests(updated),+ title: t('profile.saveError'),});}},- [updateInterests],+ [updateInterests, t],);const areas = useMemo(diff --git a/src/routes/(main)/settings/profile/features/PasswordRow.tsx b/src/routes/(main)/settings/profile/features/PasswordRow.tsxindex c2e584965d4..deb2a8514b2 100644--- a/src/routes/(main)/settings/profile/features/PasswordRow.tsx+++ b/src/routes/(main)/settings/profile/features/PasswordRow.tsx@@ -1,54 +1,46 @@'use client';+import { Flexbox, Icon, Text } from '@lobehub/ui';import { Button } from '@lobehub/ui/base-ui';-import { useCallback, useState } from 'react';+import { cssVar } from 'antd-style';+import { CheckCircle2Icon } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { notification } from '@/components/AntdStaticMethods';import { useUserStore } from '@/store/user';import { authSelectors, userProfileSelectors } from '@/store/user/selectors';import ProfileRow from './ProfileRow';+import { usePasswordReset } from './usePasswordReset';const PasswordRow = () => {const { t } = useTranslation('auth');const userProfile = useUserStore(userProfileSelectors.userProfile);const hasPasswordAccount = useUserStore(authSelectors.hasPasswordAccount);- const [sending, setSending] = useState(false);-- const handleChangePassword = useCallback(async () => {- if (!userProfile?.email) return;-- try {- setSending(true);- const { requestPasswordReset } = await import('@/libs/better-auth/auth-client');- await requestPasswordReset({- email: userProfile.email,- redirectTo: `/reset-password?email=${encodeURIComponent(userProfile.email)}`,- });- notification.success({- message: t('profile.resetPasswordSent'),- });- } catch (error) {- console.error('Failed to send reset password email:', error);- notification.error({- message: t('profile.resetPasswordError'),- });- } finally {- setSending(false);- }- }, [userProfile?.email, t]);+ const { requestReset, sending, sent } = usePasswordReset(userProfile?.email);return (<ProfileRowanchor={'profile-password'}label={t('profile.password')}action={- <Button loading={sending} size="small" onClick={handleChangePassword}>- {hasPasswordAccount ? t('profile.changePassword') : t('profile.setPassword')}+ <Button loading={sending} size="small" onClick={requestReset}>+ {sent+ ? t('betterAuth.signin.emailSent.resend')+ : hasPasswordAccount+ ? t('profile.changePassword')+ : t('profile.setPassword')}</Button>}- />+ >+ {sent && (+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon color={cssVar.colorSuccess} icon={CheckCircle2Icon} size={14} />+ <Text fontSize={12} type={'secondary'}>+ {t('profile.resetPasswordSent', { email: userProfile?.email })}+ </Text>+ </Flexbox>+ )}+ </ProfileRow>);};diff --git a/src/routes/(main)/settings/profile/features/SSOProvidersList/index.tsx b/src/routes/(main)/settings/profile/features/SSOProvidersList/index.tsxindex eca48745e96..65e04defd6a 100644--- a/src/routes/(main)/settings/profile/features/SSOProvidersList/index.tsx+++ b/src/routes/(main)/settings/profile/features/SSOProvidersList/index.tsx@@ -1,13 +1,12 @@import { isDesktop } from '@lobechat/const';import { type MenuProps } from '@lobehub/ui';-import { ActionIcon, DropdownMenu, Flexbox, Text } from '@lobehub/ui';+import { ActionIcon, DropdownMenu, Flexbox, Text, Tooltip } from '@lobehub/ui';import { confirmModal } from '@lobehub/ui/base-ui';import { ArrowRight, Plus, Unlink } from 'lucide-react';import { type CSSProperties } from 'react';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { notification } from '@/components/AntdStaticMethods';import AuthIcons from '@/components/AuthIcons';import { isBuiltinProvider, normalizeProviderId } from '@/libs/better-auth/utils/client';import { useServerConfigStore } from '@/store/serverConfig';@@ -48,13 +47,9 @@ export const SSOProvidersList = memo(() => {// Better-auth link/unlink operations are not available on desktopif (isDesktop) return;- // Prevent unlink if this is the only login method- if (!allowUnlink) {- notification.error({- message: t('profile.sso.unlink.forbidden'),- });- return;- }+ // The control is disabled when this is the only login method. Keep the+ // guard for callers outside the rendered list and for state races.+ if (!allowUnlink) return;confirmModal({content: t('profile.sso.unlink.description', { provider }),okButtonProps: {@@ -118,16 +113,26 @@ export const SSOProvidersList = memo(() => {)}</Flexbox>{!isDesktop && (- <ActionIcon- disabled={!allowUnlink}- icon={Unlink}- size={'small'}- onClick={() => handleUnlinkSSO(item.provider)}- />+ <Tooltip title={!allowUnlink ? t('profile.sso.unlink.forbidden') : undefined}>+ <span>+ <ActionIcon+ disabled={!allowUnlink}+ icon={Unlink}+ size={'small'}+ onClick={() => handleUnlinkSSO(item.provider)}+ />+ </span>+ </Tooltip>)}</Flexbox>))}+ {!isDesktop && !allowUnlink && (+ <Text fontSize={11} type="secondary">+ {t('profile.sso.unlink.forbidden')}+ </Text>+ )}+{/* Link Account Button - Only show for logged in users with available providers */}{enableAuthActions && availableProviders.length > 0 && (<DropdownMenu items={linkMenuItems} popupProps={{ style: { maxWidth: '200px' } }}>diff --git a/src/routes/(main)/settings/profile/features/usePasswordReset.test.ts b/src/routes/(main)/settings/profile/features/usePasswordReset.test.tsnew file mode 100644index 00000000000..d4b001cdb51--- /dev/null+++ b/src/routes/(main)/settings/profile/features/usePasswordReset.test.ts@@ -0,0 +1,73 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { usePasswordReset } from './usePasswordReset';++const mocks = vi.hoisted(() => ({+ requestPasswordReset: vi.fn(),+ saveToast: vi.fn(),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('@/libs/better-auth/auth-client', () => ({+ requestPasswordReset: mocks.requestPasswordReset,+}));++vi.mock('@/store/utils/saveToast', () => ({ saveToast: mocks.saveToast }));++beforeEach(() => {+ mocks.requestPasswordReset.mockReset();+ mocks.saveToast.mockReset();+});++describe('usePasswordReset', () => {+ it('marks the request sent when the client resolves without an error', async () => {+ mocks.requestPasswordReset.mockResolvedValue({ data: { status: true }, error: null });++ const { result } = renderHook(() => usePasswordReset('[email protected]'));++ await act(async () => {+ await result.current.requestReset();+ });++ expect(mocks.requestPasswordReset).toHaveBeenCalledWith(+ expect.objectContaining({ email: '[email protected]' }),+ );+ expect(result.current.sent).toBe(true);+ expect(mocks.saveToast).not.toHaveBeenCalled();+ });++ // The better-auth client resolves with `{ data, error }` rather than throwing,+ // so without an explicit error check a failed send still reports as sent.+ it('reports through the save toast and stays unsent when the client resolves with an error', async () => {+ const error = { message: 'Email provider rejected the request', status: 503 };+ mocks.requestPasswordReset.mockResolvedValue({ data: null, error });++ const { result } = renderHook(() => usePasswordReset('[email protected]'));++ await act(async () => {+ await result.current.requestReset();+ });++ await waitFor(() => {+ expect(mocks.saveToast).toHaveBeenCalledWith(error, {+ retry: expect.any(Function),+ title: 'profile.resetPasswordError',+ });+ });+ expect(result.current.sent).toBe(false);+ });++ it('does not call the client without an email', async () => {+ const { result } = renderHook(() => usePasswordReset(undefined));++ await act(async () => {+ await result.current.requestReset();+ });++ expect(mocks.requestPasswordReset).not.toHaveBeenCalled();+ });+});diff --git a/src/routes/(main)/settings/profile/features/usePasswordReset.ts b/src/routes/(main)/settings/profile/features/usePasswordReset.tsnew file mode 100644index 00000000000..b57f1cb1511--- /dev/null+++ b/src/routes/(main)/settings/profile/features/usePasswordReset.ts@@ -0,0 +1,34 @@+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { saveToast } from '@/store/utils/saveToast';++export const usePasswordReset = (email?: string | null) => {+ const { t } = useTranslation('auth');+ const [sending, setSending] = useState(false);+ const [sent, setSent] = useState(false);++ const requestReset = async () => {+ if (!email) return;++ try {+ setSending(true);+ const { requestPasswordReset } = await import('@/libs/better-auth/auth-client');+ // The better-auth client resolves with `{ data, error }` instead of+ // throwing, so a failed send would otherwise render as "link sent".+ const { error } = await requestPasswordReset({+ email,+ redirectTo: `/reset-password?email=${encodeURIComponent(email)}`,+ });+ if (error) throw error;+ setSent(true);+ } catch (error) {+ console.error('Failed to send reset password email:', error);+ saveToast(error, { retry: requestReset, title: t('profile.resetPasswordError') });+ } finally {+ setSending(false);+ }+ };++ return { requestReset, sending, sent };+};diff --git a/src/store/file/slices/chat/action.test.ts b/src/store/file/slices/chat/action.test.tsindex e77b5679c32..817bd02bd4f 100644--- a/src/store/file/slices/chat/action.test.ts+++ b/src/store/file/slices/chat/action.test.ts@@ -2,7 +2,6 @@ import { toast } from '@lobehub/ui/base-ui';import { act, renderHook } from '@testing-library/react';import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';-import { notification } from '@/components/AntdStaticMethods';import { fileService } from '@/services/file';import { agentByIdSelectors } from '@/store/agent/selectors';@@ -30,13 +29,6 @@ vi.mock('@lobehub/ui/base-ui', () => ({},}));-// Mock necessary modules and functions-vi.mock('@/components/AntdStaticMethods', () => ({- notification: {- error: vi.fn(),- },-}));-vi.mock('@/services/rag', () => ({ragService: {parseFileContent: vi.fn().mockResolvedValue(undefined),@@ -170,7 +162,7 @@ describe('useFileStore:chat', () => {expect(uploadWithProgress).toHaveBeenCalledTimes(1);});- it('shows a permission denied description when upload is rejected by RBAC', async () => {+ it('keeps a permission-denied upload in place with a retryable error', async () => {mockAgentMode({ enableAgentMode: false, heterogeneous: false });const { result } = renderHook(() => useStore());@@ -185,10 +177,14 @@ describe('useFileStore:chat', () => {await result.current.uploadChatFiles([file], AGENT_ID);});- expect(notification.error).toHaveBeenCalledWith({- description: 'You do not have permission to upload files in this workspace.',- message: 'File upload failed.',- });+ expect(result.current.chatUploadFileList).toEqual([+ expect.objectContaining({+ agentId: AGENT_ID,+ error: 'You do not have permission to upload files in this workspace.',+ id: 'test.txt',+ status: 'error',+ }),+ ]);});describe('removeChatUploadFile', () => {diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.tsindex b4cb05bc0c2..4120f8a3251 100644--- a/src/store/file/slices/chat/action.ts+++ b/src/store/file/slices/chat/action.ts@@ -4,7 +4,6 @@ import { toast } from '@lobehub/ui/base-ui';import { Buffer } from 'buffer.js';import { t } from 'i18next';-import { notification } from '@/components/AntdStaticMethods';import { FILE_UPLOAD_BLACKLIST } from '@/const/file';import { fileService } from '@/services/file';import { ragService } from '@/services/rag';@@ -111,6 +110,15 @@ export class FileActionImpl {await fileService.removeFile(id);};+ retryChatUploadFile = async (id: string): Promise<void> => {+ const { chatUploadFileList, dispatchChatUploadFileList } = this.#get();+ const item = chatUploadFileList.find((file) => file.id === id);+ if (!item?.agentId) return;++ dispatchChatUploadFileList({ id, type: 'removeFile' });+ await this.uploadChatFiles([item.file], item.agentId);+ };+startAsyncTask = async (id: string,runner: (id: string) => Promise<string>,@@ -202,7 +210,14 @@ export class FileActionImpl {base64Url = `data:${file.type};base64,${base64}`;}- return { base64Url, file, id: file.name, previewUrl, status: 'pending' } as UploadFileItem;+ return {+ agentId,+ base64Url,+ file,+ id: file.name,+ previewUrl,+ status: 'pending',+ } as UploadFileItem;}),);@@ -218,14 +233,19 @@ export class FileActionImpl {onStatusUpdate: dispatchChatUploadFileList,});} catch (error) {- // skip `UNAUTHORIZED` error- if (getErrorMessage(error) !== 'UNAUTHORIZED')- notification.error({- description: getUploadErrorDescription(error),- message: t('upload.uploadFailed', { ns: 'error' }),+ if (getErrorMessage(error) === 'UNAUTHORIZED') {+ dispatchChatUploadFileList({ id: file.name, type: 'removeFile' });+ } else {+ dispatchChatUploadFileList({+ id: file.name,+ type: 'updateFile',+ value: {+ error: getUploadErrorDescription(error),+ status: 'error',+ uploadState: undefined,+ },});-- dispatchChatUploadFileList({ id: file.name, type: 'removeFile' });+ }}if (!fileResult) return;diff --git a/src/store/file/slices/fileManager/action.test.ts b/src/store/file/slices/fileManager/action.test.tsindex 7331b497cb3..e627bfd208e 100644--- a/src/store/file/slices/fileManager/action.test.ts+++ b/src/store/file/slices/fileManager/action.test.ts@@ -130,6 +130,39 @@ describe('FileManagerActions', () => {});});+ describe('retryDockUpload', () => {+ it('keeps the item in place and restarts a transient failed upload', async () => {+ const { result } = renderHook(() => useStore());+ const upload = vi.spyOn(result.current, 'uploadWithProgress').mockResolvedValue({+ id: 'persisted-file',+ url: 'https://example.com/file.png',+ });+ vi.spyOn(result.current, 'refreshFileList').mockResolvedValue();++ act(() => {+ useStore.setState({+ dockUploadFileList: [+ {+ error: 'Upload failed',+ file: new File([], 'retry.png', { type: 'image/png' }),+ id: 'upload-1',+ status: 'error',+ },+ ],+ });+ });++ await act(async () => {+ await result.current.retryDockUpload('upload-1');+ });++ expect(upload).toHaveBeenCalledTimes(1);+ expect(result.current.dockUploadFileList[0]).toEqual(+ expect.objectContaining({ error: undefined, id: 'upload-1', status: 'pending' }),+ );+ });+ });+describe('dispatchDockFileList', () => {it('should update dockUploadFileList with new value', () => {const { result } = renderHook(() => useStore());diff --git a/src/store/file/slices/fileManager/action.ts b/src/store/file/slices/fileManager/action.tsindex ec84e2fe892..8d7831a22e7 100644--- a/src/store/file/slices/fileManager/action.ts+++ b/src/store/file/slices/fileManager/action.ts@@ -4,7 +4,7 @@ import {sanitizeFolderName,topologicalSortFolders,} from '@lobechat/utils';-import { toast } from '@lobehub/ui/base-ui';+import { toast, type ToastInstance } from '@lobehub/ui/base-ui';import { t } from 'i18next';import pMap from 'p-map';import { type SWRResponse } from 'swr';@@ -163,6 +163,51 @@ export class FileManageActionImpl {});};+ retryDockUpload = async (id: string): Promise<void> => {+ const { dispatchDockFileList, dockUploadFileList } = this.#get();+ const item = dockUploadFileList.find((file) => file.id === id);+ if (!item || item.status !== 'error' || item.errorCode) return;++ const abortController = new AbortController();+ dispatchDockFileList({+ id,+ type: 'updateFile',+ value: {+ abortController,+ error: undefined,+ errorCode: undefined,+ status: 'pending',+ uploadState: undefined,+ },+ });++ try {+ const result = await this.#get().uploadWithProgress({+ abortController,+ file: item.file,+ knowledgeBaseId: item.knowledgeBaseId,+ onStatusUpdate: dispatchDockFileList,+ parentId: item.parentId,+ uploadId: id,+ visibility: item.visibility,+ });++ if (!result) return;+ await this.#get().refreshFileList({ revalidateResources: true });++ if (!isChunkingUnsupported(item.file.type)) {+ await this.#get().parseFilesToChunks([result.id], { skipExist: false });+ }+ } catch (error) {+ console.error(error);+ dispatchDockFileList({+ id,+ type: 'updateFile',+ value: { error: t('upload.uploadFailed', { ns: 'error' }), status: 'error' },+ });+ }+ };+dispatchDockFileList = (payload: UploadFileListDispatch): void => {const nextValue = uploadFileListReducer(this.#get().dockUploadFileList, payload);if (nextValue === this.#get().dockUploadFileList) return;@@ -299,7 +344,10 @@ export class FileManageActionImpl {abortController,file,id: `upload_${generateUploadId()}`,+ knowledgeBaseId,+ parentId,status: 'pending' as const,+ visibility,};});@@ -533,10 +581,13 @@ export class FileManageActionImpl {const sortedFolderPaths = topologicalSortFolders(folders);// Show toast notification if there are folders to create- const loadingToast =- sortedFolderPaths.length > 0- ? toast.loading(t('header.actions.uploadFolder.creatingFolders', { ns: 'file' }))- : undefined;+ let creatingFoldersToast: ToastInstance | undefined;+ if (sortedFolderPaths.length > 0) {+ creatingFoldersToast = toast.loading({+ duration: Infinity, // Don't auto-dismiss+ title: t('header.actions.uploadFolder.creatingFolders', { ns: 'file' }),+ });+ }try {// Map to store created folder IDs: relative path -> folder ID@@ -589,7 +640,7 @@ export class FileManageActionImpl {}// Dismiss the toast after folders are created- loadingToast?.close();+ creatingFoldersToast?.close();// Refresh file list to show the new foldersawait this.#get().refreshFileList();@@ -625,10 +676,12 @@ export class FileManageActionImpl {// 7. Add all files to dockdispatchDockFileList({atStart: true,- files: uploadItems.map(({ abortController, file, id }) => ({+ files: uploadItems.map(({ abortController, file, id, parentId }) => ({abortController,file,id,+ knowledgeBaseId,+ parentId,status: 'pending' as const,})),type: 'addFiles',@@ -691,7 +744,7 @@ export class FileManageActionImpl {}} catch (error) {// Dismiss toast on error- loadingToast?.close();+ creatingFoldersToast?.close();throw error;}};diff --git a/src/store/file/slices/fileManager/selectors.test.ts b/src/store/file/slices/fileManager/selectors.test.tsindex 8b6fa124a7c..38f79dbe928 100644--- a/src/store/file/slices/fileManager/selectors.test.ts+++ b/src/store/file/slices/fileManager/selectors.test.ts@@ -5,6 +5,43 @@ import { initialState } from '@/store/file/initialState';import { fileManagerSelectors, getChunkTargetId } from './selectors';describe('fileManagerSelectors', () => {+ describe('overviewUploadingStatus', () => {+ it('keeps failed uploads in the error state instead of treating them as completed', () => {+ const state = {+ ...initialState,+ dockUploadFileList: [+ {+ file: { name: 'failed.pdf' },+ id: 'failed-upload',+ status: 'error',+ },+ ],+ } as any;++ expect(fileManagerSelectors.overviewUploadingStatus(state)).toBe('error');+ });++ it('reports active work while another upload is already in error', () => {+ const state = {+ ...initialState,+ dockUploadFileList: [+ {+ file: { name: 'failed.pdf' },+ id: 'failed-upload',+ status: 'error',+ },+ {+ file: { name: 'active.pdf' },+ id: 'active-upload',+ status: 'uploading',+ },+ ],+ } as any;++ expect(fileManagerSelectors.overviewUploadingStatus(state)).toBe('uploading');+ });+ });+describe('getFileByChunkTargetId', () => {it('should find resources by linked file id when they are not in fileList', () => {const state = {diff --git a/src/store/file/slices/fileManager/selectors.ts b/src/store/file/slices/fileManager/selectors.tsindex 3fcf49f9789..9a9f68ba68c 100644--- a/src/store/file/slices/fileManager/selectors.ts+++ b/src/store/file/slices/fileManager/selectors.ts@@ -20,8 +20,7 @@ const getFileByChunkTargetId = (id?: string | null) => (s: FilesStoreState) => {(s.resourceMap.get(id) as FileListItem | undefined) ??([...s.resourceMap.values()].find((item) => item.fileId === id) as FileListItem | undefined) ??(s.resourceList.find((item) => item.id === id || item.fileId === id) as- | FileListItem- | undefined)+ FileListItem | undefined));};@@ -44,6 +43,8 @@ const overviewUploadingStatus = (s: FilesStoreState): FileUploadStatus => {return 'uploading';}+ if (s.dockUploadFileList.some((file) => file.status === 'error')) return 'error';+return 'success';};diff --git a/src/store/file/slices/upload/action.test.ts b/src/store/file/slices/upload/action.test.tsindex 20d56e65117..d07f8b32574 100644--- a/src/store/file/slices/upload/action.test.ts+++ b/src/store/file/slices/upload/action.test.ts@@ -3,7 +3,6 @@ import { act, renderHook } from '@testing-library/react';import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { handleFileUploadError } from '@/business/client/handleFileUploadError';-import { notification } from '@/components/AntdStaticMethods';import { fileService } from '@/services/file';import { uploadService } from '@/services/upload';import { getImageDimensions } from '@/utils/client/imageDimensions';@@ -13,12 +12,6 @@ import { useFileStore as useStore } from '../../store';vi.mock('zustand/traditional');// Mock necessary modules-vi.mock('@/components/AntdStaticMethods', () => ({- notification: {- error: vi.fn(),- },-}));-vi.mock('@lobehub/ui/base-ui', () => ({toast: { info: vi.fn() },}));@@ -192,7 +185,6 @@ describe('FileUploadAction', () => {expect(uploadResult).toBeUndefined();expect(handleFileUploadError).toHaveBeenCalledWith(uploadError);- expect(notification.error).not.toHaveBeenCalled();});});@@ -859,7 +851,10 @@ describe('FileUploadAction', () => {vi.spyOn(fileService, 'checkFileHash').mockResolvedValue(mockCheckResult);vi.spyOn(uploadService, 'uploadFileToS3').mockRejectedValue(uploadError);vi.mocked(handleFileUploadError).mockImplementation((_error, options) => {- options?.onUploadBlocked?.();+ options?.onUploadBlocked?.({+ code: 'monthly_cap_reached',+ description: 'Storage cap reached',+ });return true;});@@ -873,13 +868,17 @@ describe('FileUploadAction', () => {expect(result).toBeUndefined();expect(onStatusUpdate).toHaveBeenCalledWith({id: mockFile.name,- type: 'removeFile',+ type: 'updateFile',+ value: {+ error: 'Storage cap reached',+ errorCode: 'monthly_cap_reached',+ status: 'error',+ },});expect(handleFileUploadError).toHaveBeenCalledWith(uploadError,expect.objectContaining({ onUploadBlocked: expect.any(Function) }),);- expect(notification.error).not.toHaveBeenCalled();});it('should handle checkFileHash errors', async () => {diff --git a/src/store/file/slices/upload/action.ts b/src/store/file/slices/upload/action.tsindex 25b5e45df42..b8d49b5e9b3 100644--- a/src/store/file/slices/upload/action.ts+++ b/src/store/file/slices/upload/action.ts@@ -239,7 +239,12 @@ export class FileUploadActionImpl {} catch (error) {if (handleFileUploadError(error, {- onUploadBlocked: () => onStatusUpdate?.({ id: statusId, type: 'removeFile' }),+ onUploadBlocked: ({ code, description }) =>+ onStatusUpdate?.({+ id: statusId,+ type: 'updateFile',+ value: { error: description, errorCode: code, status: 'error' },+ }),})) {return;diff --git a/src/store/library/slices/ragEval/actions/dataset.ts b/src/store/library/slices/ragEval/actions/dataset.tsindex 297df8d1173..d37fd649e77 100644--- a/src/store/library/slices/ragEval/actions/dataset.ts+++ b/src/store/library/slices/ragEval/actions/dataset.ts@@ -3,11 +3,8 @@ import {type EvalDatasetRecord,type RAGEvalDataSetItem,} from '@lobechat/types';-import { insertEvalDatasetRecordSchema } from '@lobechat/types';-import i18n from 'i18next';import { type SWRResponse } from 'swr';-import { notification } from '@/components/AntdStaticMethods';import { mutate, useClientDataSWR } from '@/libs/swr';import { ragEvalKeys } from '@/libs/swr/keys';import { ragEvalService } from '@/services/ragEval';@@ -36,34 +33,6 @@ export class RAGEvalDatasetActionImpl {await this.#get().refreshDatasetList();};- importDataset = async (file: File, datasetId: string): Promise<void> => {- if (!datasetId) return;- const fileType = file.name.split('.').pop();-- if (fileType === 'jsonl') {- // jsonl file needs to be split into individual entries, then validated one by one- const jsonl = await file.text();- const { default: JSONL } = await import('jsonl-parse-stringify');-- try {- const items = JSONL.parse(jsonl);-- // check if the items are valid- insertEvalDatasetRecordSchema.array().parse(items);-- // if valid, send to backend- await ragEvalService.importDatasetRecords(datasetId, file);- } catch (e) {- notification.error({- description: (e as Error).message,- message: i18n.t('errors.invalidFileFormat', { ns: 'common' }),- });- }- }-- await this.#get().refreshDatasetList();- };-refreshDatasetList = async (): Promise<void> => {await mutate(ragEvalKeys.datasetList());};diff --git a/src/store/tool/selectors/tool.test.ts b/src/store/tool/selectors/tool.test.tsindex 05437e932ce..2d9708c8a2b 100644--- a/src/store/tool/selectors/tool.test.ts+++ b/src/store/tool/selectors/tool.test.ts@@ -74,6 +74,7 @@ const mockState = {'plugin-1': false,'plugin-2': true,},+ pluginInstallErrors: {},uninstalledBuiltinTools: [],} as ToolStoreState;@@ -93,6 +94,21 @@ describe('toolSelectors', () => {const result = toolSelectors.getManifestLoadingStatus('plugin-1')(mockState);expect(result).toBe('success');});++ it('should return "error" when a refresh failed even if an old manifest remains', () => {+ const state = {+ ...mockState,+ pluginInstallErrors: {+ 'plugin-1': { cause: 'Connection refused', message: 'fetchError' },+ },+ } as unknown as ToolStoreState;++ expect(toolSelectors.getManifestLoadingStatus('plugin-1')(state)).toBe('error');+ expect(toolSelectors.getPluginInstallError('plugin-1')(state)).toEqual({+ cause: 'Connection refused',+ message: 'fetchError',+ });+ });});describe('metaList and getMetaById', () => {diff --git a/src/store/tool/selectors/tool.ts b/src/store/tool/selectors/tool.tsindex b3eb3b31a09..0fd5b41381f 100644--- a/src/store/tool/selectors/tool.ts+++ b/src/store/tool/selectors/tool.ts@@ -67,11 +67,15 @@ const getManifestLoadingStatus = (id: string) => (s: ToolStoreState) => {if (s.pluginInstallLoading[id]) return 'loading';+ if (s.pluginInstallErrors[id]) return 'error';+if (!manifest) return 'error';if (!!manifest) return 'success';};+const getPluginInstallError = (id: string) => (s: ToolStoreState) => s.pluginInstallErrors[id];+const isToolHasUI = (id: string) => (s: ToolStoreState) => {const manifest = getManifestById(id)(s);if (!manifest) return false;@@ -192,6 +196,7 @@ export const toolSelectors = {discoverableMetaList,getManifestById,getManifestLoadingStatus,+ getPluginInstallError,getMetaById,getRenderDisplayControl,isToolHasUI,diff --git a/src/store/tool/slices/customPlugin/action.test.ts b/src/store/tool/slices/customPlugin/action.test.tsindex 85adbeba87a..c8802bd8c85 100644--- a/src/store/tool/slices/customPlugin/action.test.ts+++ b/src/store/tool/slices/customPlugin/action.test.ts@@ -1,6 +1,7 @@import { act, renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { mcpService } from '@/services/mcp';import { pluginService } from '@/services/plugin';import { type LobeToolCustomPlugin } from '@/types/tool/plugin';@@ -20,6 +21,16 @@ vi.mock('@/services/plugin', () => ({},}));+vi.mock('@/services/mcp', () => ({+ mcpService: {+ getStreamableMcpServerManifest: vi.fn(),+ },+}));++vi.mock('i18next', () => ({+ t: (_key: string, options?: { error?: string }) => options?.error || 'Plugin refresh failed',+}));+describe('useToolStore:customPlugin', () => {describe('deleteCustomPlugin', () => {it('should delete custom plugin and related settings', async () => {@@ -106,6 +117,41 @@ describe('useToolStore:customPlugin', () => {});});+ describe('reinstallCustomPlugin', () => {+ it('retains the connection failure on the plugin row', async () => {+ const pluginId = 'broken-plugin';+ vi.mocked(mcpService.getStreamableMcpServerManifest).mockRejectedValueOnce({+ cause: 'Connection refused',+ message: 'connectionError',+ });++ act(() => {+ useToolStore.setState({+ installedPlugins: [+ {+ customParams: { mcp: { url: 'https://mcp.example.com' } },+ identifier: pluginId,+ type: 'customPlugin',+ } as LobeToolCustomPlugin,+ ],+ pluginInstallErrors: {},+ });+ });++ const { result } = renderHook(() => useToolStore());++ await act(async () => {+ await result.current.reinstallCustomPlugin(pluginId);+ });++ expect(result.current.pluginInstallErrors[pluginId]).toEqual({+ cause: 'Connection refused',+ message: 'connectionError',+ });+ expect(result.current.pluginInstallLoading[pluginId]).toBe(false);+ });+ });+describe('updateNewCustomPlugin', () => {it('should update the newCustomPlugin state with the provided values', () => {const initialNewCustomPlugin = {diff --git a/src/store/tool/slices/customPlugin/action.ts b/src/store/tool/slices/customPlugin/action.tsindex 76216e0f741..69fb7510f9e 100644--- a/src/store/tool/slices/customPlugin/action.ts+++ b/src/store/tool/slices/customPlugin/action.ts@@ -1,10 +1,7 @@import { merge } from 'es-toolkit/compat';-import { t } from 'i18next';-import { notification } from '@/components/AntdStaticMethods';import { mcpService } from '@/services/mcp';import { pluginService } from '@/services/plugin';-import { pluginHelpers } from '@/store/tool/helpers';import { type StoreSetter } from '@/store/types';import { type LobeToolCustomPlugin, type PluginInstallError } from '@/types/tool/plugin';import { setNamespace } from '@/utils/storeDebug';@@ -40,12 +37,13 @@ export class CustomPluginActionImpl {const plugin = pluginSelectors.getCustomPluginById(id)(this.#get());if (!plugin) return;- const { refreshPlugins, updateInstallLoadingState } = this.#get();+ const { refreshPlugins, updateInstallError, updateInstallLoadingState } = this.#get();const url = plugin.customParams?.mcp?.url;if (!plugin.customParams?.mcp || !url) return;try {+ updateInstallError(id, undefined);updateInstallLoadingState(id, true);const manifest = await mcpService.getStreamableMcpServerManifest({auth: plugin.customParams.mcp.auth,@@ -57,23 +55,14 @@ export class CustomPluginActionImpl {},url,});- updateInstallLoadingState(id, false);-await pluginService.updatePluginManifest(id, manifest);await refreshPlugins();} catch (error) {- updateInstallLoadingState(id, false);-console.error(error);const err = error as PluginInstallError;-- const meta = pluginSelectors.getPluginMetaById(id)(this.#get());- const name = pluginHelpers.getPluginTitle(meta);-- notification.error({- description: t(`error.${err.message}`, { error: err.cause, ns: 'plugin' }),- message: t('error.reinstallError', { name, ns: 'plugin' }),- });+ updateInstallError(id, { cause: err.cause, message: err.message });+ } finally {+ updateInstallLoadingState(id, false);}};diff --git a/src/store/tool/slices/plugin/action.ts b/src/store/tool/slices/plugin/action.tsindex 653814fa817..6a880cb8012 100644--- a/src/store/tool/slices/plugin/action.ts+++ b/src/store/tool/slices/plugin/action.ts@@ -7,6 +7,7 @@ import { useClientDataSWR } from '@/libs/swr';import { toolKeys } from '@/libs/swr/keys';import { pluginService } from '@/services/plugin';import { type StoreSetter } from '@/store/types';+import { type PluginInstallError } from '@/types/tool/plugin';import { merge } from '@/utils/merge';import { type ToolStore } from '../../store';@@ -50,6 +51,14 @@ export class PluginActionImpl {);};+ updateInstallError = (id: string, error: PluginInstallError | undefined): void => {+ this.#set(+ { pluginInstallErrors: { ...this.#get().pluginInstallErrors, [id]: error } },+ false,+ 'updateInstallError',+ );+ };+updateInstallMcpPlugin = async (id: string, value: any): Promise<void> => {const installedPlugin = pluginSelectors.getInstalledPluginById(id)(this.#get());diff --git a/src/store/tool/slices/plugin/initialState.ts b/src/store/tool/slices/plugin/initialState.tsindex 6190de8e0cc..131f2dedbfd 100644--- a/src/store/tool/slices/plugin/initialState.ts+++ b/src/store/tool/slices/plugin/initialState.ts@@ -1,10 +1,13 @@import { type LobeTool } from '@lobechat/types';+import { type PluginInstallError } from '@/types/tool/plugin';+export type PluginsSettings = Record<string, any>;export interface PluginState {installedPlugins: LobeTool[];loadingInstallPlugins: boolean;+ pluginInstallErrors: Record<string, PluginInstallError | undefined>;pluginInstallLoading: Record<string, boolean | undefined>;pluginsSettings: PluginsSettings;updatePluginSettingsSignal?: AbortController;@@ -13,6 +16,7 @@ export interface PluginState {export const initialPluginState: PluginState = {installedPlugins: [],loadingInstallPlugins: true,+ pluginInstallErrors: {},pluginInstallLoading: {},pluginsSettings: {},};diff --git a/src/store/user/slices/auth/action.test.ts b/src/store/user/slices/auth/action.test.tsindex a9d93a60079..db8c265fd92 100644--- a/src/store/user/slices/auth/action.test.ts+++ b/src/store/user/slices/auth/action.test.ts@@ -91,6 +91,34 @@ describe('createAuthSlice', () => {});});+ it('should explain an expired session on the signin page', async () => {+ const originalLocation = window.location;+ Object.defineProperty(window, 'location', {+ configurable: true,+ value: {+ ...originalLocation,+ href: '',+ pathname: '/chat',+ toString: () => 'http://localhost/chat',+ },+ writable: true,+ });++ const { result } = renderHook(() => useUserStore());++ await act(async () => {+ await result.current.openLogin('sessionExpired');+ });++ expect(window.location.href).toContain('reason=sessionExpired');++ Object.defineProperty(window, 'location', {+ configurable: true,+ value: originalLocation,+ writable: true,+ });+ });+it('should not redirect when already on signin page', async () => {const originalLocation = window.location;Object.defineProperty(window, 'location', {diff --git a/src/store/user/slices/auth/action.ts b/src/store/user/slices/auth/action.tsindex c58a1f5cfec..60263cf7dbd 100644--- a/src/store/user/slices/auth/action.ts+++ b/src/store/user/slices/auth/action.ts@@ -60,7 +60,7 @@ export class UserAuthActionImpl {}};- logout = async (): Promise<void> => {+ logout = async (options?: { redirectTo?: string }): Promise<void> => {// Clear the OIDC Provider session for the current browser *before*// destroying the better-auth session. This prevents a stale OIDC session// from silently issuing tokens for the old account after the user signs@@ -80,13 +80,13 @@ export class UserAuthActionImpl {clearActiveScopeKey();// Use window.location.href to trigger a full page reload// This ensures all client-side state (React, Zustand, cache) is cleared- window.location.href = '/signin';+ window.location.href = options?.redirectTo || '/signin';},},});};- openLogin = async (): Promise<void> => {+ openLogin = async (reason?: 'sessionExpired'): Promise<void> => {// Skip if already on a login page (/signin, /signup)const pathname = location.pathname;if (pathname.startsWith('/signin') || pathname.startsWith('/signup')) {@@ -94,7 +94,9 @@ export class UserAuthActionImpl {}const currentUrl = location.toString();- window.location.href = `/signin?callbackUrl=${encodeURIComponent(currentUrl)}`;+ const params = new URLSearchParams({ callbackUrl: currentUrl });+ if (reason) params.set('reason', reason);+ window.location.href = `/signin?${params.toString()}`;};refreshAuthProviders = async (): Promise<void> => {diff --git a/src/store/utils/saveToast.ts b/src/store/utils/saveToast.tsindex 6caaddc05b2..589cb01ab88 100644--- a/src/store/utils/saveToast.ts+++ b/src/store/utils/saveToast.ts@@ -4,6 +4,11 @@ import { t } from 'i18next';import { normalizeAsyncError } from '@/libs/swr/normalizeError';export interface SaveToastOptions {+ /**+ * Suppress the server-supplied cause. Only for failures whose raw message is+ * an implementation detail the user can do nothing with.+ */+ hideCause?: boolean;/*** Retry handler. A Retry action is shown only when the failure is retryable —* `normalizeAsyncError` marks auth / permission failures (401 / 403, or an@@ -20,16 +25,23 @@ export interface SaveToastOptions {* read-side `AsyncError`. Works inside zustand class actions (uses the imperative* base-ui `toast` + i18next `t`, no React context). Pass it as `runMutation`'s* `onError` so every migrated mutation surfaces failures the same way.+ *+ * The title says what failed, the description says why: a payment declined for a+ * specific reason is only actionable if that reason survives to the user, so the+ * normalized `rawMessage` is shown unless a call site opts out.*/export const saveToast = (error: unknown, options: SaveToastOptions = {}) => {- const { retry, title } = options;- const { retryable } = normalizeAsyncError(error);+ const { hideCause, retry, title } = options;+ const { rawMessage, retryable } = normalizeAsyncError(error);+ const resolvedTitle = title ?? t('saveState.saveFailed', { ns: 'error' });+ const cause = hideCause || rawMessage === resolvedTitle ? undefined : rawMessage;return toast.error({actions:retry && retryable? [{ label: t('saveState.retry', { ns: 'error' }), onClick: retry, variant: 'primary' }]: undefined,- title: title ?? t('saveState.saveFailed', { ns: 'error' }),+ description: cause,+ title: resolvedTitle,});};