Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): Cindy AI 卡片重构为账户资产模块,补齐余额与充值引导 (#1454)

Chris Zhang7cb6c3438e2e
diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
index 7f74470704..c4af0127ab 100644
--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
@@ -952,6 +952,32 @@ describe('onTurnErrorEvent — terminal error 持久化', () => {
expect(content.sdkError).toBe('access_token=[REDACTED]');
});
+ it('content 携带错误发生时的 provider 快照(session-provider-store 同步取值)', async () => {
+ const { setSessionProvider } = await import('../maker-host/session-provider-store.js');
+ const sid = 'session-provider-snapshot';
+ setSessionProvider(sid, 'xd');
+ try {
+ onTurnErrorEvent(sid, { message: '网关余额不足(provider 快照用例)' });
+ await flushWrites();
+ const body = vi.mocked(createMessage).mock.calls.at(-1)?.[1] as {
+ content: Record<string, unknown>;
+ };
+ expect(body.content.providerId).toBe('xd');
+ } finally {
+ setSessionProvider(sid, null);
+ }
+ });
+
+ it('未显式选择 provider(默认路由)时不写 providerId —— 来源不明的行读侧 fail-closed', async () => {
+ const sid = 'session-provider-unset';
+ onTurnErrorEvent(sid, { message: '无显式 provider 的失败(快照用例)' });
+ await flushWrites();
+ const body = vi.mocked(createMessage).mock.calls.at(-1)?.[1] as {
+ content: Record<string, unknown>;
+ };
+ expect('providerId' in body.content).toBe(false);
+ });
+
it('error 前的在飞 assistant 文本先 flush 落库,error 行排在其后', async () => {
onAssistantTextEvent(SESSION, { text: '正在收尾…', isFinal: false }, null);
onTurnErrorEvent(SESSION, { message: 'turn 崩了' });
diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.ts
index e77bbd348f..a4b86f6357 100644
--- a/apps/desktop/src/main/messagePersistBroadcaster.ts
+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts
@@ -45,6 +45,7 @@ import { createLogger } from './logger.js';
import { tapWindowBroadcast } from './device-link/broadcast-tap.js';
import { takeMediaToolResult } from './mcp-integrations/mediaToolResultFallback.js';
import { redactSensitiveText } from '@cindy/maker-shared/error-redaction';
+import { getSessionProvider } from './maker-host/session-provider-store.js';
import type { AgentMeta } from '../renderer/lib/ccAgent.types';
const log = createLogger('messagePersistBroadcaster');
@@ -1153,6 +1154,14 @@ export function onTurnErrorEvent(
if (typeof data?.sdkError === 'string' && data.sdkError) {
content.sdkError = redactSensitiveText(data.sdkError);
}
+ // 错误来源 provider 的**同步**快照(session-provider-store 内存态):错误分类必须
+ // 绑定到错误发生时的 provider —— session.providerId 可在任务中途切换并持久化,
+ // 恢复历史错误时用它会把别家 provider 的 insufficient_quota 误判成 Cindy AI 余额
+ // 不足(或反向丢失充值入口)。在入队前取值,写队列延迟消费不影响快照语义。
+ // null(未显式选择,走默认路由)时不写字段:来源不明确的错误行,读侧一律不启用
+ // 余额分类(fail-closed),与 live 路径「显式 providerId 才分类」同一判据。
+ const providerIdAtError = getSessionProvider(sessionId);
+ if (providerIdAtError) content.providerId = providerIdAtError;
const meta = agentMeta ?? lastAgentMetaBySession.get(sessionId) ?? null;
const dbAgentKindSnapshot = getSessionDbAgentKind(sessionId) ?? undefined;
enqueueWrite(`turn_error:${sessionId}:${persistId}`, async () => {
diff --git a/apps/desktop/src/renderer/__tests__/errorBannerGatewayQuota.test.tsx b/apps/desktop/src/renderer/__tests__/errorBannerGatewayQuota.test.tsx
new file mode 100644
index 0000000000..8739462839
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/errorBannerGatewayQuota.test.tsx
@@ -0,0 +1,211 @@
+// @vitest-environment jsdom
+
+/**
+ * ErrorBanner — Cindy AI 网关余额耗尽的导流不变量:
+ * 1. 来源确定是 xd 且计费面可见(父组件传了 onViewBalance)→ 文案换成「余额不足,
+ * 请充值后继续」并给出右端内联「查看余额」。
+ * 2. 来源是其它供应商 → 一个字都不改,也不加按钮(没有可跳的地方)。
+ * 3. 来源是 xd 但计费面不可见(org / local,父组件不传回调)→ 同样不改、不加按钮。
+ * 4. 非余额类错误不被这条分支吃掉。
+ */
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createElement } from 'react';
+
+const { useCodexRuntimeRouteMock } = vi.hoisted(() => ({
+ useCodexRuntimeRouteMock: vi.fn(),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({
+ useConfirmDialog: () => ({ confirm: async () => true }),
+}));
+
+vi.mock('@/hooks/useCodexRuntimeRoute', () => ({
+ useCodexRuntimeRoute: useCodexRuntimeRouteMock,
+}));
+
+vi.mock('@/hooks/useCodexSessionExpiredPrompt', () => ({
+ isCodexSessionExpiredError: () => false,
+ useCodexSessionExpiredPrompt: () => vi.fn(),
+}));
+
+import { ErrorBanner } from '@/components/chat/ErrorBanner';
+
+const QUOTA_ERROR = 'litellm.BadRequestError: insufficient_quota for this key';
+
+beforeEach(() => {
+ useCodexRuntimeRouteMock.mockReturnValue({ authInjection: 'env-key' });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('ErrorBanner — Cindy AI 余额不足导流', () => {
+ it('来源是 xd 且计费面可见时换文案并给「查看余额」出口', () => {
+ const onViewBalance = vi.fn();
+
+ render(
+ createElement(ErrorBanner, {
+ error: QUOTA_ERROR,
+ onRetry: vi.fn(),
+ agentKind: 'cc',
+ providerId: 'xd',
+ errorSourceProviderId: 'xd',
+ onViewBalance,
+ }),
+ );
+
+ expect(screen.getByText('chat.errorBanner.gatewayQuotaExhausted')).toBeTruthy();
+ expect(screen.queryByText(QUOTA_ERROR)).toBeNull();
+ fireEvent.click(screen.getByTitle('chat.errorBanner.viewBalanceTitle'));
+ expect(onViewBalance).toHaveBeenCalledOnce();
+ });
+
+ it('余额不足不隐藏 Retry —— 充值后原样重试就该成功', () => {
+ const onRetry = vi.fn();
+
+ render(
+ createElement(ErrorBanner, {
+ error: QUOTA_ERROR,
+ retryText: 'retry-token',
+ onRetry,
+ agentKind: 'cc',
+ providerId: 'xd',
+ errorSourceProviderId: 'xd',
+ onViewBalance: vi.fn(),
+ }),
+ );
+
+ fireEvent.click(screen.getByTitle('chat.errorBanner.retryTitle'));
+ expect(onRetry).toHaveBeenCalledWith('retry-token');
+ });
+
+ it('其它供应商保持现状:不改文案、不加按钮', () => {
+ render(
+ createElement(ErrorBanner, {
+ error: QUOTA_ERROR,
+ onRetry: vi.fn(),
+ agentKind: 'cc',
+ providerId: 'anthropic',
+ errorSourceProviderId: 'anthropic',
+ onViewBalance: vi.fn(),
+ }),
+ );
+
+ expect(screen.getByText(QUOTA_ERROR)).toBeTruthy();
+ expect(screen.queryByText('chat.errorBanner.gatewayQuotaExhausted')).toBeNull();
+ expect(screen.queryByTitle('chat.errorBanner.viewBalanceTitle')).toBeNull();
+ });
+
+ it('错误来源不明(无 errorSourceProviderId)时不启用余额分类 —— 即使会话当前是 xd', () => {
+ render(
+ createElement(ErrorBanner, {
+ error: QUOTA_ERROR,
+ onRetry: vi.fn(),
+ agentKind: 'cc',
+ // 会话当前 provider 是 xd,但这条错误的来源快照缺失(老数据):fail-closed。
+ providerId: 'xd',
+ onViewBalance: vi.fn(),
+ }),
+ );
+
+ expect(screen.getByText(QUOTA_ERROR)).toBeTruthy();
+ expect(screen.queryByTitle('chat.errorBanner.viewBalanceTitle')).toBeNull();
+ });
+
+ it('计费面对当前账号不可见(org / local,父组件不传回调)时不给点不出结果的按钮', () => {
+ render(
+ createElement(ErrorBanner, {
+ error: QUOTA_ERROR,
+ onRetry: vi.fn(),
+ agentKind: 'cc',
+ providerId: 'xd',
+ errorSourceProviderId: 'xd',
+ }),
+ );
+
+ expect(screen.getByText(QUOTA_ERROR)).toBeTruthy();
+ expect(screen.queryByText('chat.errorBanner.gatewayQuotaExhausted')).toBeNull();
+ expect(screen.queryByTitle('chat.errorBanner.viewBalanceTitle')).toBeNull();
+ });
+
+ it('非余额类错误不被这条分支吃掉', () => {
+ render(
+ createElement(ErrorBanner, {
+ error: 'Selected model is at capacity. Please try a different model.',
+ onRetry: vi.fn(),
+ agentKind: 'cc',
+ providerId: 'xd',
+ errorSourceProviderId: 'xd',
+ onViewBalance: vi.fn(),
+ }),
+ );
+
+ expect(screen.queryByText('chat.errorBanner.gatewayQuotaExhausted')).toBeNull();
+ expect(screen.queryByTitle('chat.errorBanner.viewBalanceTitle')).toBeNull();
+ });
+
+ it('持久化错误行(ErrorTailErrorBanner)同样透传「查看余额」—— 重载后恢复的历史余额错误不退化', async () => {
+ const { ErrorTailErrorBanner } = await import('@/components/chat/InterruptedTurnBanner');
+ const onViewBalance = vi.fn();
+
+ render(
+ createElement(ErrorTailErrorBanner, {
+ errorText: QUOTA_ERROR,
+ onContinue: vi.fn(),
+ onDismiss: vi.fn(),
+ agentKind: 'cc',
+ providerId: 'xd',
+ errorSourceProviderId: 'xd',
+ onViewBalance,
+ }),
+ );
+
+ expect(screen.getByText('chat.errorBanner.gatewayQuotaExhausted')).toBeTruthy();
+ fireEvent.click(screen.getByTitle('chat.errorBanner.viewBalanceTitle'));
+ expect(onViewBalance).toHaveBeenCalledTimes(1);
+ });
+
+ it('报错后切换 provider:来源快照是 xd、会话已切到 openai → 充值入口不丢', () => {
+ const onViewBalance = vi.fn();
+ render(
+ createElement(ErrorBanner, {
+ error: QUOTA_ERROR,
+ onRetry: vi.fn(),
+ agentKind: 'cc',
+ // 会话当前 provider 已经切走,但错误发生在 xd 上 —— 分类跟来源走。
+ providerId: 'openai',
+ errorSourceProviderId: 'xd',
+ onViewBalance,
+ }),
+ );
+
+ expect(screen.getByText('chat.errorBanner.gatewayQuotaExhausted')).toBeTruthy();
+ fireEvent.click(screen.getByTitle('chat.errorBanner.viewBalanceTitle'));
+ expect(onViewBalance).toHaveBeenCalledOnce();
+ });
+
+ it('报错后切换 provider:来源快照是 openai、会话切到 xd → 不误挂 Cindy AI 充值入口', () => {
+ render(
+ createElement(ErrorBanner, {
+ error: QUOTA_ERROR,
+ onRetry: vi.fn(),
+ agentKind: 'cc',
+ providerId: 'xd',
+ errorSourceProviderId: 'openai',
+ onViewBalance: vi.fn(),
+ }),
+ );
+
+ expect(screen.getByText(QUOTA_ERROR)).toBeTruthy();
+ expect(screen.queryByText('chat.errorBanner.gatewayQuotaExhausted')).toBeNull();
+ expect(screen.queryByTitle('chat.errorBanner.viewBalanceTitle')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx b/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx
new file mode 100644
index 0000000000..f025592484
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx
@@ -0,0 +1,290 @@
+// @vitest-environment jsdom
+
+/**
+ * ProvidersSection — Cindy AI 卡片的「账户资产模块」不变量:
+ * 1. 个人云账号 + 拿到余额 → 标题行下方出现「可用余额 + 金额 + 查看用量 + 余额充值」,
+ * 两个动作分别深链到计费页与计费页的充值意图。
+ * 2. 企业账号 → 整块不渲染(不是灰置、不给占位)。
+ * 3. 凭据同步失败 → 故障说明 + 重试,且**不显示「已连接」**(凭据没同步上,说已连接是假的)。
+ * 4. 正常态版面上不出现「重试 / 重新获取凭据 / 轮换密钥」这类按钮 —— 它们退进「···」菜单。
+ */
+
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import React from 'react';
+import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ProviderView } from '@cindy/model-providers';
+
+const { providersState, authState, creditUsageState, modelAccessState, apiKeyState } = vi.hoisted(
+ () => ({
+ providersState: { providers: [] as unknown[], order: [] as string[] },
+ authState: {
+ mode: 'cloud' as 'cloud' | 'local' | 'signed-out',
+ user: { membershipKind: 'personal' } as { membershipKind: 'personal' | 'org' } | null,
+ dataOwnerId: 'account-1' as string | null,
+ },
+ creditUsageState: { available: null as string | null },
+ modelAccessState: {
+ state: 'ok' as 'ok' | 'failed' | 'unsupported' | 'idle' | 'syncing' | 'disabled',
+ source: 'server' as string | null,
+ },
+ apiKeyState: { key: 'sk-live-abcd1234ef2a', hasSavedKey: true },
+ }),
+);
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ i18n: { language: 'zh-CN', resolvedLanguage: 'zh-CN' },
+ }),
+}));
+
+vi.mock('@/hooks/useProviders', () => ({
+ useProviders: () => ({
+ providers: providersState.providers,
+ providerOrder: providersState.order,
+ ownerGeneration: 1,
+ loading: false,
+ refetch: vi.fn(),
+ }),
+}));
+
+vi.mock('@/contexts/AuthContext', () => ({
+ useAuth: () => ({ ...authState, exitLocalMode: vi.fn(async () => undefined) }),
+}));
+
+vi.mock('@/hooks/useModelAccessCreditUsage', () => ({
+ useModelAccessCreditUsage: (enabled: boolean) =>
+ enabled && creditUsageState.available !== null
+ ? { available: creditUsageState.available }
+ : null,
+}));
+
+vi.mock('@/hooks/useModelAccessStatus', () => ({
+ useModelAccessStatus: () => ({ ...modelAccessState, endpoint: null }),
+}));
+
+vi.mock('@/hooks/useApiKey', () => ({
+ useApiKey: () => ({ ...apiKeyState, clearKey: vi.fn(async () => true) }),
+}));
+
+vi.mock('@/hooks/useCodexAuth', () => ({
+ isChatGptConnectionConnected: () => false,
+ useCodexAuth: () => ({
+ state: { kind: 'unauthenticated' },
+ reconnectCredentialScope: undefined,
+ recoveryCheck: 'idle',
+ refresh: vi.fn(async () => undefined),
+ triggerLogin: vi.fn(async () => 'authenticated'),
+ cancelLogin: vi.fn(async () => undefined),
+ logout: vi.fn(async () => undefined),
+ }),
+}));
+
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({
+ useConfirmDialog: () => ({ confirm: vi.fn(async () => true) }),
+}));
+
+vi.mock('@/lib/toast', () => ({
+ toast: { error: vi.fn(), success: vi.fn() },
+}));
+
+vi.mock('@/lib/customProviders', () => ({
+ appendDiscoveredCustomProviderModels: vi.fn(),
+ deleteCustomProvider: vi.fn(),
+ providerViewToCustomProviderConfig: vi.fn(),
+ readCustomProviderKey: vi.fn(async () => null),
+ updateCustomProvider: vi.fn(),
+}));
+
+vi.mock('@/lib/providerModels', () => ({
+ providerMonogram: () => 'X',
+}));
+
+vi.mock('@/lib/providerSubtitle', () => ({
+ customProviderSubtitleForDisplay: () => '',
+ providerSubtitleForDisplay: () => 'subtitle',
+}));
+
+vi.mock('@/state/modelVisibilityPrefs', () => ({
+ isModelEnabled: () => true,
+ setManyVisibility: vi.fn(),
+ setModelVisibility: vi.fn(),
+ useModelVisibilityVersion: () => 0,
+}));
+
+vi.mock('@/components/settings/CustomProviderDialog', () => ({
+ CustomProviderDialog: () => null,
+}));
+
+vi.mock('@/components/settings/AddProviderWizard', () => ({
+ AddProviderWizard: () => React.createElement('div', { 'data-testid': 'wizard-stub' }),
+}));
+
+vi.mock('@/features/billing/money', () => ({
+ BILLING_CURRENCY: 'cny',
+ formatBillingAmount: (amount: string, currency: string) => `${currency}:${amount}`,
+}));
+
+import { ProvidersSection } from '@/components/settings/ProvidersSection';
+
+function makeXd(): ProviderView {
+ return {
+ id: 'xd',
+ name: 'Cindy AI',
+ source: 'builtin',
+ agents: ['claude-code', 'codex'],
+ auth: { method: 'managed' },
+ routing: {},
+ models: { 'claude-code': [], codex: [] },
+ connected: true,
+ } as unknown as ProviderView;
+}
+
+function SearchProbe() {
+ const location = useLocation();
+ return <div data-testid="search">{`${location.pathname}${location.search}`}</div>;
+}
+
+function renderSection() {
+ return render(
+ <MemoryRouter initialEntries={['/settings?tab=providers']}>
+ <Routes>
+ <Route
+ path="/settings"
+ element={
+ <>
+ <ProvidersSection />
+ <SearchProbe />
+ </>
+ }
+ />
+ </Routes>
+ </MemoryRouter>,
+ );
+}
+
+beforeEach(() => {
+ providersState.order = [];
+ providersState.providers = [makeXd()];
+ authState.mode = 'cloud';
+ authState.user = { membershipKind: 'personal' };
+ authState.dataOwnerId = 'account-1';
+ creditUsageState.available = '18.42';
+ modelAccessState.state = 'ok';
+ modelAccessState.source = 'server';
+ apiKeyState.hasSavedKey = true;
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ maker: {
+ scanLocalCli: vi.fn(async () => ({ detections: [] })),
+ requestProviderModelsAutoRefresh: vi.fn(async () => ({ ok: true })),
+ setProviderOrder: vi.fn(async () => ({ ok: true })),
+ },
+ modelAccess: {
+ retry: vi.fn(async () => undefined),
+ rotate: vi.fn(async () => undefined),
+ },
+ };
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('ProvidersSection — Cindy AI 账户资产模块', () => {
+ it('个人云账号:显示可用余额 + 两个动作,并深链到计费页 / 充值意图', async () => {
+ renderSection();
+
+ expect(await screen.findByText('billing.balance.title')).toBeTruthy();
+ // 金额走 money.ts 的格式化 + BILLING_CURRENCY,不在这里自己拼字符串。
+ expect(screen.getByText('cny:18.42')).toBeTruthy();
+
+ fireEvent.click(screen.getByText('settings.providers.xd.asset.viewUsage'));
+ await waitFor(() =>
+ expect(screen.getByTestId('search').textContent).toBe('/settings?tab=billing'),
+ );
+
+ fireEvent.click(screen.getByText('billing.settings.topupCard.action'));
+ await waitFor(() =>
+ expect(screen.getByTestId('search').textContent).toBe('/settings?tab=billing&intent=topup'),
+ );
+
+ // Black Pill(最高强调档)必须用 pure 对(DESIGN.md §4 button/cta):
+ // --accent-cta-bg-pure + --accent-pure-cta-fg;--accent-cta-bg 在默认 Light
+ // 下是 #262626,差一档,回归防再犯。
+ const topupButton = screen.getByText('billing.settings.topupCard.action').closest('button');
+ expect(topupButton?.style.backgroundColor).toBe('var(--accent-cta-bg-pure)');
+ expect(topupButton?.style.color).toBe('var(--accent-pure-cta-fg)');
+ });
+
+ it('正常态版面上没有重试 / 轮换 / 重新获取凭据按钮(它们退进「···」菜单)', async () => {
+ renderSection();
+
+ await screen.findByText('billing.balance.title');
+ expect(screen.queryByText('settings.providers.xd.sync.retry')).toBeNull();
+ expect(screen.queryByText('settings.providers.xd.sync.rotate')).toBeNull();
+ expect(screen.queryByText('settings.providers.xd.sync.refresh')).toBeNull();
+ // 脱敏 key 也不在默认视图里。
+ expect(screen.queryByText(/sk-/)).toBeNull();
+ expect(screen.getByText('settings.providers.pill.connected')).toBeTruthy();
+ });
+
+ it('企业账号:整块资产模块不渲染,也不显示占位', async () => {
+ authState.user = { membershipKind: 'org' };
+ renderSection();
+
+ await screen.findAllByText('settings.providers.xd.title');
+ expect(screen.queryByText('billing.balance.title')).toBeNull();
+ expect(screen.queryByText('cny:18.42')).toBeNull();
+ expect(screen.queryByText('billing.settings.topupCard.action')).toBeNull();
+ });
+
+ it('local 会话(未登录云账号):同样不渲染', async () => {
+ authState.mode = 'local';
+ authState.user = null;
+ renderSection();
+
+ await screen.findAllByText('settings.providers.xd.title');
+ expect(screen.queryByText('billing.balance.title')).toBeNull();
+ });
+
+ it('拿不到余额:不渲染余额区,不显示「—」占位', async () => {
+ creditUsageState.available = null;
+ renderSection();
+
+ await screen.findAllByText('settings.providers.xd.title');
+ expect(screen.queryByText('billing.balance.title')).toBeNull();
+ expect(screen.queryByText('settings.providers.xd.asset.syncFailed')).toBeNull();
+ });
+
+ it('凭据同步失败:故障说明 + 重试,且不显示「已连接」', async () => {
+ modelAccessState.state = 'failed';
+ modelAccessState.source = null;
+ renderSection();
+
+ expect(await screen.findByText('settings.providers.xd.asset.syncFailed')).toBeTruthy();
+ expect(screen.queryByText('settings.providers.pill.connected')).toBeNull();
+
+ fireEvent.click(screen.getByText('settings.providers.xd.sync.retry'));
+ await waitFor(() => expect(window.electronAPI.modelAccess.retry).toHaveBeenCalledOnce());
+ });
+
+ it('凭据管理三项与脱敏 key 都在「···」菜单里', async () => {
+ renderSection();
+
+ // Radix 的 DropdownMenuTrigger 走 pointerdown / 键盘,jsdom 下没有 PointerEvent,
+ // 用键盘打开(与用户的键盘路径一致)。
+ fireEvent.keyDown(await screen.findByLabelText('settings.providers.detail.moreActionsAria'), {
+ key: 'Enter',
+ });
+
+ expect(await screen.findByText('settings.providers.xd.sync.refresh')).toBeTruthy();
+ expect(screen.getByText('settings.providers.xd.sync.rotate')).toBeTruthy();
+ expect(screen.getByText('settings.providers.button.disconnect')).toBeTruthy();
+ expect(screen.getByText('sk-••••••ef2a')).toBeTruthy();
+ // 共用菜单里既有的供应商级动作不被挤掉。
+ expect(screen.getByText('settings.providers.menu.disableProvider')).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/quotaError.test.ts b/apps/desktop/src/renderer/__tests__/quotaError.test.ts
new file mode 100644
index 0000000000..faf3068159
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/quotaError.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+
+import { isQuotaExhaustedErrorMessage } from '@/utils/quotaError';
+
+describe('isQuotaExhaustedErrorMessage', () => {
+ it('认得上游明确的余额 / 配额措辞', () => {
+ expect(isQuotaExhaustedErrorMessage('insufficient_quota')).toBe(true);
+ expect(isQuotaExhaustedErrorMessage('Your credit balance is insufficient balance')).toBe(true);
+ expect(isQuotaExhaustedErrorMessage('quota exceeded for this key')).toBe(true);
+ expect(isQuotaExhaustedErrorMessage('账户余额不足,请充值')).toBe(true);
+ });
+
+ it('结构化信息丢了以后仍认带上下文的 402 状态码', () => {
+ expect(isQuotaExhaustedErrorMessage('HTTP 402 Payment Required')).toBe(true);
+ expect(isQuotaExhaustedErrorMessage('request failed with status 402')).toBe(true);
+ expect(isQuotaExhaustedErrorMessage('upstream error (402)')).toBe(true);
+ expect(isQuotaExhaustedErrorMessage('code: 402')).toBe(true);
+ expect(isQuotaExhaustedErrorMessage('402 Payment Required')).toBe(true);
+ });
+
+ it('不误伤网络类 / 过载类 / 鉴权类错误', () => {
+ expect(isQuotaExhaustedErrorMessage('fetch failed: ECONNREFUSED')).toBe(false);
+ expect(isQuotaExhaustedErrorMessage('Selected model is at capacity.')).toBe(false);
+ expect(isQuotaExhaustedErrorMessage('401 Unauthorized')).toBe(false);
+ // 402 必须是独立数字,不能被 token 数、耗时之类的数字串误命中。
+ expect(isQuotaExhaustedErrorMessage('used 4021 tokens')).toBe(false);
+ });
+
+ it('正文里恰好出现的独立 402 不算状态码 —— 必须带 http/status/code 等上下文', () => {
+ expect(isQuotaExhaustedErrorMessage('processed 402 rows before failing')).toBe(false);
+ expect(isQuotaExhaustedErrorMessage('账单金额 402 元,写入失败')).toBe(false);
+ expect(isQuotaExhaustedErrorMessage('line 402: unexpected token')).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/useLiveErrorSourceProvider.test.tsx b/apps/desktop/src/renderer/__tests__/useLiveErrorSourceProvider.test.tsx
new file mode 100644
index 0000000000..236ecaed0e
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/useLiveErrorSourceProvider.test.tsx
@@ -0,0 +1,87 @@
+// @vitest-environment jsdom
+
+/**
+ * live 错误来源快照的三条不变量:
+ * 1. 快照:错误出现时取当时的 provider,错误存续期间切 provider 不跟随;
+ * 2. 任务边界:同一组件实例跨 sessionId 复用、错误文本恰好相同时,快照必须
+ * 按新任务重新取值(review 实锤:只跟 error 走会沿用上一任务的来源,
+ * 把错误引向错误的充值入口);
+ * 3. 错误清除 → 快照归零。
+ */
+
+import { act, cleanup, render } from '@testing-library/react';
+import { afterEach, describe, expect, it } from 'vitest';
+import { createElement } from 'react';
+
+import { useLiveErrorSourceProvider } from '@/hooks/useLiveErrorSourceProvider';
+
+let latest: string | null = null;
+
+function Probe({
+ error,
+ sessionId,
+ providerId,
+}: {
+ error: string | null;
+ sessionId: string;
+ providerId: string | null;
+}) {
+ latest = useLiveErrorSourceProvider(error, sessionId, providerId);
+ return null;
+}
+
+afterEach(() => {
+ cleanup();
+ latest = null;
+});
+
+describe('useLiveErrorSourceProvider', () => {
+ it('错误出现时快照当时的 provider,之后切 provider 不跟随', () => {
+ const { rerender } = render(
+ createElement(Probe, { error: null, sessionId: 's1', providerId: 'xd' }),
+ );
+ expect(latest).toBeNull();
+
+ act(() => {
+ rerender(createElement(Probe, { error: 'insufficient_quota', sessionId: 's1', providerId: 'xd' }));
+ });
+ expect(latest).toBe('xd');
+
+ // 报错后切到 openai:快照保持 xd —— 充值入口不丢。
+ act(() => {
+ rerender(createElement(Probe, { error: 'insufficient_quota', sessionId: 's1', providerId: 'openai' }));
+ });
+ expect(latest).toBe('xd');
+ });
+
+ it('同一错误文本跨任务复用组件实例时,按新任务重新取值', () => {
+ const { rerender } = render(
+ createElement(Probe, { error: 'insufficient_quota', sessionId: 's1', providerId: 'xd' }),
+ );
+ expect(latest).toBe('xd');
+
+ // 切到另一个任务,错误文本恰好相同、provider 是 openai:
+ // 快照必须重取,不能把 s1 的 xd 来源带给 s2 的错误。
+ act(() => {
+ rerender(createElement(Probe, { error: 'insufficient_quota', sessionId: 's2', providerId: 'openai' }));
+ });
+ expect(latest).toBe('openai');
+ });
+
+ it('错误清除后快照归零;再次报错重新取值', () => {
+ const { rerender } = render(
+ createElement(Probe, { error: 'quota exceeded', sessionId: 's1', providerId: 'xd' }),
+ );
+ expect(latest).toBe('xd');
+
+ act(() => {
+ rerender(createElement(Probe, { error: null, sessionId: 's1', providerId: 'openai' }));
+ });
+ expect(latest).toBeNull();
+
+ act(() => {
+ rerender(createElement(Probe, { error: 'quota exceeded again', sessionId: 's1', providerId: 'openai' }));
+ });
+ expect(latest).toBe('openai');
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
index fa0c794e18..290c0724a2 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
@@ -13,7 +13,17 @@
*/
import { useEffect, useState } from 'react';
-import { AlertCircle, Check, GitFork, Play, RotateCcw, RefreshCw, Timer, X } from 'lucide-react';
+import {
+ AlertCircle,
+ Check,
+ GitFork,
+ Play,
+ RotateCcw,
+ RefreshCw,
+ Timer,
+ Wallet,
+ X,
+} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { toast } from '@/lib/toast';
import { Spinner } from '@/components/ui/spinner';
@@ -30,6 +40,7 @@ import { cn } from '@/lib/utils';
import { isInvalidEncryptedContentError } from '@/utils/encryptedContentError';
import { isNetworkishErrorMessage, parseReconnectAttemptMessage } from '@/utils/networkError';
import { isOverloadErrorMessage, parseOverloadRetryProgress } from '@/utils/overloadError';
+import { isQuotaExhaustedErrorMessage } from '@/utils/quotaError';
import { CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON } from '../../../shared/claudeGatewayError';
import { isPiImageInputUnsupportedError } from '../../../shared/inputError';
@@ -64,6 +75,21 @@ interface ErrorBannerProps {
/** XD Gateway 返回了误导性的 Claude Pro/Opus 套餐错误时,切到已连接的
* Claude.ai 订阅来源并重试本轮。未连接 Anthropic 时不提供此操作。 */
onSwitchToClaudeSubscription?: () => Promise<void>;
+ /**
+ * 打开「用量和计费」查看余额并充值。**只有在计费面对当前账号可见时**(cloud +
+ * personal,判据 `canAccessBillingSettings`)父组件才传它 —— 判定留在有 Auth
+ * 上下文的父组件里,横幅只负责「有出口就给出口」。为空即视为没有可跳的地方:
+ * 此时余额不足的错误保持原样文案、不加按钮(加一个点不出结果的按钮比不加更糟)。
+ */
+ onViewBalance?: () => void;
+ /**
+ * **产生这条错误的** provider(错误发生时刻的快照)。余额分类只认它,不认上面的
+ * `providerId` —— providerId 是会话当前值,任务中途可切换并持久化:历史错误恢复
+ * 或报错后切换 provider 时,用当前值会把别家的 insufficient_quota 误判成 Cindy AI
+ * 余额不足(或反向丢失充值入口)。null/undefined = 来源不明,不启用余额分类。
+ * live 路径由父组件在错误出现时刻快照;持久化路径读 error 行自带的 errorProviderId。
+ */
+ errorSourceProviderId?: string | null;
silentEncryptedRetryEnabled?: boolean;
onForkStripEncrypted?: () => void | Promise<void>;
forkStripEncryptedRunning?: boolean;
@@ -89,6 +115,8 @@ export function ErrorBanner({
modelId,
providerId,
onSwitchToClaudeSubscription,
+ onViewBalance,
+ errorSourceProviderId,
silentEncryptedRetryEnabled = false,
onForkStripEncrypted,
forkStripEncryptedRunning = false,
@@ -150,6 +178,15 @@ export function ErrorBanner({
// 不能因为错误文案碰巧含 token_revoked 就引导用户去修 ChatGPT 登录态。历史无来源
// 会话仍允许从非 provider-oauth runtime + 非 XD/xAI 前缀推断 OpenAI,守住旧数据兼容。
const normalizedProviderId = providerId?.trim() || null;
+ // Cindy AI 网关的余额耗尽:钱花完那一刻是用户最需要计费页的时刻,给一条能就地
+ // 跳过去的出口。判定绑定**错误来源** provider(errorSourceProviderId,错误发生
+ // 时刻的快照),不用会话当前的 providerId —— 报错后切换 provider / 恢复历史错误
+ // 时两者会分叉,用当前值会误判来源。来源不明确(null)或非 xd 的错误一个字都不改
+ // (保持原始上游文案与既有交互):没有可跳的余额页时,给按钮点不出结果比不给更糟。
+ const isGatewayQuotaExhausted =
+ (errorSourceProviderId?.trim() || null) === 'xd' &&
+ Boolean(onViewBalance) &&
+ isQuotaExhaustedErrorMessage(error);
const hasExplicitOpenAiProvider = normalizedProviderId === 'openai';
const hasImplicitOpenAiProvider =
normalizedProviderId === null &&
@@ -267,6 +304,10 @@ export function ErrorBanner({
displayError = t('chat.errorBanner.codexAuthMissingLocal');
} else if (isClaudeGatewayOpusPlanMismatch) {
displayError = t('chat.errorBanner.claudeGatewayOpusPlanMismatch');
+ } else if (isGatewayQuotaExhausted) {
+ // 「配额或余额不足,请检查供应商账户」对网关用户是半句话:账户就在 Cindy 里,
+ // 该说的是「去充值」而不是「去检查」。右端的内联出口负责「去哪充」。
+ displayError = t('chat.errorBanner.gatewayQuotaExhausted');
} else if (isOverloadError) {
// 服务过载:上游模型没有可用容量。原始英文("Selected model is at capacity")
// 对用户没有行动价值,换成友好文案 + 明确的下一步;原始错误折叠可查。
@@ -522,6 +563,22 @@ export function ErrorBanner({
: t('chat.errorBanner.switchClaudeSubscription')}
</button>
)}
+ {isGatewayQuotaExhausted && onViewBalance && (
+ // 与「切换到 Claude.ai 并重试」同一档低打扰内联恢复动作:不弹窗、不抢焦点。
+ <button
+ type="button"
+ onClick={onViewBalance}
+ className={cn(
+ 'shrink-0 flex select-none items-center gap-1 text-xs font-medium',
+ 'text-[var(--error-fg-strong)]',
+ 'hover:opacity-70 transition-opacity',
+ )}
+ title={t('chat.errorBanner.viewBalanceTitle')}
+ >
+ <Wallet size={12} />
+ {t('chat.errorBanner.viewBalance')}
+ </button>
+ )}
{isCodexRemoteAuthMissing && !syncedSinceError && (
<button
type="button"
diff --git a/apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx b/apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx
index ac8e21b468..799d1202b6 100644
--- a/apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx
@@ -117,6 +117,8 @@ export function ErrorTailErrorBanner({
modelId,
providerId,
onSwitchToClaudeSubscription,
+ onViewBalance,
+ errorSourceProviderId,
silentEncryptedRetryEnabled,
onForkStripEncrypted,
forkStripEncryptedRunning,
@@ -136,6 +138,10 @@ export function ErrorTailErrorBanner({
modelId?: string;
providerId?: string | null;
onSwitchToClaudeSubscription?: () => Promise<void>;
+ /** 网关余额耗尽的历史错误行同样要有计费页出口 —— 语义与 ErrorBanner 同名 prop 一致。 */
+ onViewBalance?: () => void;
+ /** 产生该错误的 provider(error 行持久化的快照);undefined = 来源不明,不启用余额分类。 */
+ errorSourceProviderId?: string | null;
silentEncryptedRetryEnabled?: boolean;
onForkStripEncrypted?: () => void | Promise<void>;
forkStripEncryptedRunning?: boolean;
@@ -158,6 +164,8 @@ export function ErrorTailErrorBanner({
modelId={modelId}
providerId={providerId}
onSwitchToClaudeSubscription={onSwitchToClaudeSubscription}
+ onViewBalance={onViewBalance}
+ errorSourceProviderId={errorSourceProviderId}
silentEncryptedRetryEnabled={silentEncryptedRetryEnabled}
onForkStripEncrypted={onForkStripEncrypted}
forkStripEncryptedRunning={forkStripEncryptedRunning}
diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
index 81f3b043c9..ac98f9f237 100644
--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
@@ -18,15 +18,28 @@
*/
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
-import { useSearchParams } from 'react-router-dom';
+import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
-import { Check, GripVertical, MoreHorizontal, Pencil, Plus, RefreshCw, Trash2 } from 'lucide-react';
+import {
+ Check,
+ Copy,
+ Gift,
+ GripVertical,
+ KeyRound,
+ LogOut,
+ MoreHorizontal,
+ Pencil,
+ Plus,
+ RefreshCw,
+ Trash2,
+} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useProviders } from '@/hooks/useProviders';
import { isChatGptConnectionConnected, useCodexAuth } from '@/hooks/useCodexAuth';
import { useApiKey } from '@/hooks/useApiKey';
import { useModelAccessStatus } from '@/hooks/useModelAccessStatus';
+import { useModelAccessCreditUsage } from '@/hooks/useModelAccessCreditUsage';
import { useReducedMotion } from '@/hooks/useReducedMotion';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { useSignInToCindy } from '@/hooks/useSignInToCindy';
@@ -51,8 +64,12 @@ import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
+import { BILLING_CURRENCY, formatBillingAmount } from '@/features/billing/money';
+import { canAccessBillingSettings } from './billingVisibility';
+import { resolveXdAssetModuleState } from './providerAssetModule';
import { CustomProviderDialog } from './CustomProviderDialog';
import { AddProviderWizard, type WizardEntry } from './AddProviderWizard';
import { OAuthDeviceCodeCard } from './OAuthDeviceCodeCard';
@@ -186,6 +203,44 @@ function PillButton({
);
}
+/**
+ * 黑 CTA pill(DESIGN §4 button/cta)—— 一屏最多一颗,用于「在 Cindy 内花钱」这类
+ * 主动作。`lg` 是 brand-scale 表面(登录引导空态)用的尺码,`md` 与 PillButton 同高,
+ * 用于卡片内与次级动作并排的场合。
+ */
+function CtaPillButton({
+ label,
+ onClick,
+ size = 'md',
+ className,
+}: {
+ label: string;
+ onClick: () => void;
+ size?: 'md' | 'lg';
+ className?: string;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={cn(
+ 'flex shrink-0 items-center justify-center rounded-full px-6 text-13 font-medium transition-opacity hover:opacity-90',
+ size === 'lg' ? 'h-9' : 'h-8',
+ className,
+ )}
+ style={{
+ // Black Pill(最高强调档)按 DESIGN.md §4 用 pure 对:--accent-cta-bg-pure
+ // (Light 纯黑 / Dark 纯白反转)配 --accent-pure-cta-fg。--accent-cta-bg 在
+ // 默认 Light 下是 #262626,与规范的 #000000 差一档,不能混用。
+ backgroundColor: 'var(--accent-cta-bg-pure)',
+ color: 'var(--accent-pure-cta-fg)',
+ }}
+ >
+ {label}
+ </button>
+ );
+}
+
function CustomTag({ label }: { label: string }) {
return (
<span
@@ -235,6 +290,9 @@ function DetailHeader({
provider,
detail,
badge,
+ menuItems,
+ menuFooter,
+ assetModule,
}: {
icon: ReactNode;
title: string;
@@ -243,6 +301,15 @@ function DetailHeader({
provider?: ProviderView;
detail?: ReactNode;
badge?: ReactNode;
+ /** 供应商专属的低频动作,置于共用「···」菜单顶部(不另开第二个溢出菜单)。 */
+ menuItems?: ReactNode;
+ /** 菜单末尾的只读信息行(如脱敏 key),自带一条分隔线。 */
+ menuFooter?: ReactNode;
+ /**
+ * 账户资产模块 —— 标题行下方的固定槽位,用一条 1px 发丝线分隔(不做框中框,
+ * 见 DESIGN §2 layer rule)。判定见 providerAssetModule.ts。
+ */
+ assetModule?: ReactNode;
}) {
const { t } = useTranslation();
const hasModels = !!provider && providerHasModels(provider);
@@ -266,86 +333,91 @@ function DetailHeader({
: null;
return (
- <div className={cn('flex flex-col px-5 py-4', detail && 'gap-3')}>
- {/* 可折行:最小窗口(右栏 ~275px)放不下「状态 + 操作」时整组换行,
- 不被卡片 overflow-hidden 裁掉(PR #1102 review 第三轮)。 */}
- <div className="flex flex-wrap items-center gap-3 gap-y-2">
- <div
- className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg"
- style={{
- backgroundColor: 'var(--settings-integration-avatar-bg)',
- border: '1px solid var(--settings-integration-avatar-border)',
- color: 'var(--settings-integration-avatar-icon)',
- }}
- >
- {icon}
- </div>
+ <div className="flex shrink-0 flex-col">
+ <div className={cn('flex flex-col px-5 py-4', detail && 'gap-3')}>
+ {/* 可折行:最小窗口(右栏 ~275px)放不下「状态 + 操作」时整组换行,
+ 不被卡片 overflow-hidden 裁掉(PR #1102 review 第三轮)。 */}
+ <div className="flex flex-wrap items-center gap-3 gap-y-2">
+ <div
+ className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg"
+ style={{
+ backgroundColor: 'var(--settings-integration-avatar-bg)',
+ border: '1px solid var(--settings-integration-avatar-border)',
+ color: 'var(--settings-integration-avatar-icon)',
+ }}
+ >
+ {icon}
+ </div>
- <div className="flex min-w-0 flex-1 flex-col gap-0.5">
- <div className="flex items-center gap-2">
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <div className="flex items-center gap-2">
+ <span
+ className="min-w-0 truncate text-14 font-medium leading-tight"
+ style={{ color: 'var(--settings-section-title)' }}
+ >
+ {title}
+ </span>
+ {modelCount !== null && <ModelCountChip count={modelCount} />}
+ {subscriptionProduct && (
+ <CustomTag
+ label={t('settings.providers.models.subscriptionProduct', {
+ product: subscriptionProduct,
+ })}
+ />
+ )}
+ {provider?.suspended && <CustomTag label={t('settings.providers.pill.suspended')} />}
+ {badge}
+ </div>
<span
- className="min-w-0 truncate text-14 font-medium leading-tight"
- style={{ color: 'var(--settings-section-title)' }}
+ className="truncate text-13 leading-tight"
+ style={{ color: 'var(--settings-integration-subtitle)' }}
>
- {title}
+ {subtitle}
+ {singleAgentNote ? ` · ${singleAgentNote}` : ''}
</span>
- {modelCount !== null && <ModelCountChip count={modelCount} />}
- {subscriptionProduct && (
- <CustomTag
- label={t('settings.providers.models.subscriptionProduct', {
- product: subscriptionProduct,
- })}
- />
- )}
- {provider?.suspended && <CustomTag label={t('settings.providers.pill.suspended')} />}
- {badge}
</div>
- <span
- className="truncate text-13 leading-tight"
- style={{ color: 'var(--settings-integration-subtitle)' }}
- >
- {subtitle}
- {singleAgentNote ? ` · ${singleAgentNote}` : ''}
- </span>
+
+ {trailing}
+ {/* 供应商级低频动作(停用/启用):所有供应商详情头统一入口。停用 = 保留凭证、
+ 整体不可路由(model-disable-store);恢复入口在菜单与下方的已停用条带都有。 */}
+ {provider && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ aria-label={t('settings.providers.detail.moreActionsAria')}
+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full transition-colors hover:bg-[var(--surface-hover)]"
+ style={{ color: 'var(--text-tertiary)' }}
+ >
+ <MoreHorizontal size={15} />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {menuItems}
+ <DropdownMenuItem
+ onClick={() =>
+ writeProviderDisabled(
+ provider.id,
+ !provider.suspended,
+ t('settings.providers.models.accessWriteFailed'),
+ )
+ }
+ >
+ {t(
+ provider.suspended
+ ? 'settings.providers.menu.enableProvider'
+ : 'settings.providers.menu.disableProvider',
+ )}
+ </DropdownMenuItem>
+ {menuFooter}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
</div>
- {trailing}
- {/* 供应商级低频动作(停用/启用):所有供应商详情头统一入口。停用 = 保留凭证、
- 整体不可路由(model-disable-store);恢复入口在菜单与下方的已停用条带都有。 */}
- {provider && (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <button
- type="button"
- aria-label={t('settings.providers.detail.moreActionsAria')}
- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full transition-colors hover:bg-[var(--surface-hover)]"
- style={{ color: 'var(--text-tertiary)' }}
- >
- <MoreHorizontal size={15} />
- </button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem
- onClick={() =>
- writeProviderDisabled(
- provider.id,
- !provider.suspended,
- t('settings.providers.models.accessWriteFailed'),
- )
- }
- >
- {t(
- provider.suspended
- ? 'settings.providers.menu.enableProvider'
- : 'settings.providers.menu.disableProvider',
- )}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- )}
+ {detail}
</div>
-
- {detail}
+ {assetModule}
</div>
);
}
@@ -1022,7 +1094,14 @@ function BuiltinApiKeyHeader({
// ---------------------------------------------------------------------------
// XD 网关(Cindy AI)—— managed gateway key(useApiKey)。
-// 套餐引导 / 计费展示待服务端接口就绪后单独实现(2026-07-20 决策:本次剥离)。
+//
+// 版面口径(2026-08 计费引导 P0-1):xd 的 key 是登录后由服务端自动下发的**托管
+// 凭证**,个人用户从不手动管理它(2026-07-17「无手填入口」定案)。所以主位不给
+// 脱敏 key / 轮换 / 重新获取这三件用户几乎不碰的事,而给「我还剩多少钱、去哪充」:
+// - 标题行右端只留一个「···」溢出菜单(与所有供应商共用 DetailHeader 那一个),
+// 凭证管理三项 + 只读脱敏 key 收在里面,各自保留原有的二次确认;
+// - 标题行下方是账户资产模块(1px 发丝线分隔):可用余额 + 查看用量 + 余额充值;
+// - 故障恢复(重试)只在凭据同步失败时浮现,正常态版面上没有重试按钮。
// ---------------------------------------------------------------------------
function maskKey(key: string): string {
@@ -1037,13 +1116,31 @@ function XdGatewayHeader({
provider?: ProviderView;
onChanged: () => void;
}) {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
+ const navigate = useNavigate();
const { confirm } = useConfirmDialog();
+ const { mode, user } = useAuth();
const { key, hasSavedKey, clearKey } = useApiKey();
const syncStatus = useModelAccessStatus();
const connected = provider?.connected ?? false;
const [rotating, setRotating] = useState(false);
+ // 余额 / 充值 / 用量入口一律走同一判据:cloud + personal。org 账号是**不渲染**
+ // (不是灰置),与设置页「用量和计费」分区的可见性判定同源。
+ const billingAccessible = canAccessBillingSettings({
+ mode,
+ membershipKind: user?.membershipKind ?? null,
+ });
+ // 余额取三池账本的 available —— 与计费页余额卡、状态栏用量 chip 同一口径同一币种
+ // (见 TodaySpendChip 的「同一笔钱、必须同口径」注释)。该 hook 的防闪烁缓存按
+ // accountId 绑定,切号当帧失效,不会把上一个账号的余额显示给新账号。
+ const creditUsage = useModelAccessCreditUsage(billingAccessible);
+ const assetState = resolveXdAssetModuleState({
+ billingAccessible,
+ syncState: syncStatus.state,
+ available: creditUsage?.available ?? null,
+ });
+
// 凭据一律由服务端自动下发(个人 / 已接入企业),**无手填入口**(2026-07-17 定案)。
const serverManaged = syncStatus.state === 'ok' && syncStatus.source === 'server';
@@ -1093,6 +1190,30 @@ function XdGatewayHeader({
}
}, [confirm, onChanged, t]);
+ const maskedKey = useMemo(() => maskKey(hasSavedKey ? key : ''), [hasSavedKey, key]);
+
+ /**
+ * 只读脱敏 key 的「点击复制」复制的是**明文 key**:脱敏串本身复制出去没有用途。
+ * 这不构成新的凭证下放 —— gateway key 本来就在 renderer 侧可读(useApiKey,与
+ * 掩码展示同一份数据),这里只是把用户已经能看到的东西按他的明确点击交给剪贴板。
+ */
+ const handleCopyKey = useCallback(() => {
+ if (!hasSavedKey || !key) return;
+ void navigator.clipboard
+ .writeText(key)
+ .then(() => toast.success(t('settings.providers.xd.copyKeySuccess')))
+ .catch(() => toast.error(t('settings.providers.xd.copyKeyFailed')));
+ }, [hasSavedKey, key, t]);
+
+ const goToBilling = useCallback(
+ (intent?: 'topup') => {
+ navigate(intent ? '/settings?tab=billing&intent=topup' : '/settings?tab=billing');
+ },
+ [navigate],
+ );
+
+ // 标题行右端只剩状态位:「已连接」pill,或未连接/同步中的一句状态说明。凭证动作
+ // 全部退进「···」菜单;故障态刻意**不显示**「已连接」—— 凭据没同步上,说已连接是假的。
const trailing = (() => {
switch (syncStatus.state) {
case 'unsupported':
@@ -1103,48 +1224,17 @@ function XdGatewayHeader({
);
case 'syncing':
return (
- <PillButton
- label={t('settings.providers.xd.sync.syncing')}
- onClick={() => undefined}
- disabled
- />
+ <span className="shrink-0 text-12" style={{ color: 'var(--text-tertiary)' }}>
+ {t('settings.providers.xd.sync.syncing')}
+ </span>
);
- case 'ok':
- if (serverManaged) {
- return (
- <div className="flex shrink-0 items-center gap-2.5">
- <ConnectedPill />
- <PillButton
- label={
- rotating
- ? t('settings.providers.xd.sync.rotating')
- : t('settings.providers.xd.sync.rotate')
- }
- onClick={() => void handleRotate()}
- disabled={rotating}
- />
- </div>
- );
- }
- break;
case 'failed':
- return (
- <div className="flex shrink-0 items-center gap-2.5">
- {connected && <ConnectedPill />}
- <PillButton label={t('settings.providers.xd.sync.retry')} onClick={handleRetry} />
- </div>
- );
+ return null;
default:
break;
}
return connected ? (
- <div className="flex shrink-0 items-center gap-2.5">
- <ConnectedPill />
- <PillButton
- label={t('settings.providers.button.disconnect')}
- onClick={() => void handleDisconnect()}
- />
- </div>
+ <ConnectedPill />
) : (
<span className="shrink-0 text-12" style={{ color: 'var(--text-tertiary)' }}>
{syncStatus.state === 'disabled'
@@ -1154,34 +1244,106 @@ function XdGatewayHeader({
);
})();
- const maskedKey = useMemo(() => maskKey(hasSavedKey ? key : ''), [hasSavedKey, key]);
+ // 凭证管理三项:各自保留原有的二次确认弹窗(重新获取凭据本身无确认,与改造前一致)。
+ const menuItems = (
+ <>
+ {serverManaged && (
+ <DropdownMenuItem onClick={handleRetry}>
+ <RefreshCw size={14} className="mr-2.5 text-[var(--text-tertiary)]" />
+ {t('settings.providers.xd.sync.refresh')}
+ </DropdownMenuItem>
+ )}
+ {serverManaged && (
+ <DropdownMenuItem disabled={rotating} onClick={() => void handleRotate()}>
+ <KeyRound size={14} className="mr-2.5 text-[var(--text-tertiary)]" />
+ {rotating
+ ? t('settings.providers.xd.sync.rotating')
+ : t('settings.providers.xd.sync.rotate')}
+ </DropdownMenuItem>
+ )}
+ {connected && (
+ <DropdownMenuItem onClick={() => void handleDisconnect()}>
+ <LogOut size={14} className="mr-2.5 text-[var(--text-tertiary)]" />
+ {t('settings.providers.button.disconnect')}
+ </DropdownMenuItem>
+ )}
+ </>
+ );
- const detail =
- connected && syncStatus.state !== 'unsupported' ? (
- <div className="flex items-center gap-2.5 pl-12">
- <span
- className="flex shrink-0 items-center rounded-lg px-2 py-1 text-12"
- style={{
- backgroundColor: 'var(--surface-chip)',
- border: '1px solid var(--settings-integration-avatar-border)',
- color: 'var(--settings-section-desc)',
- }}
- >
- {maskedKey}
- </span>
- <div className="flex-1" />
- {serverManaged && (
- <button
- type="button"
- onClick={handleRetry}
- className="shrink-0 text-12 transition-colors"
- style={{ color: 'var(--settings-integration-subtitle)' }}
- >
- {t('settings.providers.xd.sync.refresh')}
- </button>
+ // 菜单末行:只读脱敏 key(点击复制)。它从主位退到这里 —— 对个人用户是纯噪音,
+ // 但排障时仍需要能拿到。
+ const menuFooter = hasSavedKey ? (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={handleCopyKey}
+ className="font-mono text-[var(--text-secondary)]"
+ aria-label={t('settings.providers.xd.copyKeyAria')}
+ >
+ <Copy size={14} className="mr-2.5 shrink-0 text-[var(--text-tertiary)]" />
+ {maskedKey}
+ </DropdownMenuItem>
+ </>
+ ) : null;
+
+ const assetModule =
+ assetState.kind === 'hidden' ? undefined : (
+ <div
+ className={cn(
+ 'flex flex-wrap justify-between gap-x-6 gap-y-4 border-t px-5 py-5',
+ assetState.kind === 'fault' ? 'items-center gap-y-3' : 'items-start',
+ )}
+ style={{ borderColor: 'var(--settings-theme-card-border)' }}
+ >
+ {assetState.kind === 'fault' ? (
+ <>
+ {/* 「本该有、这次拿不到」——讲清发生了什么 + 下一步,并就地给恢复入口
+ (DESIGN「Errors = what happened + what to do」)。 */}
+ <p
+ className="max-w-[400px] text-13 leading-relaxed"
+ style={{ color: 'var(--text-secondary)' }}
+ >
+ {t('settings.providers.xd.asset.syncFailed')}
+ </p>
+ <PillButton label={t('settings.providers.xd.sync.retry')} onClick={handleRetry} />
+ </>
+ ) : (
+ <>
+ <div className="min-w-0">
+ <p className="text-12 leading-tight" style={{ color: 'var(--text-secondary)' }}>
+ {t('billing.balance.title')}
+ </p>
+ {/* 与计费页余额卡完全同口径:20px / 500 / tabular-nums / tracking-tight。 */}
+ <p
+ className="mt-1.5 text-20 font-medium leading-[1.3] tracking-[-0.02em] tabular-nums"
+ style={{ color: 'var(--text-primary)' }}
+ >
+ {formatBillingAmount(
+ assetState.available,
+ BILLING_CURRENCY,
+ i18n.resolvedLanguage ?? i18n.language,
+ )}
+ </p>
+ </div>
+ {/* pt 与金额基线光学对齐(标签 12px + 6px 间距的一半)。 */}
+ <div className="flex shrink-0 items-center gap-4 pt-3.5">
+ <button
+ type="button"
+ onClick={() => goToBilling()}
+ className="text-13 transition-colors hover:text-[var(--text-primary)]"
+ style={{ color: 'var(--text-secondary)' }}
+ >
+ {t('settings.providers.xd.asset.viewUsage')}
+ </button>
+ <CtaPillButton
+ label={t('billing.settings.topupCard.action')}
+ onClick={() => goToBilling('topup')}
+ />
+ </div>
+ </>
)}
</div>
- ) : undefined;
+ );
return (
<DetailHeader
@@ -1193,7 +1355,9 @@ function XdGatewayHeader({
})}
trailing={trailing}
provider={provider}
- detail={detail}
+ menuItems={menuItems}
+ menuFooter={menuFooter}
+ assetModule={assetModule}
/>
);
}
@@ -2098,9 +2262,12 @@ export function ProvidersSection() {
长清单滚动时供应商名称、连接状态与工具行不随之滚走(2026-07 定稿)。 */}
<div className="flex min-w-0 flex-1 flex-col">
{cindySigninActive ? (
- <div className="flex flex-1 flex-col items-center justify-center gap-3 px-8 text-center">
+ /* 登录引导是 brand-scale surface(DESIGN §3):48px 标识 → 24px 名字 →
+ 一行价值主张 → 赠送余额徽标 → 黑 CTA,间距走 8px 系统。底部留白比
+ 顶部多,视觉重心才落在上三分之一。 */
+ <div className="flex flex-1 flex-col items-center justify-center px-10 pb-14 pt-8 text-center">
<div
- className="flex h-12 w-12 items-center justify-center rounded-xl"
+ className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl"
style={{
backgroundColor: 'var(--settings-integration-avatar-bg)',
border: '1px solid var(--settings-integration-avatar-border)',
@@ -2110,28 +2277,35 @@ export function ProvidersSection() {
<XDIncMark size={24} />
</div>
<span
- className="text-15 font-medium"
+ className="mt-4 text-24 font-medium leading-[1.2]"
style={{ color: 'var(--settings-section-title)' }}
>
{t('settings.providers.xd.title')}
</span>
<span
- className="max-w-[360px] text-13 leading-relaxed"
+ className="mt-3 max-w-[380px] text-14 leading-[1.5]"
style={{ color: 'var(--text-secondary)' }}
>
{t('settings.providers.xdSignin.desc')}
</span>
- <button
- type="button"
- onClick={() => void signInToCindy()}
- className="mt-1 flex h-9 items-center justify-center rounded-full px-6 text-13 font-medium transition-opacity hover:opacity-90"
+ {/* 赠送余额是一个安静的事实标签,不是促销文案:灰阶 chip、不写金额
+ (CN / Global 金额不同且服务端可调,数字只在计费页出现)。 */}
+ <span
+ className="mt-4 flex items-center gap-1.5 rounded-full px-3 py-1.5 text-12 font-medium"
style={{
- backgroundColor: 'var(--accent-cta-bg)',
- color: 'var(--accent-pure-cta-fg)',
+ backgroundColor: 'var(--surface-chip)',
+ color: 'var(--text-secondary)',
}}
>
- {t('settings.providers.xdSignin.cta')}
- </button>
+ <Gift size={13} />
+ {t('settings.providers.xdSignin.grantBadge')}
+ </span>
+ <CtaPillButton
+ size="lg"
+ className="mt-6"
+ label={t('settings.providers.xdSignin.cta')}
+ onClick={() => void signInToCindy()}
+ />
</div>
) : effectiveSelected ? (
<>
diff --git a/apps/desktop/src/renderer/components/settings/SettingsView.tsx b/apps/desktop/src/renderer/components/settings/SettingsView.tsx
index f7f7f3053d..cf858659d6 100644
--- a/apps/desktop/src/renderer/components/settings/SettingsView.tsx
+++ b/apps/desktop/src/renderer/components/settings/SettingsView.tsx
@@ -89,6 +89,9 @@ export function SettingsView() {
if (rawTab !== 'billing' || canAccessBilling) return;
const next = new URLSearchParams(searchParams);
next.delete('tab');
+ // 计费页不可见时它的深链意图(intent=topup)也一并作废,不留在 URL 上等着
+ // 用户切到别的 tab 再被误消费。
+ next.delete('intent');
setSearchParams(next, { replace: true });
}, [canAccessBilling, rawTab, searchParams, setSearchParams]);
@@ -118,9 +121,11 @@ export function SettingsView() {
next.delete('ghost');
next.delete('imGroup');
next.delete('section');
- // providers 页深链参数(connect/wizard):切走 tab 即作废,防再切回来被误消费。
+ // providers 页深链参数(connect/wizard)与计费页深链参数(intent):切走 tab 即
+ // 作废,防再切回来被误消费。
next.delete('connect');
next.delete('wizard');
+ next.delete('intent');
if (tab === 'general') {
next.delete('tab');
} else {
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/providerAssetModule.test.ts b/apps/desktop/src/renderer/components/settings/__tests__/providerAssetModule.test.ts
new file mode 100644
index 0000000000..aa92f2c128
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/providerAssetModule.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveXdAssetModuleState } from '../providerAssetModule';
+
+const OK = {
+ billingAccessible: true,
+ syncState: 'ok' as const,
+ available: '18.42',
+};
+
+describe('resolveXdAssetModuleState', () => {
+ it('个人云账号 + 拿到余额 → 渲染余额块', () => {
+ expect(resolveXdAssetModuleState(OK)).toEqual({ kind: 'balance', available: '18.42' });
+ });
+
+ it('企业账号 → 整个资产模块不渲染(不是灰置、不给占位、也不给重试)', () => {
+ expect(resolveXdAssetModuleState({ ...OK, billingAccessible: false })).toEqual({
+ kind: 'hidden',
+ });
+ // 关键:企业账号即使凭据同步失败也不该看到「重试余额」——那笔钱不属于这个账号。
+ expect(
+ resolveXdAssetModuleState({ ...OK, billingAccessible: false, syncState: 'failed' }),
+ ).toEqual({ kind: 'hidden' });
+ });
+
+ it('凭据同步失败 → 故障态(本该有、这次拿不到,所以给重试)', () => {
+ expect(resolveXdAssetModuleState({ ...OK, syncState: 'failed' })).toEqual({ kind: 'fault' });
+ // 故障态优先于「余额还没回来」:两者同时成立时用户需要的是恢复入口。
+ expect(resolveXdAssetModuleState({ ...OK, syncState: 'failed', available: null })).toEqual({
+ kind: 'fault',
+ });
+ });
+
+ it('企业未开通 / 服务未启用 → 不渲染(没有可恢复的东西,给重试是假承诺)', () => {
+ expect(resolveXdAssetModuleState({ ...OK, syncState: 'unsupported' })).toEqual({
+ kind: 'hidden',
+ });
+ expect(resolveXdAssetModuleState({ ...OK, syncState: 'disabled' })).toEqual({ kind: 'hidden' });
+ });
+
+ it('余额查询不支持 / 尚未返回 → 不渲染,不显示「—」占位', () => {
+ expect(resolveXdAssetModuleState({ ...OK, available: null })).toEqual({ kind: 'hidden' });
+ expect(resolveXdAssetModuleState({ ...OK, syncState: 'syncing', available: null })).toEqual({
+ kind: 'hidden',
+ });
+ });
+
+ it('同步中但余额已有缓存 → 照常显示(不为了一次刷新把数字抽走)', () => {
+ expect(resolveXdAssetModuleState({ ...OK, syncState: 'syncing' })).toEqual({
+ kind: 'balance',
+ available: '18.42',
+ });
+ });
+});
diff --git a/apps/desktop/src/renderer/components/settings/providerAssetModule.ts b/apps/desktop/src/renderer/components/settings/providerAssetModule.ts
new file mode 100644
index 0000000000..588ab08e19
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/providerAssetModule.ts
@@ -0,0 +1,45 @@
+/**
+ * 供应商详情头下方「账户资产模块」的状态判定(纯函数,与渲染分离)。
+ *
+ * 这个槽位是通用的:网关账号填「可用余额 + 充值」,将来订阅账号可以填「当前套餐 +
+ * 用量」。目前只有 Cindy AI 网关一种填充,判定逻辑先集中在这里,避免把三种互斥
+ * 状态(不渲染 / 故障 / 有余额)散进 JSX 的嵌套三元里。
+ *
+ * 三种状态刻意区分开:
+ * - `hidden`:**本来就不该有**。org 账号(`canAccessBillingSettings` 同一判据)、
+ * local / 未登录、企业未开通网关,以及账户不支持余额查询。此时不显示「—」占位、
+ * 也不留空的资产区 —— 卡片退化成标题行 + 状态 + 菜单。
+ * - `fault`:**本该有、这次拿不到**(凭据同步失败)。所以给一条故障说明 + 重试。
+ * - `balance`:正常态,标签 + 金额 + 右侧动作。
+ *
+ * 「不渲染」与「故障」的分野是这份判定存在的理由:把两者合成一个空态会让确实有钱
+ * 的用户看不到恢复入口,把两者都给重试又会让 org 账号看到一个永远重试不出结果的
+ * 按钮。
+ */
+
+import type { ModelAccessStatus } from '../../../shared/modelAccess';
+
+export type ProviderAssetModuleState =
+ { kind: 'hidden' } | { kind: 'fault' } | { kind: 'balance'; available: string };
+
+export interface XdAssetModuleInput {
+ /** `canAccessBillingSettings` 的结果:cloud + personal 才为 true。 */
+ billingAccessible: boolean;
+ /** 网关凭据自动下发的同步状态(useModelAccessStatus)。 */
+ syncState: ModelAccessStatus['state'];
+ /** 额度池账本里的可用余额(useModelAccessCreditUsage);拿不到为 null。 */
+ available: string | null;
+}
+
+export function resolveXdAssetModuleState(input: XdAssetModuleInput): ProviderAssetModuleState {
+ const { billingAccessible, syncState, available } = input;
+ // 企业账号 / 未登录 / local:整个余额与充值面都不属于这个账号,连故障态都不该有。
+ if (!billingAccessible) return { kind: 'hidden' };
+ // 企业未开通网关(unsupported)不是故障:没有可恢复的东西,给重试是假承诺。
+ if (syncState === 'unsupported' || syncState === 'disabled') return { kind: 'hidden' };
+ // 凭据没同步上 → 余额本该有但这次拿不到,给说明 + 重试。
+ if (syncState === 'failed') return { kind: 'fault' };
+ // 账户未开通余额 / 租户不提供余额查询 / 首次请求还没回来 → 什么都不渲染。
+ if (available === null) return { kind: 'hidden' };
+ return { kind: 'balance', available };
+}
diff --git a/apps/desktop/src/renderer/features/billing/BillingPage.tsx b/apps/desktop/src/renderer/features/billing/BillingPage.tsx
index 822c3edd31..8fd37ccea0 100644
--- a/apps/desktop/src/renderer/features/billing/BillingPage.tsx
+++ b/apps/desktop/src/renderer/features/billing/BillingPage.tsx
@@ -12,6 +12,7 @@ import {
X,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
+import { useSearchParams } from 'react-router-dom';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import {
@@ -36,7 +37,6 @@ import type {
BillingPurchaseOption,
BillingSubscription,
} from '../../../shared/billing';
-import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
import type {
ModelAccessBalance,
ModelAccessCreditPoolUsage,
@@ -46,7 +46,7 @@ import type {
import { AlipayIcon } from './AlipayIcon';
import { billingApi } from './api';
import { BillingCheckoutDialog } from './BillingCheckoutDialog';
-import { formatBillingAmount as formatMoney } from './money';
+import { BILLING_CURRENCY, formatBillingAmount as formatMoney } from './money';
import {
PlanChangeStatusDialog,
PlanChangeTargetDialog,
@@ -327,6 +327,23 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
setCustomAmount('');
}, []);
+ /**
+ * 深链 `?tab=billing&intent=topup` —— 别处(供应商设置页的账户资产模块)想触发
+ * 充值时唯一的入口。充值弹窗依赖本 section 的目录 / 选项 / checkout 会话状态,
+ * 跨 feature 直接复用会把这一大摊状态拉到调用方,所以外部只投递意图、由这里
+ * 打开弹窗。消费即从 URL 摘除(replace,防返回/刷新重复弹窗),与
+ * ProvidersSection 的 `?connect` 同款契约。
+ */
+ const [searchParams, setSearchParams] = useSearchParams();
+ useEffect(() => {
+ if (searchParams.get('intent') !== 'topup') return;
+ const next = new URLSearchParams(searchParams);
+ next.delete('intent');
+ setSearchParams(next, { replace: true });
+ resetSelection();
+ setTopupDialogOpen(true);
+ }, [resetSelection, searchParams, setSearchParams]);
+
const loadBalance = useCallback(async () => {
setLoadingBalance(true);
setBalanceError(null);
@@ -1271,8 +1288,6 @@ function PendingPlanChangeBanner({
);
}
-const BILLING_CURRENCY = CURRENT_CINDY_REGION === 'global' ? 'usd' : 'cny';
-
function BillingGroup({
title,
titleId,
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
index f870f2ee34..cd53fc423d 100644
--- a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
@@ -21,6 +21,12 @@ const uiMocks = vi.hoisted(() => ({
const authState = vi.hoisted(() => ({ dataOwnerId: 'account-fixture' as string | null }));
+/**
+ * 计费页只用 useSearchParams 消费 `?intent=topup` 深链,不需要真的挂 Router:
+ * 用一个可读写的 URLSearchParams 替身,既能驱动深链分支,也能断言参数被摘除。
+ */
+const routerState = vi.hoisted(() => ({ search: '' as string }));
+
const checkout = {
state: {
open: false,
@@ -63,6 +69,17 @@ vi.mock('@/features/feature-context', () => ({
vi.mock('@/contexts/AuthContext', () => ({
useAuth: () => ({ dataOwnerId: authState.dataOwnerId }),
}));
+// 只覆写 useSearchParams(深链 ?intent=topup 的读写口),其余导出保留真实实现 ——
+// 全量替换会让后续用到 Link / useNavigate 等导出的用例拿到 undefined 才炸在别处。
+vi.mock('react-router-dom', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('react-router-dom')>()),
+ useSearchParams: () => [
+ new URLSearchParams(routerState.search),
+ (next: URLSearchParams) => {
+ routerState.search = next.toString();
+ },
+ ],
+}));
vi.mock('@/components/ui/confirm-dialog-provider', () => ({
useConfirmDialog: () => ({ confirm: uiMocks.confirm }),
}));
@@ -90,6 +107,7 @@ beforeEach(() => {
uiMocks.toastError.mockReset();
uiMocks.toastSuccess.mockReset();
authState.dataOwnerId = 'account-fixture';
+ routerState.search = '';
});
async function openSubscriptionManagementMenu() {
@@ -825,6 +843,25 @@ describe('BillingPage remote catalog rendering', () => {
);
});
+ it('深链 ?intent=topup 直接打开充值弹窗,并把参数摘掉防返回/刷新重复弹', async () => {
+ // 供应商设置页的账户资产模块「余额充值」走的就是这条深链:充值弹窗依赖本页的
+ // 目录 / 选项 / checkout 状态,跨 feature 只投递意图。
+ routerState.search = 'tab=billing&intent=topup';
+
+ render(<BillingPage />);
+
+ expect(await screen.findByText('Configured top-up')).toBeTruthy();
+ expect(new URLSearchParams(routerState.search).get('intent')).toBeNull();
+ expect(new URLSearchParams(routerState.search).get('tab')).toBe('billing');
+ });
+
+ it('没有 intent 参数时不自动弹充值弹窗', async () => {
+ render(<BillingPage />);
+
+ await screen.findByText('billing.settings.topupCard.action');
+ expect(screen.queryByText('Configured top-up')).toBeNull();
+ });
+
it('shows server-visible unavailable offers and only enables purchasable offers', async () => {
render(<BillingPage />);
diff --git a/apps/desktop/src/renderer/features/billing/money.ts b/apps/desktop/src/renderer/features/billing/money.ts
index 2c8fbfed11..7efc87ba70 100644
--- a/apps/desktop/src/renderer/features/billing/money.ts
+++ b/apps/desktop/src/renderer/features/billing/money.ts
@@ -4,6 +4,15 @@
* must not re-introduce binary floating point rounding artifacts.
*/
+import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
+
+/**
+ * 计费面的币种由发行区域决定(服务端下发的金额本身不带币种)。所有展示余额 /
+ * 充值金额的界面必须用同一个常量,否则同一笔钱会在两个界面显示成不同货币
+ * (见 TodaySpendChip 的「与账单页 BILLING_CURRENCY 同一笔钱、必须同口径」注释)。
+ */
+export const BILLING_CURRENCY = CURRENT_CINDY_REGION === 'global' ? 'usd' : 'cny';
+
const DECIMAL_PATTERN = /^([+-]?)(\d+)(?:\.(\d+))?$/;
function billingCurrencyFormatOptions(currency: string): Intl.NumberFormatOptions {
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index adca150199..2450255ae4 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -103,8 +103,11 @@ import { SessionContentHeaderRegistration } from './SessionContentHeader';
import { useSessionBinding } from '@/hooks/useSessionBinding';
import { useVendorAuthGate } from '@/hooks/useVendorAuthGate';
import { useProviders } from '@/hooks/useProviders';
+import { useAuth } from '@/contexts/AuthContext';
+import { canAccessBillingSettings } from '@/components/settings/billingVisibility';
import { useDeviceProviders } from '@/hooks/useDeviceProviders';
import { useAgentCapabilities } from '@/hooks/useAgentCapabilities';
+import { useLiveErrorSourceProvider } from '@/hooks/useLiveErrorSourceProvider';
import { resolveFastSupported } from '@/lib/providerModels';
import { useRemoteSessionSync } from '@/features/cc-agent/hooks/useRemoteSessionSync';
import {
@@ -1255,6 +1258,7 @@ export function CCAgentSessionView({
// 与模型选择器同源(见下方 M35 vendor fallback effect)。本地 IPC 极快返回,有模块级缓存。
// device-link 远程会话用被控端经隧道带来的 providers(per-provider,fast 判定与本地同口径)。
const { providers: localProviders } = useProviders();
+ const { mode: authMode, user: authUser } = useAuth();
const { providers: deviceProviders } = useDeviceProviders(remoteDeviceId);
const providers = remoteDeviceId ? deviceProviders : localProviders;
const canSwitchToClaudeSubscription = useMemo(() => {
@@ -1278,6 +1282,25 @@ export function CCAgentSessionView({
session?.model,
session?.remoteHostId,
]);
+ /**
+ * 余额不足横幅的「查看余额」出口 —— 只在计费面对当前账号可见时提供(cloud +
+ * personal,与设置页「用量和计费」同一判据)。org / local / 未登录账号在 Cindy 里
+ * 没有余额页可跳,此时不传回调,ErrorBanner 会保持原样文案、不加按钮。
+ */
+ const canAccessBilling = canAccessBillingSettings({
+ mode: authMode,
+ membershipKind: authUser?.membershipKind ?? null,
+ });
+ const handleViewBalance = useCallback(() => {
+ navigate('/settings?tab=billing');
+ }, [navigate]);
+ // live 错误的来源 provider 快照:错误出现时取值、任务切换时重置、错误存续期间
+ // 切 provider 不跟随。语义与边界条件见 useLiveErrorSourceProvider 头注释。
+ const liveErrorSourceProviderId = useLiveErrorSourceProvider(
+ error,
+ sessionId,
+ session?.providerId ?? null,
+ );
// 该会话 agent 的能力(agent 级 hasFastMode + 旧被控端拍平回退用 availableModels);按 remoteDeviceId 作用域。
const { capabilities: sessionCaps } = useAgentCapabilities(displayAgentKind, remoteDeviceId);
// 这里曾有 useErrorReadAck:ErrorBanner 在视图内聚焦驻留 1.5s 即 explicit 清红点。
@@ -3333,6 +3356,8 @@ export function CCAgentSessionView({
deviceLinkDeviceId={remoteDeviceId}
modelId={session?.model}
providerId={session?.providerId}
+ onViewBalance={canAccessBilling ? handleViewBalance : undefined}
+ errorSourceProviderId={errorTailMsg?.errorProviderId ?? null}
onSwitchToClaudeSubscription={
canSwitchToClaudeSubscription
? handleSwitchToClaudeSubscription
@@ -3386,6 +3411,8 @@ export function CCAgentSessionView({
onSwitchToClaudeSubscription={
canSwitchToClaudeSubscription ? handleSwitchToClaudeSubscription : undefined
}
+ onViewBalance={canAccessBilling ? handleViewBalance : undefined}
+ errorSourceProviderId={liveErrorSourceProviderId}
silentEncryptedRetryEnabled={silentEncryptedRetryEnabled}
onForkStripEncrypted={ownsWindowRoute ? handleForkStripEncrypted : undefined}
forkStripEncryptedRunning={forkStripEncryptedRunning}
diff --git a/apps/desktop/src/renderer/hooks/useLiveErrorSourceProvider.ts b/apps/desktop/src/renderer/hooks/useLiveErrorSourceProvider.ts
new file mode 100644
index 0000000000..8031d7fbf9
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useLiveErrorSourceProvider.ts
@@ -0,0 +1,31 @@
+/**
+ * useLiveErrorSourceProvider —— live 错误的「来源 provider」快照。
+ *
+ * 语义:错误**出现的那一刻**记下当时的 session provider,错误存续期间用户切换
+ * provider 不跟随 —— 余额分类必须绑错误发生时的来源(ErrorBanner 的
+ * errorSourceProviderId),否则「xd 报余额不足 → 切到 OpenAI」会丢充值入口,
+ * 「OpenAI 报配额 → 切到 xd」会误挂 Cindy AI 充值入口。
+ *
+ * **任务身份是快照边界的一部分**:同一个 `:sessionId` 路由复用同一个组件实例,
+ * 只跟 error 文本走的快照会在「两个任务恰好有相同错误文本」时沿用上一任务的
+ * 来源(deps 相等,effect 不重跑),把错误引向错误的充值入口。所以 sessionId
+ * 变化时必须重新取值;同一任务同一条错误存续期间仍保持稳定。
+ *
+ * currentProviderId 刻意不进 deps:那正是「快照」与「跟随」的分界。
+ */
+
+import { useEffect, useState } from 'react';
+
+export function useLiveErrorSourceProvider(
+ error: string | null,
+ sessionId: string | null | undefined,
+ currentProviderId: string | null,
+): string | null {
+ const [snapshot, setSnapshot] = useState<string | null>(null);
+ useEffect(() => {
+ if (error) setSnapshot(currentProviderId);
+ else setSnapshot(null);
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- 快照语义:只在错误出现/消失或任务切换时取值,provider 变化不跟随
+ }, [error, sessionId]);
+ return snapshot;
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index cb09c9c562..043543a481 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1256,9 +1256,9 @@
},
"xd": {
"title": "Cindy AI",
- "subtitle": "All models · Claude Code / Codex · billed per token",
+ "subtitle": "All models · Claude Code / Codex · billed from your balance per token",
"modelLabel": "All models",
- "billingLabel": "billed per token",
+ "billingLabel": "billed from your balance per token",
"disconnectConfirm": {
"title": "Disconnect Cindy AI?",
"description": "Disconnecting clears the Cindy AI key saved locally. You will need to reconnect to keep using models provided by Cindy AI."
@@ -1280,7 +1280,14 @@
"confirm": "Rotate"
},
"rotateSuccess": "Key rotated",
- "rotateFailed": "Rotation failed, please try again later"
+ "rotateFailed": "Rotation failed, please try again later",
+ "copyKeyAria": "Copy Cindy AI key",
+ "copyKeySuccess": "Cindy AI key copied",
+ "copyKeyFailed": "Copy failed, please try again later",
+ "asset": {
+ "viewUsage": "View usage",
+ "syncFailed": "Credential sync failed, so the balance is unavailable right now. Your saved model settings are unaffected."
+ }
},
"custom": {
"tag": "Custom",
@@ -1574,7 +1581,8 @@
},
"xdSignin": {
"badge": "Recommended",
- "desc": "Sign in to Cindy to enable the official Cindy AI service — all models work out of the box, no keys to manage.",
+ "desc": "The official service — all models work out of the box, no keys to manage.",
+ "grantBadge": "Promotional balance for new users",
"cta": "Sign in to Cindy"
},
"menu": {
@@ -5308,7 +5316,7 @@
"title": "Cindy AI",
"desc": "Official service · all models · works with Claude Code and Codex",
"loginTitle": "Sign in to Cindy",
- "loginDesc": "Sign in to enable the official Cindy AI service with access to all models"
+ "loginDesc": "Sign in to enable the official Cindy AI service with access to all models — new users get a promotional balance"
},
"othersToggle": "Other providers ({{count}})",
"presetSub": "Paste an API key to connect",
@@ -5513,6 +5521,9 @@
"retry": "Retry",
"continueAfterReset": "Continue After Reset",
"continueAfterResetTitle": "Create a one-time Automation to continue this task after usage resets",
+ "gatewayQuotaExhausted": "Your Cindy AI balance is used up. Add funds to continue.",
+ "viewBalance": "View balance",
+ "viewBalanceTitle": "Open Usage & Billing to check your balance and add funds",
"credentialSwitchBusy": "Another Codex task is still running, so the provider for this session can't be applied yet (the shared Codex process needs a restart). Retry after those tasks finish.",
"codexThreadStale": "Codex auth mode changed — this session can't continue. Start a new session to apply it.",
"claudeGatewayOpusPlanMismatch": "This Opus request went through XD Gateway, not your Claude.ai subscription. That gateway route rejected the model. Switch to your Claude.ai subscription and retry, or choose another model.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 5f5e82aecd..a5f09a03ad 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1256,9 +1256,9 @@
},
"xd": {
"title": "Cindy AI",
- "subtitle": "すべてのモデル · Claude Code / Codex 共通 · トークン課金",
+ "subtitle": "すべてのモデル · Claude Code / Codex 共通 · トークン単位で残高から引き落とし",
"modelLabel": "すべてのモデル",
- "billingLabel": "トークン課金",
+ "billingLabel": "トークン単位で残高から引き落とし",
"disconnectConfirm": {
"title": "Cindy AI を切断しますか?",
"description": "切断するとローカルに保存された Cindy AI Key が削除されます。Cindy AI のモデルを引き続き使うには再接続が必要です。"
@@ -1280,7 +1280,14 @@
"confirm": "ローテーション"
},
"rotateSuccess": "キーをローテーションしました",
- "rotateFailed": "ローテーションに失敗しました。後でもう一度お試しください"
+ "rotateFailed": "ローテーションに失敗しました。後でもう一度お試しください",
+ "copyKeyAria": "Cindy AI Key をコピー",
+ "copyKeySuccess": "Cindy AI Key をコピーしました",
+ "copyKeyFailed": "コピーに失敗しました。後でもう一度お試しください",
+ "asset": {
+ "viewUsage": "使用量を見る",
+ "syncFailed": "認証情報の同期に失敗したため、残高を取得できません。保存済みのモデル設定には影響しません。"
+ }
},
"custom": {
"tag": "カスタム",
@@ -1573,7 +1580,8 @@
},
"xdSignin": {
"badge": "おすすめ",
- "desc": "Cindy にサインインすると公式 Cindy AI サービスが有効になります。全モデルがすぐ使え、キー管理は不要です。",
+ "desc": "公式サービス。全モデルがすぐ使え、キー管理は不要です。",
+ "grantBadge": "新規ユーザーには特典残高付き",
"cta": "Cindy にサインイン"
},
"menu": {
@@ -5306,7 +5314,7 @@
"title": "Cindy AI",
"desc": "公式サービス · 全モデル · Claude Code / Codex 対応",
"loginTitle": "Cindy にサインイン",
- "loginDesc": "サインインすると公式 Cindy AI サービスが有効になり、全モデルを利用できます"
+ "loginDesc": "サインインすると公式 Cindy AI サービスが有効になり、全モデルを利用できます。新規ユーザーには特典残高が付きます"
},
"othersToggle": "その他のプロバイダー({{count}})",
"presetSub": "API キーを入力して接続",
@@ -5511,6 +5519,9 @@
"retry": "再試行",
"continueAfterReset": "リセット後に続行",
"continueAfterResetTitle": "利用上限のリセット後にこのタスクを続行する一回限りの自動化を作成",
+ "gatewayQuotaExhausted": "Cindy AI の残高が不足しています。チャージすると続行できます。",
+ "viewBalance": "残高を見る",
+ "viewBalanceTitle": "「使用量と請求」を開いて残高を確認・チャージ",
"credentialSwitchBusy": "他の Codex タスクが実行中のため、このセッションで選択したプロバイダーへまだ切り替えられません(共有 Codex プロセスの再起動が必要です)。他のタスクの終了後に「再試行」を押してください。",
"codexThreadStale": "Codex の認証モードが切り替わりました。このセッションは続行できません。新しいセッションを開始してください。",
"claudeGatewayOpusPlanMismatch": "この Opus リクエストは Claude.ai サブスクリプションではなく、XD Gateway 経由で送信され、このモデルが拒否されました。Claude.ai サブスクリプションに切り替えて再試行するか、別のモデルを選択してください。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 0bc3c3507d..34280485c0 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1256,9 +1256,9 @@
},
"xd": {
"title": "Cindy AI",
- "subtitle": "모든 모델 · Claude Code / Codex 공용 · 토큰 단위 과금",
+ "subtitle": "모든 모델 · Claude Code / Codex 공용 · 토큰 단위로 잔액에서 차감",
"modelLabel": "모든 모델",
- "billingLabel": "토큰 단위 과금",
+ "billingLabel": "토큰 단위로 잔액에서 차감",
"disconnectConfirm": {
"title": "Cindy AI 연결을 해제할까요?",
"description": "연결을 해제하면 로컬에 저장된 Cindy AI Key가 삭제됩니다. Cindy AI 모델을 계속 사용하려면 다시 연결해야 합니다."
@@ -1280,7 +1280,14 @@
"confirm": "교체"
},
"rotateSuccess": "키를 교체했습니다",
- "rotateFailed": "교체에 실패했습니다. 나중에 다시 시도해 주세요"
+ "rotateFailed": "교체에 실패했습니다. 나중에 다시 시도해 주세요",
+ "copyKeyAria": "Cindy AI Key 복사",
+ "copyKeySuccess": "Cindy AI Key를 복사했습니다",
+ "copyKeyFailed": "복사에 실패했습니다. 나중에 다시 시도해 주세요",
+ "asset": {
+ "viewUsage": "사용량 보기",
+ "syncFailed": "자격 증명 동기화에 실패해 잔액을 가져올 수 없습니다. 저장된 모델 설정은 영향을 받지 않습니다."
+ }
},
"custom": {
"tag": "사용자 지정",
@@ -1573,7 +1580,8 @@
},
"xdSignin": {
"badge": "추천",
- "desc": "Cindy에 로그인하면 공식 Cindy AI 서비스가 활성화됩니다. 모든 모델을 바로 사용할 수 있으며 키 관리가 필요 없습니다.",
+ "desc": "공식 서비스. 모든 모델을 바로 사용할 수 있으며 키 관리가 필요 없습니다.",
+ "grantBadge": "신규 사용자 프로모션 잔액 제공",
"cta": "Cindy 로그인"
},
"menu": {
@@ -5306,7 +5314,7 @@
"title": "Cindy AI",
"desc": "공식 서비스 · 전체 모델 · Claude Code / Codex 지원",
"loginTitle": "Cindy 로그인",
- "loginDesc": "로그인하면 공식 Cindy AI 서비스가 활성화되어 모든 모델을 사용할 수 있습니다"
+ "loginDesc": "로그인하면 공식 Cindy AI 서비스가 활성화되어 모든 모델을 사용할 수 있습니다. 신규 사용자에게는 프로모션 잔액이 제공됩니다"
},
"othersToggle": "기타 제공자 ({{count}})",
"presetSub": "API 키를 입력하여 연결",
@@ -5511,6 +5519,9 @@
"retry": "다시 시도",
"continueAfterReset": "재설정 후 계속",
"continueAfterResetTitle": "사용량 제한 재설정 후 현재 작업을 계속할 일회성 자동화 만들기",
+ "gatewayQuotaExhausted": "Cindy AI 잔액이 부족합니다. 충전한 후 계속하세요.",
+ "viewBalance": "잔액 보기",
+ "viewBalanceTitle": "「사용량 및 청구」를 열어 잔액을 확인하고 충전",
"credentialSwitchBusy": "다른 Codex 작업이 실행 중이어서 이 세션에서 선택한 제공자로 아직 전환할 수 없습니다(공유 Codex 프로세스 재시작 필요). 다른 작업이 끝난 후 ‘재시도’를 눌러 주세요.",
"codexThreadStale": "Codex 인증 모드가 변경되었습니다. 이 세션은 계속할 수 없습니다. 새 세션을 시작하세요.",
"claudeGatewayOpusPlanMismatch": "이 Opus 요청은 Claude.ai 구독이 아니라 XD Gateway를 통해 전송되었고, 해당 게이트웨이 경로에서 모델을 거부했습니다. Claude.ai 구독으로 전환해 다시 시도하거나 다른 모델을 선택하세요.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index f2650997d0..c33b1bc9b0 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1256,9 +1256,9 @@
},
"xd": {
"title": "Cindy AI",
- "subtitle": "全部模型 · Claude Code / Codex 通用 · 按 token 计费",
+ "subtitle": "全部模型 · Claude Code / Codex 通用 · 按 token 从余额扣费",
"modelLabel": "全部模型",
- "billingLabel": "按 token 计费",
+ "billingLabel": "按 token 从余额扣费",
"disconnectConfirm": {
"title": "断开 Cindy AI?",
"description": "断开后将清除本地保存的 Cindy AI Key,需要重新连接才能继续使用 Cindy AI 提供的模型。"
@@ -1280,7 +1280,14 @@
"confirm": "轮换"
},
"rotateSuccess": "密钥已轮换",
- "rotateFailed": "轮换失败,请稍后重试"
+ "rotateFailed": "轮换失败,请稍后重试",
+ "copyKeyAria": "复制 Cindy AI Key",
+ "copyKeySuccess": "已复制 Cindy AI Key",
+ "copyKeyFailed": "复制失败,请稍后重试",
+ "asset": {
+ "viewUsage": "查看用量",
+ "syncFailed": "凭据同步失败,暂时无法获取余额。已保存的模型配置不受影响。"
+ }
},
"custom": {
"tag": "自定义",
@@ -1573,7 +1580,8 @@
},
"xdSignin": {
"badge": "推荐",
- "desc": "登录 Cindy 即可开通官方 Cindy AI 服务,全部模型开箱即用,无需管理任何 Key。",
+ "desc": "官方服务,全部模型开箱即用,无需管理任何 Key。",
+ "grantBadge": "新用户含赠送余额",
"cta": "登录 Cindy"
},
"menu": {
@@ -5306,7 +5314,7 @@
"title": "Cindy AI",
"desc": "官方服务 · 全部模型 · Claude Code / Codex 通用",
"loginTitle": "登录 Cindy",
- "loginDesc": "登录后自动开通 Cindy AI 官方服务,即可使用全部模型"
+ "loginDesc": "登录后自动开通 Cindy AI 官方服务,即可使用全部模型,新用户含赠送余额"
},
"othersToggle": "其他供应商({{count}})",
"presetSub": "填入 API Key 即可连接",
@@ -5511,6 +5519,9 @@
"retry": "重试",
"continueAfterReset": "恢复后继续",
"continueAfterResetTitle": "创建一次性自动化,在用量恢复后继续当前任务",
+ "gatewayQuotaExhausted": "Cindy AI 余额不足,请充值后继续",
+ "viewBalance": "查看余额",
+ "viewBalanceTitle": "打开「用量和计费」查看余额并充值",
"credentialSwitchBusy": "Codex 正在其它任务中运行,暂时无法按本任务选择的模型来源切换(需要重启共享的 Codex 后台进程)。等它结束后点「重试」即可。",
"codexThreadStale": "Codex 鉴权模式已切换,当前任务无法继续 —— 请新建任务后生效。",
"claudeGatewayOpusPlanMismatch": "这次 Opus 请求实际走的是 XD Gateway,不是你的 Claude.ai 订阅;该网关路由拒绝了此模型。可切换到 Claude.ai 订阅后重试,或换一个模型。",
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index e268e268f8..d2311052bd 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -380,6 +380,14 @@ export interface ChatMessage {
* 里的原始 message 文案。live 报错仍走 ErrorBanner(store.error),与本字段无关。
*/
errorReason?: string;
+ /**
+ * 产生这条 error 行的 provider(错误发生时刻的快照,main 侧 onTurnErrorEvent
+ * 从 session-provider-store 同步取值落进 content.providerId)。错误分类必须绑
+ * 这个来源,不能用可中途切换的 session.providerId —— 否则恢复历史错误时会把
+ * 别家 provider 的额度错误误判成 Cindy AI 余额不足(或反向丢失充值入口)。
+ * undefined = 来源不明(老行 / 未显式选择 provider),读侧不启用余额分类。
+ */
+ errorProviderId?: string;
/**
* interrupted-turn-resume:app 退出中断行(errorReason='app-exit-interrupted')
* 被用户点「忽略」后置 true(content.dismissed 持久化)。banner 与红点判定
@@ -10535,12 +10543,15 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {
>;
const message = typeof c.message === 'string' ? c.message : '';
const reason = typeof c.reason === 'string' ? c.reason : undefined;
+ const errorProviderId = typeof c.providerId === 'string' && c.providerId ? c.providerId : undefined;
return {
clientId: m.clientId,
role: m.role,
content: message,
isStreaming: false,
...(reason ? { errorReason: reason } : {}),
+ // 错误发生时的 provider 快照:恢复后的分类按它走,不用当前 session.providerId。
+ ...(errorProviderId ? { errorProviderId } : {}),
// interrupted-turn-resume:「忽略」的持久化标记(updateContent 写入)。
...(c.dismissed === true ? { errorDismissed: true } : {}),
};
diff --git a/apps/desktop/src/renderer/utils/quotaError.ts b/apps/desktop/src/renderer/utils/quotaError.ts
new file mode 100644
index 0000000000..c946fee376
--- /dev/null
+++ b/apps/desktop/src/renderer/utils/quotaError.ts
@@ -0,0 +1,29 @@
+/**
+ * 余额 / 配额耗尽类错误识别(renderer 侧)—— 判断一条错误 message 是不是「上游明确
+ * 说这个账号没钱 / 没配额了」。ErrorBanner 用它在来源确定是 Cindy AI 网关时把错误条
+ * 换成「余额不足,请充值后继续」并给出通往计费页的内联出口。
+ *
+ * **与 networkError.ts / overloadError.ts 的分工**:那两份分别管「网络到不了上游」与
+ * 「上游没有容量」,本份管「上游通了、账号自己的钱用完了」。三者的下一步完全不同:
+ * 网络类让用户查网络、过载类让用户换模型、本类让用户充值。
+ *
+ * **判定为什么在这里而不是复用 classifyProviderError**:走到 renderer 的会话错误已经
+ * 是一条字符串,status 与响应体都不在手里,classifyProviderError 的 status 分支用不上。
+ * 文案 pattern 直接复用 shared 那一份(`matchesQuotaExhaustedText`),不在这里重写,
+ * 避免「什么算余额耗尽」两处漂移。
+ */
+
+import { matchesQuotaExhaustedText } from '../../shared/providerErrors';
+
+/**
+ * 状态码兜底:402 常以 `HTTP 402` / `status 402` / `code: 402` / `(402)` /
+ * `402 Payment Required` 之类的形态透出到 message。只认**带状态码上下文**的 402 ——
+ * 裸 `\b402\b` 会把正文里恰好出现的独立数字(报价、行号、金额)也判成额度耗尽,
+ * 而这条判定会改写错误文案并挂上充值入口,误伤代价高。
+ */
+const HTTP_402_RE =
+ /(?:\b(?:http|status|code|error)\b[^0-9a-z]{0,10}402\b|\(\s*402\s*\)|\b402\s+payment\s+required\b)/i;
+
+export function isQuotaExhaustedErrorMessage(message: string): boolean {
+ return matchesQuotaExhaustedText(message) || HTTP_402_RE.test(message);
+}
diff --git a/apps/desktop/src/shared/providerErrors.ts b/apps/desktop/src/shared/providerErrors.ts
index e31ab3a176..30a109b496 100644
--- a/apps/desktop/src/shared/providerErrors.ts
+++ b/apps/desktop/src/shared/providerErrors.ts
@@ -88,6 +88,19 @@ const WIRE_RE =
/** 鉴权失败措辞(个别网关 401 语义但回 400/403 文本)。 */
const AUTH_RE = /invalid.{0,10}(api.?key|token)|authentication_error|unauthorized|api key not valid|令牌|鉴权失败/i;
+/**
+ * 单独暴露「余额 / 配额耗尽」的文案判定,供只拿得到一条错误 message、拿不到
+ * status 与响应体的消费方使用(会话内 ErrorBanner:错误经 IPC 投影成字符串后,
+ * classifyProviderError 的 status 分支已经用不上了)。
+ *
+ * 与 classifyProviderError 共用同一份 pattern,是为了不让「什么算余额耗尽」在两处
+ * 各写一遍后漂移;本函数不参与分类优先级,加它不改变 classifyProviderError 的行为。
+ * 新增 pattern 仍需真实错误体为证(见文件头注释)。
+ */
+export function matchesQuotaExhaustedText(text: string): boolean {
+ return QUOTA_RE.test(text);
+}
+
/**
* 分类一次供应商上游失败。确定性纯函数:同输入必同输出。
* 优先级:网络层错误 > 明确 status > 错误体 pattern > UNKNOWN。