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: show plan limit upgrade UI on desktop builds (#15628)

YuTengjingb8339abc7671
diff --git a/locales/en-US/error.json b/locales/en-US/error.json
index 9129d6344fe..6a062e4b74e 100644
--- a/locales/en-US/error.json
+++ b/locales/en-US/error.json
@@ -109,9 +109,11 @@
"transfer.targetNoWriteAccess": "You need Member or Owner access to move resources into the target workspace.",
"tts.responseError": "Service request failed, please check the configuration or try again",
"unknownError.copyTraceId": "Trace ID Copied",
+ "unknownError.copyTraceIdTooltip": "Click to copy",
"unknownError.desc": "An unexpected error occurred. You can retry or report on",
"unknownError.retry": "Retry",
"unknownError.title": "Oops, the request took a nap",
+ "unknownError.traceIdLabel": "Trace ID:",
"unlock.addProxyUrl": "Add OpenAI proxy URL (optional)",
"unlock.apiKey.description": "Enter your {{name}} API Key to start the session",
"unlock.apiKey.imageGenerationDescription": "Enter your {{name}} API Key to start generating",
diff --git a/locales/zh-CN/error.json b/locales/zh-CN/error.json
index da9c44036ae..4cfba508ae7 100644
--- a/locales/zh-CN/error.json
+++ b/locales/zh-CN/error.json
@@ -109,9 +109,11 @@
"transfer.targetNoWriteAccess": "您需要成员或所有者权限才能将资源移动到目标工作区。",
"tts.responseError": "请求失败。请检查配置后重试",
"unknownError.copyTraceId": "Trace ID 已复制",
+ "unknownError.copyTraceIdTooltip": "点击复制",
"unknownError.desc": "遇到了意外错误,请重试或反馈至",
"unknownError.retry": "重试",
"unknownError.title": "糟糕,请求打了个盹",
+ "unknownError.traceIdLabel": "追踪 ID:",
"unlock.addProxyUrl": "添加 OpenAI 代理地址(可选)",
"unlock.apiKey.description": "输入你的 {{name}} API Key,即可开始会话",
"unlock.apiKey.imageGenerationDescription": "输入你的 {{name}} API Key,即可开始生成",
diff --git a/packages/business/const/src/branding.ts b/packages/business/const/src/branding.ts
index ea970e1cd19..8624df54e85 100644
--- a/packages/business/const/src/branding.ts
+++ b/packages/business/const/src/branding.ts
@@ -12,7 +12,7 @@ export const ORG_NAME = 'LobeHub';
export const BRANDING_URL = {
help: undefined,
privacy: undefined,
- subscription: undefined,
+ subscription: 'https://app.lobehub.com/settings/plans',
support: undefined,
terms: undefined,
};
diff --git a/packages/locales/src/default/error.ts b/packages/locales/src/default/error.ts
index 81ec7375548..131ac1744bc 100644
--- a/packages/locales/src/default/error.ts
+++ b/packages/locales/src/default/error.ts
@@ -94,8 +94,10 @@ export default {
'exceededContext.title': 'Context Window Exceeded',
'unknownError.copyTraceId': 'Trace ID Copied',
+ 'unknownError.copyTraceIdTooltip': 'Click to copy',
'unknownError.desc': 'An unexpected error occurred. You can retry or report on',
'unknownError.retry': 'Retry',
+ 'unknownError.traceIdLabel': 'Trace ID:',
'unknownError.title': 'Oops, the request took a nap',
'response.ExceededContextWindowCloud':
diff --git a/src/features/Conversation/Error/DeprecatedModelError.tsx b/src/features/Conversation/Error/DeprecatedModelError.tsx
new file mode 100644
index 00000000000..021614f30c6
--- /dev/null
+++ b/src/features/Conversation/Error/DeprecatedModelError.tsx
@@ -0,0 +1,26 @@
+import { Icon } from '@lobehub/ui';
+import { AlertTriangle } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import BaseErrorForm from '@/features/Conversation/Error/BaseErrorForm';
+
+interface DeprecatedModelErrorProps {
+ requestedModel?: string;
+}
+
+const DeprecatedModelError = memo<DeprecatedModelErrorProps>(({ requestedModel }) => {
+ const { t } = useTranslation('error');
+
+ return (
+ <BaseErrorForm
+ avatar={<Icon icon={AlertTriangle} size={24} />}
+ title={t('fetchError.title')}
+ desc={t('response.LobeHubModelDeprecated', {
+ model: requestedModel ?? '-',
+ })}
+ />
+ );
+});
+
+export default DeprecatedModelError;
diff --git a/src/features/Conversation/Error/ExceededContextWindowError.tsx b/src/features/Conversation/Error/ExceededContextWindowError.tsx
index a82d88c02ef..4b128a8ebf5 100644
--- a/src/features/Conversation/Error/ExceededContextWindowError.tsx
+++ b/src/features/Conversation/Error/ExceededContextWindowError.tsx
@@ -1,7 +1,7 @@
import { Icon } from '@lobehub/ui';
import { Button } from 'antd';
import { Minimize2 } from 'lucide-react';
-import { memo, useCallback, useState } from 'react';
+import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { usePermission } from '@/hooks/usePermission';
@@ -9,6 +9,7 @@ import { useChatStore } from '@/store/chat';
import { useConversationStore } from '../store';
import BaseErrorForm from './BaseErrorForm';
+import { useRetryParentMessage } from './useRetryParentMessage';
interface ExceededContextWindowErrorProps {
id: string;
@@ -16,26 +17,16 @@ interface ExceededContextWindowErrorProps {
const ExceededContextWindowError = memo<ExceededContextWindowErrorProps>(({ id }) => {
const { t } = useTranslation('error');
- const [loading, setLoading] = useState(false);
const { allowed: canCreate } = usePermission('create_content');
const context = useConversationStore((s) => s.context);
- const regenerateUserMessage = useConversationStore((s) => s.regenerateUserMessage);
- const parentId = useConversationStore(
- (s) => s.displayMessages.find((m) => m.id === id)?.parentId,
- );
+ const { disabled, loading, retryParentMessage } = useRetryParentMessage(id);
const handleCompact = useCallback(async () => {
- if (!canCreate || !context.topicId || !parentId) return;
+ if (!canCreate || !context.topicId) return;
- setLoading(true);
- try {
- await useChatStore.getState().executeCompression(context, '');
- await regenerateUserMessage(parentId);
- } finally {
- setLoading(false);
- }
- }, [canCreate, context, parentId, regenerateUserMessage]);
+ await retryParentMessage(() => useChatStore.getState().executeCompression(context, ''));
+ }, [canCreate, context, retryParentMessage]);
return (
<BaseErrorForm
@@ -44,7 +35,7 @@ const ExceededContextWindowError = memo<ExceededContextWindowErrorProps>(({ id }
title={t('exceededContext.title')}
action={
<Button
- disabled={!canCreate || !context.topicId}
+ disabled={!canCreate || !context.topicId || disabled}
loading={loading}
type={'primary'}
onClick={handleCompact}
diff --git a/src/features/Conversation/Error/PlanLimitCard/budget.test.ts b/src/features/Conversation/Error/PlanLimitCard/budget.test.ts
new file mode 100644
index 00000000000..a360a219e94
--- /dev/null
+++ b/src/features/Conversation/Error/PlanLimitCard/budget.test.ts
@@ -0,0 +1,54 @@
+import { Plans } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import {
+ getBudgetContextFromErrorBody,
+ getNextUpgradePlan,
+ isFableCampaignLimitContext,
+ isKnownPlan,
+} from './budget';
+
+describe('PlanLimitCard budget helpers', () => {
+ it('should extract budget context from an error body', () => {
+ const context = {
+ pricingBasis: 'estimated',
+ requiredCredits: 2_500_000,
+ shortfallCredits: 1_500_000,
+ } as const;
+
+ expect(getBudgetContextFromErrorBody({ budget: context })).toBe(context);
+ expect(getBudgetContextFromErrorBody('error')).toBeUndefined();
+ expect(getBudgetContextFromErrorBody(null)).toBeUndefined();
+ expect(getBudgetContextFromErrorBody({})).toBeUndefined();
+ expect(getBudgetContextFromErrorBody({ budget: 'oops' })).toBeUndefined();
+ });
+
+ it('should detect fable campaign limit context', () => {
+ expect(isFableCampaignLimitContext({ modelId: 'claude-fable-5', providerId: 'lobehub' })).toBe(
+ true,
+ );
+ expect(isFableCampaignLimitContext({ modelId: 'claude-opus-4-8', providerId: 'lobehub' })).toBe(
+ false,
+ );
+ expect(
+ isFableCampaignLimitContext({ modelId: 'claude-fable-5', providerId: 'anthropic' }),
+ ).toBe(false);
+ expect(isFableCampaignLimitContext(undefined)).toBe(false);
+ });
+
+ it('should resolve the next upgrade plan', () => {
+ expect(getNextUpgradePlan(Plans.Free)).toBe(Plans.Starter);
+ expect(getNextUpgradePlan(Plans.Starter)).toBe(Plans.Premium);
+ expect(getNextUpgradePlan(Plans.Premium)).toBe(Plans.Ultimate);
+ expect(getNextUpgradePlan(Plans.Ultimate)).toBeUndefined();
+ expect(getNextUpgradePlan(Plans.Hobby)).toBeUndefined();
+ expect(getNextUpgradePlan(undefined)).toBeUndefined();
+ });
+
+ it('should detect known plan ids', () => {
+ expect(isKnownPlan(Plans.Free)).toBe(true);
+ expect(isKnownPlan(Plans.Hobby)).toBe(true);
+ expect(isKnownPlan('legacy')).toBe(false);
+ expect(isKnownPlan(undefined)).toBe(false);
+ });
+});
diff --git a/src/features/Conversation/Error/PlanLimitCard/budget.ts b/src/features/Conversation/Error/PlanLimitCard/budget.ts
new file mode 100644
index 00000000000..098bdba49db
--- /dev/null
+++ b/src/features/Conversation/Error/PlanLimitCard/budget.ts
@@ -0,0 +1,44 @@
+import { Plans } from '@lobechat/types';
+import { isRecord } from '@lobechat/utils';
+
+export type PlanLimitPricingBasis = 'approximate' | 'estimated' | 'exact' | 'unknown';
+
+/**
+ * Budget context snapshot attached to plan-limit error bodies by the server.
+ * Only the fields needed for the lightweight fallback card are typed here.
+ */
+export interface PlanLimitBudgetContext {
+ modelId?: string;
+ planAtError?: string;
+ pricingBasis?: PlanLimitPricingBasis;
+ providerId?: string;
+ requiredCredits?: number;
+ shortfallCredits?: number;
+}
+
+export const getBudgetContextFromErrorBody = (
+ body: unknown,
+): PlanLimitBudgetContext | undefined => {
+ if (!isRecord(body)) return undefined;
+
+ const { budget } = body as { budget?: unknown };
+ if (!isRecord(budget)) return undefined;
+
+ return budget as PlanLimitBudgetContext;
+};
+
+export const isFableCampaignLimitContext = (context?: PlanLimitBudgetContext): boolean =>
+ context?.modelId === 'claude-fable-5' && context.providerId === 'lobehub';
+
+const PLAN_VALUES = new Set<string>(Object.values(Plans));
+
+export const isKnownPlan = (plan?: string): plan is Plans => !!plan && PLAN_VALUES.has(plan);
+
+const PLAN_UPGRADE_PATH: Partial<Record<Plans, Plans>> = {
+ [Plans.Free]: Plans.Starter,
+ [Plans.Premium]: Plans.Ultimate,
+ [Plans.Starter]: Plans.Premium,
+};
+
+export const getNextUpgradePlan = (plan?: Plans): Plans | undefined =>
+ plan ? PLAN_UPGRADE_PATH[plan] : undefined;
diff --git a/src/features/Conversation/Error/PlanLimitCard/index.tsx b/src/features/Conversation/Error/PlanLimitCard/index.tsx
new file mode 100644
index 00000000000..3d5fe6f9717
--- /dev/null
+++ b/src/features/Conversation/Error/PlanLimitCard/index.tsx
@@ -0,0 +1,190 @@
+import { BRANDING_URL } from '@lobechat/business-const';
+import { ChatErrorType, Plans } from '@lobechat/types';
+import { Button, Flexbox } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatIntergerNumber, formatNumber } from '@/utils/format';
+
+import { ErrorActionContainer, FormAction } from '../style';
+import {
+ getBudgetContextFromErrorBody,
+ getNextUpgradePlan,
+ isFableCampaignLimitContext,
+ isKnownPlan,
+ type PlanLimitPricingBasis,
+} from './budget';
+
+/** Credits are displayed in units of 1M */
+const CREDIT_UNIT = 1_000_000;
+
+/** Plans with a `plans.plan.<id>.title` locale key */
+const PLAN_TITLE_KEYS = {
+ [Plans.Free]: 'plans.plan.free.title',
+ [Plans.Hobby]: 'plans.plan.hobby.title',
+ [Plans.Premium]: 'plans.plan.premium.title',
+ [Plans.Starter]: 'plans.plan.starter.title',
+ [Plans.Ultimate]: 'plans.plan.ultimate.title',
+} as const satisfies Record<Plans, string>;
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ budgetFact: css`
+ display: flex;
+ justify-content: space-between;
+
+ width: 100%;
+
+ font-size: 13px;
+ line-height: 1.4;
+ `,
+ budgetFactLabel: css`
+ color: ${cssVar.colorTextTertiary};
+ `,
+ budgetFactValue: css`
+ font-weight: 600;
+ color: ${cssVar.colorText};
+ white-space: nowrap;
+ `,
+ budgetFactWarningValue: css`
+ font-weight: 700;
+ color: ${cssVar.colorError};
+ `,
+ budgetFacts: css`
+ width: 100%;
+ `,
+}));
+
+const getBudgetDescriptionKey = (pricingBasis?: PlanLimitPricingBasis) => {
+ switch (pricingBasis) {
+ case 'approximate': {
+ return 'limitation.insufficientBudget.approximateDesc';
+ }
+ case 'estimated': {
+ return 'limitation.insufficientBudget.estimatedDesc';
+ }
+ case 'exact': {
+ return 'limitation.insufficientBudget.exactDesc';
+ }
+ default: {
+ return 'limitation.insufficientBudget.desc';
+ }
+ }
+};
+
+const formatCreditAmount = (credits: number): string => {
+ if (credits >= CREDIT_UNIT) return `${formatNumber(credits / CREDIT_UNIT, 2)}M`;
+
+ return formatIntergerNumber(credits);
+};
+
+interface PlanLimitCardProps {
+ errorBody?: unknown;
+ errorType?: string;
+ onRetry: () => void;
+}
+
+/**
+ * Lightweight fallback for cloud billing errors. Used in builds without the
+ * business override (e.g. desktop), so it only reads the budget snapshot from
+ * the error body and links to the web plans page instead of fetching live
+ * subscription state.
+ */
+const PlanLimitCard = memo<PlanLimitCardProps>(({ errorBody, errorType, onRetry }) => {
+ const { t } = useTranslation('subscription');
+
+ const context = getBudgetContextFromErrorBody(errorBody);
+ const isFableCampaign = isFableCampaignLimitContext(context);
+ const isInsufficientBudget = errorType === ChatErrorType.InsufficientBudgetForModel;
+
+ const planAtError = isKnownPlan(context?.planAtError) ? context.planAtError : Plans.Free;
+
+ const getPlanTitle = (plan: Plans) => t(PLAN_TITLE_KEYS[plan]);
+
+ let title: string;
+ let description: string;
+ let upgradeLabel: string;
+
+ if (isFableCampaign) {
+ // Hobby has no credit allowance to restore, so skip the plan recommendation
+ const targetPlan = context?.planAtError === Plans.Hobby ? undefined : Plans.Starter;
+
+ title = t('limitation.fableCampaign.title');
+ description = t('limitation.fableCampaign.desc');
+ upgradeLabel = targetPlan
+ ? t('limitation.fableCampaign.upgradeToPlan', { plan: getPlanTitle(targetPlan) })
+ : t('limitation.fableCampaign.upgrade');
+ } else {
+ const nextPlan = getNextUpgradePlan(planAtError);
+
+ title = isInsufficientBudget
+ ? t('limitation.insufficientBudget.title')
+ : t('limitation.limited.title');
+ description = isInsufficientBudget
+ ? t(getBudgetDescriptionKey(context?.pricingBasis))
+ : t('limitation.limited.desc', { plan: getPlanTitle(planAtError) });
+ upgradeLabel = nextPlan
+ ? t('limitation.limited.upgradeToPlan', { plan: getPlanTitle(nextPlan) })
+ : t('limitation.limited.upgrade');
+ }
+
+ const facts = (
+ [
+ {
+ label: t('limitation.insufficientBudget.required'),
+ value: context?.requiredCredits,
+ warning: false,
+ },
+ {
+ label: t('limitation.insufficientBudget.shortfall'),
+ value: context?.shortfallCredits,
+ warning: true,
+ },
+ ] as const
+ ).filter((fact) => fact.value !== undefined && fact.value > 0);
+
+ return (
+ <ErrorActionContainer>
+ <FormAction animation avatar={'💰'} description={description} title={title}>
+ {facts.length > 0 && (
+ <Flexbox className={styles.budgetFacts} gap={8}>
+ {facts.map((fact) => (
+ <div className={styles.budgetFact} key={fact.label}>
+ <span className={styles.budgetFactLabel}>{fact.label}</span>
+ <span
+ className={
+ fact.warning
+ ? `${styles.budgetFactValue} ${styles.budgetFactWarningValue}`
+ : styles.budgetFactValue
+ }
+ >
+ {formatCreditAmount(fact.value!)}
+ </span>
+ </div>
+ ))}
+ </Flexbox>
+ )}
+
+ <Flexbox gap={8} width={'100%'}>
+ {BRANDING_URL.subscription && (
+ <a
+ href={BRANDING_URL.subscription}
+ rel={'noopener noreferrer'}
+ style={{ width: '100%' }}
+ target={'_blank'}
+ >
+ <Button block size={'large'} type={'primary'}>
+ {upgradeLabel}
+ </Button>
+ </a>
+ )}
+ <Button block size={'large'} onClick={onRetry}>
+ {t('limitation.insufficientBudget.retry')}
+ </Button>
+ </Flexbox>
+ </FormAction>
+ </ErrorActionContainer>
+ );
+});
+
+export default PlanLimitCard;
diff --git a/src/features/Conversation/Error/QuotaLimitError.tsx b/src/features/Conversation/Error/QuotaLimitError.tsx
new file mode 100644
index 00000000000..81a20ae825c
--- /dev/null
+++ b/src/features/Conversation/Error/QuotaLimitError.tsx
@@ -0,0 +1,39 @@
+import { Icon } from '@lobehub/ui';
+import { Button } from 'antd';
+import { AlertTriangle, RotateCw } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import BaseErrorForm from '@/features/Conversation/Error/BaseErrorForm';
+
+import { useRetryParentMessage } from './useRetryParentMessage';
+
+interface QuotaLimitErrorProps {
+ id: string;
+}
+
+const QuotaLimitError = memo<QuotaLimitErrorProps>(({ id }) => {
+ const { t } = useTranslation('error');
+ const { disabled, loading, retryParentMessage } = useRetryParentMessage(id);
+
+ return (
+ <BaseErrorForm
+ avatar={<Icon icon={AlertTriangle} size={24} />}
+ title={t('response.QuotaLimitReachedCloud')}
+ action={
+ <Button
+ disabled={disabled}
+ icon={<Icon icon={RotateCw} />}
+ loading={loading}
+ size={'small'}
+ type={'primary'}
+ onClick={() => retryParentMessage()}
+ >
+ {t('unknownError.retry')}
+ </Button>
+ }
+ />
+ );
+});
+
+export default QuotaLimitError;
diff --git a/src/features/Conversation/Error/TraceIdError.tsx b/src/features/Conversation/Error/TraceIdError.tsx
new file mode 100644
index 00000000000..aa7ec5ba66a
--- /dev/null
+++ b/src/features/Conversation/Error/TraceIdError.tsx
@@ -0,0 +1,88 @@
+import { SOCIAL_URL } from '@lobechat/business-const';
+import { copyToClipboard, Icon } from '@lobehub/ui';
+import { DiscordIcon } from '@lobehub/ui/icons';
+import { Button, message } from 'antd';
+import { cssVar } from 'antd-style';
+import { AlertTriangle, Copy, RotateCw } from 'lucide-react';
+import { memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import BaseErrorForm from '@/features/Conversation/Error/BaseErrorForm';
+
+import { useRetryParentMessage } from './useRetryParentMessage';
+
+interface TraceIdErrorProps {
+ id: string;
+ traceId: string;
+}
+
+const TraceIdError = memo<TraceIdErrorProps>(({ id, traceId }) => {
+ const { t } = useTranslation('error');
+ const { disabled, loading, retryParentMessage } = useRetryParentMessage(id);
+
+ const handleCopyTraceId = useCallback(async () => {
+ try {
+ await copyToClipboard(traceId);
+ message.success(t('unknownError.copyTraceId'));
+ } catch {
+ /* noop */
+ }
+ }, [t, traceId]);
+
+ return (
+ <BaseErrorForm
+ avatar={<Icon icon={AlertTriangle} size={24} />}
+ title={t('unknownError.title')}
+ action={
+ <Button
+ disabled={disabled}
+ icon={<Icon icon={RotateCw} />}
+ loading={loading}
+ size={'small'}
+ type={'primary'}
+ onClick={() => retryParentMessage()}
+ >
+ {t('unknownError.retry')}
+ </Button>
+ }
+ desc={
+ <span>
+ {t('unknownError.desc')}{' '}
+ <a
+ href={SOCIAL_URL.discord}
+ rel="noopener noreferrer"
+ target="_blank"
+ style={{
+ alignItems: 'center',
+ color: '#5865F2',
+ display: 'inline-flex',
+ gap: 2,
+ verticalAlign: 'middle',
+ }}
+ >
+ <Icon icon={DiscordIcon} size={14} />
+ Discord
+ </a>
+ {' · '}
+ {t('unknownError.traceIdLabel')}{' '}
+ <code
+ title={t('unknownError.copyTraceIdTooltip')}
+ style={{
+ cursor: 'pointer',
+ opacity: 0.65,
+ textDecoration: 'underline dashed',
+ textDecorationColor: cssVar.colorTextQuaternary,
+ textUnderlineOffset: 3,
+ }}
+ onClick={handleCopyTraceId}
+ >
+ {traceId}
+ <Icon icon={Copy} size={11} style={{ marginLeft: 3, verticalAlign: 'middle' }} />
+ </code>
+ </span>
+ }
+ />
+ );
+});
+
+export default TraceIdError;
diff --git a/src/features/Conversation/Error/index.test.tsx b/src/features/Conversation/Error/index.test.tsx
index 38d3945807f..4bd1bb2fca7 100644
--- a/src/features/Conversation/Error/index.test.tsx
+++ b/src/features/Conversation/Error/index.test.tsx
@@ -5,12 +5,14 @@ import type * as lobechatTypesModule from '@lobechat/types';
import type * as lobehubUiModule from '@lobehub/ui';
import { render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import ErrorMessageExtra from './index';
const navigateMock = vi.fn();
+const serverConfigMock = vi.hoisted(() => ({ enableBusinessFeatures: false }));
+
vi.mock('@lobechat/business-const', async (importOriginal) => {
const actual = (await importOriginal()) as typeof businessConstModule;
@@ -105,7 +107,7 @@ vi.mock('@/libs/next/dynamic', () => ({
vi.mock('@/store/serverConfig', () => ({
serverConfigSelectors: {
- enableBusinessFeatures: () => false,
+ enableBusinessFeatures: () => serverConfigMock.enableBusinessFeatures,
},
useServerConfigStore: (selector: (s: unknown) => unknown) => selector({}),
}));
@@ -119,6 +121,50 @@ vi.mock('@/features/Conversation/store', () => ({
}));
describe('ErrorMessageExtra', () => {
+ beforeEach(() => {
+ serverConfigMock.enableBusinessFeatures = false;
+ });
+
+ it('keeps the localized message for known error types even when a traceId exists', () => {
+ serverConfigMock.enableBusinessFeatures = true;
+
+ render(
+ <ErrorMessageExtra
+ error={{ message: 'response.LocationNotSupportError' }}
+ data={{
+ error: {
+ body: { traceId: 'trace-123' },
+ type: 'LocationNotSupportError',
+ } as any,
+ id: 'msg-known-trace',
+ }}
+ />,
+ );
+
+ // Not swallowed by the TraceIdError fallback (rendered via mocked dynamic)
+ expect(screen.queryByText('dynamic')).not.toBeInTheDocument();
+ expect(screen.getByText('response.LocationNotSupportError')).toBeInTheDocument();
+ });
+
+ it('shows the trace-id report UI for unknown traceable errors', () => {
+ serverConfigMock.enableBusinessFeatures = true;
+
+ render(
+ <ErrorMessageExtra
+ error={{ message: 'response.SomeUnmappedError' }}
+ data={{
+ error: {
+ body: { traceId: 'trace-456' },
+ type: 'SomeUnmappedError',
+ } as any,
+ id: 'msg-unknown-trace',
+ }}
+ />,
+ );
+
+ expect(screen.getByText('dynamic')).toBeInTheDocument();
+ });
+
it('renders the auth guide when the refreshed error is missing type but still carries session code', () => {
render(
<ErrorMessageExtra
diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsx
index d65fd683780..f9f72114d27 100644
--- a/src/features/Conversation/Error/index.tsx
+++ b/src/features/Conversation/Error/index.tsx
@@ -1,7 +1,7 @@
import type { HeterogeneousAgentSessionError } from '@lobechat/electron-client-ipc';
import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';
import { type ILobeAgentRuntimeErrorType } from '@lobechat/model-runtime';
-import { AgentRuntimeErrorType } from '@lobechat/model-runtime';
+import { AgentRuntimeErrorType, getErrorCodeSpec } from '@lobechat/model-runtime';
import { type ChatMessageError, type ErrorType, type IToolErrorType } from '@lobechat/types';
import { ChatErrorType } from '@lobechat/types';
import { type AlertProps } from '@lobehub/ui';
@@ -76,6 +76,17 @@ const OllamaSetupGuide = dynamic(() => import('./OllamaSetupGuide'), {
ssr: false,
});
+const PlanLimitCard = dynamic(() => import('./PlanLimitCard'), { loading, ssr: false });
+
+const DeprecatedModelError = dynamic(() => import('./DeprecatedModelError'), {
+ loading,
+ ssr: false,
+});
+
+const QuotaLimitError = dynamic(() => import('./QuotaLimitError'), { loading, ssr: false });
+
+const TraceIdError = dynamic(() => import('./TraceIdError'), { loading, ssr: false });
+
const HETEROGENEOUS_AGENT_STATUS_GUIDE_ERROR_CODES = new Set<string>([
HeterogeneousAgentSessionErrorCode.AuthRequired,
HeterogeneousAgentSessionErrorCode.CliNotFound,
@@ -83,6 +94,28 @@ const HETEROGENEOUS_AGENT_STATUS_GUIDE_ERROR_CODES = new Set<string>([
HeterogeneousAgentSessionErrorCode.RateLimit,
]);
+// `UnknownChatFetchError` is excluded: its localized copy is a generic
+// "unknown error" message, so the trace-id report UI is strictly more useful.
+const LEGACY_LOCALIZED_ERROR_TYPES = new Set<string>(
+ Object.values(ChatErrorType)
+ .map(String)
+ .filter((type) => type !== ChatErrorType.UnknownChatFetchError),
+);
+
+/**
+ * Whether `getRuntimeErrorMessage` resolves a dedicated localized message for
+ * this error type — known runtime codes (spec table) plus legacy
+ * `error:response.<X>` entries (ChatErrorType members and HTTP status codes).
+ */
+const hasLocalizedErrorMessage = (
+ errorType?: IToolErrorType | ILobeAgentRuntimeErrorType | ErrorType,
+): boolean => {
+ if (errorType === undefined || errorType === null) return false;
+ if (typeof errorType === 'number') return true;
+ if (getErrorCodeSpec(String(errorType))) return true;
+ return LEGACY_LOCALIZED_ERROR_TYPES.has(String(errorType));
+};
+
const isHeterogeneousAgentStatusGuideError = (
value: unknown,
): value is HeterogeneousAgentSessionError => {
@@ -213,6 +246,34 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data, onRe
if (enableBusinessFeatures && businessChatErrorMessageExtra) return businessChatErrorMessageExtra;
switch (error?.type) {
+ // Lightweight fallbacks for cloud billing errors, used in builds without a
+ // business override (e.g. desktop). The business hook above takes
+ // precedence when installed.
+ case ChatErrorType.FreePlanLimit:
+ case ChatErrorType.SubscriptionPlanLimit:
+ case ChatErrorType.InsufficientBudgetForModel: {
+ if (enableBusinessFeatures)
+ return (
+ <PlanLimitCard
+ errorBody={error?.body}
+ errorType={error?.type}
+ onRetry={handleRetryAgentMessage}
+ />
+ );
+ break;
+ }
+
+ case ChatErrorType.LobeHubModelDeprecated: {
+ if (enableBusinessFeatures)
+ return <DeprecatedModelError requestedModel={error?.body?.requestedModel} />;
+ break;
+ }
+
+ case AgentRuntimeErrorType.QuotaLimitReached: {
+ if (enableBusinessFeatures) return <QuotaLimitError id={data.id} />;
+ break;
+ }
+
case AgentRuntimeErrorType.OllamaServiceUnavailable: {
return <OllamaSetupGuide id={data.id} />;
}
@@ -236,6 +297,16 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data, onRe
return <ChatInvalidAPIKey id={data.id} provider={data.error?.body?.provider} />;
}
+ // Show a report action for unknown traceable errors instead of the raw body.
+ // Error types with a dedicated localized message keep the ErrorContent below.
+ if (
+ enableBusinessFeatures &&
+ !hasLocalizedErrorMessage(error?.type) &&
+ typeof error?.body?.traceId === 'string'
+ ) {
+ return <TraceIdError id={data.id} traceId={error.body.traceId} />;
+ }
+
return (
<ErrorContent
id={data.id}
diff --git a/src/features/Conversation/Error/useRetryParentMessage.test.ts b/src/features/Conversation/Error/useRetryParentMessage.test.ts
new file mode 100644
index 00000000000..570cb06d1dc
--- /dev/null
+++ b/src/features/Conversation/Error/useRetryParentMessage.test.ts
@@ -0,0 +1,71 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useRetryParentMessage } from './useRetryParentMessage';
+
+const storeMock = vi.hoisted(() => ({
+ displayMessages: [] as { id: string; parentId?: string }[],
+ regenerateUserMessage: vi.fn(async (_id: string) => {}),
+}));
+
+vi.mock('@/features/Conversation/store', () => ({
+ useConversationStore: (
+ selector: (state: {
+ displayMessages: { id: string; parentId?: string }[];
+ regenerateUserMessage: typeof storeMock.regenerateUserMessage;
+ }) => unknown,
+ ) =>
+ selector({
+ displayMessages: storeMock.displayMessages,
+ regenerateUserMessage: storeMock.regenerateUserMessage,
+ }),
+}));
+
+describe('useRetryParentMessage', () => {
+ beforeEach(() => {
+ storeMock.displayMessages = [{ id: 'assistant-message', parentId: 'user-message' }];
+ storeMock.regenerateUserMessage.mockClear();
+ });
+
+ it('should retry the parent message', async () => {
+ const { result } = renderHook(() => useRetryParentMessage('assistant-message'));
+
+ await act(async () => {
+ await result.current.retryParentMessage();
+ });
+
+ expect(result.current.disabled).toBe(false);
+ expect(storeMock.regenerateUserMessage).toHaveBeenCalledWith('user-message');
+ });
+
+ it('should run the pre-retry action before regenerating the parent message', async () => {
+ const calls: string[] = [];
+ const beforeRetry = vi.fn(async () => {
+ calls.push('before');
+ });
+ storeMock.regenerateUserMessage.mockImplementationOnce(async () => {
+ calls.push('regenerate');
+ });
+
+ const { result } = renderHook(() => useRetryParentMessage('assistant-message'));
+
+ await act(async () => {
+ await result.current.retryParentMessage(beforeRetry);
+ });
+
+ expect(beforeRetry).toHaveBeenCalledTimes(1);
+ expect(calls).toEqual(['before', 'regenerate']);
+ });
+
+ it('should skip retry when the message has no parent', async () => {
+ storeMock.displayMessages = [{ id: 'assistant-message' }];
+ const { result } = renderHook(() => useRetryParentMessage('assistant-message'));
+
+ await act(async () => {
+ await result.current.retryParentMessage();
+ });
+
+ expect(result.current.disabled).toBe(true);
+ expect(storeMock.regenerateUserMessage).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Conversation/Error/useRetryParentMessage.ts b/src/features/Conversation/Error/useRetryParentMessage.ts
new file mode 100644
index 00000000000..dcf219c6b12
--- /dev/null
+++ b/src/features/Conversation/Error/useRetryParentMessage.ts
@@ -0,0 +1,35 @@
+import { useCallback, useState } from 'react';
+
+import { useConversationStore } from '@/features/Conversation/store';
+
+type BeforeRetry = () => Promise<void> | void;
+
+export const useRetryParentMessage = (id: string) => {
+ const [loading, setLoading] = useState(false);
+
+ const regenerateUserMessage = useConversationStore((s) => s.regenerateUserMessage);
+ const parentId = useConversationStore(
+ (s) => s.displayMessages.find((m) => m.id === id)?.parentId,
+ );
+
+ const retryParentMessage = useCallback(
+ async (beforeRetry?: BeforeRetry) => {
+ if (!parentId) return;
+
+ setLoading(true);
+ try {
+ await beforeRetry?.();
+ await regenerateUserMessage(parentId);
+ } finally {
+ setLoading(false);
+ }
+ },
+ [parentId, regenerateUserMessage],
+ );
+
+ return {
+ disabled: !parentId,
+ loading,
+ retryParentMessage,
+ };
+};