Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix: 展示同快照赠送额度明细 (#368)
GaoWei Liu3caf24b8306b
diff --git a/apps/desktop/src/main/billing/__tests__/index.test.ts b/apps/desktop/src/main/billing/__tests__/index.test.tsindex 1c44333188..c903ab5df3 100644--- a/apps/desktop/src/main/billing/__tests__/index.test.ts+++ b/apps/desktop/src/main/billing/__tests__/index.test.ts@@ -68,7 +68,7 @@ function harness() {},],promotionalGrantsComplete: true,- promotionalGrantConsistency: 'LAST_SETTLED',+ promotionalGrantConsistency: 'OBSERVED',ledgerUpdatedAt: now,scale: 9,observedAt: now,@@ -140,7 +140,15 @@ describe('billing IPC', () => {await expect(call(BILLING_INVOKE.GET_CREDIT_USAGE)).resolves.toMatchObject({available: '12.345678901',plan: { remaining: '7.000000001', used: '3', total: '10.000000001' },- promotionalGrants: [{ grantId: 'welcome', state: 'active' }],+ promotionalGrants: [+ {+ grantId: 'welcome',+ state: 'active',+ usedAmount: '0.654321102',+ remainingAmount: '0.345678898',+ },+ ],+ promotionalGrantConsistency: 'OBSERVED',});expect(fetch).toHaveBeenCalledWith('/api/model-access/credit-usage', {baseUrl: 'https://model-access.example',diff --git a/apps/desktop/src/main/billing/__tests__/projection.test.ts b/apps/desktop/src/main/billing/__tests__/projection.test.tsindex c99a110966..3a7ec91f0b 100644--- a/apps/desktop/src/main/billing/__tests__/projection.test.ts+++ b/apps/desktop/src/main/billing/__tests__/projection.test.ts@@ -99,14 +99,23 @@ describe('billing response projection', () => {grantId: 'expired',displayName: null,originalAmount: '5',- usedAmount: null,+ usedAmount: '1.25',remainingAmount: '0',expiresAt: '2026-07-01T00:00:00Z',state: 'expired',},+ {+ grantId: 'voided',+ displayName: 'Voided',+ originalAmount: '3',+ usedAmount: '0.5',+ remainingAmount: '0',+ expiresAt: '2026-08-01T00:00:00Z',+ state: 'voided',+ },],promotionalGrantsComplete: true,- promotionalGrantConsistency: 'LAST_SETTLED',+ promotionalGrantConsistency: 'OBSERVED',ledgerUpdatedAt: '2026-07-23T11:00:00Z',scale: 9,observedAt: '2026-07-23T12:00:00.123456789Z',@@ -131,14 +140,23 @@ describe('billing response projection', () => {grantId: 'expired',displayName: null,originalAmount: '5',- usedAmount: null,+ usedAmount: '1.25',remainingAmount: '0',expiresAt: '2026-07-01T00:00:00Z',state: 'expired',},+ {+ grantId: 'voided',+ displayName: 'Voided',+ originalAmount: '3',+ usedAmount: '0.5',+ remainingAmount: '0',+ expiresAt: '2026-08-01T00:00:00Z',+ state: 'voided',+ },],promotionalGrantsComplete: true,- promotionalGrantConsistency: 'LAST_SETTLED',+ promotionalGrantConsistency: 'OBSERVED',ledgerUpdatedAt: '2026-07-23T11:00:00Z',scale: 9,observedAt: '2026-07-23T12:00:00.123456789Z',@@ -163,7 +181,7 @@ describe('billing response projection', () => {},],promotionalGrantsComplete: true,- promotionalGrantConsistency: 'LAST_SETTLED',+ promotionalGrantConsistency: 'OBSERVED',ledgerUpdatedAt: null,scale: 9,observedAt: now,@@ -181,6 +199,25 @@ describe('billing response projection', () => {promotionalGrantsComplete: false,}),).toThrow();+ expect(() =>+ projectModelAccessCreditUsage({+ ...valid,+ promotional: { remaining: '0', used: '2', total: '2' },+ }),+ ).toThrow();+ expect(() =>+ projectModelAccessCreditUsage({+ ...valid,+ promotional: { remaining: '1', used: '1', total: '2' },+ promotionalGrants: [+ {+ ...valid.promotionalGrants[0],+ usedAmount: '0.5',+ remainingAmount: '1.5',+ },+ ],+ }),+ ).toThrow();expect(() =>projectModelAccessCreditUsage({...valid,@@ -190,15 +227,63 @@ describe('billing response projection', () => {expect(() =>projectModelAccessCreditUsage({...valid,+ promotionalGrantConsistency: ['LAST', 'SETTLED'].join('_'),+ }),+ ).toThrow();+ expect(() =>+ projectModelAccessCreditUsage({+ ...valid,+ observedAt: '2026-07-23T12:00:00.000000001Z',promotionalGrants: [{...valid.promotionalGrants[0],- state: 'expired',- usedAmount: '2',- remainingAmount: '0',+ expiresAt: '2026-07-23T12:00:00.000000002Z',},],}),+ ).not.toThrow();++ const historical = {+ ...valid,+ available: '5',+ promotional: { remaining: '0', used: null, total: null },+ promotionalGrants: [+ {+ ...valid.promotionalGrants[0],+ state: 'expired',+ usedAmount: '1',+ remainingAmount: '0',+ expiresAt: '2026-07-01T00:00:00Z',+ },+ ],+ promotionalGrantsComplete: false,+ };+ expect(projectModelAccessCreditUsage(historical)).toMatchObject({+ promotionalGrants: [{ state: 'expired', usedAmount: '1', remainingAmount: '0' }],+ });+ expect(() =>+ projectModelAccessCreditUsage({+ ...historical,+ promotionalGrants: [{ ...historical.promotionalGrants[0], usedAmount: '2.000000001' }],+ }),+ ).toThrow();+ expect(() =>+ projectModelAccessCreditUsage({+ ...historical,+ promotionalGrants: [+ {+ ...historical.promotionalGrants[0],+ state: 'voided',+ remainingAmount: '1',+ },+ ],+ }),+ ).toThrow();+ expect(() =>+ projectModelAccessCreditUsage({+ ...historical,+ promotionalGrants: [{ ...historical.promotionalGrants[0], usedAmount: null }],+ }),).toThrow();expect(() =>projectModelAccessCreditUsage({diff --git a/apps/desktop/src/main/billing/projection.ts b/apps/desktop/src/main/billing/projection.tsindex 60ef3727a5..93329fcb93 100644--- a/apps/desktop/src/main/billing/projection.ts+++ b/apps/desktop/src/main/billing/projection.ts@@ -156,6 +156,16 @@ function observedAt(value: unknown): string | null {return value;}+function compareObservedAt(left: string, right: string): number {+ const [leftWhole, leftFraction = ''] = left.slice(0, -1).split('.');+ const [rightWhole, rightFraction = ''] = right.slice(0, -1).split('.');+ if (leftWhole !== rightWhole) return leftWhole < rightWhole ? -1 : 1;+ const normalizedLeft = leftFraction.padEnd(9, '0');+ const normalizedRight = rightFraction.padEnd(9, '0');+ if (normalizedLeft === normalizedRight) return 0;+ return normalizedLeft < normalizedRight ? -1 : 1;+}+export function projectModelAccessBalance(value: unknown): ModelAccessBalance {if (!isRecord(value) || value.scale !== 9) invalidResponse();const planCredits = ledgerDecimal(value.planCredits);@@ -230,7 +240,7 @@ function projectPromotionalGrant(value: unknown): ModelAccessPromotionalGrantUsa? null: (boundedString(value.displayName, MAX_NAME_LENGTH) ?? undefined);const originalAmount = ledgerDecimal(value.originalAmount);- const usedAmount = value.usedAmount === null ? null : ledgerDecimal(value.usedAmount);+ const usedAmount = ledgerDecimal(value.usedAmount);const remainingAmount = ledgerDecimal(value.remainingAmount);const expiresAt = observedAt(value.expiresAt);const state =@@ -242,23 +252,20 @@ function projectPromotionalGrant(value: unknown): ModelAccessPromotionalGrantUsa!grantId ||displayName === undefined ||!originalAmount ||+ !usedAmount ||!remainingAmount ||originalAmount.scaled <= 0n ||+ usedAmount.scaled < 0n ||remainingAmount.scaled < 0n ||!expiresAt ||!state ||(state === 'active' &&(remainingAmount.scaled === 0n ||- !usedAmount ||- usedAmount.scaled < 0n ||usedAmount.scaled + remainingAmount.scaled !== originalAmount.scaled)) ||(state === 'depleted' &&- (remainingAmount.scaled !== 0n ||- (!usedAmount ||- usedAmount.scaled < 0n ||- usedAmount.scaled !== originalAmount.scaled))) ||+ (remainingAmount.scaled !== 0n || usedAmount.scaled !== originalAmount.scaled)) ||((state === 'expired' || state === 'voided') &&- (value.usedAmount !== null || remainingAmount.scaled !== 0n))+ (remainingAmount.scaled !== 0n || usedAmount.scaled > originalAmount.scaled))) {invalidResponse();}@@ -266,7 +273,7 @@ function projectPromotionalGrant(value: unknown): ModelAccessPromotionalGrantUsagrantId,displayName,originalAmount: originalAmount.source,- usedAmount: usedAmount?.source ?? null,+ usedAmount: usedAmount.source,remainingAmount: remainingAmount.source,expiresAt,state,@@ -280,7 +287,7 @@ export function projectModelAccessCreditUsage(value: unknown): ModelAccessCredit!Array.isArray(value.promotionalGrants) ||value.promotionalGrants.length > MAX_PROMOTIONAL_GRANTS ||typeof value.promotionalGrantsComplete !== 'boolean' ||- value.promotionalGrantConsistency !== 'LAST_SETTLED'+ value.promotionalGrantConsistency !== 'OBSERVED') {invalidResponse();}@@ -301,22 +308,29 @@ export function projectModelAccessCreditUsage(value: unknown): ModelAccessCreditconst grantIds = new Set<string>();let currentOriginalTotal = 0n;- const observedAtMs = Date.parse(snapshotTime);+ let currentUsedTotal = 0n;+ let currentRemainingTotal = 0n;const promotionalGrants = value.promotionalGrants.map((grant) => {const projected = projectPromotionalGrant(grant);if (grantIds.has(projected.grantId)) invalidResponse();grantIds.add(projected.grantId);if ((projected.state === 'active' || projected.state === 'depleted') &&- Date.parse(projected.expiresAt) > observedAtMs+ compareObservedAt(projected.expiresAt, snapshotTime) > 0) {currentOriginalTotal += ledgerDecimal(projected.originalAmount)!.scaled;+ currentUsedTotal += ledgerDecimal(projected.usedAmount)!.scaled;+ currentRemainingTotal += ledgerDecimal(projected.remainingAmount)!.scaled;}return projected;});if ((value.promotionalGrantsComplete &&- (promotional.total === null || promotional.total !== currentOriginalTotal)) ||+ (promotional.total === null ||+ promotional.used === null ||+ promotional.total !== currentOriginalTotal ||+ promotional.used !== currentUsedTotal ||+ promotional.remaining !== currentRemainingTotal)) ||(!value.promotionalGrantsComplete && (promotional.used !== null || promotional.total !== null))) {invalidResponse();@@ -329,7 +343,7 @@ export function projectModelAccessCreditUsage(value: unknown): ModelAccessCreditpromotional: promotional.value,promotionalGrants,promotionalGrantsComplete: value.promotionalGrantsComplete,- promotionalGrantConsistency: 'LAST_SETTLED',+ promotionalGrantConsistency: 'OBSERVED',ledgerUpdatedAt,scale: 9,observedAt: snapshotTime,diff --git a/apps/desktop/src/renderer/features/billing/BillingPage.tsx b/apps/desktop/src/renderer/features/billing/BillingPage.tsxindex 1104e24494..89498a79bc 100644--- a/apps/desktop/src/renderer/features/billing/BillingPage.tsx+++ b/apps/desktop/src/renderer/features/billing/BillingPage.tsx@@ -1152,9 +1152,6 @@ function PromotionalGrantLedger({currency: string;}) {const { t } = useTranslation();- const hasUnavailableHistoricalUsage = usage.promotionalGrants.some(- (grant) => grant.usedAmount === null,- );return (<div className="border-t border-[var(--border-default)] px-5 py-5"><div className="flex items-start justify-between gap-4">@@ -1180,11 +1177,6 @@ function PromotionalGrantLedger({})}</p>)}- {hasUnavailableHistoricalUsage && (- <p className="mt-3 rounded-lg bg-[var(--surface-chip)] px-3 py-2 text-11 leading-4 text-[var(--text-secondary)]">- {t('billing.usage.promotionalDetails.historicalUsageUnavailable')}- </p>- )}{usage.promotionalGrants.length === 0 ? (<p className="mt-4 rounded-xl border border-[var(--border-default)] px-4 py-5 text-12 text-[var(--text-secondary)]">@@ -1255,14 +1247,14 @@ function GrantAmount({currency,}: {label: string;- amount: string | null;+ amount: string;currency: string;}) {return (<div className="min-w-0 text-right"><p className="truncate text-10 text-[var(--text-tertiary)]">{label}</p><p className="mt-0.5 truncate text-11 font-medium tabular-nums text-[var(--text-primary)]">- {amount === null ? '—' : formatMoney(amount, currency)}+ {formatMoney(amount, currency)}</p></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 bef93ad4d1..56f3cc318e 100644--- a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx@@ -1,6 +1,6 @@// @vitest-environment jsdom-import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';import type { BillingPaymentOrder, BillingSubscription } from '../../../../shared/billing';@@ -563,7 +563,7 @@ describe('BillingPage remote catalog rendering', () => {available: '66',plan: { remaining: '40', used: '60', total: '100' },purchased: { remaining: '20', used: '30', total: '50' },- promotional: { remaining: '6', used: '4', total: '10' },+ promotional: { remaining: '6', used: '6', total: '12' },promotionalGrants: [{grantId: 'welcome',@@ -574,18 +574,36 @@ describe('BillingPage remote catalog rendering', () => {expiresAt: '2026-08-01T00:00:00Z',state: 'active' as const,},+ {+ grantId: 'depleted',+ displayName: 'Depleted grant',+ originalAmount: '2',+ usedAmount: '2',+ remainingAmount: '0',+ expiresAt: '2026-08-02T00:00:00Z',+ state: 'depleted' as const,+ },{grantId: 'expired',displayName: null,originalAmount: '5',- usedAmount: null,+ usedAmount: '1.25',remainingAmount: '0',expiresAt: '2026-07-01T00:00:00Z',state: 'expired' as const,},+ {+ grantId: 'voided',+ displayName: 'Voided grant',+ originalAmount: '3',+ usedAmount: '0.5',+ remainingAmount: '0',+ expiresAt: '2026-08-03T00:00:00Z',+ state: 'voided' as const,+ },],promotionalGrantsComplete: true,- promotionalGrantConsistency: 'LAST_SETTLED' as const,+ promotionalGrantConsistency: 'OBSERVED' as const,ledgerUpdatedAt: '2026-07-23T12:00:00Z',scale: 9 as const,observedAt: '2026-07-23T12:00:00Z',@@ -596,10 +614,26 @@ describe('BillingPage remote catalog rendering', () => {expect(await screen.findByText('Welcome grant')).toBeTruthy();expect(screen.getByText('billing.usage.promotionalDetails.unnamed')).toBeTruthy();expect(screen.getByText('billing.usage.promotionalDetails.states.active')).toBeTruthy();+ expect(screen.getByText('billing.usage.promotionalDetails.states.depleted')).toBeTruthy();expect(screen.getByText('billing.usage.promotionalDetails.states.expired')).toBeTruthy();- expect(- screen.getByText('billing.usage.promotionalDetails.historicalUsageUnavailable'),- ).toBeTruthy();+ expect(screen.getByText('billing.usage.promotionalDetails.states.voided')).toBeTruthy();++ const grantRows = within(screen.getByRole('list')).getAllByRole('listitem');+ const formatter = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'CNY' });+ for (const [row, usedAmount] of [+ [grantRows[0], 4],+ [grantRows[1], 2],+ [grantRows[2], 1.25],+ [grantRows[3], 0.5],+ ] as const) {+ const usedLabel = within(row).getByText('billing.usage.promotionalDetails.used');+ expect(usedLabel.nextElementSibling?.textContent).toBe(formatter.format(usedAmount));+ }+ const legacyWarningKey = `billing.usage.promotionalDetails.${[+ 'historical',+ 'UsageUnavailable',+ ].join('')}`;+ expect(screen.queryByText(legacyWarningKey)).toBeNull();expect(screen.getAllByRole('progressbar')).toHaveLength(3);expect(window.electronAPI.billing.getBalance).not.toHaveBeenCalled();});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex f55fabd5f8..0a6229ed2a 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -7039,11 +7039,10 @@"detailsUnavailable": "Usage details are temporarily unavailable. Current balances are shown instead.","promotionalDetails": {"title": "Promotional Credit Details",- "description": "Each grant has its own status and expiration. Remaining amounts come from the last ledger settlement and may be slightly delayed.",+ "description": "Current grants and the total balance use the same credit snapshot. Used amounts include model consumption only.","count": "{{count}} grants","empty": "No promotional credit grants are available.","incomplete": "There are many grant records. Only the latest {{count}} are shown.",- "historicalUsageUnavailable": "Gateway cannot currently reconstruct actual usage for expired or voided grants; “—” is shown.","unnamed": "Promotional credit","original": "Original","used": "Used",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex d55e088690..5e0598933e 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -7028,11 +7028,10 @@"detailsUnavailable": "使用量の詳細を取得できないため、現在の残高のみ表示しています。","promotionalDetails": {"title": "特典クレジット明細",- "description": "付与ごとに状態と有効期限が異なります。残量は前回の台帳精算時点の値で、反映が少し遅れる場合があります。",+ "description": "現在の付与明細と合計残高は同じクレジットスナップショットに基づき、使用済み額には実際のモデル利用分のみが含まれます。","count": "{{count}}件","empty": "特典クレジットの付与履歴はありません。","incomplete": "付与履歴が多いため、最新の{{count}}件のみ表示しています。",- "historicalUsageUnavailable": "期限切れまたは無効化された付与の実使用量は現在 Gateway から復元できないため、「—」で表示します。","unnamed": "特典クレジット","original": "付与額","used": "使用済み",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 08411a028a..a6dc840a90 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -7028,11 +7028,10 @@"detailsUnavailable": "사용량 상세를 불러올 수 없어 현재 잔액만 표시합니다.","promotionalDetails": {"title": "프로모션 크레딧 상세",- "description": "각 지급 건은 상태와 만료 시간이 서로 다릅니다. 잔여 금액은 마지막 원장 정산 기준이며 반영이 조금 늦을 수 있습니다.",+ "description": "현재 지급 내역과 총 잔액은 동일한 크레딧 스냅샷을 기준으로 하며, 사용 금액에는 실제 모델 사용량만 포함됩니다.","count": "{{count}}건","empty": "프로모션 크레딧 지급 내역이 없습니다.","incomplete": "지급 내역이 많아 최근 {{count}}건만 표시합니다.",- "historicalUsageUnavailable": "만료되었거나 무효화된 지급분의 실제 사용량은 현재 Gateway에서 복원할 수 없어 '—'로 표시됩니다.","unnamed": "프로모션 크레딧","original": "지급액","used": "사용",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 4ec451b7a9..57564128ef 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -7028,11 +7028,10 @@"detailsUnavailable": "用量明细暂时不可用,当前仅显示各类余额。","promotionalDetails": {"title": "赠送额度明细",- "description": "每笔赠送拥有独立有效期和状态。剩余额度来自上次账本结算,可能稍有延迟。",+ "description": "当前赠送与总余额基于同一次额度快照,已用额度仅统计实际模型消费。","count": "{{count}} 笔","empty": "当前没有赠送额度记录。","incomplete": "赠送记录较多,当前仅显示最近的 {{count}} 笔。",- "historicalUsageUnavailable": "已过期或作废记录的真实已用额度当前无法由 Gateway 还原,以“—”显示。","unnamed": "赠送额度","original": "原始额度","used": "已用",diff --git a/apps/desktop/src/shared/modelAccess.ts b/apps/desktop/src/shared/modelAccess.tsindex b21d99fb73..9b290f9756 100644--- a/apps/desktop/src/shared/modelAccess.ts+++ b/apps/desktop/src/shared/modelAccess.ts@@ -57,8 +57,7 @@ export interface ModelAccessPromotionalGrantUsage {grantId: string;displayName: string | null;originalAmount: string;- /** expired / voided 时 Gateway 当前 contract 无法还原真实已用量。 */- usedAmount: string | null;+ usedAmount: string;remainingAmount: string;expiresAt: string;state: ModelAccessPromotionalGrantState;@@ -73,8 +72,8 @@ export interface ModelAccessCreditUsage {promotionalGrants: ModelAccessPromotionalGrantUsage[];/** false 表示 Gateway 历史超过 Server 的安全分页上限,列表只含最近记录。 */promotionalGrantsComplete: boolean;- /** 逐笔 remainingAmount 来自 Gateway 上次持久化结算,不是实时扣减值。 */- promotionalGrantConsistency: 'LAST_SETTLED';+ /** 当前逐笔赠送与总余额来自同一次 Gateway 额度快照。 */+ promotionalGrantConsistency: 'OBSERVED';ledgerUpdatedAt: string | null;scale: 9;observedAt: string;