Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(billing): 区分无订阅与账本历史不完整 (#991)
GaoWei Liuc1939120feed
diff --git a/apps/desktop/src/renderer/features/billing/BillingPage.tsx b/apps/desktop/src/renderer/features/billing/BillingPage.tsxindex 606d8ef466..b9a89a2be0 100644--- a/apps/desktop/src/renderer/features/billing/BillingPage.tsx+++ b/apps/desktop/src/renderer/features/billing/BillingPage.tsx@@ -784,7 +784,13 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullusageDetailsUnavailable ? t('billing.usage.detailsUnavailable') : undefined}>- <UsageBreakdownCard usage={creditUsage} balance={balance} />+ <UsageBreakdownCard+ usage={creditUsage}+ balance={balance}+ hasNoActiveSubscription={+ !loadingSubscription && !subscriptionError && currentSubscription === null+ }+ /></BillingGroup>)}@@ -1161,9 +1167,11 @@ function BalanceOverviewCard({function UsageBreakdownCard({usage,balance,+ hasNoActiveSubscription,}: {usage: ModelAccessCreditUsage | null;balance: ModelAccessBalance | null;+ hasNoActiveSubscription: boolean;}) {const { t, i18n } = useTranslation();const billingLocale = i18n.resolvedLanguage ?? i18n.language;@@ -1181,7 +1189,14 @@ function UsageBreakdownCard({['purchased', usage.purchased],['promotional', usage.promotional],] as const- ).map(([key, pool]) => <CreditPoolRow key={key} label={poolLabels[key]} pool={pool} />)+ ).map(([key, pool]) => (+ <CreditPoolRow+ key={key}+ label={poolLabels[key]}+ pool={pool}+ noActiveSubscription={key === 'plan' && hasNoActiveSubscription}+ />+ )): balance? ([@@ -1205,7 +1220,19 @@ function UsageBreakdownCard({);}-function CreditPoolRow({ label, pool }: { label: string; pool: ModelAccessCreditPoolUsage }) {+function isZeroCreditAmount(amount: string): boolean {+ return /^[+-]?0+(?:\.0+)?$/.test(amount.trim());+}++function CreditPoolRow({+ label,+ pool,+ noActiveSubscription,+}: {+ label: string;+ pool: ModelAccessCreditPoolUsage;+ noActiveSubscription: boolean;+}) {const { t, i18n } = useTranslation();const billingLocale = i18n.resolvedLanguage ?? i18n.language;const percent = usagePercent(pool);@@ -1215,7 +1242,9 @@ function CreditPoolRow({ label, pool }: { label: string; pool: ModelAccessCreditused: formatMoney(pool.used, BILLING_CURRENCY, billingLocale),total: formatMoney(pool.total, BILLING_CURRENCY, billingLocale),})- : t('billing.usage.historyUnavailable');+ : noActiveSubscription && isZeroCreditAmount(pool.remaining)+ ? t('billing.usage.noPlanCredits')+ : t('billing.usage.historyUnavailable');return (<div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-2 px-5 py-3.5"><div className="min-w-0">@@ -1425,7 +1454,6 @@ function BillingOfferDialog({<StateCardicon={<PackageOpen size={22} />}title={t('billing.catalog.emptyTitle')}- description={t('billing.catalog.emptyDescription')}/>) : (<>@@ -1459,19 +1487,30 @@ function BillingOfferDialog({)}><div className="min-w-0 flex-1">- <div className="flex flex-wrap items-center gap-2">+ <div+ className={cn(+ 'grid items-center gap-2',+ currentPlan || unavailableReason+ ? 'grid-cols-[6rem_minmax(0,1fr)]'+ : 'grid-cols-[minmax(0,1fr)]',+ )}+ ><p className="truncate text-13 font-medium text-[var(--text-primary)]">{product.name}</p>- {currentPlan && (- <span className="rounded-full bg-[var(--surface)] px-2 py-0.5 text-10 font-medium text-[var(--text-secondary)]">- {t('billing.catalog.currentPlan')}- </span>- )}- {unavailableReason && (- <span className="rounded-full bg-[var(--surface-chip)] px-2 py-0.5 text-10 font-medium text-[var(--text-secondary)]">- {t(`billing.catalog.unavailableReasons.${unavailableReason}`)}- </span>+ {(currentPlan || unavailableReason) && (+ <div className="min-w-0">+ {currentPlan && (+ <span className="rounded-full bg-[var(--surface)] px-2 py-0.5 text-10 font-medium text-[var(--text-secondary)]">+ {t('billing.catalog.currentPlan')}+ </span>+ )}+ {unavailableReason && (+ <span className="rounded-full bg-[var(--surface-chip)] px-2 py-0.5 text-10 font-medium text-[var(--text-secondary)]">+ {t(`billing.catalog.unavailableReasons.${unavailableReason}`)}+ </span>+ )}+ </div>)}</div></div>@@ -1612,7 +1651,7 @@ function StateCard({}: {icon: React.ReactNode;title: string;- description: string;+ description?: string;action?: React.ReactNode;}) {return (@@ -1621,7 +1660,7 @@ function StateCard({{icon}</div><p className="mt-4 text-sm font-medium">{title}</p>- <p className="mt-1 text-12 text-[var(--text-secondary)]">{description}</p>+ {description && <p className="mt-1 text-12 text-[var(--text-secondary)]">{description}</p>}{action}</div>);diff --git a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsxindex 987495169f..cdeb2a3112 100644--- a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx@@ -364,6 +364,46 @@ describe('BillingPage remote catalog rendering', () => {expect(screen.getByText('billing.usage.detailsUnavailable')).toBeTruthy();});+ it('does not describe missing plan credits as incomplete history when there is no subscription', async () => {+ window.electronAPI.billing.getCreditUsage = vi.fn(async () => ({+ available: '3',+ plan: { remaining: '0', used: null, total: null },+ purchased: { remaining: '0', used: '0', total: '0' },+ promotional: { remaining: '3', used: '0', total: '3' },+ promotionalGrants: [],+ promotionalGrantsComplete: true,+ promotionalGrantConsistency: 'OBSERVED' as const,+ ledgerUpdatedAt: null,+ scale: 9 as const,+ observedAt: '2026-07-23T12:00:00Z',+ }));++ render(<BillingPage />);++ expect(await screen.findByText('billing.usage.noPlanCredits')).toBeTruthy();+ expect(screen.queryByText('billing.usage.historyUnavailable')).toBeNull();+ });++ it('keeps nonzero plan balances truthful when there is no subscription', async () => {+ window.electronAPI.billing.getCreditUsage = vi.fn(async () => ({+ available: '3',+ plan: { remaining: '3', used: null, total: null },+ purchased: { remaining: '0', used: '0', total: '0' },+ promotional: { remaining: '0', used: '0', total: '0' },+ promotionalGrants: [],+ promotionalGrantsComplete: true,+ promotionalGrantConsistency: 'OBSERVED' as const,+ ledgerUpdatedAt: null,+ scale: 9 as const,+ observedAt: '2026-07-23T12:00:00Z',+ }));++ render(<BillingPage />);++ expect(await screen.findByText('billing.usage.historyUnavailable')).toBeTruthy();+ expect(screen.queryByText('billing.usage.noPlanCredits')).toBeNull();+ });+it('shows current plan price, included credits, status, and renewal date', async () => {i18n.resolvedLanguage = 'ja';window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => ({diff --git a/apps/desktop/src/renderer/features/billing/__tests__/money.test.ts b/apps/desktop/src/renderer/features/billing/__tests__/money.test.tsindex 5539a72e0f..6451c13da5 100644--- a/apps/desktop/src/renderer/features/billing/__tests__/money.test.ts+++ b/apps/desktop/src/renderer/features/billing/__tests__/money.test.ts@@ -50,6 +50,10 @@ describe('formatBillingAmount', () => {it('falls back to the raw amount when the value is not numeric', () => {expect(formatBillingAmount('not-a-number', 'usd')).toBe('not-a-number USD');});++ it('uses the dollar symbol for USD in Chinese', () => {+ expect(formatBillingAmount('3', 'usd', 'zh-CN')).toBe('$3.00');+ });});describe('formatBillingMinorAmount', () => {diff --git a/apps/desktop/src/renderer/features/billing/money.ts b/apps/desktop/src/renderer/features/billing/money.tsindex 621f993884..2c8fbfed11 100644--- a/apps/desktop/src/renderer/features/billing/money.ts+++ b/apps/desktop/src/renderer/features/billing/money.ts@@ -6,6 +6,15 @@const DECIMAL_PATTERN = /^([+-]?)(\d+)(?:\.(\d+))?$/;+function billingCurrencyFormatOptions(currency: string): Intl.NumberFormatOptions {+ const normalizedCurrency = currency.toUpperCase();+ return {+ style: 'currency',+ currency: normalizedCurrency,+ ...(normalizedCurrency === 'USD' ? { currencyDisplay: 'narrowSymbol' } : {}),+ };+}+function roundToMinorUnits(amount: string, digits: number): bigint | null {const matched = DECIMAL_PATTERN.exec(amount.trim());if (!matched) return null;@@ -50,10 +59,7 @@ function formatMinorUnits(export function formatBillingAmount(amount: string, currency: string, locale?: string): string {try {- const fmt = new Intl.NumberFormat(locale, {- style: 'currency',- currency: currency.toUpperCase(),- });+ const fmt = new Intl.NumberFormat(locale, billingCurrencyFormatOptions(currency));const digits = fmt.resolvedOptions().maximumFractionDigits ?? 2;const minor = roundToMinorUnits(amount, digits);return minor === null@@ -71,10 +77,7 @@ export function formatBillingMinorAmount(): string {try {if (!Number.isSafeInteger(minor)) return `${minor} ${currency.toUpperCase()}`;- const fmt = new Intl.NumberFormat(locale, {- style: 'currency',- currency: currency.toUpperCase(),- });+ const fmt = new Intl.NumberFormat(locale, billingCurrencyFormatOptions(currency));const digits = fmt.resolvedOptions().maximumFractionDigits ?? 2;return formatMinorUnits(BigInt(minor), fmt, digits);} catch {diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex caf7255e6b..b2fa4f6f51 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -7564,6 +7564,7 @@"poolDetail": "Used {{used}} · Total {{total}}","remaining": "Remaining","progressLabel": "{{label}} usage",+ "noPlanCredits": "No subscription credits because there is no active subscription.","historyUnavailable": "Usage history is incomplete. Only the remaining balance is available.","detailsUnavailable": "Usage details are temporarily unavailable. Current balances are shown instead.","promotionalDetails": {@@ -7607,8 +7608,7 @@"catalog": {"errorTitle": "Plans are temporarily unavailable","errorDescription": "Check your connection and retry. Local fallback plans will not be used.",- "emptyTitle": "No Plans Available",- "emptyDescription": "The server has not published any plans yet.",+ "emptyTitle": "Coming soon. Stay tuned.","currentPlan": "Current Plan","unavailableReasons": {"OFFER_COMING_SOON": "Coming Soon",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 24e8f5bcef..4c541e0078 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -7553,6 +7553,7 @@"poolDetail": "使用済み {{used}} · 合計 {{total}}","remaining": "残り","progressLabel": "{{label}}の使用量",+ "noPlanCredits": "有効なサブスクリプションがないため、サブスクリプションクレジットはありません。","historyUnavailable": "使用履歴が完全ではないため、残りのクレジットのみ表示しています。","detailsUnavailable": "使用量の詳細を取得できないため、現在の残高のみ表示しています。","promotionalDetails": {@@ -7596,8 +7597,7 @@"catalog": {"errorTitle": "プランを取得できません","errorDescription": "接続を確認して再試行してください。ローカルの代替プランは表示しません。",- "emptyTitle": "プランはまだありません",- "emptyDescription": "サーバーで公開中のプランはまだありません。",+ "emptyTitle": "近日公開予定です。お楽しみに。","currentPlan": "現在のプラン","unavailableReasons": {"OFFER_COMING_SOON": "近日提供",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 3153ea6aee..7aac48a7f9 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -7553,6 +7553,7 @@"poolDetail": "사용 {{used}} · 전체 {{total}}","remaining": "잔여","progressLabel": "{{label}} 사용량",+ "noPlanCredits": "활성 구독이 없어 구독 크레딧이 없습니다.","historyUnavailable": "사용 기록이 완전하지 않아 잔여 크레딧만 표시합니다.","detailsUnavailable": "사용량 상세를 불러올 수 없어 현재 잔액만 표시합니다.","promotionalDetails": {@@ -7596,8 +7597,7 @@"catalog": {"errorTitle": "요금제를 불러올 수 없습니다","errorDescription": "네트워크를 확인하고 다시 시도하세요. 로컬 대체 요금제는 표시하지 않습니다.",- "emptyTitle": "요금제가 없습니다",- "emptyDescription": "서버에서 공개한 요금제가 아직 없습니다.",+ "emptyTitle": "곧 출시됩니다. 기대해 주세요.","currentPlan": "현재 요금제","unavailableReasons": {"OFFER_COMING_SOON": "출시 예정",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex eb8300cc6e..509f2eca49 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -7553,6 +7553,7 @@"poolDetail": "已用 {{used}} · 总额 {{total}}","remaining": "剩余","progressLabel": "{{label}}使用进度",+ "noPlanCredits": "当前无生效订阅,因此没有订阅点数。","historyUnavailable": "历史记录不完整,暂时仅显示剩余余额。","detailsUnavailable": "用量明细暂时不可用,当前仅显示各类余额。","promotionalDetails": {@@ -7596,8 +7597,7 @@"catalog": {"errorTitle": "暂时无法获取套餐","errorDescription": "请检查网络后重试。不会使用本地套餐替代。",- "emptyTitle": "当前暂无套餐",- "emptyDescription": "服务端尚未配置公开的套餐。",+ "emptyTitle": "即将上线,敬请期待","currentPlan": "当前套餐","unavailableReasons": {"OFFER_COMING_SOON": "敬请期待",