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(skill-store): stop a rate-limited skill list from self-sustaining (#17955)

LiJian82d0fccace91
diff --git a/apps/server/src/routers/lambda/market/skill.test.ts b/apps/server/src/routers/lambda/market/skill.test.ts
index 47259aeb4ac..d4eb099faed 100644
--- a/apps/server/src/routers/lambda/market/skill.test.ts
+++ b/apps/server/src/routers/lambda/market/skill.test.ts
@@ -1,4 +1,6 @@
// @vitest-environment node
+import { MarketAPIError } from '@lobehub/market-sdk';
+import { TRPCError } from '@trpc/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const {
@@ -177,3 +179,77 @@ describe('skillRouter.getSkillRatingDistribution', () => {
).rejects.toThrow('Failed to fetch skill rating distribution');
});
});
+
+describe('skillRouter.getSkillList error mapping', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ /**
+ * Collapsing an upstream 429 into a blanket 500 is what made the skill store
+ * fail on open: the client could not tell a throttle from an outage, so SWR
+ * retried on a 1s/2s/4s/8s/16s backoff and every retry landed back inside the
+ * rate-limit window, keeping the bucket empty.
+ */
+ it('surfaces an upstream rate limit as TOO_MANY_REQUESTS, not a blanket 500', async () => {
+ mockSearchSkill.mockRejectedValue(
+ new MarketAPIError(429, 'Too Many Requests', {
+ error: 'Too many requests. Please try again later.',
+ }),
+ );
+ const caller = await createCaller();
+
+ await expect(caller.getSkillList({ page: 1 })).rejects.toMatchObject({
+ code: 'TOO_MANY_REQUESTS',
+ });
+ });
+
+ it.each([
+ [400, 'BAD_REQUEST'],
+ [403, 'FORBIDDEN'],
+ [404, 'NOT_FOUND'],
+ ])('maps upstream %i to %s', async (status, code) => {
+ mockSearchSkill.mockRejectedValue(new MarketAPIError(status, 'nope', undefined));
+ const caller = await createCaller();
+
+ await expect(caller.getSkillList({ page: 1 })).rejects.toMatchObject({ code });
+ });
+
+ /**
+ * `UNAUTHORIZED` drives re-authentication UI: `createResponseMeta` tags it
+ * with `X-Auth-Required` (unless it carries the Market sentinel message) and
+ * the desktop proxy opens the LobeHub re-login prompt on that header. These
+ * are `publicProcedure`s authenticated by the server's trusted-client token,
+ * so an upstream 401 is our misconfiguration — it must never ask the user to
+ * sign in again.
+ */
+ it('never maps an upstream 401 onto the app re-auth path', async () => {
+ mockSearchSkill.mockRejectedValue(new MarketAPIError(401, 'invalid_token', undefined));
+ const caller = await createCaller();
+
+ const error = await caller.getSkillList({ page: 1 }).catch((e) => e);
+
+ expect(error.code).toBe('INTERNAL_SERVER_ERROR');
+ expect(error.code).not.toBe('UNAUTHORIZED');
+ });
+
+ it('falls back to INTERNAL_SERVER_ERROR for unmapped upstream statuses', async () => {
+ mockSearchSkill.mockRejectedValue(new MarketAPIError(503, 'Service Unavailable', undefined));
+ const caller = await createCaller();
+
+ await expect(caller.getSkillList({ page: 1 })).rejects.toMatchObject({
+ code: 'INTERNAL_SERVER_ERROR',
+ });
+ });
+
+ it('wraps non-Market failures into an internal server error', async () => {
+ mockSearchSkill.mockRejectedValue(new Error('boom'));
+ const caller = await createCaller();
+
+ const error = await caller.getSkillList({ page: 1 }).catch((e) => e);
+
+ expect(error).toBeInstanceOf(TRPCError);
+ expect(error.code).toBe('INTERNAL_SERVER_ERROR');
+ expect(error.message).toBe('Failed to fetch skill list');
+ });
+});
diff --git a/apps/server/src/routers/lambda/market/skill.ts b/apps/server/src/routers/lambda/market/skill.ts
index 1925f7726a7..8fd626303f1 100644
--- a/apps/server/src/routers/lambda/market/skill.ts
+++ b/apps/server/src/routers/lambda/market/skill.ts
@@ -1,3 +1,4 @@
+import { MarketAPIError } from '@lobehub/market-sdk';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
import { z } from 'zod';
@@ -9,6 +10,51 @@ import { SkillSorts } from '@/types/discover';
const log = debug('lambda-router:market:skill');
+/**
+ * Note the deliberate absence of `401`.
+ *
+ * `UNAUTHORIZED` is not an inert status code here — it drives re-authentication
+ * UI. `createResponseMeta` tags any `UNAUTHORIZED` whose message isn't the
+ * `MARKET_AUTH_REQUIRED_MESSAGE` sentinel with `X-Auth-Required`, and the
+ * desktop proxy opens the LobeHub re-login prompt on that header. Mapping an
+ * upstream 401 through would therefore ask the user to re-sign into LobeHub
+ * because *Market* rejected a credential.
+ *
+ * Routing it to the Market sentinel instead would be just as wrong for this
+ * router: these are `publicProcedure`s with no `requireMarketAuth`, authenticated
+ * by the server's trusted-client token. A 401 here means that server credential
+ * is broken — a misconfiguration the user cannot fix by signing in anywhere. So
+ * it stays a 500, which is what it is: our problem, not theirs.
+ */
+const MARKET_STATUS_TO_TRPC_CODE: Record<number, TRPCError['code']> = {
+ 400: 'BAD_REQUEST',
+ 403: 'FORBIDDEN',
+ 404: 'NOT_FOUND',
+ 429: 'TOO_MANY_REQUESTS',
+};
+
+/**
+ * Preserve the upstream Market status instead of collapsing everything into a
+ * blanket 500.
+ *
+ * This matters most for `429`: Market rate limits these endpoints, and a client
+ * that only sees `INTERNAL_SERVER_ERROR` cannot tell a transient throttle from a
+ * real outage — so it retries with exponential backoff, and those retries land
+ * inside the same rate-limit window and keep the bucket empty. Surfacing
+ * `TOO_MANY_REQUESTS` lets the SWR retry gate stand down (see `useClientDataSWR`)
+ * and lets the UI say something true.
+ */
+function mapMarketError(error: unknown, fallbackMessage: string): TRPCError {
+ if (error instanceof MarketAPIError) {
+ return new TRPCError({
+ cause: error,
+ code: MARKET_STATUS_TO_TRPC_CODE[error.status] ?? 'INTERNAL_SERVER_ERROR',
+ message: error.message || fallbackMessage,
+ });
+ }
+ return new TRPCError({ cause: error, code: 'INTERNAL_SERVER_ERROR', message: fallbackMessage });
+}
+
// Public procedure with optional user info for trusted client token
const marketProcedure = publicProcedure
.use(serverDatabase)
@@ -41,10 +87,7 @@ export const skillRouter = router({
return await ctx.marketService.getSkillCategories();
} catch (error) {
log('Error fetching skill categories: %O', error);
- throw new TRPCError({
- code: 'INTERNAL_SERVER_ERROR',
- message: 'Failed to fetch skill categories',
- });
+ throw mapMarketError(error, 'Failed to fetch skill categories');
}
}),
@@ -66,10 +109,7 @@ export const skillRouter = router({
return await ctx.marketService.getSkillComments(identifier, params);
} catch (error) {
log('Error fetching skill comments: %O', error);
- throw new TRPCError({
- code: 'INTERNAL_SERVER_ERROR',
- message: 'Failed to fetch skill comments',
- });
+ throw mapMarketError(error, 'Failed to fetch skill comments');
}
}),
@@ -100,10 +140,7 @@ export const skillRouter = router({
};
} catch (error) {
log('Error fetching skill detail: %O', error);
- throw new TRPCError({
- code: 'INTERNAL_SERVER_ERROR',
- message: 'Failed to fetch skill detail',
- });
+ throw mapMarketError(error, 'Failed to fetch skill detail');
}
}),
@@ -128,10 +165,7 @@ export const skillRouter = router({
return await ctx.marketService.searchSkill(input ?? {});
} catch (error) {
log('Error fetching skill list: %O', error);
- throw new TRPCError({
- code: 'INTERNAL_SERVER_ERROR',
- message: 'Failed to fetch skill list',
- });
+ throw mapMarketError(error, 'Failed to fetch skill list');
}
}),
@@ -144,10 +178,7 @@ export const skillRouter = router({
return await ctx.marketService.getSkillRatingDistribution(input.identifier);
} catch (error) {
log('Error fetching skill rating distribution: %O', error);
- throw new TRPCError({
- code: 'INTERNAL_SERVER_ERROR',
- message: 'Failed to fetch skill rating distribution',
- });
+ throw mapMarketError(error, 'Failed to fetch skill rating distribution');
}
}),
});
diff --git a/apps/server/src/services/market/index.test.ts b/apps/server/src/services/market/index.test.ts
index d9d8bada55e..844f25f0fd0 100644
--- a/apps/server/src/services/market/index.test.ts
+++ b/apps/server/src/services/market/index.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { CacheRevalidate, CacheTag } from '@lobechat/types';
import { MarketSDK } from '@lobehub/market-sdk';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -753,3 +754,33 @@ describe('MarketService', () => {
});
});
});
+
+describe('MarketService.searchSkill', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ /**
+ * The skill store was the one browse surface hitting Market on every open and
+ * every page, so it alone went down when the upstream was throttled or a
+ * credential went stale — the MCP tab looked healthy through the same
+ * incidents only because it was served from this cache.
+ */
+ it('caches the catalogue like every other discover list', async () => {
+ const service = new MarketService();
+ const getSkillList = service.market.marketSkills.getSkillList as ReturnType<typeof vi.fn>;
+ getSkillList.mockResolvedValue({ currentPage: 1, items: [], totalPages: 1 });
+
+ await service.searchSkill({ page: 1, sort: 'installCount' });
+
+ expect(getSkillList).toHaveBeenCalledWith(
+ { page: 1, sort: 'installCount' },
+ expect.objectContaining({
+ next: expect.objectContaining({
+ revalidate: CacheRevalidate.List,
+ tags: expect.arrayContaining([CacheTag.Discover, CacheTag.Skills]),
+ }),
+ }),
+ );
+ });
+});
diff --git a/apps/server/src/services/market/index.ts b/apps/server/src/services/market/index.ts
index 090ed921710..98b34412daa 100644
--- a/apps/server/src/services/market/index.ts
+++ b/apps/server/src/services/market/index.ts
@@ -1,4 +1,5 @@
import { type LobeToolManifest } from '@lobechat/context-engine';
+import { CacheRevalidate, CacheTag } from '@lobechat/types';
import { MarketSDK, type OrgRef, orgRefToPathSegment } from '@lobehub/market-sdk';
import debug from 'debug';
import { type NextRequest } from 'next/server';
@@ -443,7 +444,18 @@ export class MarketService {
}) {
log('searchSkill: %O', params);
- const result = await this.market.marketSkills.getSkillList(params);
+ // Cache the catalogue the same way every other discover list is cached
+ // (see DiscoverService.getMcpList). Without this the skill store was the one
+ // browse surface that hit Market on every open and every page, which is why
+ // it — alone among the store's tabs — went down whenever the upstream was
+ // throttled or a credential went stale. The MCP tab looked healthy through
+ // the same incidents only because it was being served from this cache.
+ const result = await this.market.marketSkills.getSkillList(params, {
+ next: {
+ revalidate: CacheRevalidate.List,
+ tags: [CacheTag.Discover, CacheTag.Skills],
+ },
+ });
log('searchSkill response: %O', result);
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 0112b70306b..489036fb75a 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -1121,6 +1121,7 @@
"skillStore.empty": "Browse the Skill Store. Install one to get started, add more later.",
"skillStore.emptySearch": "No matching Skills",
"skillStore.networkError": "Network error, please try again",
+ "skillStore.rateLimited": "Too many requests just now. Please wait a moment and try again.",
"skillStore.search": "Search skills by name or keyword, press Enter to search…",
"skillStore.tabs.community": "Community",
"skillStore.tabs.custom": "Custom",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 4c53c06aa2b..3290af1dbd3 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -1121,6 +1121,7 @@
"skillStore.empty": "浏览技能商店。安装一个技能开始使用,之后可随时添加更多。",
"skillStore.emptySearch": "未找到匹配的技能",
"skillStore.networkError": "网络错误,请重试",
+ "skillStore.rateLimited": "刚才的请求有点频繁,请稍等片刻再试。",
"skillStore.search": "搜索技能名称或关键词,按回车键搜索…",
"skillStore.tabs.community": "社区",
"skillStore.tabs.custom": "自定义",
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index e0a19b9295c..7f98888f9af 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -1296,6 +1296,7 @@ export default {
'skillStore.empty': 'Browse the Skill Store. Install one to get started, add more later.',
'skillStore.emptySearch': 'No matching Skills',
'skillStore.networkError': 'Network error, please try again',
+ 'skillStore.rateLimited': 'Too many requests just now. Please wait a moment and try again.',
'skillStore.search': 'Search skills by name or keyword, press Enter to search…',
'skillStore.tabs.community': 'Community',
'skillStore.tabs.custom': 'Custom',
diff --git a/src/features/SkillStore/SkillList/MarketSkills/index.tsx b/src/features/SkillStore/SkillList/MarketSkills/index.tsx
index eb7f1ef63a0..60b65318ad4 100644
--- a/src/features/SkillStore/SkillList/MarketSkills/index.tsx
+++ b/src/features/SkillStore/SkillList/MarketSkills/index.tsx
@@ -1,6 +1,7 @@
'use client';
-import { Center, Icon, Text } from '@lobehub/ui';
+import { Center, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
import { uniqBy } from 'es-toolkit/compat';
import { ServerCrash } from 'lucide-react';
import { memo, useCallback, useEffect, useRef, useState } from 'react';
@@ -9,6 +10,7 @@ import { VirtuosoGrid } from 'react-virtuoso';
import { useClientDataSWR } from '@/libs/swr';
import { discoverKeys } from '@/libs/swr/keys';
+import { normalizeAsyncError } from '@/libs/swr/normalizeError';
import { discoverService } from '@/services/discover';
import { globalHelpers } from '@/store/global/helpers';
import { useToolStore } from '@/store/tool';
@@ -25,8 +27,20 @@ interface MarketSkillListProps {
keywords?: string;
}
+/**
+ * Collapse repeat mounts of the store into one upstream request.
+ *
+ * All three store tabs mount at once (they toggle with `display`, not
+ * conditional rendering), so this list fetches whenever the modal opens — even
+ * while the user is looking at another tab. The global `useClientDataSWR`
+ * default is `dedupingInterval: 0`, which is right for interactive data the user
+ * edits but wrong here: reopening the modal is not a request for fresher data,
+ * and Market rate limits this endpoint.
+ */
+const MARKET_SKILL_LIST_DEDUPING_INTERVAL = 60_000;
+
const MarketSkillList = memo<MarketSkillListProps>(({ keywords }) => {
- const { t } = useTranslation('setting');
+ const { t } = useTranslation(['setting', 'common']);
// Ensure agent skills are fetched so install status is available
const useFetchAgentSkills = useToolStore((s) => s.useFetchAgentSkills);
@@ -38,7 +52,7 @@ const MarketSkillList = memo<MarketSkillListProps>(({ keywords }) => {
const [totalPages, setTotalPages] = useState<number>();
const locale = globalHelpers.getCurrentLanguage();
- const { data, isLoading, error } = useClientDataSWR(
+ const { data, isLoading, error, mutate } = useClientDataSWR(
discoverKeys.skillStoreMarketSkills(locale, keywords || '', page),
() =>
discoverService.getSkillList({
@@ -47,7 +61,10 @@ const MarketSkillList = memo<MarketSkillListProps>(({ keywords }) => {
q: keywords || undefined,
sort: SkillSorts.InstallCount,
}),
- { revalidateOnFocus: false },
+ {
+ dedupingInterval: MARKET_SKILL_LIST_DEDUPING_INTERVAL,
+ revalidateOnFocus: false,
+ },
);
// Accumulate items across pages
@@ -74,18 +91,37 @@ const MarketSkillList = memo<MarketSkillListProps>(({ keywords }) => {
}, [keywords]);
const loadMore = useCallback(() => {
+ // Don't let the scroll observer walk into the next page while the current
+ // one is still failing — that turns a rate limit into a silent retry loop.
+ if (error) return;
if (totalPages === undefined || page < totalPages) {
setPage((p) => p + 1);
}
- }, [page, totalPages]);
+ }, [error, page, totalPages]);
+
+ const retry = useCallback(() => {
+ void mutate();
+ }, [mutate]);
+
+ // A rate limit is not a network error, and saying so sends the user off
+ // debugging their connection. Both are retryable, just not immediately.
+ const errorMessage =
+ normalizeAsyncError(error).status === 429
+ ? t('skillStore.rateLimited')
+ : t('skillStore.networkError');
if (isLoading && items.length === 0) return <Loading />;
- if (error) {
+ // Only take over the whole surface when there is nothing to show. Once pages
+ // have loaded, a failed *next* page must not wipe them.
+ if (error && items.length === 0) {
return (
<Center gap={12} padding={40}>
<Icon icon={ServerCrash} size={80} />
- <Text type={'secondary'}>{t('skillStore.networkError')}</Text>
+ <Text type={'secondary'}>{errorMessage}</Text>
+ <Button size={'small'} onClick={retry}>
+ {t('retry', { ns: 'common' })}
+ </Button>
</Center>
);
}
@@ -96,6 +132,15 @@ const MarketSkillList = memo<MarketSkillListProps>(({ keywords }) => {
const renderFooter = () => {
if (isLoading) return <VirtuosoLoading />;
+ if (error)
+ return (
+ <Flexbox horizontal align={'center'} gap={8} justify={'center'} padding={16}>
+ <Text type={'secondary'}>{errorMessage}</Text>
+ <Button size={'small'} onClick={retry}>
+ {t('retry', { ns: 'common' })}
+ </Button>
+ </Flexbox>
+ );
if (hasReachedEnd) return <WantMoreSkills />;
return <div style={{ height: 16 }} />;
};
diff --git a/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx b/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx
index 8b22b41f482..ae63d224199 100644
--- a/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx
+++ b/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx
@@ -2,7 +2,7 @@
import { toast } from '@lobehub/ui/base-ui';
import { type ReactNode } from 'react';
-import { createContext, use, useCallback, useEffect, useState } from 'react';
+import { createContext, use, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { mutate as globalMutate } from 'swr';
@@ -20,6 +20,7 @@ import MarketAuthConfirmModal from './MarketAuthConfirmModal';
import { MarketOIDC } from './oidc';
import ProfileSetupModal from './ProfileSetupModal';
import type { MarketAuthScene } from './scenes';
+import { createSingleFlight } from './singleFlight';
import {
type MarketAuthContextType,
type MarketAuthSession,
@@ -157,6 +158,10 @@ export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderPr
(() => void) | null
>(null);
+ // Shared in-flight token refresh, so concurrent callers never replay a
+ // single-use refresh token against each other (see `runTokenRefresh`).
+ const refreshSingleFlightRef = useRef(createSingleFlight<boolean>());
+
// Subscribe to user store init state; when isUserStateInit is true, settings data is fully loaded
const isUserStateInit = useUserStore((s) => s.isUserStateInit);
@@ -187,47 +192,112 @@ export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderPr
}, [isDesktop]);
/**
- * Try to refresh the access token using a refresh token
- * This is used during initialization when the access token is expired or invalid
+ * Run a token refresh, collapsing concurrent callers onto one in-flight request.
+ *
+ * Market rotates refresh tokens, so a refresh token is single-use. Refreshes
+ * are triggered from several independent places — the pre-expiry timer, the
+ * `market-unauthorized` listener, `handleUnauthorized`, and session init — so
+ * two of them overlapping is routine rather than exotic. Without this guard
+ * they race: the first rotates the token and stores the new pair, the second
+ * replays the now-consumed token and fails. Sharing one promise means the
+ * second caller observes the first one's success instead of a phantom failure.
*/
- const tryRefreshToken = async (refreshTokenValue: string): Promise<boolean> => {
- try {
- const clientId = isDesktop ? 'lobehub-desktop' : 'lobechat-com';
+ const runTokenRefresh = useCallback(
+ (refreshTokenValue: string): Promise<boolean> =>
+ refreshSingleFlightRef.current(async (): Promise<boolean> => {
+ try {
+ const clientId = isDesktop ? 'lobehub-desktop' : 'lobechat-com';
+
+ const response = await lambdaClient.market.oidc.refreshToken.mutate({
+ clientId,
+ refreshToken: refreshTokenValue,
+ });
+
+ // Calculate new expiration time (default to 1 hour if not provided)
+ const expiresIn = response.expiresIn ?? 3600;
+ const expiresAt = Date.now() + expiresIn * 1000;
+
+ // Save new tokens to DB
+ await saveMarketTokensToDB(response.accessToken, response.refreshToken, expiresAt);
+
+ // Fetch user info with new token
+ const userInfo = await fetchUserInfo(response.accessToken);
+
+ // Update session state
+ const newSession: MarketAuthSession = {
+ accessToken: response.accessToken,
+ expiresAt,
+ expiresIn,
+ scope: response.scope || 'openid profile email',
+ tokenType: 'Bearer',
+ userInfo: userInfo || undefined,
+ };
+
+ setSession(newSession);
+ setStatus('authenticated');
+
+ console.info('[MarketAuth] Token refreshed successfully');
+ return true;
+ } catch (error) {
+ console.error('[MarketAuth] Failed to refresh token:', error);
+ return false;
+ }
+ }),
+ [isDesktop],
+ );
- const response = await lambdaClient.market.oidc.refreshToken.mutate({
- clientId,
- refreshToken: refreshTokenValue,
- });
+ /**
+ * Whether another refresh has already replaced the token we just tried to use.
+ *
+ * The in-flight guard above only covers one JS context; a second tab (or the
+ * desktop app alongside the web app) shares the same stored credentials and
+ * can rotate them underneath us. Losing that race is not an auth failure —
+ * working credentials are sitting in the store — so callers must not treat it
+ * as one and wipe them.
+ */
+ const wasRotatedByAnotherRefresh = (usedRefreshToken: string): boolean => {
+ const latest = getMarketTokensFromDB();
+ return Boolean(latest?.refreshToken) && latest?.refreshToken !== usedRefreshToken;
+ };
- // Calculate new expiration time (default to 1 hour if not provided)
- const expiresIn = response.expiresIn ?? 3600;
- const expiresAt = Date.now() + expiresIn * 1000;
+ /**
+ * Adopt credentials another refresh stored, publishing them as our session.
+ *
+ * Detecting that we lost the race is only half the job: this context never ran
+ * the success path, so without adopting the result the caller would report
+ * success while `status` stayed `loading` and no session was ever set.
+ */
+ const adoptRotatedSession = async (): Promise<boolean> => {
+ const latest = getMarketTokensFromDB();
+ if (!latest?.accessToken || !latest.expiresAt || latest.expiresAt <= Date.now()) return false;
- // Save new tokens to DB
- await saveMarketTokensToDB(response.accessToken, response.refreshToken, expiresAt);
+ const userInfo = await fetchUserInfo(latest.accessToken);
+ if (!userInfo) return false;
- // Fetch user info with new token
- const userInfo = await fetchUserInfo(response.accessToken);
+ setSession({
+ accessToken: latest.accessToken,
+ expiresAt: latest.expiresAt,
+ expiresIn: Math.floor((latest.expiresAt - Date.now()) / 1000),
+ scope: 'openid profile email',
+ tokenType: 'Bearer',
+ userInfo,
+ });
+ setStatus('authenticated');
- // Update session state
- const newSession: MarketAuthSession = {
- accessToken: response.accessToken,
- expiresAt,
- expiresIn,
- scope: response.scope || 'openid profile email',
- tokenType: 'Bearer',
- userInfo: userInfo || undefined,
- };
+ console.info('[MarketAuth] Adopted tokens refreshed by a concurrent refresh');
+ return true;
+ };
- setSession(newSession);
- setStatus('authenticated');
+ /**
+ * Try to refresh the access token using a refresh token
+ * This is used during initialization when the access token is expired or invalid
+ */
+ const tryRefreshToken = async (refreshTokenValue: string): Promise<boolean> => {
+ const refreshed = await runTokenRefresh(refreshTokenValue);
+ if (refreshed) return true;
- console.info('[MarketAuth] Token refreshed successfully during initialization');
- return true;
- } catch (error) {
- console.error('[MarketAuth] Failed to refresh token during initialization:', error);
- return false;
- }
+ if (!wasRotatedByAnotherRefresh(refreshTokenValue)) return false;
+ return adoptRotatedSession();
};
/**
@@ -587,48 +657,22 @@ export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderPr
return false;
}
- try {
- const clientId = isDesktop ? 'lobehub-desktop' : 'lobechat-com';
+ const usedRefreshToken = dbTokens.refreshToken;
+ if (await runTokenRefresh(usedRefreshToken)) return true;
- const response = await lambdaClient.market.oidc.refreshToken.mutate({
- clientId,
- refreshToken: dbTokens.refreshToken,
- });
+ // Losing a rotation race is not an auth failure — a concurrent refresh has
+ // already stored working credentials. Clearing here would throw those away,
+ // which is precisely how one transient failure used to strand the user
+ // signed out: the wipe leaves no refresh token, so every later recovery
+ // attempt has nothing to retry with and the session can never heal itself.
+ if (wasRotatedByAnotherRefresh(usedRefreshToken) && (await adoptRotatedSession())) return true;
- // Calculate new expiration time (default to 1 hour if not provided)
- const expiresIn = response.expiresIn ?? 3600;
- const expiresAt = Date.now() + expiresIn * 1000;
-
- // Save new tokens to DB
- await saveMarketTokensToDB(response.accessToken, response.refreshToken, expiresAt);
-
- // Fetch user info with new token
- const userInfo = await fetchUserInfo(response.accessToken);
-
- // Update session state
- const newSession: MarketAuthSession = {
- accessToken: response.accessToken,
- expiresAt,
- expiresIn,
- scope: response.scope || 'openid profile email',
- tokenType: 'Bearer',
- userInfo: userInfo || undefined,
- };
-
- setSession(newSession);
- setStatus('authenticated');
-
- console.info('[MarketAuth] Token refreshed successfully');
- return true;
- } catch (error) {
- console.error('[MarketAuth] Failed to refresh token:', error);
- // Clear invalid tokens
- await clearMarketTokensFromDB();
- setSession(null);
- setStatus('unauthenticated');
- return false;
- }
- }, [isDesktop]);
+ // The refresh token is genuinely spent — drop it so we stop replaying it.
+ await clearMarketTokensFromDB();
+ setSession(null);
+ setStatus('unauthenticated');
+ return false;
+ }, [runTokenRefresh]);
/**
* Handle unauthorized (401) error from Market API
diff --git a/src/layout/AuthProvider/MarketAuth/singleFlight.test.ts b/src/layout/AuthProvider/MarketAuth/singleFlight.test.ts
new file mode 100644
index 00000000000..46d5c156d20
--- /dev/null
+++ b/src/layout/AuthProvider/MarketAuth/singleFlight.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createSingleFlight } from './singleFlight';
+
+/** A promise plus the handles to settle it from the test body. */
+const deferred = <T>() => {
+ let resolve!: (_value: T) => void;
+ let reject!: (_reason?: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, reject, resolve };
+};
+
+describe('createSingleFlight', () => {
+ /**
+ * The regression this exists for: Market rotates refresh tokens, so the second
+ * of two overlapping refreshes replays a consumed token and fails. That
+ * phantom failure used to wipe the credentials the first refresh had just
+ * stored, stranding the user signed out with no refresh token left to recover
+ * with.
+ */
+ it('runs the operation once for callers that overlap', async () => {
+ const singleFlight = createSingleFlight<string>();
+ const gate = deferred<string>();
+ const run = vi.fn(() => gate.promise);
+
+ const first = singleFlight(run);
+ const second = singleFlight(run);
+
+ expect(run).toHaveBeenCalledTimes(1);
+
+ gate.resolve('fresh-token');
+
+ await expect(first).resolves.toBe('fresh-token');
+ // The straggler observes the winner's result rather than a failure of its own
+ await expect(second).resolves.toBe('fresh-token');
+ });
+
+ it('hands every overlapping caller the same promise', () => {
+ const singleFlight = createSingleFlight<string>();
+ const gate = deferred<string>();
+
+ const first = singleFlight(() => gate.promise);
+ const second = singleFlight(() => gate.promise);
+
+ expect(second).toBe(first);
+
+ gate.resolve('done');
+ });
+
+ it('is not a cache — a call after settling performs fresh work', async () => {
+ const singleFlight = createSingleFlight<number>();
+ const run = vi.fn().mockResolvedValueOnce(1).mockResolvedValueOnce(2);
+
+ await expect(singleFlight(run)).resolves.toBe(1);
+ await expect(singleFlight(run)).resolves.toBe(2);
+
+ expect(run).toHaveBeenCalledTimes(2);
+ });
+
+ it('shares a rejection with overlapping callers and then recovers', async () => {
+ const singleFlight = createSingleFlight<string>();
+ const gate = deferred<string>();
+ const failing = vi.fn(() => gate.promise);
+
+ const first = singleFlight(failing);
+ const second = singleFlight(failing);
+
+ gate.reject(new Error('invalid_grant'));
+
+ await expect(first).rejects.toThrow('invalid_grant');
+ await expect(second).rejects.toThrow('invalid_grant');
+
+ // A failed flight must not wedge the gate shut
+ const succeeding = vi.fn().mockResolvedValue('recovered');
+ await expect(singleFlight(succeeding)).resolves.toBe('recovered');
+ expect(succeeding).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/layout/AuthProvider/MarketAuth/singleFlight.ts b/src/layout/AuthProvider/MarketAuth/singleFlight.ts
new file mode 100644
index 00000000000..d907e06d88b
--- /dev/null
+++ b/src/layout/AuthProvider/MarketAuth/singleFlight.ts
@@ -0,0 +1,30 @@
+/**
+ * Collapse overlapping calls of an async operation onto a single execution.
+ *
+ * Built for OAuth token refresh, where the operation is not idempotent: Market
+ * rotates refresh tokens, so a refresh token is single-use. Two overlapping
+ * refreshes therefore don't merely waste a request — the second replays a token
+ * the first already consumed and fails, and a naive failure handler treats that
+ * phantom failure as "the session is dead" and discards the credentials the
+ * first call just obtained.
+ *
+ * Collapsing them means the later caller observes the first call's real outcome
+ * instead. Deliberately *not* a cache: the shared promise is released as soon as
+ * it settles, so a subsequent call always performs fresh work.
+ */
+export const createSingleFlight = <T>(): ((_run: () => Promise<T>) => Promise<T>) => {
+ let inFlight: Promise<T> | null = null;
+
+ return (run: () => Promise<T>): Promise<T> => {
+ if (inFlight) return inFlight;
+
+ // Assign before awaiting so a caller arriving in the same tick — before any
+ // microtask boundary — still sees the in-flight promise.
+ const promise = run().finally(() => {
+ inFlight = null;
+ });
+ inFlight = promise;
+
+ return promise;
+ };
+};
diff --git a/src/libs/swr/index.ts b/src/libs/swr/index.ts
index 33cd4cc7c0b..28aa54299a4 100644
--- a/src/libs/swr/index.ts
+++ b/src/libs/swr/index.ts
@@ -4,6 +4,7 @@ import useSWR from 'swr';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { augmentKey } from './augmentKey';
+import { isAutoRetryable } from './normalizeError';
export { augmentKey };
@@ -32,8 +33,9 @@ export const useClientDataSWR: SWRHook = (key, fetch, config) => {
const revalidate = args[2];
const { retryCount } = args[3];
- // Check if error is marked as non-retryable (e.g., 401 authentication errors)
- if (error?.meta?.shouldRetry === false) {
+ // Auth walls, rate limits, and anything explicitly marked non-retryable:
+ // an automatic backoff can't help and, for 429, actively hurts.
+ if (!isAutoRetryable(error)) {
return;
}
// For other errors, use default SWR retry behavior
diff --git a/src/libs/swr/normalizeError.test.ts b/src/libs/swr/normalizeError.test.ts
index 21d5d0532ef..ae91759237d 100644
--- a/src/libs/swr/normalizeError.test.ts
+++ b/src/libs/swr/normalizeError.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { normalizeAsyncError } from './normalizeError';
+import { isAutoRetryable, normalizeAsyncError } from './normalizeError';
describe('normalizeAsyncError', () => {
it('treats a missing error as retryable with no status', () => {
@@ -39,3 +39,36 @@ describe('normalizeAsyncError', () => {
expect(normalizeAsyncError({ status: 408 }).retryable).toBe(true);
});
});
+
+describe('isAutoRetryable', () => {
+ /**
+ * The skill store regression: an upstream 429 used to be retried on a
+ * 1s/2s/4s/8s/16s backoff, so one failed open became six requests — all of
+ * them landing inside the very window that caused the 429.
+ */
+ it('stands down on a rate limit so the backoff cannot refill the window', () => {
+ expect(isAutoRetryable({ data: { httpStatus: 429 } })).toBe(false);
+ expect(isAutoRetryable({ status: 429 })).toBe(false);
+ });
+
+ it('keeps a rate limit user-retryable even though auto-retry stands down', () => {
+ // Different questions: a manual Retry a minute later works fine.
+ expect(normalizeAsyncError({ status: 429 }).retryable).toBe(true);
+ });
+
+ it('does not auto-retry auth / permission walls', () => {
+ expect(isAutoRetryable({ data: { httpStatus: 401 } })).toBe(false);
+ expect(isAutoRetryable({ status: 403 })).toBe(false);
+ });
+
+ it('honors an explicit non-retryable marker regardless of status', () => {
+ expect(isAutoRetryable({ meta: { shouldRetry: false }, status: 500 })).toBe(false);
+ });
+
+ it('still auto-retries transient failures', () => {
+ expect(isAutoRetryable({ status: 500 })).toBe(true);
+ expect(isAutoRetryable({ status: 408 })).toBe(true);
+ expect(isAutoRetryable(new Error('network down'))).toBe(true);
+ expect(isAutoRetryable(undefined)).toBe(true);
+ });
+});
diff --git a/src/libs/swr/normalizeError.ts b/src/libs/swr/normalizeError.ts
index dcf90e5997c..a747ec47b7e 100644
--- a/src/libs/swr/normalizeError.ts
+++ b/src/libs/swr/normalizeError.ts
@@ -62,3 +62,28 @@ export const normalizeAsyncError = (error: unknown): NormalizedAsyncError => {
return { code, rawMessage, retryable, status };
};
+
+/**
+ * Statuses an *automatic* backoff must not retry.
+ *
+ * Deliberately wider than {@link NormalizedAsyncError.retryable}, because the
+ * two answer different questions. `retryable` asks "could the user usefully
+ * press Retry?"; this asks "should a timer fire the same request again on its
+ * own?". `429` splits them: pressing Retry once the window has passed works
+ * fine, but an automatic backoff at 1s/2s/4s/8s/16s lands every attempt inside
+ * the very window that produced the `429` — turning one failed load into six
+ * requests that keep the bucket empty and make the error self-sustaining. So a
+ * `429` stays user-retryable while auto-retry stands down.
+ */
+const NON_AUTO_RETRYABLE_STATUS = new Set([401, 403, 429]);
+
+/**
+ * Whether SWR's error-retry loop should keep retrying this failure on a timer.
+ */
+export const isAutoRetryable = (error: unknown): boolean => {
+ const err = error as any;
+ if (err?.meta?.shouldRetry === false) return false;
+
+ const status = extractStatus(err);
+ return !(typeof status === 'number' && NON_AUTO_RETRYABLE_STATUS.has(status));
+};