Skip to content

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

fix: slove when desktop 401 not pop up many message (#9789)

Shinji-Li3ec394d77ada
diff --git a/src/layout/GlobalProvider/StoreInitialization.tsx b/src/layout/GlobalProvider/StoreInitialization.tsx
index 432422ae5ad..790eb00aa76 100644
--- a/src/layout/GlobalProvider/StoreInitialization.tsx
+++ b/src/layout/GlobalProvider/StoreInitialization.tsx
@@ -50,9 +50,12 @@ const StoreInitialization = memo(() => {
* The store function of `isLogin` will both consider the values of `enableAuth` and `isSignedIn`.
* But during initialization, the value of `enableAuth` might be incorrect cause of the async fetch.
* So we need to use `isSignedIn` only to determine whether request for the default agent config and user state.
+ *
+ * IMPORTANT: Explicitly convert to boolean to avoid passing null/undefined downstream,
+ * which would cause unnecessary API requests with invalid login state.
*/
const isDBInited = useGlobalStore(systemStatusSelectors.isDBInited);
- const isLoginOnInit = isDBInited && (enableNextAuth ? isSignedIn : isLogin);
+ const isLoginOnInit = isDBInited ? Boolean(enableNextAuth ? isSignedIn : isLogin) : false;
// init inbox agent and default agent config
useInitAgentStore(isLoginOnInit, serverConfig.defaultAgent?.config);
diff --git a/src/libs/swr/index.ts b/src/libs/swr/index.ts
index b1f092f3e5a..6a33b2e7eef 100644
--- a/src/libs/swr/index.ts
+++ b/src/libs/swr/index.ts
@@ -34,6 +34,19 @@ export const useClientDataSWR: SWRHook = (key, fetch, config) =>
? 1500
: // web 300s
5 * 60 * 1000,
+ // Custom error retry logic: don't retry on 401 errors
+ onErrorRetry: (error: any, key: any, config: any, revalidate: any, { retryCount }: any) => {
+ // Check if error is marked as non-retryable (e.g., 401 authentication errors)
+ if (error?.meta?.shouldRetry === false) {
+ return;
+ }
+ // For other errors, use default SWR retry behavior
+ // Default: exponential backoff, max 5 retries
+ if (retryCount >= 5) return;
+ const exponentialDelay = 1000 * Math.pow(2, Math.min(retryCount, 10));
+ const timeout = Math.min(exponentialDelay, 30_000);
+ setTimeout(() => revalidate({ retryCount }), timeout);
+ },
refreshWhenOffline: false,
revalidateOnFocus: true,
revalidateOnReconnect: true,
diff --git a/src/libs/trpc/client/lambda.ts b/src/libs/trpc/client/lambda.ts
index 8a9f1181c0a..249151fe062 100644
--- a/src/libs/trpc/client/lambda.ts
+++ b/src/libs/trpc/client/lambda.ts
@@ -10,6 +10,10 @@ import type { LambdaRouter } from '@/server/routers/lambda';
const log = debug('lobe-image:lambda-client');
+// 401 error debouncing: prevent showing multiple login notifications in short time
+let last401Time = 0;
+const MIN_401_INTERVAL = 5000; // 5 seconds
+
// handle error
const errorHandlingLink: TRPCLink<LambdaRouter> = () => {
return ({ op, next }) =>
@@ -18,10 +22,9 @@ const errorHandlingLink: TRPCLink<LambdaRouter> = () => {
complete: () => observer.complete(),
error: async (err) => {
const showError = (op.context?.showNotification as boolean) ?? true;
+ const status = err.data?.httpStatus as number;
if (showError) {
- const status = err.data?.httpStatus as number;
-
const { loginRequired } = await import('@/components/Error/loginRequiredNotification');
const { fetchErrorNotification } = await import(
'@/components/Error/fetchErrorNotification'
@@ -29,7 +32,14 @@ const errorHandlingLink: TRPCLink<LambdaRouter> = () => {
switch (status) {
case 401: {
- loginRequired.redirect();
+ // Debounce: only show login notification once every 5 seconds
+ const now = Date.now();
+ if (now - last401Time > MIN_401_INTERVAL) {
+ last401Time = now;
+ loginRequired.redirect();
+ }
+ // Mark error as non-retryable to prevent SWR infinite retry loop
+ err.meta = { ...err.meta, shouldRetry: false };
break;
}
diff --git a/src/store/agent/slices/chat/action.ts b/src/store/agent/slices/chat/action.ts
index a7e7f0d525b..a1048dd0205 100644
--- a/src/store/agent/slices/chat/action.ts
+++ b/src/store/agent/slices/chat/action.ts
@@ -160,7 +160,8 @@ export const createChatSlice: StateCreator<
},
useFetchAgentConfig: (isLogin, sessionId) =>
useClientDataSWR<LobeAgentConfig>(
- isLogin && !sessionId.startsWith('cg_')
+ // Only fetch when login status is explicitly true (not null/undefined)
+ isLogin === true && !sessionId.startsWith('cg_')
? ([FETCH_AGENT_CONFIG_KEY, sessionId] as const)
: null,
([, id]: readonly [string, string]) => sessionService.getSessionConfig(id),
@@ -192,7 +193,8 @@ export const createChatSlice: StateCreator<
useInitInboxAgentStore: (isLogin, defaultAgentConfig) =>
useOnlyFetchOnceSWR<PartialDeep<LobeAgentConfig>>(
- !!isLogin ? 'fetchInboxAgentConfig' : null,
+ // Only fetch when login status is explicitly true (not null/undefined/false)
+ isLogin === true ? 'fetchInboxAgentConfig' : null,
() => sessionService.getSessionConfig(INBOX_SESSION_ID),
{
onSuccess: (data) => {
diff --git a/src/store/aiInfra/slices/aiProvider/action.ts b/src/store/aiInfra/slices/aiProvider/action.ts
index e1faad6a454..304bb4d5071 100644
--- a/src/store/aiInfra/slices/aiProvider/action.ts
+++ b/src/store/aiInfra/slices/aiProvider/action.ts
@@ -237,10 +237,12 @@ export const createAiProviderSlice: StateCreator<
useFetchAiProviderRuntimeState: (isLogin) => {
const isAuthLoaded = authSelectors.isLoaded(useUserStore.getState());
+ // Only fetch when auth is loaded and login status is explicitly defined (true or false)
+ // Prevents unnecessary requests when login state is null/undefined
+ const shouldFetch =
+ isAuthLoaded && !isDeprecatedEdition && isLogin !== null && isLogin !== undefined;
return useClientDataSWR<AiProviderRuntimeStateWithBuiltinModels | undefined>(
- isAuthLoaded && !isDeprecatedEdition
- ? [AiProviderSwrKey.fetchAiProviderRuntimeState, isLogin]
- : null,
+ shouldFetch ? [AiProviderSwrKey.fetchAiProviderRuntimeState, isLogin] : null,
async ([, isLogin]) => {
const [{ LOBE_DEFAULT_MODEL_LIST: builtinAiModelList }, { DEFAULT_MODEL_PROVIDER_LIST }] =
await Promise.all([import('model-bank'), import('@/config/modelProviders')]);