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): 接入服务端配置驱动的计费入口 (#250)

GaoWei Liu38e644166c13
diff --git a/apps/desktop/src/main/__tests__/serverApiClient.test.ts b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
index f50871ce45..236a47b33f 100644
--- a/apps/desktop/src/main/__tests__/serverApiClient.test.ts
+++ b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
@@ -10,6 +10,10 @@ const mocks = vi.hoisted(() => ({
getAccessToken: vi.fn(),
refresh: vi.fn(),
invalidateSession: vi.fn(),
+ logger: {
+ error: vi.fn(),
+ warn: vi.fn(),
+ },
}));
vi.mock('electron', () => ({ net: { fetch: mocks.netFetch } }));
@@ -19,7 +23,7 @@ vi.mock('../authManager', () => ({
invalidateSession: mocks.invalidateSession,
}));
vi.mock('../logger', () => ({
- createLogger: () => ({ error: vi.fn(), warn: vi.fn() }),
+ createLogger: () => mocks.logger,
}));
import { serverApiFetch } from '../serverApiClient';
@@ -162,4 +166,58 @@ describe('serverApiFetch', () => {
expect(mocks.refresh).not.toHaveBeenCalled();
expect(mocks.invalidateSession).not.toHaveBeenCalled();
});
+
+ it('redacted requests do not persist upstream messages, bodies, or network errors', async () => {
+ mocks.getAccessToken.mockReturnValue('token-a');
+ mocks.netFetch
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 502,
+ json: async () => ({
+ error: {
+ code: 'PROVIDER_PRIVATE_FAILURE',
+ message: 'merchant private response body',
+ },
+ }),
+ })
+ .mockRejectedValueOnce(new Error('network URL contained private detail'));
+
+ await expect(
+ serverApiFetch('/api/billing/orders/order-1', {
+ baseUrl: 'https://model-access.example.com',
+ redactErrorDetails: true,
+ }),
+ ).rejects.toMatchObject({
+ code: 'INTERNAL_ERROR',
+ statusCode: 502,
+ message: '请求失败 (502)',
+ });
+ await expect(
+ serverApiFetch('/api/billing/orders/order-1', {
+ baseUrl: 'https://model-access.example.com',
+ redactErrorDetails: true,
+ }),
+ ).rejects.toBeTruthy();
+
+ const logged = JSON.stringify({
+ error: mocks.logger.error.mock.calls,
+ warn: mocks.logger.warn.mock.calls,
+ });
+ expect(logged).not.toContain('PROVIDER_PRIVATE_FAILURE');
+ expect(logged).not.toContain('merchant private response body');
+ expect(logged).not.toContain('private detail');
+ expect(logged).not.toContain('order-1');
+ expect(mocks.logger.warn).toHaveBeenCalledWith(
+ 'serverApiFetch.redacted_not_ok',
+ 'path=/api/billing/orders',
+ 'method=GET',
+ 'status=502',
+ 'code=INTERNAL_ERROR',
+ );
+ expect(mocks.logger.error).toHaveBeenCalledWith(
+ 'serverApiFetch.redacted_network_error',
+ 'path=/api/billing/orders',
+ 'method=GET',
+ );
+ });
});
diff --git a/apps/desktop/src/main/billing/__tests__/index.test.ts b/apps/desktop/src/main/billing/__tests__/index.test.ts
new file mode 100644
index 0000000000..1c44333188
--- /dev/null
+++ b/apps/desktop/src/main/billing/__tests__/index.test.ts
@@ -0,0 +1,472 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { BrowserWindow } from 'electron';
+
+import { BILLING_INVOKE } from '../../../shared/billing.js';
+import { ServerApiError } from '../../serverApiClient.js';
+import { createBillingHandlers } from '../index.js';
+
+function harness() {
+ const mainFrame = { routingId: 1 };
+ const mainWebContents = { id: 1, mainFrame };
+ const mainWindow = {
+ isDestroyed: () => false,
+ webContents: mainWebContents,
+ } as unknown as BrowserWindow;
+ const now = '2026-07-23T12:00:00.000Z';
+ const paymentOrder = {
+ orderId: 'order_1',
+ productCode: 'credit_topup',
+ offerCode: 'credit_topup_custom',
+ amount: '20',
+ currency: 'cny',
+ status: 'PENDING',
+ paymentAction: null,
+ createdAt: now,
+ updatedAt: now,
+ };
+ const subscription = {
+ subscriptionId: 'subscription_1',
+ status: 'INCOMPLETE',
+ currentPeriodStartAt: null,
+ currentPeriodEndAt: null,
+ entitlementValidUntil: null,
+ cancelAtPeriodEnd: false,
+ effectivePlan: null,
+ purchaseAttemptId: 'attempt_1',
+ paymentAction: null,
+ };
+ const fetch = vi.fn(async (path: string) => {
+ if (path === '/api/model-access/balance') {
+ return {
+ planCredits: '7.000000001',
+ purchasedCredits: '5.000000002',
+ promotionalCredits: '0.345678898',
+ available: '12.345678901',
+ scale: 9,
+ observedAt: now,
+ };
+ }
+ if (path === '/api/model-access/credit-usage') {
+ return {
+ available: '12.345678901',
+ plan: { remaining: '7.000000001', used: '3', total: '10.000000001' },
+ purchased: { remaining: '5.000000002', used: '5', total: '10.000000002' },
+ promotional: {
+ remaining: '0.345678898',
+ used: '0.654321102',
+ total: '1',
+ },
+ promotionalGrants: [
+ {
+ grantId: 'welcome',
+ displayName: 'Welcome',
+ originalAmount: '1',
+ usedAmount: '0.654321102',
+ remainingAmount: '0.345678898',
+ expiresAt: '2026-08-23T12:00:00.000Z',
+ state: 'active',
+ },
+ ],
+ promotionalGrantsComplete: true,
+ promotionalGrantConsistency: 'LAST_SETTLED',
+ ledgerUpdatedAt: now,
+ scale: 9,
+ observedAt: now,
+ };
+ }
+ if (path === '/api/billing/catalog') return { products: [] };
+ if (path === '/api/billing/orders?limit=20') return { orders: [], nextCursor: null };
+ if (path === '/api/billing/subscription') return { subscription };
+ if (path.includes('/subscriptions')) return subscription;
+ return paymentOrder;
+ }) as unknown as NonNullable<Parameters<typeof createBillingHandlers>[0]['fetch']> &
+ ReturnType<typeof vi.fn>;
+ const openExternal = vi.fn(async () => undefined);
+ const requirePersonalAccount = vi.fn();
+ const handlers = createBillingHandlers({
+ getMainWindow: () => mainWindow,
+ requirePersonalAccount,
+ getBaseUrl: () => 'https://model-access.example',
+ fetch,
+ openExternal,
+ });
+ const call = (
+ channel: string,
+ payload?: unknown,
+ sender: unknown = mainWebContents,
+ senderFrame: unknown = mainFrame,
+ ) => handlers[channel]!({ sender, senderFrame } as never, payload);
+ return {
+ call,
+ fetch,
+ mainFrame,
+ mainWebContents,
+ openExternal,
+ requirePersonalAccount,
+ };
+}
+
+describe('billing IPC', () => {
+ it('queries the fixed current-account balance endpoint without a renderer payload', async () => {
+ const { call, fetch } = harness();
+
+ await expect(call(BILLING_INVOKE.GET_BALANCE)).resolves.toEqual({
+ planCredits: '7.000000001',
+ purchasedCredits: '5.000000002',
+ promotionalCredits: '0.345678898',
+ available: '12.345678901',
+ scale: 9,
+ observedAt: '2026-07-23T12:00:00.000Z',
+ });
+ expect(fetch).toHaveBeenCalledWith('/api/model-access/balance', {
+ baseUrl: 'https://model-access.example',
+ timeoutMs: 20_000,
+ redactErrorDetails: true,
+ });
+ });
+
+ it('rejects any balance payload before network access', async () => {
+ const { call, fetch } = harness();
+
+ await expect(call(BILLING_INVOKE.GET_BALANCE, {})).rejects.toMatchObject({
+ code: 'INVALID_PARAMS',
+ });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('queries the fixed current-account credit usage endpoint', async () => {
+ const { call, fetch } = harness();
+
+ 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' }],
+ });
+ expect(fetch).toHaveBeenCalledWith('/api/model-access/credit-usage', {
+ baseUrl: 'https://model-access.example',
+ timeoutMs: 20_000,
+ redactErrorDetails: true,
+ });
+ });
+
+ it.each([
+ BILLING_INVOKE.GET_CREDIT_USAGE,
+ BILLING_INVOKE.GET_CATALOG,
+ BILLING_INVOKE.GET_CURRENT_SUBSCRIPTION,
+ ])('rejects any payload on the no-payload channel %s before network access', async (channel) => {
+ const { call, fetch } = harness();
+
+ await expect(call(channel, {})).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['NOT_FOUND', 404, 'NOT_FOUND'],
+ ['INTERNAL', 501, 'UNSUPPORTED_CAPABILITY'],
+ ['INTERNAL', 503, 'MODEL_ACCESS_FAILED'],
+ ])('maps balance error %s (%i) to safe IPC code %s', async (serverCode, statusCode, ipcCode) => {
+ const { call, fetch } = harness();
+ fetch.mockRejectedValueOnce(new ServerApiError(serverCode, statusCode, 'sensitive detail'));
+
+ await expect(call(BILLING_INVOKE.GET_BALANCE)).rejects.toMatchObject({
+ code: ipcCode,
+ });
+ });
+
+ it('rejects a malformed balance snapshot as an invalid server response', async () => {
+ const { call, fetch } = harness();
+ fetch.mockResolvedValueOnce({
+ planCredits: '7',
+ purchasedCredits: '5',
+ promotionalCredits: '4',
+ available: '999',
+ scale: 9,
+ observedAt: '2026-07-23T12:00:00.000Z',
+ });
+
+ await expect(call(BILLING_INVOKE.GET_BALANCE)).rejects.toMatchObject({
+ code: 'INTERNAL',
+ message: '[INTERNAL] billing service response was invalid',
+ });
+ });
+
+ it('maps a top-up to the fixed model-access endpoint and idempotency header', async () => {
+ const { call, fetch } = harness();
+ await call(BILLING_INVOKE.CREATE_TOPUP, {
+ request: {
+ offerCode: 'credit_topup_custom',
+ amount: '20.00',
+ purchaseOptionId: 'listing_alipay',
+ },
+ idempotencyKey: 'desktop:topup:12345678',
+ });
+
+ expect(fetch).toHaveBeenCalledWith('/api/billing/credit-topup/orders', {
+ baseUrl: 'https://model-access.example',
+ timeoutMs: 20_000,
+ redactErrorDetails: true,
+ method: 'POST',
+ body: {
+ offerCode: 'credit_topup_custom',
+ amount: '20.00',
+ purchaseOptionId: 'listing_alipay',
+ },
+ headers: { 'Idempotency-Key': 'desktop:topup:12345678' },
+ });
+ });
+
+ it('encodes resource ids and fixes the refresh method', async () => {
+ const { call, fetch } = harness();
+ await call(BILLING_INVOKE.REFRESH_SUBSCRIPTION_PURCHASE, {
+ purchaseAttemptId: 'attempt/1',
+ });
+ expect(fetch).toHaveBeenCalledWith('/api/billing/subscriptions/purchases/attempt%2F1/refresh', {
+ baseUrl: 'https://model-access.example',
+ timeoutMs: 20_000,
+ redactErrorDetails: true,
+ method: 'POST',
+ });
+ });
+
+ it('rejects non-main-window senders before network access', async () => {
+ const { call, fetch } = harness();
+ await expect(call(BILLING_INVOKE.GET_CATALOG, undefined, { id: 2 })).rejects.toMatchObject({
+ code: 'PERMISSION_DENIED',
+ });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('rejects non-top-level frames in the main window before network access', async () => {
+ const { call, fetch, mainWebContents } = harness();
+ await expect(
+ call(BILLING_INVOKE.GET_CATALOG, undefined, mainWebContents, { routingId: 2 }),
+ ).rejects.toMatchObject({
+ code: 'PERMISSION_DENIED',
+ });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it.each(Object.values(BILLING_INVOKE))(
+ 'rejects account-ineligible access on %s before payload parsing or network access',
+ async (channel) => {
+ const { call, fetch, openExternal, requirePersonalAccount } = harness();
+ requirePersonalAccount.mockImplementation(() => {
+ throw Object.assign(new Error('[PERMISSION_DENIED] Billing requires a personal account.'), {
+ code: 'PERMISSION_DENIED',
+ });
+ });
+
+ await expect(call(channel, { invalid: true })).rejects.toMatchObject({
+ code: 'PERMISSION_DENIED',
+ });
+ expect(fetch).not.toHaveBeenCalled();
+ expect(openExternal).not.toHaveBeenCalled();
+ },
+ );
+
+ it('rejects unknown fields and invalid idempotency keys', async () => {
+ const { call, fetch } = harness();
+ await expect(
+ call(BILLING_INVOKE.CREATE_SUBSCRIPTION, {
+ request: {
+ offerCode: 'plus_month',
+ purchaseOptionId: 'listing_alipay',
+ provider: 'alipay',
+ },
+ idempotencyKey: 'short',
+ }),
+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('bounds order list requests', async () => {
+ const { call, fetch } = harness();
+ await expect(call(BILLING_INVOKE.LIST_ORDERS, { limit: 101 })).rejects.toMatchObject({
+ code: 'INVALID_PARAMS',
+ });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('converts backend failures to the IPC error protocol without leaking details', async () => {
+ const { call, fetch } = harness();
+ fetch.mockRejectedValueOnce(
+ new ServerApiError('UPSTREAM_SECRET_CODE', 500, 'sensitive backend response'),
+ );
+
+ await expect(call(BILLING_INVOKE.GET_CATALOG)).rejects.toMatchObject({
+ code: 'INTERNAL',
+ message: '[INTERNAL] billing service request failed',
+ });
+ });
+
+ it('converts malformed single-resource responses to a fixed INTERNAL error', async () => {
+ const { call, fetch } = harness();
+ fetch.mockResolvedValueOnce({
+ orderId: 'order_1',
+ status: 'FUTURE_STATUS',
+ providerError: 'private response detail',
+ });
+
+ await expect(call(BILLING_INVOKE.GET_ORDER, { orderId: 'order_1' })).rejects.toMatchObject({
+ code: 'INTERNAL',
+ message: '[INTERNAL] billing service response was invalid',
+ });
+ });
+
+ it('fail-closes an unknown current subscription status instead of returning no subscription', async () => {
+ const { call, fetch } = harness();
+ fetch.mockResolvedValueOnce({
+ subscription: {
+ subscriptionId: 'subscription_1',
+ status: 'FUTURE_STATUS',
+ currentPeriodStartAt: null,
+ currentPeriodEndAt: null,
+ entitlementValidUntil: null,
+ cancelAtPeriodEnd: false,
+ effectivePlan: null,
+ purchaseAttemptId: null,
+ paymentAction: null,
+ },
+ });
+
+ await expect(call(BILLING_INVOKE.GET_CURRENT_SUBSCRIPTION)).rejects.toMatchObject({
+ code: 'INTERNAL',
+ message: '[INTERNAL] billing service response was invalid',
+ });
+ });
+
+ it('maps a plan change quote to the fixed endpoint with the idempotency header', async () => {
+ const { call, fetch } = harness();
+ const change = {
+ planChangeId: 'plan_change_1',
+ changeType: 'DOWNGRADE',
+ status: 'QUOTED',
+ quotedAmountMinor: null,
+ quotedCurrency: null,
+ quoteExpiresAt: '2026-07-23T12:05:00.000Z',
+ effectiveAt: '2026-08-01T00:00:00.000Z',
+ paymentAction: null,
+ };
+ fetch.mockResolvedValueOnce(change);
+
+ await expect(
+ call(BILLING_INVOKE.QUOTE_PLAN_CHANGE, {
+ targetOfferCode: 'plus_month',
+ idempotencyKey: 'desktop:plan-change:12345678',
+ }),
+ ).resolves.toEqual(change);
+ expect(fetch).toHaveBeenCalledWith('/api/billing/subscription/plan-change-quotes', {
+ baseUrl: 'https://model-access.example',
+ timeoutMs: 20_000,
+ redactErrorDetails: true,
+ method: 'POST',
+ body: { targetOfferCode: 'plus_month' },
+ headers: { 'Idempotency-Key': 'desktop:plan-change:12345678' },
+ });
+ });
+
+ it('rejects a plan change quote without a valid idempotency key before network access', async () => {
+ const { call, fetch } = harness();
+ await expect(
+ call(BILLING_INVOKE.QUOTE_PLAN_CHANGE, { targetOfferCode: 'plus_month' }),
+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('cancels a plan change with DELETE and an encoded id', async () => {
+ const { call, fetch } = harness();
+ fetch.mockResolvedValueOnce({
+ planChangeId: 'plan/1',
+ changeType: 'DOWNGRADE',
+ status: 'CANCELED',
+ quotedAmountMinor: null,
+ quotedCurrency: null,
+ quoteExpiresAt: null,
+ effectiveAt: '2026-08-01T00:00:00.000Z',
+ paymentAction: null,
+ });
+
+ await call(BILLING_INVOKE.CANCEL_PLAN_CHANGE, { planChangeId: 'plan/1' });
+ expect(fetch).toHaveBeenCalledWith('/api/billing/subscription/plan-changes/plan%2F1', {
+ baseUrl: 'https://model-access.example',
+ timeoutMs: 20_000,
+ redactErrorDetails: true,
+ method: 'DELETE',
+ });
+ });
+
+ it('fail-closes an unknown plan change status from confirm', async () => {
+ const { call, fetch } = harness();
+ fetch.mockResolvedValueOnce({
+ planChangeId: 'plan_change_1',
+ changeType: 'UPGRADE',
+ status: 'FUTURE_STATUS',
+ quotedAmountMinor: 1500,
+ quotedCurrency: 'cny',
+ quoteExpiresAt: null,
+ effectiveAt: '2026-08-01T00:00:00.000Z',
+ paymentAction: null,
+ providerError: 'private detail',
+ });
+
+ await expect(
+ call(BILLING_INVOKE.CONFIRM_PLAN_CHANGE, { planChangeId: 'plan_change_1' }),
+ ).rejects.toMatchObject({
+ code: 'INTERNAL',
+ message: '[INTERNAL] billing service response was invalid',
+ });
+ });
+
+ it('opens only public HTTPS Stripe Checkout URLs from the main top-level frame', async () => {
+ const { call, openExternal } = harness();
+ const url = 'https://checkout.stripe.com/c/pay/session_fixture#fragment';
+
+ await expect(call(BILLING_INVOKE.OPEN_PAYMENT_REDIRECT, { url })).resolves.toEqual({
+ success: true,
+ });
+ expect(openExternal).toHaveBeenCalledWith(url);
+ });
+
+ it.each([
+ 'http://checkout.stripe.com/c/pay/test',
+ 'file:///tmp/payment.html',
+ 'javascript:alert(1)',
+ 'stripe://checkout/session',
+ 'https://checkout.stripe.com.evil.example/c/pay/test',
+ 'https://[email protected]/c/pay/test',
+ 'https://user:[email protected]/c/pay/test',
+ 'https://checkout.stripe.com:444/c/pay/test',
+ `https://checkout.stripe.com/c/pay/${'x'.repeat(2_100)}`,
+ ])('rejects an unsafe billing redirect without opening it: %s', async (url) => {
+ const { call, openExternal } = harness();
+ await expect(call(BILLING_INVOKE.OPEN_PAYMENT_REDIRECT, { url })).rejects.toMatchObject({
+ code: 'INVALID_PARAMS',
+ });
+ expect(openExternal).not.toHaveBeenCalled();
+ });
+
+ it('rejects billing redirects from a child frame', async () => {
+ const { call, mainWebContents, openExternal } = harness();
+ await expect(
+ call(
+ BILLING_INVOKE.OPEN_PAYMENT_REDIRECT,
+ { url: 'https://checkout.stripe.com/c/pay/test' },
+ mainWebContents,
+ { routingId: 2 },
+ ),
+ ).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ expect(openExternal).not.toHaveBeenCalled();
+ });
+
+ it('rejects billing redirects from a different window', async () => {
+ const { call, openExternal } = harness();
+ await expect(
+ call(
+ BILLING_INVOKE.OPEN_PAYMENT_REDIRECT,
+ { url: 'https://checkout.stripe.com/c/pay/test' },
+ { id: 2 },
+ ),
+ ).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ expect(openExternal).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/billing/__tests__/projection.test.ts b/apps/desktop/src/main/billing/__tests__/projection.test.ts
new file mode 100644
index 0000000000..de0cc23828
--- /dev/null
+++ b/apps/desktop/src/main/billing/__tests__/projection.test.ts
@@ -0,0 +1,677 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ projectBillingCatalog,
+ projectBillingCurrentSubscription,
+ projectBillingOrderList,
+ projectBillingPaymentOrder,
+ projectBillingPlanChange,
+ projectModelAccessBalance,
+ projectModelAccessCreditUsage,
+} from '../projection.js';
+
+const now = '2026-07-23T12:00:00.000Z';
+
+function order(overrides: Record<string, unknown> = {}) {
+ return {
+ orderId: 'order_1',
+ productCode: 'credit_topup',
+ offerCode: 'credit_topup_20',
+ amount: '20',
+ currency: 'cny',
+ status: 'PENDING',
+ paymentAction: {
+ type: 'REDIRECT',
+ url: 'https://checkout.stripe.com/c/pay/session_fixture',
+ expiresAt: now,
+ },
+ createdAt: now,
+ updatedAt: now,
+ internalProviderResponse: 'must not cross IPC',
+ ...overrides,
+ };
+}
+
+describe('billing response projection', () => {
+ it('projects one exact ledger snapshot and strips server-only fields', () => {
+ expect(
+ projectModelAccessBalance({
+ planCredits: '7.000000001',
+ purchasedCredits: '-2.5',
+ promotionalCredits: '0.499999999',
+ available: '5',
+ scale: 9,
+ observedAt: '2026-07-23T12:00:00.123456789Z',
+ tenantId: 'must not cross IPC',
+ }),
+ ).toEqual({
+ planCredits: '7.000000001',
+ purchasedCredits: '-2.5',
+ promotionalCredits: '0.499999999',
+ available: '5',
+ scale: 9,
+ observedAt: '2026-07-23T12:00:00.123456789Z',
+ });
+ });
+
+ it('rejects inconsistent, negative protected-pool, and invalid-date balance snapshots', () => {
+ const valid = {
+ planCredits: '7',
+ purchasedCredits: '5',
+ promotionalCredits: '4',
+ available: '16',
+ scale: 9,
+ observedAt: now,
+ };
+
+ expect(() => projectModelAccessBalance({ ...valid, available: '15.999999999' })).toThrow();
+ expect(() =>
+ projectModelAccessBalance({
+ ...valid,
+ planCredits: '-1',
+ purchasedCredits: '13',
+ }),
+ ).toThrow();
+ expect(() =>
+ projectModelAccessBalance({ ...valid, observedAt: '2026-02-31T12:00:00Z' }),
+ ).toThrow();
+ });
+
+ it('projects exact pool usage and independent promotional grant states', () => {
+ expect(
+ projectModelAccessCreditUsage({
+ available: '6',
+ plan: { remaining: '3', used: '7', total: '10' },
+ purchased: { remaining: '2', used: '3', total: '5' },
+ promotional: { remaining: '1', used: '1', total: '2' },
+ promotionalGrants: [
+ {
+ grantId: 'welcome',
+ displayName: 'Welcome',
+ originalAmount: '2',
+ usedAmount: '1',
+ remainingAmount: '1',
+ expiresAt: '2026-08-01T00:00:00.123456789Z',
+ state: 'active',
+ internalMetadata: 'hidden',
+ },
+ {
+ grantId: 'expired',
+ displayName: null,
+ originalAmount: '5',
+ usedAmount: null,
+ remainingAmount: '0',
+ expiresAt: '2026-07-01T00:00:00Z',
+ state: 'expired',
+ },
+ ],
+ promotionalGrantsComplete: true,
+ promotionalGrantConsistency: 'LAST_SETTLED',
+ ledgerUpdatedAt: '2026-07-23T11:00:00Z',
+ scale: 9,
+ observedAt: '2026-07-23T12:00:00.123456789Z',
+ serviceKey: 'must not cross IPC',
+ }),
+ ).toEqual({
+ available: '6',
+ plan: { remaining: '3', used: '7', total: '10' },
+ purchased: { remaining: '2', used: '3', total: '5' },
+ promotional: { remaining: '1', used: '1', total: '2' },
+ promotionalGrants: [
+ {
+ grantId: 'welcome',
+ displayName: 'Welcome',
+ originalAmount: '2',
+ usedAmount: '1',
+ remainingAmount: '1',
+ expiresAt: '2026-08-01T00:00:00.123456789Z',
+ state: 'active',
+ },
+ {
+ grantId: 'expired',
+ displayName: null,
+ originalAmount: '5',
+ usedAmount: null,
+ remainingAmount: '0',
+ expiresAt: '2026-07-01T00:00:00Z',
+ state: 'expired',
+ },
+ ],
+ promotionalGrantsComplete: true,
+ promotionalGrantConsistency: 'LAST_SETTLED',
+ ledgerUpdatedAt: '2026-07-23T11:00:00Z',
+ scale: 9,
+ observedAt: '2026-07-23T12:00:00.123456789Z',
+ });
+ });
+
+ it('rejects inconsistent pool identities and dishonest promotional histories', () => {
+ const valid = {
+ available: '6',
+ plan: { remaining: '3', used: '7', total: '10' },
+ purchased: { remaining: '2', used: '3', total: '5' },
+ promotional: { remaining: '1', used: '1', total: '2' },
+ promotionalGrants: [
+ {
+ grantId: 'welcome',
+ displayName: null,
+ originalAmount: '2',
+ usedAmount: '1',
+ remainingAmount: '1',
+ expiresAt: '2026-08-01T00:00:00Z',
+ state: 'active',
+ },
+ ],
+ promotionalGrantsComplete: true,
+ promotionalGrantConsistency: 'LAST_SETTLED',
+ ledgerUpdatedAt: null,
+ scale: 9,
+ observedAt: now,
+ };
+
+ expect(() =>
+ projectModelAccessCreditUsage({
+ ...valid,
+ plan: { remaining: '3', used: '8', total: '10' },
+ }),
+ ).toThrow();
+ expect(() =>
+ projectModelAccessCreditUsage({
+ ...valid,
+ promotionalGrantsComplete: false,
+ }),
+ ).toThrow();
+ expect(() =>
+ projectModelAccessCreditUsage({
+ ...valid,
+ promotionalGrants: [valid.promotionalGrants[0], { ...valid.promotionalGrants[0] }],
+ }),
+ ).toThrow();
+ expect(() =>
+ projectModelAccessCreditUsage({
+ ...valid,
+ promotionalGrants: [
+ {
+ ...valid.promotionalGrants[0],
+ state: 'expired',
+ usedAmount: '2',
+ remainingAmount: '0',
+ },
+ ],
+ }),
+ ).toThrow();
+ expect(() =>
+ projectModelAccessCreditUsage({
+ ...valid,
+ promotionalGrants: [
+ {
+ ...valid.promotionalGrants[0],
+ state: 'active',
+ usedAmount: '2',
+ remainingAmount: '0',
+ },
+ ],
+ }),
+ ).toThrow();
+ expect(() =>
+ projectModelAccessCreditUsage({
+ ...valid,
+ promotionalGrants: [
+ {
+ ...valid.promotionalGrants[0],
+ state: 'depleted',
+ usedAmount: '1',
+ remainingAmount: '1',
+ },
+ ],
+ }),
+ ).toThrow();
+ });
+
+ it('keeps valid catalog entries while dropping malformed and unsupported nested entries', () => {
+ const projected = projectBillingCatalog({
+ products: [
+ {
+ code: 'credit_topup',
+ name: 'Credits',
+ kind: 'CREDIT_TOPUP',
+ level: null,
+ sortOrder: 1,
+ internalField: 'hidden',
+ offers: [
+ {
+ code: 'credit_topup_20',
+ interval: null,
+ currency: 'cny',
+ amount: '20',
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: '20',
+ rolloverCap: null,
+ purchaseOptions: [
+ {
+ id: 'listing_alipay',
+ provider: 'alipay',
+ capability: 'ONE_TIME_PAYMENT',
+ paymentAction: 'QR_CODE',
+ merchantId: 'hidden',
+ },
+ {
+ id: 'listing_future',
+ provider: 'future_provider',
+ capability: 'ONE_TIME_PAYMENT',
+ paymentAction: 'QR_CODE',
+ },
+ {
+ id: 'listing_future_action',
+ provider: 'stripe',
+ capability: 'ONE_TIME_PAYMENT',
+ paymentAction: 'EMBEDDED_WIDGET',
+ },
+ {
+ id: 'listing_future_capability',
+ provider: 'stripe',
+ capability: 'FUTURE_CAPABILITY',
+ paymentAction: 'REDIRECT',
+ },
+ ],
+ },
+ { code: 'broken', purchaseOptions: [] },
+ ],
+ },
+ {
+ code: 'future_product',
+ name: 'Future',
+ kind: 'USAGE_PACKAGE',
+ level: null,
+ sortOrder: 2,
+ offers: [],
+ },
+ ],
+ });
+
+ expect(projected).toEqual({
+ products: [
+ {
+ code: 'credit_topup',
+ name: 'Credits',
+ kind: 'CREDIT_TOPUP',
+ level: null,
+ sortOrder: 1,
+ offers: [
+ {
+ code: 'credit_topup_20',
+ interval: null,
+ currency: 'cny',
+ amount: '20',
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: '20',
+ rolloverCap: null,
+ purchaseOptions: [
+ {
+ id: 'listing_alipay',
+ provider: 'alipay',
+ capability: 'ONE_TIME_PAYMENT',
+ paymentAction: 'QR_CODE',
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+ });
+
+ it('enforces the server contract that offer codes are globally unique', () => {
+ const purchaseOption = {
+ id: 'listing_stripe',
+ provider: 'stripe',
+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION',
+ paymentAction: 'REDIRECT',
+ };
+ const offer = (code: string) => ({
+ code,
+ interval: 'MONTH',
+ currency: 'usd',
+ amount: '10',
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: '100',
+ rolloverCap: '0',
+ purchaseOptions: [purchaseOption],
+ });
+
+ expect(
+ projectBillingCatalog({
+ products: [
+ {
+ code: 'plus',
+ name: 'Plus',
+ kind: 'SUBSCRIPTION',
+ level: 1,
+ sortOrder: 1,
+ offers: [offer('shared_month')],
+ },
+ {
+ code: 'max',
+ name: 'Max',
+ kind: 'SUBSCRIPTION',
+ level: 2,
+ sortOrder: 2,
+ offers: [offer('shared_month'), offer('max_month')],
+ },
+ ],
+ }),
+ ).toMatchObject({
+ products: [
+ { code: 'plus', offers: [{ code: 'shared_month' }] },
+ { code: 'max', offers: [{ code: 'max_month' }] },
+ ],
+ });
+ });
+
+ it('drops malformed list rows and strips unknown payment actions without leaking extra fields', () => {
+ const projected = projectBillingOrderList({
+ orders: [
+ order(),
+ order({ orderId: 'order_unknown_status', status: 'REFUNDING' }),
+ order({
+ orderId: 'order_unknown_action',
+ paymentAction: {
+ type: 'CUSTOM_SCHEME',
+ value: 'javascript:alert(1)',
+ expiresAt: now,
+ },
+ }),
+ order({
+ orderId: 'order_oversized_qr',
+ paymentAction: {
+ type: 'QR_CODE',
+ value: 'x'.repeat(4_097),
+ expiresAt: now,
+ },
+ }),
+ ],
+ nextCursor: null,
+ serverDebug: 'hidden',
+ });
+
+ expect(projected.orders).toHaveLength(3);
+ expect(projected.orders[0]).not.toHaveProperty('internalProviderResponse');
+ expect(projected.orders[1]).toMatchObject({
+ orderId: 'order_unknown_action',
+ paymentAction: null,
+ });
+ expect(projected.orders[2]).toMatchObject({
+ orderId: 'order_oversized_qr',
+ paymentAction: null,
+ });
+ });
+
+ it('rejects malformed single orders and fail-closes unknown subscription status', () => {
+ expect(() => projectBillingPaymentOrder(order({ status: 'REFUNDING' }))).toThrow();
+ expect(() =>
+ projectBillingPaymentOrder(order({ createdAt: '2026-02-31T12:00:00.000Z' })),
+ ).toThrow();
+ expect(() =>
+ projectBillingCurrentSubscription({
+ subscription: {
+ subscriptionId: 'subscription_1',
+ status: 'FUTURE_STATUS',
+ currentPeriodStartAt: null,
+ currentPeriodEndAt: null,
+ entitlementValidUntil: null,
+ cancelAtPeriodEnd: false,
+ effectivePlan: null,
+ purchaseAttemptId: null,
+ paymentAction: null,
+ },
+ }),
+ ).toThrow();
+ });
+
+ it('strips provider identifiers and unsafe redirect actions from subscriptions', () => {
+ const projected = projectBillingCurrentSubscription({
+ subscription: {
+ subscriptionId: 'subscription_1',
+ status: 'ACTIVE',
+ provider: 'future_provider',
+ managementAction: 'FUTURE_ACTION',
+ currentPeriodStartAt: now,
+ currentPeriodEndAt: '2026-08-23T12:00:00.000Z',
+ entitlementValidUntil: null,
+ cancelAtPeriodEnd: false,
+ effectivePlan: {
+ version: 1,
+ product: {
+ id: 'internal_product_id',
+ code: 'subscription_plus',
+ kind: 'SUBSCRIPTION',
+ level: 1,
+ },
+ offer: {
+ id: 'internal_offer_id',
+ code: 'subscription_plus_month',
+ interval: 'MONTH',
+ },
+ provider: {
+ id: 'internal_listing_id',
+ provider: 'stripe',
+ providerProductId: 'prod_fixture',
+ providerPurchaseId: 'price_fixture',
+ },
+ terms: {
+ amount: '20',
+ currency: 'usd',
+ creditAmount: '20',
+ rolloverCap: '0',
+ },
+ capturedAt: now,
+ },
+ purchaseAttemptId: null,
+ paymentAction: {
+ type: 'REDIRECT',
+ url: 'https://checkout.stripe.com.evil.example/pay',
+ expiresAt: now,
+ },
+ },
+ });
+
+ expect(projected.subscription).not.toHaveProperty('provider');
+ expect(projected.subscription).not.toHaveProperty('managementAction');
+ expect(projected.subscription?.paymentAction).toBeNull();
+ expect(projected.subscription?.effectivePlan).toEqual({
+ version: 1,
+ product: { code: 'subscription_plus', kind: 'SUBSCRIPTION', level: 1 },
+ offer: { code: 'subscription_plus_month', interval: 'MONTH' },
+ terms: {
+ amount: '20',
+ currency: 'usd',
+ creditAmount: '20',
+ rolloverCap: '0',
+ },
+ capturedAt: now,
+ });
+ });
+
+ it('accepts the provider-neutral Alipay subscription response without exposing mandate data', () => {
+ const projected = projectBillingCurrentSubscription({
+ subscription: {
+ subscriptionId: 'subscription_1',
+ status: 'INCOMPLETE',
+ currentPeriodStartAt: null,
+ currentPeriodEndAt: null,
+ entitlementValidUntil: null,
+ cancelAtPeriodEnd: false,
+ effectivePlan: null,
+ purchaseAttemptId: 'purchase_1',
+ mandate: {
+ mandateId: 'internal_mandate_1',
+ status: 'PENDING',
+ signedAt: null,
+ },
+ paymentAction: {
+ type: 'QR_CODE',
+ value: 'https://qr.alipay.example/session_fixture',
+ expiresAt: now,
+ },
+ },
+ });
+
+ expect(projected.subscription).toMatchObject({
+ subscriptionId: 'subscription_1',
+ status: 'INCOMPLETE',
+ paymentAction: {
+ type: 'QR_CODE',
+ value: 'https://qr.alipay.example/session_fixture',
+ expiresAt: now,
+ },
+ });
+ expect(projected.subscription).not.toHaveProperty('mandate');
+ });
+});
+
+describe('plan change projection', () => {
+ const planChange = (overrides: Record<string, unknown> = {}) => ({
+ planChangeId: 'plan_change_1',
+ changeType: 'UPGRADE',
+ status: 'AWAITING_PAYMENT',
+ quotedAmountMinor: 1500,
+ quotedCurrency: 'cny',
+ quoteExpiresAt: now,
+ effectiveAt: now,
+ paymentAction: {
+ type: 'QR_CODE',
+ value: 'https://qr.alipay.example/pay',
+ expiresAt: now,
+ },
+ providerChangeId: 'must not cross IPC',
+ ...overrides,
+ });
+
+ const subscription = (overrides: Record<string, unknown> = {}) => ({
+ subscriptionId: 'subscription_1',
+ status: 'ACTIVE',
+ provider: 'alipay',
+ currentPeriodStartAt: null,
+ currentPeriodEndAt: null,
+ entitlementValidUntil: null,
+ cancelAtPeriodEnd: false,
+ effectivePlan: null,
+ purchaseAttemptId: null,
+ paymentAction: null,
+ ...overrides,
+ });
+
+ it('projects a plan change and strips server-only fields', () => {
+ expect(projectBillingPlanChange(planChange())).toEqual({
+ planChangeId: 'plan_change_1',
+ changeType: 'UPGRADE',
+ status: 'AWAITING_PAYMENT',
+ quotedAmountMinor: 1500,
+ quotedCurrency: 'cny',
+ quoteExpiresAt: now,
+ effectiveAt: now,
+ paymentAction: {
+ type: 'QR_CODE',
+ value: 'https://qr.alipay.example/pay',
+ expiresAt: now,
+ },
+ });
+ });
+
+ it.each([
+ ['unknown status', { status: 'FUTURE_STATUS' }],
+ ['unknown change type', { changeType: 'SIDEGRADE' }],
+ ['negative quoted amount', { quotedAmountMinor: -1 }],
+ ['fractional quoted amount', { quotedAmountMinor: 10.5 }],
+ ['missing effectiveAt', { effectiveAt: null }],
+ ])('fail-closes a direct plan change response with %s', (_name, overrides) => {
+ expect(() => projectBillingPlanChange(planChange(overrides))).toThrow(
+ 'invalid billing response',
+ );
+ });
+
+ it('keeps a downgrade quote without amount or action', () => {
+ expect(
+ projectBillingPlanChange(
+ planChange({
+ changeType: 'DOWNGRADE',
+ status: 'SCHEDULED',
+ quotedAmountMinor: null,
+ quotedCurrency: null,
+ quoteExpiresAt: null,
+ paymentAction: null,
+ }),
+ ),
+ ).toMatchObject({ changeType: 'DOWNGRADE', status: 'SCHEDULED', quotedAmountMinor: null });
+ });
+
+ it('projects pendingPlanChange with the safe target plan subset', () => {
+ const projected = projectBillingCurrentSubscription({
+ subscription: subscription({
+ pendingPlanChange: {
+ ...planChange(),
+ targetPlan: {
+ product: { code: 'max', level: 300, internal: 'x' },
+ offer: { code: 'max_month', interval: 'MONTH' },
+ terms: { amount: '50', currency: 'cny', creditAmount: '50' },
+ },
+ },
+ }),
+ });
+ expect(projected.subscription?.provider).toBe('alipay');
+ expect(projected.subscription?.pendingPlanChange).toEqual({
+ planChangeId: 'plan_change_1',
+ changeType: 'UPGRADE',
+ status: 'AWAITING_PAYMENT',
+ quotedAmountMinor: 1500,
+ quotedCurrency: 'cny',
+ quoteExpiresAt: now,
+ effectiveAt: now,
+ paymentAction: {
+ type: 'QR_CODE',
+ value: 'https://qr.alipay.example/pay',
+ expiresAt: now,
+ },
+ targetPlan: {
+ product: { code: 'max', level: 300 },
+ offer: { code: 'max_month', interval: 'MONTH' },
+ terms: { amount: '50', currency: 'cny', creditAmount: '50' },
+ },
+ });
+ });
+
+ it('keeps pendingPlanChange null and distinguishes an omitted field', () => {
+ const explicit = projectBillingCurrentSubscription({
+ subscription: subscription({ pendingPlanChange: null }),
+ });
+ expect(explicit.subscription?.pendingPlanChange).toBeNull();
+
+ const omitted = projectBillingCurrentSubscription({ subscription: subscription() });
+ expect(omitted.subscription).not.toHaveProperty('pendingPlanChange');
+ });
+
+ it('drops an unknown pendingPlanChange instead of failing the subscription', () => {
+ const projected = projectBillingCurrentSubscription({
+ subscription: subscription({
+ pendingPlanChange: { ...planChange({ status: 'FUTURE_STATUS' }), targetPlan: null },
+ }),
+ });
+ expect(projected.subscription?.subscriptionId).toBe('subscription_1');
+ expect(projected.subscription).not.toHaveProperty('pendingPlanChange');
+ });
+
+ it('degrades a malformed target plan to null without dropping the change', () => {
+ const projected = projectBillingCurrentSubscription({
+ subscription: subscription({
+ pendingPlanChange: {
+ ...planChange(),
+ targetPlan: { product: { code: 'max' }, offer: {}, terms: {} },
+ },
+ }),
+ });
+ expect(projected.subscription?.pendingPlanChange).toMatchObject({ targetPlan: null });
+ });
+});
diff --git a/apps/desktop/src/main/billing/index.ts b/apps/desktop/src/main/billing/index.ts
new file mode 100644
index 0000000000..36634d4efe
--- /dev/null
+++ b/apps/desktop/src/main/billing/index.ts
@@ -0,0 +1,399 @@
+import { ipcMain, shell, type BrowserWindow, type IpcMainInvokeEvent } from 'electron';
+
+import {
+ BILLING_INVOKE,
+ type CreateBillingSubscriptionRequest,
+ type CreateBillingTopupRequest,
+} from '../../shared/billing.js';
+import { getClientEndpoint } from '../clientEndpointsService.js';
+import { ServerApiError, serverApiFetch, type ApiFetchOptions } from '../serverApiClient.js';
+import { requireObject, throwIpcError } from '../utils/ipcValidate.js';
+import { isAllowedBillingRedirectUrl } from './paymentRedirect.js';
+import {
+ projectBillingCatalog,
+ projectBillingCurrentSubscription,
+ projectBillingOrderList,
+ projectBillingPaymentOrder,
+ projectBillingPlanChange,
+ projectBillingSubscription,
+ projectModelAccessBalance,
+ projectModelAccessCreditUsage,
+} from './projection.js';
+
+const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9._:-]{8,128}$/;
+const CODE_PATTERN = /^[a-z][a-z0-9_]{1,63}$/;
+const DECIMAL_PATTERN = /^(0|[1-9]\d{0,14})(?:\.\d{1,9})?$/;
+const ID_MAX_LENGTH = 128;
+const BILLING_REQUEST_TIMEOUT_MS = 20_000;
+
+type ServerFetch = <T>(path: string, options: ApiFetchOptions) => Promise<T>;
+
+export type BillingIpcDependencies = {
+ getMainWindow: () => BrowserWindow | null;
+ requirePersonalAccount: () => void;
+ getBaseUrl?: () => string;
+ fetch?: ServerFetch;
+ openExternal?: (url: string) => Promise<void>;
+};
+
+type BillingInvokeEvent = Pick<IpcMainInvokeEvent, 'sender' | 'senderFrame'>;
+type BillingHandler = (event: BillingInvokeEvent, payload?: unknown) => Promise<unknown>;
+
+function assertMainWindowSender(
+ event: BillingInvokeEvent,
+ getMainWindow: () => BrowserWindow | null,
+): void {
+ const mainWindow = getMainWindow();
+ if (
+ !mainWindow ||
+ mainWindow.isDestroyed() ||
+ event.sender !== mainWindow.webContents ||
+ event.senderFrame !== mainWindow.webContents.mainFrame
+ ) {
+ throwIpcError('PERMISSION_DENIED', 'billing IPC is only available to the main window');
+ }
+}
+
+function throwBillingFetchError(error: unknown): never {
+ if (error instanceof ServerApiError) {
+ if (error.statusCode === 400) {
+ throwIpcError('INVALID_PARAMS', 'billing request was rejected');
+ }
+ if (error.statusCode === 401 || error.statusCode === 403) {
+ throwIpcError('PERMISSION_DENIED', 'billing request is not authorized');
+ }
+ if (error.statusCode === 404) {
+ throwIpcError('NOT_FOUND', 'billing resource was not found');
+ }
+ if (error.statusCode === 409 || error.statusCode === 412) {
+ throwIpcError('PRECONDITION_FAILED', 'billing request conflicts with the current state');
+ }
+ }
+ throwIpcError('INTERNAL', 'billing service request failed');
+}
+
+function throwBalanceFetchError(error: unknown): never {
+ if (error instanceof ServerApiError) {
+ if (error.statusCode === 401 || error.statusCode === 403) {
+ throwIpcError('PERMISSION_DENIED', 'balance request is not authorized');
+ }
+ if (error.statusCode === 404) {
+ throwIpcError('NOT_FOUND', 'balance account is not provisioned');
+ }
+ if (error.statusCode === 501) {
+ throwIpcError('UNSUPPORTED_CAPABILITY', 'balance is not supported for this account');
+ }
+ }
+ throwIpcError('MODEL_ACCESS_FAILED', 'balance service request failed');
+}
+
+function projectResponse<T>(value: unknown, projector: (input: unknown) => T): T {
+ try {
+ return projector(value);
+ } catch {
+ throwIpcError('INTERNAL', 'billing service response was invalid');
+ }
+}
+
+function assertOnlyKeys(
+ value: Record<string, unknown>,
+ allowed: readonly string[],
+ name: string,
+): void {
+ const unknownKey = Object.keys(value).find((key) => !allowed.includes(key));
+ if (unknownKey) throwIpcError('INVALID_PARAMS', `${name}.${unknownKey} is not allowed`);
+}
+
+function requireBoundedString(value: unknown, name: string): string {
+ if (typeof value !== 'string' || value.length === 0 || value.length > ID_MAX_LENGTH) {
+ throwIpcError('INVALID_PARAMS', `${name} must be a non-empty string`);
+ }
+ return value;
+}
+
+function requireCode(value: unknown, name: string): string {
+ const code = requireBoundedString(value, name);
+ if (!CODE_PATTERN.test(code)) throwIpcError('INVALID_PARAMS', `${name} is invalid`);
+ return code;
+}
+
+function requireIdempotencyKey(value: unknown): string {
+ if (typeof value !== 'string' || !IDEMPOTENCY_KEY_PATTERN.test(value)) {
+ throwIpcError('INVALID_PARAMS', 'idempotencyKey is invalid');
+ }
+ return value;
+}
+
+function requireAmount(value: unknown, name: string): string {
+ if (typeof value !== 'string' || !DECIMAL_PATTERN.test(value)) {
+ throwIpcError('INVALID_PARAMS', `${name} is invalid`);
+ }
+ return value;
+}
+
+function parseIdPayload(raw: unknown, key: 'orderId' | 'purchaseAttemptId' | 'planChangeId') {
+ const payload = requireObject(raw);
+ assertOnlyKeys(payload, [key], 'payload');
+ return { [key]: requireBoundedString(payload[key], key) } as Record<typeof key, string>;
+}
+
+function parseCreateTopup(raw: unknown): {
+ request: CreateBillingTopupRequest;
+ idempotencyKey: string;
+} {
+ const payload = requireObject(raw);
+ assertOnlyKeys(payload, ['request', 'idempotencyKey'], 'payload');
+ const request = requireObject(payload.request, 'request');
+ assertOnlyKeys(request, ['offerCode', 'amount', 'purchaseOptionId'], 'request');
+ return {
+ request: {
+ offerCode: requireCode(request.offerCode, 'offerCode'),
+ ...(request.amount === undefined ? {} : { amount: requireAmount(request.amount, 'amount') }),
+ purchaseOptionId: requireBoundedString(request.purchaseOptionId, 'purchaseOptionId'),
+ },
+ idempotencyKey: requireIdempotencyKey(payload.idempotencyKey),
+ };
+}
+
+function parseCreateSubscription(raw: unknown): {
+ request: CreateBillingSubscriptionRequest;
+ idempotencyKey: string;
+} {
+ const payload = requireObject(raw);
+ assertOnlyKeys(payload, ['request', 'idempotencyKey'], 'payload');
+ const request = requireObject(payload.request, 'request');
+ assertOnlyKeys(request, ['offerCode', 'purchaseOptionId'], 'request');
+ return {
+ request: {
+ offerCode: requireCode(request.offerCode, 'offerCode'),
+ purchaseOptionId: requireBoundedString(request.purchaseOptionId, 'purchaseOptionId'),
+ },
+ idempotencyKey: requireIdempotencyKey(payload.idempotencyKey),
+ };
+}
+
+export function createBillingHandlers(
+ deps: BillingIpcDependencies,
+): Record<string, BillingHandler> {
+ const fetch = deps.fetch ?? serverApiFetch;
+ const getBaseUrl = deps.getBaseUrl ?? (() => getClientEndpoint('modelAccessApiBaseUrl'));
+ const openExternal = deps.openExternal ?? ((url: string) => shell.openExternal(url));
+ const invoke = async <T>(path: string, options: Omit<ApiFetchOptions, 'baseUrl'> = {}) => {
+ try {
+ return await fetch<T>(path, {
+ timeoutMs: BILLING_REQUEST_TIMEOUT_MS,
+ ...options,
+ redactErrorDetails: true,
+ baseUrl: getBaseUrl(),
+ });
+ } catch (error) {
+ throwBillingFetchError(error);
+ }
+ };
+ const protect =
+ (handler: (payload?: unknown) => Promise<unknown>): BillingHandler =>
+ async (event, payload) => {
+ assertMainWindowSender(event, deps.getMainWindow);
+ deps.requirePersonalAccount();
+ return handler(payload);
+ };
+
+ return {
+ [BILLING_INVOKE.GET_BALANCE]: protect(async (raw) => {
+ if (raw !== undefined) {
+ throwIpcError('INVALID_PARAMS', 'balance request does not accept a payload');
+ }
+ let response: unknown;
+ try {
+ response = await fetch<unknown>('/api/model-access/balance', {
+ timeoutMs: BILLING_REQUEST_TIMEOUT_MS,
+ redactErrorDetails: true,
+ baseUrl: getBaseUrl(),
+ });
+ } catch (error) {
+ throwBalanceFetchError(error);
+ }
+ return projectResponse(response, projectModelAccessBalance);
+ }),
+ [BILLING_INVOKE.GET_CREDIT_USAGE]: protect(async (raw) => {
+ if (raw !== undefined) {
+ throwIpcError('INVALID_PARAMS', 'credit usage request does not accept a payload');
+ }
+ let response: unknown;
+ try {
+ response = await fetch<unknown>('/api/model-access/credit-usage', {
+ timeoutMs: BILLING_REQUEST_TIMEOUT_MS,
+ redactErrorDetails: true,
+ baseUrl: getBaseUrl(),
+ });
+ } catch (error) {
+ throwBalanceFetchError(error);
+ }
+ return projectResponse(response, projectModelAccessCreditUsage);
+ }),
+ [BILLING_INVOKE.GET_CATALOG]: protect(async (raw) => {
+ if (raw !== undefined) {
+ throwIpcError('INVALID_PARAMS', 'catalog request does not accept a payload');
+ }
+ return projectResponse(await invoke<unknown>('/api/billing/catalog'), projectBillingCatalog);
+ }),
+ [BILLING_INVOKE.LIST_ORDERS]: protect(async (raw) => {
+ const payload = requireObject(raw);
+ assertOnlyKeys(payload, ['limit'], 'payload');
+ if (
+ typeof payload.limit !== 'number' ||
+ !Number.isInteger(payload.limit) ||
+ payload.limit < 1 ||
+ payload.limit > 100
+ )
+ throwIpcError('INVALID_PARAMS', 'limit must be an integer between 1 and 100');
+ return projectResponse(
+ await invoke<unknown>(`/api/billing/orders?limit=${payload.limit}`),
+ projectBillingOrderList,
+ );
+ }),
+ [BILLING_INVOKE.GET_ORDER]: protect(async (raw) => {
+ const { orderId } = parseIdPayload(raw, 'orderId');
+ return projectResponse(
+ await invoke<unknown>(`/api/billing/orders/${encodeURIComponent(orderId)}`),
+ projectBillingPaymentOrder,
+ );
+ }),
+ [BILLING_INVOKE.CREATE_TOPUP]: protect(async (raw) => {
+ const payload = parseCreateTopup(raw);
+ return projectResponse(
+ await invoke<unknown>('/api/billing/credit-topup/orders', {
+ method: 'POST',
+ body: payload.request,
+ headers: { 'Idempotency-Key': payload.idempotencyKey },
+ }),
+ projectBillingPaymentOrder,
+ );
+ }),
+ [BILLING_INVOKE.REFRESH_TOPUP]: protect(async (raw) => {
+ const { orderId } = parseIdPayload(raw, 'orderId');
+ return projectResponse(
+ await invoke<unknown>(`/api/billing/orders/${encodeURIComponent(orderId)}/refresh`, {
+ method: 'POST',
+ }),
+ projectBillingPaymentOrder,
+ );
+ }),
+ [BILLING_INVOKE.CANCEL_TOPUP]: protect(async (raw) => {
+ const { orderId } = parseIdPayload(raw, 'orderId');
+ return projectResponse(
+ await invoke<unknown>(`/api/billing/orders/${encodeURIComponent(orderId)}/cancel`, {
+ method: 'POST',
+ }),
+ projectBillingPaymentOrder,
+ );
+ }),
+ [BILLING_INVOKE.RETRY_TOPUP]: protect(async (raw) => {
+ const payload = requireObject(raw);
+ assertOnlyKeys(payload, ['orderId', 'idempotencyKey'], 'payload');
+ const orderId = requireBoundedString(payload.orderId, 'orderId');
+ const idempotencyKey = requireIdempotencyKey(payload.idempotencyKey);
+ return projectResponse(
+ await invoke<unknown>(`/api/billing/orders/${encodeURIComponent(orderId)}/retry`, {
+ method: 'POST',
+ headers: { 'Idempotency-Key': idempotencyKey },
+ }),
+ projectBillingPaymentOrder,
+ );
+ }),
+ [BILLING_INVOKE.CREATE_SUBSCRIPTION]: protect(async (raw) => {
+ const payload = parseCreateSubscription(raw);
+ return projectResponse(
+ await invoke<unknown>('/api/billing/subscriptions', {
+ method: 'POST',
+ body: payload.request,
+ headers: { 'Idempotency-Key': payload.idempotencyKey },
+ }),
+ projectBillingSubscription,
+ );
+ }),
+ [BILLING_INVOKE.GET_CURRENT_SUBSCRIPTION]: protect(async (raw) => {
+ if (raw !== undefined) {
+ throwIpcError('INVALID_PARAMS', 'subscription request does not accept a payload');
+ }
+ return projectResponse(
+ await invoke<unknown>('/api/billing/subscription'),
+ projectBillingCurrentSubscription,
+ );
+ }),
+ [BILLING_INVOKE.REFRESH_SUBSCRIPTION_PURCHASE]: protect(async (raw) => {
+ const { purchaseAttemptId } = parseIdPayload(raw, 'purchaseAttemptId');
+ return projectResponse(
+ await invoke<unknown>(
+ `/api/billing/subscriptions/purchases/${encodeURIComponent(purchaseAttemptId)}/refresh`,
+ { method: 'POST' },
+ ),
+ projectBillingSubscription,
+ );
+ }),
+ [BILLING_INVOKE.QUOTE_PLAN_CHANGE]: protect(async (raw) => {
+ const payload = requireObject(raw);
+ assertOnlyKeys(payload, ['targetOfferCode', 'idempotencyKey'], 'payload');
+ const targetOfferCode = requireCode(payload.targetOfferCode, 'targetOfferCode');
+ const idempotencyKey = requireIdempotencyKey(payload.idempotencyKey);
+ return projectResponse(
+ await invoke<unknown>('/api/billing/subscription/plan-change-quotes', {
+ method: 'POST',
+ body: { targetOfferCode },
+ headers: { 'Idempotency-Key': idempotencyKey },
+ }),
+ projectBillingPlanChange,
+ );
+ }),
+ [BILLING_INVOKE.CONFIRM_PLAN_CHANGE]: protect(async (raw) => {
+ const { planChangeId } = parseIdPayload(raw, 'planChangeId');
+ return projectResponse(
+ await invoke<unknown>(
+ `/api/billing/subscription/plan-changes/${encodeURIComponent(planChangeId)}/confirm`,
+ { method: 'POST' },
+ ),
+ projectBillingPlanChange,
+ );
+ }),
+ [BILLING_INVOKE.REFRESH_PLAN_CHANGE]: protect(async (raw) => {
+ const { planChangeId } = parseIdPayload(raw, 'planChangeId');
+ return projectResponse(
+ await invoke<unknown>(
+ `/api/billing/subscription/plan-changes/${encodeURIComponent(planChangeId)}/refresh`,
+ { method: 'POST' },
+ ),
+ projectBillingPlanChange,
+ );
+ }),
+ [BILLING_INVOKE.CANCEL_PLAN_CHANGE]: protect(async (raw) => {
+ const { planChangeId } = parseIdPayload(raw, 'planChangeId');
+ return projectResponse(
+ await invoke<unknown>(
+ `/api/billing/subscription/plan-changes/${encodeURIComponent(planChangeId)}`,
+ { method: 'DELETE' },
+ ),
+ projectBillingPlanChange,
+ );
+ }),
+ [BILLING_INVOKE.OPEN_PAYMENT_REDIRECT]: protect(async (raw) => {
+ const payload = requireObject(raw);
+ assertOnlyKeys(payload, ['url'], 'payload');
+ if (!isAllowedBillingRedirectUrl(payload.url)) {
+ throwIpcError('INVALID_PARAMS', 'billing redirect URL is not allowed');
+ }
+ try {
+ await openExternal(payload.url);
+ return { success: true };
+ } catch {
+ return { success: false };
+ }
+ }),
+ };
+}
+
+export function registerBillingIpc(deps: BillingIpcDependencies): void {
+ const handlers = createBillingHandlers(deps);
+ for (const [channel, handler] of Object.entries(handlers)) {
+ ipcMain.handle(channel, handler);
+ }
+}
diff --git a/apps/desktop/src/main/billing/paymentRedirect.ts b/apps/desktop/src/main/billing/paymentRedirect.ts
new file mode 100644
index 0000000000..b08f1d247b
--- /dev/null
+++ b/apps/desktop/src/main/billing/paymentRedirect.ts
@@ -0,0 +1,27 @@
+const MAX_BILLING_REDIRECT_URL_LENGTH = 2_048;
+
+// Public provider-owned checkout hosts only. Merchant and Cindy-owned hosts do
+// not belong here; adding a host changes the desktop trust boundary.
+const ALLOWED_BILLING_REDIRECT_HOSTS = new Set(['checkout.stripe.com']);
+
+export function isAllowedBillingRedirectUrl(value: unknown): value is string {
+ if (
+ typeof value !== 'string' ||
+ value.length === 0 ||
+ value.length > MAX_BILLING_REDIRECT_URL_LENGTH
+ ) {
+ return false;
+ }
+ try {
+ const parsed = new URL(value);
+ return (
+ parsed.protocol === 'https:' &&
+ parsed.username === '' &&
+ parsed.password === '' &&
+ parsed.port === '' &&
+ ALLOWED_BILLING_REDIRECT_HOSTS.has(parsed.hostname)
+ );
+ } catch {
+ return false;
+ }
+}
diff --git a/apps/desktop/src/main/billing/projection.ts b/apps/desktop/src/main/billing/projection.ts
new file mode 100644
index 0000000000..61ba5350b8
--- /dev/null
+++ b/apps/desktop/src/main/billing/projection.ts
@@ -0,0 +1,802 @@
+import type {
+ BillingCatalog,
+ BillingCatalogOffer,
+ BillingCatalogProduct,
+ BillingCurrentSubscription,
+ BillingFulfillmentStatus,
+ BillingOrderList,
+ BillingPaymentAction,
+ BillingPaymentOrder,
+ BillingPaymentOrderStatus,
+ BillingPendingPlanChange,
+ BillingPlanChange,
+ BillingPlanChangeStatus,
+ BillingPlanChangeTargetPlan,
+ BillingPurchaseOption,
+ BillingSubscription,
+ BillingSubscriptionStatus,
+} from '../../shared/billing.js';
+import type {
+ ModelAccessBalance,
+ ModelAccessCreditPoolUsage,
+ ModelAccessCreditUsage,
+ ModelAccessPromotionalGrantState,
+ ModelAccessPromotionalGrantUsage,
+} from '../../shared/modelAccess.js';
+import { isAllowedBillingRedirectUrl } from './paymentRedirect.js';
+
+const MAX_ID_LENGTH = 128;
+const MAX_NAME_LENGTH = 128;
+const MAX_CURSOR_LENGTH = 512;
+const MAX_QR_VALUE_LENGTH = 4_096;
+const MAX_PROMOTIONAL_GRANTS = 1_000;
+const CODE_PATTERN = /^[a-z][a-z0-9_]{1,63}$/;
+const CURRENCY_PATTERN = /^[a-z]{3}$/;
+const DECIMAL_PATTERN = /^(0|[1-9]\d{0,14})(?:\.\d{1,9})?$/;
+const LEDGER_DECIMAL_PATTERN = /^-?(?:0|[1-9]\d{0,9})(?:\.\d{1,9})?$/;
+const ISO_TIME_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
+const RFC3339_UTC_PATTERN = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?Z$/;
+const MAX_LEDGER_SCALED_AMOUNT = 9_000_000_000_000_000_000n;
+const PROMOTIONAL_GRANT_STATES = new Set<ModelAccessPromotionalGrantState>([
+ 'active',
+ 'depleted',
+ 'expired',
+ 'voided',
+]);
+
+const PAYMENT_ORDER_STATUSES = new Set<BillingPaymentOrderStatus>([
+ 'CREATED',
+ 'PENDING',
+ 'SUCCEEDED',
+ 'FAILED',
+ 'CANCELED',
+ 'EXPIRED',
+]);
+const SUBSCRIPTION_STATUSES = new Set<BillingSubscriptionStatus>([
+ 'INCOMPLETE',
+ 'INCOMPLETE_EXPIRED',
+ 'TRIALING',
+ 'ACTIVE',
+ 'PAST_DUE',
+ 'UNPAID',
+ 'CANCELED',
+ 'PAUSED',
+]);
+const FULFILLMENT_STATUSES = new Set<BillingFulfillmentStatus>([
+ 'NOT_STARTED',
+ 'PENDING',
+ 'SUCCEEDED',
+ 'FAILED',
+]);
+const SUPPORTED_PROVIDERS = new Set(['alipay', 'stripe']);
+const SUBSCRIPTION_CAPABILITIES = new Set([
+ 'MERCHANT_INITIATED_MANDATE',
+ 'PROVIDER_MANAGED_SUBSCRIPTION',
+]);
+const PLAN_CHANGE_STATUSES = new Set<BillingPlanChangeStatus>([
+ 'QUOTED',
+ 'PENDING_PROVIDER',
+ 'AWAITING_PAYMENT',
+ 'SCHEDULED',
+ 'APPLIED',
+ 'CANCELED',
+ 'FAILED',
+ 'EXPIRED',
+]);
+const MAX_QUOTED_AMOUNT_MINOR = 9_007_199_254_740_991;
+
+function invalidResponse(): never {
+ throw new Error('invalid billing response');
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function boundedString(value: unknown, maxLength = MAX_ID_LENGTH): string | null {
+ return typeof value === 'string' && value.length > 0 && value.length <= maxLength ? value : null;
+}
+
+function code(value: unknown): string | null {
+ return typeof value === 'string' && CODE_PATTERN.test(value) ? value : null;
+}
+
+function decimal(value: unknown): string | null {
+ return typeof value === 'string' && DECIMAL_PATTERN.test(value) ? value : null;
+}
+
+function ledgerDecimal(value: unknown): { source: string; scaled: bigint } | null {
+ if (typeof value !== 'string' || !LEDGER_DECIMAL_PATTERN.test(value)) return null;
+ const negative = value.startsWith('-');
+ const unsigned = negative ? value.slice(1) : value;
+ const [whole, fraction = ''] = unsigned.split('.');
+ const scaled = BigInt(whole) * 1_000_000_000n + BigInt(fraction.padEnd(9, '0') || '0');
+ if (scaled > MAX_LEDGER_SCALED_AMOUNT) return null;
+ return { source: value, scaled: negative ? -scaled : scaled };
+}
+
+function currency(value: unknown): string | null {
+ return typeof value === 'string' && CURRENCY_PATTERN.test(value) ? value : null;
+}
+
+function nullable<T>(value: unknown, parse: (input: unknown) => T | null): T | null | undefined {
+ return value === null ? null : (parse(value) ?? undefined);
+}
+
+function isoTime(value: unknown): string | null {
+ if (typeof value !== 'string' || !ISO_TIME_PATTERN.test(value)) return null;
+ const timestamp = Date.parse(value);
+ return Number.isFinite(timestamp) && new Date(timestamp).toISOString() === value ? value : null;
+}
+
+function observedAt(value: unknown): string | null {
+ if (typeof value !== 'string') return null;
+ const match = RFC3339_UTC_PATTERN.exec(value);
+ if (!match) return null;
+ const [, yearText, monthText, dayText, hourText, minuteText, secondText] = match;
+ const year = Number(yearText);
+ const month = Number(monthText);
+ const day = Number(dayText);
+ const hour = Number(hourText);
+ const minute = Number(minuteText);
+ const second = Number(secondText);
+ const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
+ const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
+ if (
+ month < 1 ||
+ month > 12 ||
+ day < 1 ||
+ day > daysInMonth[month - 1] ||
+ hour > 23 ||
+ minute > 59 ||
+ second > 59
+ ) {
+ return null;
+ }
+ return value;
+}
+
+export function projectModelAccessBalance(value: unknown): ModelAccessBalance {
+ if (!isRecord(value) || value.scale !== 9) invalidResponse();
+ const planCredits = ledgerDecimal(value.planCredits);
+ const purchasedCredits = ledgerDecimal(value.purchasedCredits);
+ const promotionalCredits = ledgerDecimal(value.promotionalCredits);
+ const available = ledgerDecimal(value.available);
+ const snapshotTime = observedAt(value.observedAt);
+ if (
+ !planCredits ||
+ !purchasedCredits ||
+ !promotionalCredits ||
+ !available ||
+ planCredits.scaled < 0n ||
+ promotionalCredits.scaled < 0n ||
+ planCredits.scaled + purchasedCredits.scaled + promotionalCredits.scaled !== available.scaled ||
+ !snapshotTime
+ ) {
+ invalidResponse();
+ }
+ return {
+ planCredits: planCredits.source,
+ purchasedCredits: purchasedCredits.source,
+ promotionalCredits: promotionalCredits.source,
+ available: available.source,
+ scale: 9,
+ observedAt: snapshotTime,
+ };
+}
+
+function projectCreditPool(
+ value: unknown,
+ allowNegativeRemaining: boolean,
+): {
+ value: ModelAccessCreditPoolUsage;
+ remaining: bigint;
+ used: bigint | null;
+ total: bigint | null;
+} {
+ if (!isRecord(value)) invalidResponse();
+ const remaining = ledgerDecimal(value.remaining);
+ const used = value.used === null ? null : ledgerDecimal(value.used);
+ const total = value.total === null ? null : ledgerDecimal(value.total);
+ if (
+ !remaining ||
+ (!allowNegativeRemaining && remaining.scaled < 0n) ||
+ (value.used !== null && !used) ||
+ (value.total !== null && !total) ||
+ (used === null) !== (total === null) ||
+ (used !== null &&
+ total !== null &&
+ (used.scaled < 0n || total.scaled < 0n || used.scaled + remaining.scaled !== total.scaled))
+ ) {
+ invalidResponse();
+ }
+ return {
+ value: {
+ remaining: remaining.source,
+ used: used?.source ?? null,
+ total: total?.source ?? null,
+ },
+ remaining: remaining.scaled,
+ used: used?.scaled ?? null,
+ total: total?.scaled ?? null,
+ };
+}
+
+function projectPromotionalGrant(value: unknown): ModelAccessPromotionalGrantUsage {
+ if (!isRecord(value)) invalidResponse();
+ const grantId = boundedString(value.grantId);
+ const displayName =
+ value.displayName === null
+ ? null
+ : (boundedString(value.displayName, MAX_NAME_LENGTH) ?? undefined);
+ const originalAmount = ledgerDecimal(value.originalAmount);
+ const usedAmount = value.usedAmount === null ? null : ledgerDecimal(value.usedAmount);
+ const remainingAmount = ledgerDecimal(value.remainingAmount);
+ const expiresAt = observedAt(value.expiresAt);
+ const state =
+ typeof value.state === 'string' &&
+ PROMOTIONAL_GRANT_STATES.has(value.state as ModelAccessPromotionalGrantState)
+ ? (value.state as ModelAccessPromotionalGrantState)
+ : null;
+ if (
+ !grantId ||
+ displayName === undefined ||
+ !originalAmount ||
+ !remainingAmount ||
+ originalAmount.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))) ||
+ ((state === 'expired' || state === 'voided') &&
+ (value.usedAmount !== null || remainingAmount.scaled !== 0n))
+ ) {
+ invalidResponse();
+ }
+ return {
+ grantId,
+ displayName,
+ originalAmount: originalAmount.source,
+ usedAmount: usedAmount?.source ?? null,
+ remainingAmount: remainingAmount.source,
+ expiresAt,
+ state,
+ };
+}
+
+export function projectModelAccessCreditUsage(value: unknown): ModelAccessCreditUsage {
+ if (
+ !isRecord(value) ||
+ value.scale !== 9 ||
+ !Array.isArray(value.promotionalGrants) ||
+ value.promotionalGrants.length > MAX_PROMOTIONAL_GRANTS ||
+ typeof value.promotionalGrantsComplete !== 'boolean' ||
+ value.promotionalGrantConsistency !== 'LAST_SETTLED'
+ ) {
+ invalidResponse();
+ }
+ const available = ledgerDecimal(value.available);
+ const plan = projectCreditPool(value.plan, false);
+ const purchased = projectCreditPool(value.purchased, true);
+ const promotional = projectCreditPool(value.promotional, false);
+ const snapshotTime = observedAt(value.observedAt);
+ const ledgerUpdatedAt = value.ledgerUpdatedAt === null ? null : observedAt(value.ledgerUpdatedAt);
+ if (
+ !available ||
+ plan.remaining + purchased.remaining + promotional.remaining !== available.scaled ||
+ !snapshotTime ||
+ (value.ledgerUpdatedAt !== null && !ledgerUpdatedAt)
+ ) {
+ invalidResponse();
+ }
+
+ const grantIds = new Set<string>();
+ let currentOriginalTotal = 0n;
+ const observedAtMs = Date.parse(snapshotTime);
+ 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
+ ) {
+ currentOriginalTotal += ledgerDecimal(projected.originalAmount)!.scaled;
+ }
+ return projected;
+ });
+ if (
+ (value.promotionalGrantsComplete &&
+ (promotional.total === null || promotional.total !== currentOriginalTotal)) ||
+ (!value.promotionalGrantsComplete && (promotional.used !== null || promotional.total !== null))
+ ) {
+ invalidResponse();
+ }
+
+ return {
+ available: available.source,
+ plan: plan.value,
+ purchased: purchased.value,
+ promotional: promotional.value,
+ promotionalGrants,
+ promotionalGrantsComplete: value.promotionalGrantsComplete,
+ promotionalGrantConsistency: 'LAST_SETTLED',
+ ledgerUpdatedAt,
+ scale: 9,
+ observedAt: snapshotTime,
+ };
+}
+
+function projectPaymentAction(value: unknown): BillingPaymentAction | null {
+ if (!isRecord(value)) return null;
+ const expiresAt = isoTime(value.expiresAt);
+ if (!expiresAt) return null;
+ if (value.type === 'QR_CODE') {
+ const qrValue = boundedString(value.value, MAX_QR_VALUE_LENGTH);
+ return qrValue ? { type: 'QR_CODE', value: qrValue, expiresAt } : null;
+ }
+ if (value.type === 'REDIRECT' && isAllowedBillingRedirectUrl(value.url)) {
+ return { type: 'REDIRECT', url: value.url, expiresAt };
+ }
+ return null;
+}
+
+function projectPurchaseOption(
+ value: unknown,
+ productKind: BillingCatalogProduct['kind'],
+): BillingPurchaseOption | null {
+ if (!isRecord(value)) return null;
+ const id = boundedString(value.id);
+ const provider = boundedString(value.provider, 32);
+ if (
+ !id ||
+ !provider ||
+ !SUPPORTED_PROVIDERS.has(provider) ||
+ (value.paymentAction !== 'QR_CODE' && value.paymentAction !== 'REDIRECT')
+ ) {
+ return null;
+ }
+ const capability =
+ productKind === 'CREDIT_TOPUP'
+ ? value.capability === 'ONE_TIME_PAYMENT'
+ ? value.capability
+ : null
+ : typeof value.capability === 'string' && SUBSCRIPTION_CAPABILITIES.has(value.capability)
+ ? (value.capability as BillingPurchaseOption['capability'])
+ : null;
+ return capability ? { id, provider, capability, paymentAction: value.paymentAction } : null;
+}
+
+function projectOffer(
+ value: unknown,
+ productKind: BillingCatalogProduct['kind'],
+): BillingCatalogOffer | null {
+ if (!isRecord(value) || !Array.isArray(value.purchaseOptions)) return null;
+ const offerCode = code(value.code);
+ const offerCurrency = currency(value.currency);
+ const amount = nullable(value.amount, decimal);
+ const minAmount = nullable(value.minAmount, decimal);
+ const maxAmount = nullable(value.maxAmount, decimal);
+ const creditAmount = nullable(value.creditAmount, decimal);
+ const rolloverCap = nullable(value.rolloverCap, decimal);
+ const interval =
+ value.interval === 'MONTH' || value.interval === 'YEAR' || value.interval === null
+ ? value.interval
+ : undefined;
+ if (
+ !offerCode ||
+ !offerCurrency ||
+ interval === undefined ||
+ amount === undefined ||
+ minAmount === undefined ||
+ maxAmount === undefined ||
+ creditAmount === undefined ||
+ rolloverCap === undefined
+ ) {
+ return null;
+ }
+
+ const isSubscription =
+ productKind === 'SUBSCRIPTION' &&
+ interval !== null &&
+ amount !== null &&
+ minAmount === null &&
+ maxAmount === null &&
+ creditAmount !== null &&
+ rolloverCap !== null;
+ const isFixedTopup =
+ productKind === 'CREDIT_TOPUP' &&
+ interval === null &&
+ amount !== null &&
+ creditAmount !== null &&
+ minAmount === null &&
+ maxAmount === null &&
+ rolloverCap === null;
+ const isCustomTopup =
+ productKind === 'CREDIT_TOPUP' &&
+ interval === null &&
+ amount === null &&
+ creditAmount === null &&
+ minAmount !== null &&
+ maxAmount !== null &&
+ rolloverCap === null;
+ if (!isSubscription && !isFixedTopup && !isCustomTopup) return null;
+
+ const optionIds = new Set<string>();
+ const purchaseOptions = value.purchaseOptions
+ .map((option) => projectPurchaseOption(option, productKind))
+ .filter((option): option is BillingPurchaseOption => {
+ if (!option || optionIds.has(option.id)) return false;
+ optionIds.add(option.id);
+ return true;
+ });
+ if (purchaseOptions.length === 0) return null;
+ return {
+ code: offerCode,
+ interval: isSubscription ? interval : null,
+ currency: offerCurrency,
+ amount,
+ minAmount,
+ maxAmount,
+ creditAmount,
+ rolloverCap,
+ purchaseOptions,
+ };
+}
+
+function projectProduct(value: unknown): BillingCatalogProduct | null {
+ if (
+ !isRecord(value) ||
+ !Array.isArray(value.offers) ||
+ (value.kind !== 'CREDIT_TOPUP' && value.kind !== 'SUBSCRIPTION')
+ ) {
+ return null;
+ }
+ const productCode = code(value.code);
+ const name = boundedString(value.name, MAX_NAME_LENGTH);
+ const kind = value.kind;
+ const level =
+ kind === 'CREDIT_TOPUP'
+ ? value.level === null
+ ? null
+ : undefined
+ : typeof value.level === 'number' && Number.isSafeInteger(value.level) && value.level >= 0
+ ? value.level
+ : undefined;
+ if (
+ !productCode ||
+ !name ||
+ level === undefined ||
+ typeof value.sortOrder !== 'number' ||
+ !Number.isSafeInteger(value.sortOrder)
+ ) {
+ return null;
+ }
+
+ const offerCodes = new Set<string>();
+ const offers = value.offers
+ .map((offer) => projectOffer(offer, kind))
+ .filter((offer): offer is BillingCatalogOffer => {
+ if (!offer || offerCodes.has(offer.code)) return false;
+ offerCodes.add(offer.code);
+ return true;
+ });
+ if (offers.length === 0) return null;
+ return {
+ code: productCode,
+ name,
+ kind,
+ level,
+ sortOrder: value.sortOrder,
+ offers,
+ };
+}
+
+export function projectBillingCatalog(value: unknown): BillingCatalog {
+ if (!isRecord(value) || !Array.isArray(value.products)) invalidResponse();
+ const productCodes = new Set<string>();
+ const offerCodes = new Set<string>();
+ const products: BillingCatalogProduct[] = [];
+ for (const valueProduct of value.products) {
+ const product = projectProduct(valueProduct);
+ if (!product || productCodes.has(product.code)) continue;
+ const offers = product.offers.filter((offer) => !offerCodes.has(offer.code));
+ if (offers.length === 0) continue;
+ productCodes.add(product.code);
+ for (const offer of offers) offerCodes.add(offer.code);
+ products.push({ ...product, offers });
+ }
+ return { products };
+}
+
+function projectPaymentOrder(value: unknown): BillingPaymentOrder {
+ if (!isRecord(value)) invalidResponse();
+ const orderId = boundedString(value.orderId);
+ const productCode = code(value.productCode);
+ const offerCode = code(value.offerCode);
+ const amount = decimal(value.amount);
+ const orderCurrency = currency(value.currency);
+ const status =
+ typeof value.status === 'string' &&
+ PAYMENT_ORDER_STATUSES.has(value.status as BillingPaymentOrderStatus)
+ ? (value.status as BillingPaymentOrderStatus)
+ : null;
+ const createdAt = isoTime(value.createdAt);
+ const updatedAt = isoTime(value.updatedAt);
+ if (
+ !orderId ||
+ !productCode ||
+ !offerCode ||
+ !amount ||
+ !orderCurrency ||
+ !status ||
+ !createdAt ||
+ !updatedAt
+ ) {
+ invalidResponse();
+ }
+ const fulfillmentStatus =
+ typeof value.fulfillmentStatus === 'string' &&
+ FULFILLMENT_STATUSES.has(value.fulfillmentStatus as BillingFulfillmentStatus)
+ ? (value.fulfillmentStatus as BillingFulfillmentStatus)
+ : undefined;
+ return {
+ orderId,
+ productCode,
+ offerCode,
+ amount,
+ currency: orderCurrency,
+ status,
+ paymentAction: projectPaymentAction(value.paymentAction),
+ ...(fulfillmentStatus ? { fulfillmentStatus } : {}),
+ createdAt,
+ updatedAt,
+ };
+}
+
+export function projectBillingPaymentOrder(value: unknown): BillingPaymentOrder {
+ return projectPaymentOrder(value);
+}
+
+export function projectBillingOrderList(value: unknown): BillingOrderList {
+ if (!isRecord(value) || !Array.isArray(value.orders) || value.orders.length > 100) {
+ invalidResponse();
+ }
+ const nextCursor =
+ value.nextCursor === null ? null : boundedString(value.nextCursor, MAX_CURSOR_LENGTH);
+ if (nextCursor === null && value.nextCursor !== null) invalidResponse();
+ const orders: BillingPaymentOrder[] = [];
+ for (const order of value.orders) {
+ try {
+ orders.push(projectPaymentOrder(order));
+ } catch {
+ // Unknown or malformed rows must not block recovery of the remaining orders.
+ }
+ }
+ return { orders, nextCursor };
+}
+
+function projectEffectivePlan(value: unknown): BillingSubscription['effectivePlan'] {
+ if (
+ !isRecord(value) ||
+ !isRecord(value.product) ||
+ !isRecord(value.offer) ||
+ !isRecord(value.terms)
+ ) {
+ invalidResponse();
+ }
+ const productCode = code(value.product.code);
+ const offerCode = code(value.offer.code);
+ const level =
+ typeof value.product.level === 'number' &&
+ Number.isSafeInteger(value.product.level) &&
+ value.product.level >= 0
+ ? value.product.level
+ : null;
+ const amount = decimal(value.terms.amount);
+ const planCurrency = currency(value.terms.currency);
+ const creditAmount = decimal(value.terms.creditAmount);
+ const rolloverCap = decimal(value.terms.rolloverCap);
+ const capturedAt = isoTime(value.capturedAt);
+ if (
+ value.version !== 1 ||
+ value.product.kind !== 'SUBSCRIPTION' ||
+ !productCode ||
+ level === null ||
+ !offerCode ||
+ (value.offer.interval !== 'MONTH' && value.offer.interval !== 'YEAR') ||
+ !amount ||
+ !planCurrency ||
+ !creditAmount ||
+ !rolloverCap ||
+ !capturedAt
+ ) {
+ invalidResponse();
+ }
+ return {
+ version: 1,
+ product: { code: productCode, kind: 'SUBSCRIPTION', level },
+ offer: { code: offerCode, interval: value.offer.interval },
+ terms: { amount, currency: planCurrency, creditAmount, rolloverCap },
+ capturedAt,
+ };
+}
+
+function planChangeBase(value: unknown): BillingPlanChange | null {
+ if (!isRecord(value)) return null;
+ const planChangeId = boundedString(value.planChangeId);
+ const changeType =
+ value.changeType === 'UPGRADE' || value.changeType === 'DOWNGRADE' ? value.changeType : null;
+ const status =
+ typeof value.status === 'string' &&
+ PLAN_CHANGE_STATUSES.has(value.status as BillingPlanChangeStatus)
+ ? (value.status as BillingPlanChangeStatus)
+ : null;
+ const quotedAmountMinor =
+ value.quotedAmountMinor === null
+ ? null
+ : typeof value.quotedAmountMinor === 'number' &&
+ Number.isSafeInteger(value.quotedAmountMinor) &&
+ value.quotedAmountMinor >= 0 &&
+ value.quotedAmountMinor <= MAX_QUOTED_AMOUNT_MINOR
+ ? value.quotedAmountMinor
+ : undefined;
+ const quotedCurrency = nullable(value.quotedCurrency, currency);
+ const quoteExpiresAt = nullable(value.quoteExpiresAt, isoTime);
+ const effectiveAt = isoTime(value.effectiveAt);
+ if (
+ !planChangeId ||
+ !changeType ||
+ !status ||
+ quotedAmountMinor === undefined ||
+ quotedCurrency === undefined ||
+ quoteExpiresAt === undefined ||
+ !effectiveAt
+ ) {
+ return null;
+ }
+ return {
+ planChangeId,
+ changeType,
+ status,
+ quotedAmountMinor,
+ quotedCurrency,
+ quoteExpiresAt,
+ effectiveAt,
+ paymentAction: projectPaymentAction(value.paymentAction),
+ };
+}
+
+/**
+ * Direct plan-change endpoint responses must parse; an unknown enum here means
+ * the client cannot reason about the operation it just performed, so fail
+ * closed by rejecting the response instead of guessing.
+ */
+export function projectBillingPlanChange(value: unknown): BillingPlanChange {
+ const change = planChangeBase(value);
+ if (!change) invalidResponse();
+ return change;
+}
+
+function projectPlanChangeTargetPlan(value: unknown): BillingPlanChangeTargetPlan | null {
+ if (
+ !isRecord(value) ||
+ !isRecord(value.product) ||
+ !isRecord(value.offer) ||
+ !isRecord(value.terms)
+ ) {
+ return null;
+ }
+ const productCode = code(value.product.code);
+ const offerCode = code(value.offer.code);
+ const amount = decimal(value.terms.amount);
+ const planCurrency = currency(value.terms.currency);
+ const creditAmount = decimal(value.terms.creditAmount);
+ if (
+ !productCode ||
+ typeof value.product.level !== 'number' ||
+ !Number.isSafeInteger(value.product.level) ||
+ value.product.level < 0 ||
+ !offerCode ||
+ (value.offer.interval !== 'MONTH' && value.offer.interval !== 'YEAR') ||
+ !amount ||
+ !planCurrency ||
+ !creditAmount
+ ) {
+ return null;
+ }
+ return {
+ product: { code: productCode, level: value.product.level },
+ offer: { code: offerCode, interval: value.offer.interval },
+ terms: { amount, currency: planCurrency, creditAmount },
+ };
+}
+
+/**
+ * Recovery projection embedded in the subscription. A malformed or unknown
+ * entry is dropped (undefined) rather than failing the whole subscription:
+ * the client then behaves like an older server and relies on server-side
+ * rejection of conflicting writes.
+ */
+function projectPendingPlanChange(value: unknown): BillingPendingPlanChange | null | undefined {
+ if (value === null) return null;
+ const change = planChangeBase(value);
+ if (!change) return undefined;
+ return {
+ ...change,
+ targetPlan: projectPlanChangeTargetPlan((value as Record<string, unknown>).targetPlan),
+ };
+}
+
+export function projectBillingSubscription(value: unknown): BillingSubscription {
+ if (!isRecord(value)) invalidResponse();
+ const subscriptionId = boundedString(value.subscriptionId);
+ const status =
+ typeof value.status === 'string' &&
+ SUBSCRIPTION_STATUSES.has(value.status as BillingSubscriptionStatus)
+ ? (value.status as BillingSubscriptionStatus)
+ : null;
+ const currentPeriodStartAt = nullable(value.currentPeriodStartAt, isoTime);
+ const currentPeriodEndAt = nullable(value.currentPeriodEndAt, isoTime);
+ const entitlementValidUntil = nullable(value.entitlementValidUntil, isoTime);
+ const purchaseAttemptId = nullable(value.purchaseAttemptId, boundedString);
+ if (
+ !subscriptionId ||
+ !status ||
+ currentPeriodStartAt === undefined ||
+ currentPeriodEndAt === undefined ||
+ entitlementValidUntil === undefined ||
+ typeof value.cancelAtPeriodEnd !== 'boolean' ||
+ purchaseAttemptId === undefined ||
+ (value.effectivePlan !== null && !isRecord(value.effectivePlan))
+ ) {
+ invalidResponse();
+ }
+ const provider =
+ typeof value.provider === 'string' && SUPPORTED_PROVIDERS.has(value.provider)
+ ? value.provider
+ : undefined;
+ const managementAction =
+ value.managementAction === 'API_CANCEL' || value.managementAction === 'PORTAL'
+ ? value.managementAction
+ : undefined;
+ const entitlementStatus =
+ typeof value.entitlementStatus === 'string' &&
+ FULFILLMENT_STATUSES.has(value.entitlementStatus as BillingFulfillmentStatus)
+ ? (value.entitlementStatus as BillingFulfillmentStatus)
+ : undefined;
+ const pendingPlanChange =
+ 'pendingPlanChange' in value ? projectPendingPlanChange(value.pendingPlanChange) : undefined;
+ return {
+ subscriptionId,
+ status,
+ ...(provider ? { provider } : {}),
+ ...(managementAction ? { managementAction } : {}),
+ ...(entitlementStatus ? { entitlementStatus } : {}),
+ currentPeriodStartAt,
+ currentPeriodEndAt,
+ entitlementValidUntil,
+ cancelAtPeriodEnd: value.cancelAtPeriodEnd,
+ effectivePlan: value.effectivePlan === null ? null : projectEffectivePlan(value.effectivePlan),
+ purchaseAttemptId,
+ paymentAction: projectPaymentAction(value.paymentAction),
+ ...(pendingPlanChange === undefined ? {} : { pendingPlanChange }),
+ };
+}
+
+export function projectBillingCurrentSubscription(value: unknown): BillingCurrentSubscription {
+ if (!isRecord(value) || !('subscription' in value)) invalidResponse();
+ return {
+ subscription:
+ value.subscription === null ? null : projectBillingSubscription(value.subscription),
+ };
+}
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 7dd4fb1f6d..b6e30625ae 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -500,6 +500,7 @@ import {
initClientEndpoints,
registerClientEndpointsIpc,
} from './clientEndpointsService.js';
+import { registerBillingIpc } from './billing/index.js';
import {
initModelAccess,
noteManualXdKeySaved,
@@ -2310,6 +2311,19 @@ const registerIpcHandlers = () => {
return windows.find((w) => !w.isDestroyed() && w.isMinimizable()) ?? windows[0];
};
+ registerBillingIpc({
+ getMainWindow: () => mainWindowRef,
+ requirePersonalAccount: () => {
+ requireAppCapability(
+ 'canUseCindyAccountServices',
+ 'Billing requires a personal Cindy account.',
+ );
+ if (authManager.getAuthState().user?.membershipKind !== 'personal') {
+ throwIpcError('PERMISSION_DENIED', 'Billing is only available to personal accounts.');
+ }
+ },
+ });
+
initAppBadgeService({
getWindow: () => getWindow() ?? null,
onSessionAttentionMarked: (sessionId) => {
diff --git a/apps/desktop/src/main/serverApiClient.ts b/apps/desktop/src/main/serverApiClient.ts
index 03f8461671..6f09c9305d 100644
--- a/apps/desktop/src/main/serverApiClient.ts
+++ b/apps/desktop/src/main/serverApiClient.ts
@@ -16,6 +16,12 @@ import { createLogger } from './logger';
const log = createLogger('serverApiClient');
+function redactedLogPath(apiPath: string): string {
+ const pathname = apiPath.split(/[?#]/, 1)[0];
+ const segments = pathname.split('/').filter(Boolean).slice(0, 3);
+ return segments.length > 0 ? `/${segments.join('/')}` : '/';
+}
+
export class ServerApiError extends Error {
constructor(
public readonly code: string,
@@ -42,6 +48,8 @@ export interface ApiFetchOptions {
baseUrl: string;
/** Abort the request after this many milliseconds; 0 disables the deadline. */
timeoutMs?: number;
+ /** Keep upstream response/network details out of local logs for sensitive flows. */
+ redactErrorDetails?: boolean;
}
interface RawResponse<T> {
@@ -63,9 +71,7 @@ async function rawFetch<T>(apiPath: string, opts: ApiFetchOptions): Promise<RawR
}
const timeoutMs = opts.timeoutMs ?? 0;
const controller = timeoutMs > 0 ? new AbortController() : null;
- const timeoutId = controller
- ? setTimeout(() => controller.abort(), timeoutMs)
- : null;
+ const timeoutId = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
try {
const body = opts.bodyFactory ? opts.bodyFactory() : opts.body;
const response = await net.fetch(url, {
@@ -83,7 +89,15 @@ async function rawFetch<T>(apiPath: string, opts: ApiFetchOptions): Promise<RawR
}
return { ok: response.ok, status: response.status, data };
} catch (err) {
- log.error('fetch failed', apiPath, err);
+ if (opts.redactErrorDetails) {
+ log.error(
+ 'serverApiFetch.redacted_network_error',
+ 'path=' + redactedLogPath(apiPath),
+ 'method=' + method,
+ );
+ } else {
+ log.error('fetch failed', apiPath, err);
+ }
return { ok: false, status: 0, data: null };
} finally {
if (timeoutId !== null) clearTimeout(timeoutId);
@@ -94,10 +108,7 @@ async function rawFetch<T>(apiPath: string, opts: ApiFetchOptions): Promise<RawR
* 高层 API:成功 → 返回 data;失败 → throw ServerApiError。
* 可恢复的 401 自动 refresh 一次再重试(除非 `skipAutoRefresh`)。
*/
-export async function serverApiFetch<T>(
- apiPath: string,
- opts: ApiFetchOptions,
-): Promise<T> {
+export async function serverApiFetch<T>(apiPath: string, opts: ApiFetchOptions): Promise<T> {
let result = await rawFetch<T>(apiPath, opts);
let refreshedAndRetried = false;
const firstCode = readErrorCode(result.data) ?? statusToCode(result.status);
@@ -131,15 +142,29 @@ export async function serverApiFetch<T>(
}
// 网络异常 rawFetch 已 log;这里补 not-ok 响应(401/5xx 等)的日志,
// 否则上层 catch 一吞,排查调用链时完全看不到原因。
- log.warn(
- 'serverApiFetch.not_ok',
- 'path=' + apiPath,
- 'method=' + (opts.method ?? 'GET'),
- 'status=' + result.status,
- 'code=' + errCode,
- 'msg=' + errMsg,
+ if (opts.redactErrorDetails) {
+ log.warn(
+ 'serverApiFetch.redacted_not_ok',
+ 'path=' + redactedLogPath(apiPath),
+ 'method=' + (opts.method ?? 'GET'),
+ 'status=' + result.status,
+ 'code=' + statusToCode(result.status),
+ );
+ } else {
+ log.warn(
+ 'serverApiFetch.not_ok',
+ 'path=' + apiPath,
+ 'method=' + (opts.method ?? 'GET'),
+ 'status=' + result.status,
+ 'code=' + errCode,
+ 'msg=' + errMsg,
+ );
+ }
+ throw new ServerApiError(
+ opts.redactErrorDetails ? statusToCode(result.status) : errCode,
+ result.status,
+ opts.redactErrorDetails ? `请求失败 (${result.status})` : errMsg,
);
- throw new ServerApiError(errCode, result.status, errMsg);
}
if (result.data === null) {
throw new ServerApiError('EMPTY_RESPONSE', result.status, '响应体为空');
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index f87e7ec178..e468dd9b66 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -86,6 +86,7 @@ import type {
DesktopLoginAction,
DesktopLoginActionResult,
} from '../shared/authIpc';
+import { BILLING_INVOKE, type BillingRendererApi } from '../shared/billing';
// Codex 元 IPC 全部升级到 maker.* (agentKind 参数化), preload 不再 import vendor/codex/ipcChannels。
// auth → maker:auth:*(agentKind)
@@ -1424,6 +1425,30 @@ contextBridge.exposeInMainWorld('electronAPI', {
// apiRequest(renderer → main → 主 server 通用代理)与 imageUpload.putToOss
// (presign 直传桥)已随 2026-07 apiBaseUrl 清理退役:renderer 对业务 server
// 零请求;头像等上传走 main 侧 profileEdit 链路。
+ billing: {
+ getBalance: () => ipcRenderer.invoke(BILLING_INVOKE.GET_BALANCE),
+ getCreditUsage: () => ipcRenderer.invoke(BILLING_INVOKE.GET_CREDIT_USAGE),
+ getCatalog: () => ipcRenderer.invoke(BILLING_INVOKE.GET_CATALOG),
+ listOrders: (payload) => ipcRenderer.invoke(BILLING_INVOKE.LIST_ORDERS, payload),
+ getOrder: (payload) => ipcRenderer.invoke(BILLING_INVOKE.GET_ORDER, payload),
+ createTopup: (payload) => ipcRenderer.invoke(BILLING_INVOKE.CREATE_TOPUP, payload),
+ refreshTopup: (payload) => ipcRenderer.invoke(BILLING_INVOKE.REFRESH_TOPUP, payload),
+ cancelTopup: (payload) => ipcRenderer.invoke(BILLING_INVOKE.CANCEL_TOPUP, payload),
+ retryTopup: (payload) => ipcRenderer.invoke(BILLING_INVOKE.RETRY_TOPUP, payload),
+ createSubscription: (payload) =>
+ ipcRenderer.invoke(BILLING_INVOKE.CREATE_SUBSCRIPTION, payload),
+ getCurrentSubscription: () => ipcRenderer.invoke(BILLING_INVOKE.GET_CURRENT_SUBSCRIPTION),
+ refreshSubscriptionPurchase: (payload) =>
+ ipcRenderer.invoke(BILLING_INVOKE.REFRESH_SUBSCRIPTION_PURCHASE, payload),
+ quotePlanChange: (payload) => ipcRenderer.invoke(BILLING_INVOKE.QUOTE_PLAN_CHANGE, payload),
+ confirmPlanChange: (payload) =>
+ ipcRenderer.invoke(BILLING_INVOKE.CONFIRM_PLAN_CHANGE, payload),
+ refreshPlanChange: (payload) =>
+ ipcRenderer.invoke(BILLING_INVOKE.REFRESH_PLAN_CHANGE, payload),
+ cancelPlanChange: (payload) => ipcRenderer.invoke(BILLING_INVOKE.CANCEL_PLAN_CHANGE, payload),
+ openPaymentRedirect: (payload) =>
+ ipcRenderer.invoke(BILLING_INVOKE.OPEN_PAYMENT_REDIRECT, payload),
+ } satisfies BillingRendererApi,
// ── Workdir File Browser (vscode-style file tree + content viewer) ──
// All paths in/out are workdir-relative POSIX. Main side blocks traversal.
diff --git a/apps/desktop/src/renderer/components/settings/SettingsView.tsx b/apps/desktop/src/renderer/components/settings/SettingsView.tsx
index 8e4d0a25b8..19a6c8bba4 100644
--- a/apps/desktop/src/renderer/components/settings/SettingsView.tsx
+++ b/apps/desktop/src/renderer/components/settings/SettingsView.tsx
@@ -39,6 +39,8 @@ import { ContactsSection } from './contacts/ContactsSection';
import { ComputerUseSection } from './ComputerUseSection';
import { useAuth } from '@/contexts/AuthContext';
import { getLastWorkingDir, subscribeToLastWorkingDir } from '@/state/lastWorkingDir';
+import { BillingSettingsSection } from '@/features/billing/BillingPage';
+import { canAccessBillingSettings } from './billingVisibility';
const DEFAULT_SETTINGS_MENU_WIDTH = 260;
@@ -51,7 +53,7 @@ export function SettingsView() {
const outletContext = useOutletContext<SettingsOutletContext | null>();
const [searchParams, setSearchParams] = useSearchParams();
const { t } = useTranslation();
- const { mode, dataOwnerId } = useAuth();
+ const { mode, dataOwnerId, user } = useAuth();
const menuWidth = outletContext?.sidebarWidth ?? DEFAULT_SETTINGS_MENU_WIDTH;
const isMac = window.electronAPI?.platform === 'darwin';
const [helpAssistantOpen, setHelpAssistantOpen] = useState(false);
@@ -61,6 +63,10 @@ export function SettingsView() {
getLastWorkingDir,
);
const rawTab = searchParams.get('tab');
+ const canAccessBilling = canAccessBillingSettings({
+ mode,
+ membershipKind: user?.membershipKind ?? null,
+ });
const shouldRedirectToPlugins =
rawTab === 'ghosts' || rawTab === 'api-keys' || rawTab === 'connections';
@@ -72,9 +78,17 @@ export function SettingsView() {
if (raw === 'feishu-bot' || raw === 'slack-bot') return 'im-bot';
// legacy 别名:旧独立「Tina」(tina) 已并入「IM 机器人」(im-bot)。
if (raw === 'tina') return 'im-bot';
+ if (raw === 'billing' && !canAccessBilling) return 'general';
if (raw === 'agent-island' && !isMac) return 'general';
return isSettingsTab(raw) ? raw : 'general';
- }, [isMac, rawTab]);
+ }, [canAccessBilling, isMac, rawTab]);
+
+ useEffect(() => {
+ if (rawTab !== 'billing' || canAccessBilling) return;
+ const next = new URLSearchParams(searchParams);
+ next.delete('tab');
+ setSearchParams(next, { replace: true });
+ }, [canAccessBilling, rawTab, searchParams, setSearchParams]);
// 「IM 机器人」页内分栏:?imGroup=cindy|personal 定位到某个 tab(深链可直达)。
// 缺省/非法 imGroup 一律落到默认分栏:旧「飞书机器人」深链落「个人」(飞书在
@@ -137,8 +151,11 @@ export function SettingsView() {
}, [activeTab, searchParams, setSearchParams]);
const visibleTabIds = useMemo(
- () => TAB_IDS.filter((tabId) => isMac || tabId !== 'agent-island'),
- [isMac],
+ () =>
+ TAB_IDS.filter(
+ (tabId) => (isMac || tabId !== 'agent-island') && (canAccessBilling || tabId !== 'billing'),
+ ),
+ [canAccessBilling, isMac],
);
// deep-link: ?section=... → scroll to a section inside General settings.
@@ -301,6 +318,21 @@ export function SettingsView() {
</div>
)}
+ {activeTab === 'billing' && (
+ <div
+ role="tabpanel"
+ id="settings-panel-billing"
+ aria-labelledby="settings-tab-billing"
+ >
+ <section aria-label={t('settings.sections.billing')}>
+ <BillingSettingsSection
+ key={`billing:${dataOwnerId ?? 'none'}`}
+ accountId={dataOwnerId}
+ />
+ </section>
+ </div>
+ )}
+
{activeTab === 'personalization' && (
<div
role="tabpanel"
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/billingVisibility.test.ts b/apps/desktop/src/renderer/components/settings/__tests__/billingVisibility.test.ts
new file mode 100644
index 0000000000..906a6a8f02
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/billingVisibility.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest';
+
+import { canAccessBillingSettings, type BillingSettingsIdentity } from '../billingVisibility';
+
+function identity(overrides: Partial<BillingSettingsIdentity> = {}): BillingSettingsIdentity {
+ return { mode: 'cloud', membershipKind: 'personal', ...overrides };
+}
+
+describe('billingVisibility', () => {
+ it('allows only personal cloud accounts', () => {
+ expect(canAccessBillingSettings(identity())).toBe(true);
+ expect(canAccessBillingSettings(identity({ membershipKind: 'org' }))).toBe(false);
+ expect(canAccessBillingSettings(identity({ mode: 'local', membershipKind: null }))).toBe(false);
+ expect(canAccessBillingSettings(identity({ mode: 'signed-out', membershipKind: null }))).toBe(
+ false,
+ );
+ });
+});
diff --git a/apps/desktop/src/renderer/components/settings/billingVisibility.ts b/apps/desktop/src/renderer/components/settings/billingVisibility.ts
new file mode 100644
index 0000000000..a05fa93193
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/billingVisibility.ts
@@ -0,0 +1,8 @@
+export type BillingSettingsIdentity = {
+ mode: 'signed-out' | 'local' | 'cloud';
+ membershipKind: 'personal' | 'org' | null;
+};
+
+export function canAccessBillingSettings(identity: BillingSettingsIdentity): boolean {
+ return identity.mode === 'cloud' && identity.membershipKind === 'personal';
+}
diff --git a/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsx b/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsx
new file mode 100644
index 0000000000..02a7634e2d
--- /dev/null
+++ b/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsx
@@ -0,0 +1,285 @@
+import { useEffect, useMemo, useState } from 'react';
+import * as Dialog from '@radix-ui/react-dialog';
+import * as QRCode from 'qrcode';
+import { Check, CircleAlert, ExternalLink, LoaderCircle, RotateCcw, X } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Spinner } from '@/components/ui/spinner';
+import { cn } from '@/lib/utils';
+import { billingApi } from './api';
+import type { BillingCheckoutState } from './useBillingCheckout';
+
+interface BillingCheckoutDialogProps {
+ state: BillingCheckoutState;
+ onClose: () => void;
+ onRefresh: () => void;
+ onRetry: () => void;
+ onCancel: () => void;
+}
+
+function actionOf(state: BillingCheckoutState) {
+ return state.order?.paymentAction ?? state.subscription?.paymentAction ?? null;
+}
+
+export function BillingCheckoutDialog({
+ state,
+ onClose,
+ onRefresh,
+ onRetry,
+ onCancel,
+}: BillingCheckoutDialogProps) {
+ const { t } = useTranslation();
+ const action = actionOf(state);
+ const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);
+ const [remainingSeconds, setRemainingSeconds] = useState<number | null>(null);
+
+ useEffect(() => {
+ let active = true;
+ setQrDataUrl(null);
+ if (action?.type === 'QR_CODE') {
+ void QRCode.toDataURL(action.value, {
+ width: 1024,
+ margin: 4,
+ })
+ .then((dataUrl) => {
+ if (active) setQrDataUrl(dataUrl);
+ })
+ .catch(() => {
+ if (active) setQrDataUrl(null);
+ });
+ }
+ return () => {
+ active = false;
+ };
+ }, [action]);
+
+ useEffect(() => {
+ if (!action) {
+ setRemainingSeconds(null);
+ return;
+ }
+ const update = () => {
+ setRemainingSeconds(
+ Math.max(0, Math.ceil((Date.parse(action.expiresAt) - Date.now()) / 1000)),
+ );
+ };
+ update();
+ const timer = window.setInterval(update, 1_000);
+ return () => window.clearInterval(timer);
+ }, [action]);
+
+ const title = useMemo(() => {
+ if (state.phase === 'CREATING') return t('billing.checkout.creatingTitle');
+ if (state.phase === 'AWAITING_PAYMENT') return t('billing.checkout.awaitingTitle');
+ if (state.phase === 'FULFILLING') return t('billing.checkout.fulfillingTitle');
+ if (state.phase === 'COMPLETED') return t('billing.checkout.completedTitle');
+ if (state.phase === 'EXPIRED') return t('billing.checkout.expiredTitle');
+ if (state.phase === 'CANCELED') return t('billing.checkout.canceledTitle');
+ return t('billing.checkout.failedTitle');
+ }, [state.phase, t]);
+
+ const openRedirect = () => {
+ if (action?.type === 'REDIRECT') void billingApi.openPaymentRedirect(action.url);
+ };
+
+ const canRetry =
+ (state.error && state.intent !== null && state.order === null && state.subscription === null) ||
+ (state.kind === 'TOPUP' &&
+ (state.order?.status === 'FAILED' || state.order?.status === 'EXPIRED'));
+ const canCancel =
+ state.kind === 'TOPUP' &&
+ state.order !== null &&
+ (state.order.status === 'CREATED' || state.order.status === 'PENDING');
+
+ return (
+ <Dialog.Root
+ open={state.open}
+ onOpenChange={(open) => !open && state.phase !== 'CREATING' && onClose()}
+ >
+ <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-[10000] bg-[var(--overlay-modal)]" />
+ <Dialog.Content
+ className={cn(
+ 'fixed left-1/2 top-1/2 z-[10001] w-[calc(100vw-40px)] max-w-[620px]',
+ '-translate-x-1/2 -translate-y-1/2 overflow-hidden rounded-xl',
+ 'border border-[var(--border-default)] bg-[var(--surface-elevated)]',
+ 'text-[var(--text-primary)] focus:outline-none',
+ )}
+ aria-describedby={undefined}
+ >
+ <div className="flex items-start justify-between gap-4 border-b border-[var(--border-default)] px-6 py-5">
+ <div>
+ <Dialog.Title className="text-lg font-medium">{title}</Dialog.Title>
+ <p className="mt-1 text-12 leading-5 text-[var(--text-secondary)]">
+ {state.kind === 'TOPUP'
+ ? t('billing.checkout.topupSubtitle')
+ : t('billing.checkout.subscriptionSubtitle')}
+ </p>
+ </div>
+ {state.phase !== 'CREATING' && (
+ <Dialog.Close asChild>
+ <button
+ type="button"
+ className="grid size-8 shrink-0 place-items-center rounded-full text-[var(--text-tertiary)] transition-colors hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)]"
+ aria-label={t('billing.actions.close')}
+ >
+ <X size={16} />
+ </button>
+ </Dialog.Close>
+ )}
+ </div>
+
+ <div className="flex min-h-[300px] flex-col items-center justify-center px-6 py-7 text-center">
+ {state.phase === 'CREATING' && (
+ <>
+ <Spinner icon={LoaderCircle} size={28} className="text-[var(--text-secondary)]" />
+ <p className="mt-4 text-sm text-[var(--text-secondary)]">
+ {t('billing.checkout.creatingBody')}
+ </p>
+ </>
+ )}
+
+ {state.phase === 'AWAITING_PAYMENT' && action?.type === 'QR_CODE' && (
+ <>
+ <div
+ className="grid place-items-center rounded-xl border border-[var(--border-default)] bg-white p-2"
+ style={{
+ width: 'min(512px, calc(100vw - 96px), calc(100vh - 260px))',
+ height: 'min(512px, calc(100vw - 96px), calc(100vh - 260px))',
+ }}
+ >
+ {qrDataUrl ? (
+ <img src={qrDataUrl} className="size-full" alt={t('billing.checkout.qrAlt')} />
+ ) : (
+ <Spinner size={24} className="text-[var(--text-secondary)]" />
+ )}
+ </div>
+ <p className="mt-4 text-sm font-medium">{t('billing.checkout.scanHint')}</p>
+ <p className="mt-1 text-12 text-[var(--text-tertiary)]">
+ {remainingSeconds === null
+ ? t('billing.checkout.checkingExpiry')
+ : t('billing.checkout.expiresIn', {
+ minutes: Math.floor(remainingSeconds / 60),
+ seconds: String(remainingSeconds % 60).padStart(2, '0'),
+ })}
+ </p>
+ </>
+ )}
+
+ {state.phase === 'AWAITING_PAYMENT' && action?.type === 'REDIRECT' && (
+ <>
+ <div className="grid size-14 place-items-center rounded-full bg-[var(--surface-chip)]">
+ <ExternalLink size={22} />
+ </div>
+ <p className="mt-4 text-sm font-medium">{t('billing.checkout.redirectHint')}</p>
+ <button
+ type="button"
+ onClick={openRedirect}
+ className="mt-5 inline-flex h-9 items-center gap-2 rounded-full bg-[var(--text-primary)] px-5 text-sm font-medium text-[var(--surface)]"
+ >
+ <ExternalLink size={14} />
+ {t('billing.checkout.openPayment')}
+ </button>
+ </>
+ )}
+
+ {state.phase === 'AWAITING_PAYMENT' && !action && (
+ <>
+ <Spinner size={26} className="text-[var(--text-secondary)]" />
+ <p className="mt-4 text-sm text-[var(--text-secondary)]">
+ {t('billing.checkout.refreshingAction')}
+ </p>
+ </>
+ )}
+
+ {state.phase === 'FULFILLING' && (
+ <>
+ <Spinner size={26} className="text-[var(--text-secondary)]" />
+ <p className="mt-4 text-sm text-[var(--text-secondary)]">
+ {t('billing.checkout.creditingBody')}
+ </p>
+ </>
+ )}
+
+ {state.phase === 'COMPLETED' && (
+ <>
+ <div className="grid size-14 place-items-center rounded-full bg-[var(--text-primary)] text-[var(--surface)]">
+ <Check size={24} />
+ </div>
+ <p className="mt-4 text-sm font-medium">{t('billing.checkout.paymentCompleted')}</p>
+ </>
+ )}
+
+ {(state.phase === 'FAILED' ||
+ state.phase === 'EXPIRED' ||
+ state.phase === 'CANCELED') && (
+ <>
+ <div className="grid size-14 place-items-center rounded-full bg-[var(--surface-chip)]">
+ <CircleAlert size={23} />
+ </div>
+ <p className="mt-4 max-w-[320px] text-sm text-[var(--text-secondary)]">
+ {state.error
+ ? t('billing.checkout.requestFailed')
+ : state.phase === 'EXPIRED'
+ ? t('billing.checkout.expiredBody')
+ : state.phase === 'CANCELED'
+ ? t('billing.checkout.canceledBody')
+ : t('billing.checkout.failedBody')}
+ </p>
+ </>
+ )}
+ </div>
+
+ <div className="flex min-h-16 items-center justify-between gap-3 border-t border-[var(--border-default)] px-6 py-3">
+ <div>
+ {canCancel && (
+ <button
+ type="button"
+ onClick={onCancel}
+ className="h-9 rounded-full px-3 text-12 text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-hover-soft)]"
+ >
+ {t('billing.actions.cancelPayment')}
+ </button>
+ )}
+ </div>
+ <div className="flex items-center gap-2">
+ {(state.phase === 'AWAITING_PAYMENT' || state.phase === 'FULFILLING') && (
+ <button
+ type="button"
+ onClick={onRefresh}
+ className="inline-flex h-9 items-center gap-2 rounded-full border border-[var(--border-default)] px-4 text-12 font-medium transition-colors hover:bg-[var(--surface-hover-soft)]"
+ >
+ <RotateCcw size={14} />
+ {t('billing.actions.refresh')}
+ </button>
+ )}
+ {(state.phase === 'FAILED' || state.phase === 'EXPIRED') && canRetry && (
+ <button
+ type="button"
+ onClick={onRetry}
+ className="inline-flex h-9 items-center gap-2 rounded-full bg-[var(--text-primary)] px-4 text-12 font-medium text-[var(--surface)]"
+ >
+ <RotateCcw size={14} />
+ {t('billing.actions.retry')}
+ </button>
+ )}
+ {isTerminalPhase(state.phase) && (
+ <button
+ type="button"
+ onClick={onClose}
+ className="h-9 rounded-full border border-[var(--border-default)] px-4 text-12 font-medium transition-colors hover:bg-[var(--surface-hover-soft)]"
+ >
+ {t('billing.actions.close')}
+ </button>
+ )}
+ </div>
+ </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
+
+function isTerminalPhase(phase: BillingCheckoutState['phase']): boolean {
+ return phase === 'COMPLETED' || phase === 'FAILED' || phase === 'EXPIRED' || phase === 'CANCELED';
+}
diff --git a/apps/desktop/src/renderer/features/billing/BillingPage.tsx b/apps/desktop/src/renderer/features/billing/BillingPage.tsx
new file mode 100644
index 0000000000..205400b909
--- /dev/null
+++ b/apps/desktop/src/renderer/features/billing/BillingPage.tsx
@@ -0,0 +1,1433 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import * as Dialog from '@radix-ui/react-dialog';
+import {
+ ArrowRight,
+ Check,
+ CircleDollarSign,
+ CreditCard,
+ PackageOpen,
+ RefreshCcw,
+ ShieldCheck,
+ X,
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Spinner } from '@/components/ui/spinner';
+import { useAuth } from '@/contexts/AuthContext';
+import { cn } from '@/lib/utils';
+import { extractIpcError } from '@/utils/ipcError';
+import type {
+ BillingCatalog,
+ BillingCatalogOffer,
+ BillingCatalogProduct,
+ BillingPendingPlanChange,
+ BillingPurchaseOption,
+ BillingSubscription,
+} from '../../../shared/billing';
+import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
+import type {
+ ModelAccessBalance,
+ ModelAccessCreditPoolUsage,
+ ModelAccessCreditUsage,
+ ModelAccessPromotionalGrantState,
+} from '../../../shared/modelAccess';
+import { billingApi } from './api';
+import { BillingCheckoutDialog } from './BillingCheckoutDialog';
+import { formatBillingAmount as formatMoney } from './money';
+import {
+ PlanChangeStatusDialog,
+ PlanChangeTargetDialog,
+ type PlanChangeCandidate,
+} from './PlanChangeDialog';
+import { useBillingCheckout } from './useBillingCheckout';
+import { usePlanChange, type PlanChangeSettledKind } from './usePlanChange';
+
+type PurchasableOffer = {
+ product: BillingCatalogProduct;
+ offer: BillingCatalogOffer;
+ purchaseOptions: SupportedPurchaseOption[];
+};
+
+type SupportedBillingProvider = 'alipay' | 'stripe';
+type SupportedPurchaseOption = BillingPurchaseOption & {
+ provider: SupportedBillingProvider;
+};
+
+type PurchaseKind = BillingCatalogProduct['kind'];
+type BalanceIssue = 'NOT_PROVISIONED' | 'NOT_SUPPORTED' | 'UNAVAILABLE' | null;
+
+const SUPPORTED_BILLING_PROVIDERS = new Set<SupportedBillingProvider>(['alipay', 'stripe']);
+const SUPPORTED_PAYMENT_ACTIONS = new Set<BillingPurchaseOption['paymentAction']>([
+ 'QR_CODE',
+ 'REDIRECT',
+]);
+const SUPPORTED_SUBSCRIPTION_CAPABILITIES = new Set<BillingPurchaseOption['capability']>([
+ 'MERCHANT_INITIATED_MANDATE',
+ 'PROVIDER_MANAGED_SUBSCRIPTION',
+]);
+
+const SUBSCRIPTION_PURCHASE_BLOCKING_STATUSES: BillingSubscription['status'][] = [
+ 'INCOMPLETE',
+ 'TRIALING',
+ 'ACTIVE',
+ 'PAST_DUE',
+ 'UNPAID',
+ 'PAUSED',
+];
+
+function decimalParts(value: string): { value: bigint; scale: number } | null {
+ const match = /^(0|[1-9]\d{0,14})(?:\.(\d{1,9}))?$/.exec(value.trim());
+ if (!match) return null;
+ const fraction = match[2] ?? '';
+ return {
+ value: BigInt(`${match[1]}${fraction}`),
+ scale: fraction.length,
+ };
+}
+
+function compareDecimal(left: string, right: string): number | null {
+ const a = decimalParts(left);
+ const b = decimalParts(right);
+ if (!a || !b) return null;
+ const scale = Math.max(a.scale, b.scale);
+ const av = a.value * 10n ** BigInt(scale - a.scale);
+ const bv = b.value * 10n ** BigInt(scale - b.scale);
+ return av < bv ? -1 : av > bv ? 1 : 0;
+}
+
+function ledgerUnits(value: string): bigint | null {
+ const match = /^(-?)(0|[1-9]\d{0,9})(?:\.(\d{1,9}))?$/.exec(value);
+ if (!match) return null;
+ const fraction = (match[3] ?? '').padEnd(9, '0');
+ const units = BigInt(match[2]) * 1_000_000_000n + BigInt(fraction || '0');
+ return match[1] === '-' ? -units : units;
+}
+
+function usagePercent(pool: ModelAccessCreditPoolUsage): number | null {
+ if (pool.used === null || pool.total === null) return null;
+ const used = ledgerUnits(pool.used);
+ const total = ledgerUnits(pool.total);
+ if (used === null || total === null || used < 0n || total < 0n) return null;
+ if (total === 0n) return used === 0n ? 0 : null;
+ const tenths = (used * 1_000n) / total;
+ return Number(tenths > 1_000n ? 1_000n : tenths) / 10;
+}
+
+function formatLedgerTimestamp(value: string): string {
+ const timestamp = Date.parse(value);
+ if (!Number.isFinite(timestamp)) return value;
+ try {
+ return new Intl.DateTimeFormat(undefined, {
+ dateStyle: 'medium',
+ timeStyle: 'short',
+ }).format(timestamp);
+ } catch {
+ return value;
+ }
+}
+
+function isCustomTopup(offer: BillingCatalogOffer): boolean {
+ return offer.amount === null && offer.minAmount !== null && offer.maxAmount !== null;
+}
+
+function isSupportedPurchaseOption(
+ option: BillingPurchaseOption,
+ productKind: BillingCatalogProduct['kind'],
+): option is SupportedPurchaseOption {
+ if (!SUPPORTED_BILLING_PROVIDERS.has(option.provider as SupportedBillingProvider)) return false;
+ if (!SUPPORTED_PAYMENT_ACTIONS.has(option.paymentAction)) return false;
+ return productKind === 'CREDIT_TOPUP'
+ ? option.capability === 'ONE_TIME_PAYMENT'
+ : SUPPORTED_SUBSCRIPTION_CAPABILITIES.has(option.capability);
+}
+
+function currencyFractionDigits(currency: string): number {
+ try {
+ return (
+ new Intl.NumberFormat(undefined, {
+ style: 'currency',
+ currency: currency.toUpperCase(),
+ }).resolvedOptions().maximumFractionDigits ?? 2
+ );
+ } catch {
+ return 2;
+ }
+}
+
+function balanceIssue(error: unknown): Exclude<BalanceIssue, null> {
+ const code = extractIpcError(error)?.code;
+ if (code === 'NOT_FOUND') return 'NOT_PROVISIONED';
+ if (code === 'UNSUPPORTED_CAPABILITY') return 'NOT_SUPPORTED';
+ return 'UNAVAILABLE';
+}
+
+/**
+ * Kept as a compatibility export for focused tests and old imports.
+ * The actual product entry now lives in Settings.
+ */
+export function BillingPage() {
+ const { dataOwnerId } = useAuth();
+ return (
+ <BillingSettingsSection key={`billing:${dataOwnerId ?? 'none'}`} accountId={dataOwnerId} />
+ );
+}
+
+export function BillingSettingsSection({ accountId }: { accountId: string | null }) {
+ const { t } = useTranslation();
+ const [catalog, setCatalog] = useState<BillingCatalog | null>(null);
+ const [catalogError, setCatalogError] = useState(false);
+ const [loadingCatalog, setLoadingCatalog] = useState(true);
+ const [currentSubscription, setCurrentSubscription] = useState<BillingSubscription | null>(null);
+ const [loadingSubscription, setLoadingSubscription] = useState(true);
+ const [subscriptionError, setSubscriptionError] = useState(false);
+ const [creditUsage, setCreditUsage] = useState<ModelAccessCreditUsage | null>(null);
+ const [balance, setBalance] = useState<ModelAccessBalance | null>(null);
+ const [usageDetailsUnavailable, setUsageDetailsUnavailable] = useState(false);
+ const [loadingBalance, setLoadingBalance] = useState(true);
+ const [balanceError, setBalanceError] = useState<BalanceIssue>(null);
+ const [subscriptionDialogOpen, setSubscriptionDialogOpen] = useState(false);
+ const [topupDialogOpen, setTopupDialogOpen] = useState(false);
+ const [planChangeTargetOpen, setPlanChangeTargetOpen] = useState(false);
+ const [selectedOfferCode, setSelectedOfferCode] = useState<string | null>(null);
+ const [selectedPurchaseOptionId, setSelectedPurchaseOptionId] = useState<string | null>(null);
+ const [customAmount, setCustomAmount] = useState('');
+ const checkout = useBillingCheckout(accountId);
+ const previousCheckoutPhaseRef = useRef(checkout.state.phase);
+
+ const resetSelection = useCallback(() => {
+ setSelectedOfferCode(null);
+ setSelectedPurchaseOptionId(null);
+ setCustomAmount('');
+ }, []);
+
+ const loadBalance = useCallback(async () => {
+ setLoadingBalance(true);
+ setBalanceError(null);
+ setUsageDetailsUnavailable(false);
+ try {
+ setCreditUsage(await billingApi.getCreditUsage());
+ setBalance(null);
+ } catch {
+ try {
+ setBalance(await billingApi.getBalance());
+ setCreditUsage(null);
+ setUsageDetailsUnavailable(true);
+ } catch (error) {
+ setCreditUsage(null);
+ setBalance(null);
+ setBalanceError(balanceIssue(error));
+ }
+ } finally {
+ setLoadingBalance(false);
+ }
+ }, []);
+
+ const loadSubscription = useCallback(async () => {
+ setLoadingSubscription(true);
+ setSubscriptionError(false);
+ try {
+ setCurrentSubscription((await billingApi.getCurrentSubscription()).subscription);
+ } catch {
+ setCurrentSubscription(null);
+ setSubscriptionError(true);
+ } finally {
+ setLoadingSubscription(false);
+ }
+ }, []);
+
+ const loadBillingState = useCallback(async () => {
+ setLoadingCatalog(true);
+ setCatalogError(false);
+ await Promise.allSettled([
+ billingApi
+ .getCatalog()
+ .then(setCatalog, () => {
+ setCatalog(null);
+ setCatalogError(true);
+ })
+ .finally(() => setLoadingCatalog(false)),
+ loadSubscription(),
+ loadBalance(),
+ ]);
+ }, [loadBalance, loadSubscription]);
+
+ useEffect(() => {
+ void loadBillingState();
+ }, [loadBillingState]);
+
+ useEffect(() => {
+ if (checkout.state.subscription) {
+ setCurrentSubscription(checkout.state.subscription);
+ setSubscriptionError(false);
+ }
+ }, [checkout.state.subscription]);
+
+ useEffect(() => {
+ const previousPhase = previousCheckoutPhaseRef.current;
+ previousCheckoutPhaseRef.current = checkout.state.phase;
+ if (previousPhase !== 'COMPLETED' && checkout.state.phase === 'COMPLETED') {
+ void loadBalance();
+ }
+ }, [checkout.state.phase, loadBalance]);
+
+ const handlePlanChangeSettled = useCallback(
+ (kind: PlanChangeSettledKind) => {
+ // APPLIED is the only settle that moves credits; one full reload covers
+ // subscription, catalog, and balance without a second balance call.
+ if (kind === 'APPLIED') void loadBillingState();
+ else void loadSubscription();
+ },
+ [loadBillingState, loadSubscription],
+ );
+ const planChange = usePlanChange(accountId, handlePlanChangeSettled);
+
+ const offers = useMemo<PurchasableOffer[]>(() => {
+ if (!catalog) return [];
+ return catalog.products
+ .flatMap((product) =>
+ product.offers.map((offer) => ({
+ product,
+ offer,
+ purchaseOptions: Array.isArray(offer.purchaseOptions)
+ ? offer.purchaseOptions.filter((option) =>
+ isSupportedPurchaseOption(option, product.kind),
+ )
+ : [],
+ })),
+ )
+ .filter(({ purchaseOptions }) => purchaseOptions.length > 0)
+ .sort((left, right) => {
+ const productOrder = left.product.sortOrder - right.product.sortOrder;
+ if (productOrder !== 0) return productOrder;
+ return left.offer.code.localeCompare(right.offer.code);
+ });
+ }, [catalog]);
+
+ const subscriptionOffers = useMemo(
+ () => offers.filter(({ product }) => product.kind === 'SUBSCRIPTION'),
+ [offers],
+ );
+ const topupOffers = useMemo(
+ () => offers.filter(({ product }) => product.kind === 'CREDIT_TOPUP'),
+ [offers],
+ );
+
+ const selected = useMemo(
+ () => offers.find(({ offer }) => offer.code === selectedOfferCode) ?? null,
+ [offers, selectedOfferCode],
+ );
+ const selectedOption = useMemo(
+ () =>
+ selected?.purchaseOptions.find((option) => option.id === selectedPurchaseOptionId) ?? null,
+ [selected, selectedPurchaseOptionId],
+ );
+
+ useEffect(() => {
+ if (!selectedOfferCode) return;
+ if (!offers.some(({ offer }) => offer.code === selectedOfferCode)) {
+ resetSelection();
+ }
+ }, [offers, resetSelection, selectedOfferCode]);
+
+ useEffect(() => {
+ if (!selectedPurchaseOptionId) return;
+ if (!selected?.purchaseOptions.some((option) => option.id === selectedPurchaseOptionId)) {
+ setSelectedPurchaseOptionId(null);
+ }
+ }, [selected, selectedPurchaseOptionId]);
+
+ const amountError = useMemo(() => {
+ if (!selected || !isCustomTopup(selected.offer)) return null;
+ if (!customAmount) return null;
+ const amountParts = decimalParts(customAmount);
+ const fractionDigits = currencyFractionDigits(selected.offer.currency);
+ if (!amountParts || amountParts.scale > fractionDigits) {
+ return t('billing.amount.formatError', { digits: fractionDigits });
+ }
+ const min = selected.offer.minAmount!;
+ const max = selected.offer.maxAmount!;
+ const minComparison = compareDecimal(customAmount, min);
+ const maxComparison = compareDecimal(customAmount, max);
+ if (
+ minComparison === null ||
+ minComparison < 0 ||
+ maxComparison === null ||
+ maxComparison > 0
+ ) {
+ return t('billing.amount.rangeError', {
+ min: formatMoney(min, selected.offer.currency),
+ max: formatMoney(max, selected.offer.currency),
+ });
+ }
+ return null;
+ }, [customAmount, selected, t]);
+
+ const subscriptionPurchaseBlocked =
+ currentSubscription !== null &&
+ SUBSCRIPTION_PURCHASE_BLOCKING_STATUSES.includes(currentSubscription.status);
+ const canCheckout =
+ !checkout.recovering &&
+ selected !== null &&
+ selectedOption !== null &&
+ !(
+ selected.product.kind === 'SUBSCRIPTION' &&
+ (loadingSubscription || subscriptionError || subscriptionPurchaseBlocked)
+ ) &&
+ (!isCustomTopup(selected.offer) || (customAmount.length > 0 && amountError === null));
+
+ const planNameOf = useCallback(
+ (productCode: string | null | undefined) => {
+ if (!productCode) return null;
+ return catalog?.products.find((product) => product.code === productCode)?.name ?? productCode;
+ },
+ [catalog],
+ );
+
+ const currentPlanName = useMemo(
+ () => planNameOf(currentSubscription?.effectivePlan?.product.code),
+ [planNameOf, currentSubscription],
+ );
+
+ const currentPlan = currentSubscription?.effectivePlan ?? null;
+ const pendingPlanChange = currentSubscription?.pendingPlanChange ?? null;
+ const planChangeable =
+ currentSubscription?.status === 'ACTIVE' &&
+ !currentSubscription.cancelAtPeriodEnd &&
+ currentPlan?.offer.interval === 'MONTH';
+
+ // UI candidates only. The quote is the authority on whether a target is
+ // actually reachable; this filter just avoids offering obviously invalid
+ // targets (other interval, same level, or another provider's offers).
+ const planChangeCandidates = useMemo<PlanChangeCandidate[]>(() => {
+ if (!planChangeable || !currentPlan) return [];
+ const currentProvider = currentSubscription?.provider ?? null;
+ return subscriptionOffers
+ .filter(
+ ({ product, offer }) =>
+ offer.interval === currentPlan.offer.interval &&
+ offer.code !== currentPlan.offer.code &&
+ product.level !== null &&
+ product.level !== currentPlan.product.level &&
+ (currentProvider === null ||
+ offer.purchaseOptions.some((option) => option.provider === currentProvider)),
+ )
+ .map(({ product, offer }) => ({
+ product,
+ offer,
+ direction:
+ (product.level ?? 0) > currentPlan.product.level
+ ? ('UPGRADE' as const)
+ : ('DOWNGRADE' as const),
+ }));
+ }, [subscriptionOffers, planChangeable, currentPlan, currentSubscription?.provider]);
+
+ const openPurchaseDialog = (kind: PurchaseKind) => {
+ resetSelection();
+ if (kind === 'SUBSCRIPTION') {
+ setSubscriptionDialogOpen(true);
+ } else {
+ setTopupDialogOpen(true);
+ }
+ };
+
+ const selectOffer = (offerCode: string) => {
+ if (selectedOfferCode === offerCode) return;
+ setSelectedOfferCode(offerCode);
+ setSelectedPurchaseOptionId(null);
+ setCustomAmount('');
+ };
+
+ const submit = () => {
+ if (!selected || !selectedOption || !canCheckout) return;
+ setSubscriptionDialogOpen(false);
+ setTopupDialogOpen(false);
+ if (selected.product.kind === 'CREDIT_TOPUP') {
+ void checkout.startTopup({
+ offerCode: selected.offer.code,
+ ...(isCustomTopup(selected.offer) ? { amount: customAmount.trim() } : {}),
+ purchaseOptionId: selectedOption.id,
+ });
+ } else {
+ void checkout.startSubscription({
+ offerCode: selected.offer.code,
+ purchaseOptionId: selectedOption.id,
+ });
+ }
+ };
+
+ const closeSubscriptionDialog = () => {
+ setSubscriptionDialogOpen(false);
+ resetSelection();
+ };
+ const closeTopupDialog = () => {
+ setTopupDialogOpen(false);
+ resetSelection();
+ };
+
+ const openPlanChange = () => {
+ // An open change is the server's fact; re-enter it instead of quoting anew.
+ if (pendingPlanChange) {
+ planChange.resumePending(pendingPlanChange);
+ } else {
+ setPlanChangeTargetOpen(true);
+ }
+ };
+
+ const selectPlanChangeTarget = (candidate: PlanChangeCandidate) => {
+ if (candidate.offer.interval === null) return;
+ setPlanChangeTargetOpen(false);
+ void planChange.startQuote(candidate.offer.code, {
+ product: { code: candidate.product.code, level: candidate.product.level ?? 0 },
+ offer: { code: candidate.offer.code, interval: candidate.offer.interval },
+ terms: {
+ amount: candidate.offer.amount ?? '0',
+ currency: candidate.offer.currency,
+ creditAmount: candidate.offer.creditAmount ?? '0',
+ },
+ });
+ };
+
+ const closePlanChangeStatus = () => {
+ const phase = planChange.state.phase;
+ planChange.close();
+ // Leaving an open change mid-flow: re-sync the pending projection so the
+ // banner reflects what is still open on the server.
+ if (phase === 'QUOTE_READY' || phase === 'PENDING_PROVIDER' || phase === 'AWAITING_PAYMENT')
+ void loadSubscription();
+ };
+
+ return (
+ <>
+ <div>
+ <div className="flex items-start justify-between gap-6">
+ <div>
+ <h2 className="text-20 font-medium tracking-[-0.01em] text-[var(--settings-section-title)]">
+ {t('billing.settings.title')}
+ </h2>
+ <p className="mt-1.5 max-w-[620px] text-13 leading-5 text-[var(--settings-section-desc)]">
+ {t('billing.settings.subtitle')}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={() => void loadBillingState()}
+ disabled={loadingCatalog || loadingSubscription || loadingBalance}
+ className="inline-flex h-8 shrink-0 items-center gap-2 rounded-full border border-[var(--border-default)] px-3.5 text-12 font-medium text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-hover-soft)] disabled:opacity-45"
+ >
+ {loadingCatalog || loadingSubscription || loadingBalance ? (
+ <Spinner size={13} />
+ ) : (
+ <RefreshCcw size={13} />
+ )}
+ {t('billing.actions.refreshCatalog')}
+ </button>
+ </div>
+
+ <div className="mt-8 overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)]">
+ <BillingUsageSummary
+ usage={creditUsage}
+ balance={balance}
+ issue={balanceError}
+ loading={loadingBalance}
+ detailsUnavailable={usageDetailsUnavailable}
+ />
+ <div className="border-t border-[var(--border-default)]">
+ <BillingSummaryRow
+ label={t('billing.settings.subscriptionCard.title')}
+ title={
+ currentPlanName ??
+ (currentSubscription
+ ? t('billing.settings.subscriptionCard.unnamedPlan')
+ : t('billing.settings.subscriptionCard.emptyTitle'))
+ }
+ description={
+ loadingSubscription
+ ? t('billing.settings.loading')
+ : subscriptionError
+ ? t('billing.settings.subscriptionCard.unavailable')
+ : currentSubscription
+ ? t(`billing.subscriptionStatus.${currentSubscription.status}`)
+ : t('billing.settings.subscriptionCard.empty')
+ }
+ loading={loadingSubscription}
+ disabled={loadingSubscription || subscriptionError}
+ actionLabel={
+ planChangeable
+ ? t('billing.settings.subscriptionCard.changeAction')
+ : t('billing.settings.subscriptionCard.action')
+ }
+ onAction={() => {
+ if (planChangeable) openPlanChange();
+ else openPurchaseDialog('SUBSCRIPTION');
+ }}
+ />
+ {pendingPlanChange && (
+ <PendingPlanChangeBanner
+ pending={pendingPlanChange}
+ targetName={planNameOf(pendingPlanChange.targetPlan?.product.code)}
+ onResume={() => planChange.resumePending(pendingPlanChange)}
+ onUndo={() => void planChange.cancelChange(pendingPlanChange.planChangeId)}
+ />
+ )}
+ </div>
+ <div className="border-t border-[var(--border-default)]">
+ <BillingSummaryRow
+ label={t('billing.settings.topupCard.title')}
+ title={t('billing.settings.topupCard.cardTitle')}
+ description={t('billing.settings.topupCard.cardDescription')}
+ actionLabel={t('billing.settings.topupCard.action')}
+ onAction={() => openPurchaseDialog('CREDIT_TOPUP')}
+ />
+ </div>
+ </div>
+
+ {!checkout.recovering &&
+ (checkout.recoverables.topups.length > 0 ||
+ checkout.recoverables.subscription !== null) && (
+ <div className="mt-5 rounded-xl border border-[var(--border-default)] px-5 py-4">
+ <p className="text-sm font-medium">{t('billing.recovery.title')}</p>
+ <p className="mt-1 text-12 text-[var(--text-secondary)]">
+ {t('billing.recovery.description')}
+ </p>
+ <div className="mt-3 flex flex-wrap gap-2">
+ {checkout.recoverables.topups.map((order) => (
+ <button
+ key={order.orderId}
+ type="button"
+ onClick={() => checkout.resumeTopup(order)}
+ className="rounded-full border border-[var(--border-default)] px-3 py-1.5 text-12 font-medium hover:bg-[var(--surface-hover-soft)]"
+ >
+ {t('billing.recovery.continueTopup', {
+ amount: formatMoney(order.amount, order.currency),
+ })}
+ </button>
+ ))}
+ {checkout.recoverables.subscription && (
+ <button
+ type="button"
+ onClick={() => checkout.resumeSubscription(checkout.recoverables.subscription!)}
+ className="rounded-full border border-[var(--border-default)] px-3 py-1.5 text-12 font-medium hover:bg-[var(--surface-hover-soft)]"
+ >
+ {t('billing.recovery.continueSubscription')}
+ </button>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+
+ <BillingOfferDialog
+ open={subscriptionDialogOpen}
+ kind="SUBSCRIPTION"
+ offers={subscriptionOffers}
+ loading={loadingCatalog}
+ catalogError={catalogError}
+ selected={selected?.product.kind === 'SUBSCRIPTION' ? selected : null}
+ selectedPurchaseOptionId={selectedPurchaseOptionId}
+ customAmount={customAmount}
+ amountError={amountError}
+ subscriptionPurchaseBlocked={subscriptionPurchaseBlocked}
+ canCheckout={canCheckout}
+ onClose={closeSubscriptionDialog}
+ onRetry={() => void loadBillingState()}
+ onSelectOffer={selectOffer}
+ onSelectPurchaseOption={setSelectedPurchaseOptionId}
+ onCustomAmountChange={setCustomAmount}
+ onSubmit={submit}
+ />
+
+ <BillingOfferDialog
+ open={topupDialogOpen}
+ kind="CREDIT_TOPUP"
+ offers={topupOffers}
+ loading={loadingCatalog}
+ catalogError={catalogError}
+ selected={selected?.product.kind === 'CREDIT_TOPUP' ? selected : null}
+ selectedPurchaseOptionId={selectedPurchaseOptionId}
+ customAmount={customAmount}
+ amountError={amountError}
+ subscriptionPurchaseBlocked={false}
+ canCheckout={canCheckout}
+ onClose={closeTopupDialog}
+ onRetry={() => void loadBillingState()}
+ onSelectOffer={selectOffer}
+ onSelectPurchaseOption={setSelectedPurchaseOptionId}
+ onCustomAmountChange={setCustomAmount}
+ onSubmit={submit}
+ />
+
+ <BillingCheckoutDialog
+ state={checkout.state}
+ onClose={checkout.close}
+ onRefresh={() => void checkout.refreshActive()}
+ onRetry={() => void checkout.retry()}
+ onCancel={() => void checkout.cancel()}
+ />
+
+ <PlanChangeTargetDialog
+ open={planChangeTargetOpen}
+ candidates={planChangeCandidates}
+ currentPlanName={currentPlanName}
+ onClose={() => setPlanChangeTargetOpen(false)}
+ onSelect={selectPlanChangeTarget}
+ />
+
+ <PlanChangeStatusDialog
+ state={planChange.state}
+ targetName={planNameOf(planChange.state.targetPlan?.product.code)}
+ onClose={closePlanChangeStatus}
+ onConfirm={() => void planChange.confirm()}
+ onRefresh={() => void planChange.refresh()}
+ onAbandon={() => {
+ const change = planChange.state.planChange;
+ if (change) void planChange.cancelChange(change.planChangeId);
+ }}
+ />
+ </>
+ );
+}
+
+function PendingPlanChangeBanner({
+ pending,
+ targetName,
+ onResume,
+ onUndo,
+}: {
+ pending: BillingPendingPlanChange;
+ targetName: string | null;
+ onResume: () => void;
+ onUndo: () => void;
+}) {
+ const { t } = useTranslation();
+ const effectiveDate = useMemo(() => {
+ const timestamp = Date.parse(pending.effectiveAt);
+ if (!Number.isFinite(timestamp)) return pending.effectiveAt;
+ try {
+ return new Intl.DateTimeFormat(undefined, { dateStyle: 'medium' }).format(timestamp);
+ } catch {
+ return pending.effectiveAt;
+ }
+ }, [pending.effectiveAt]);
+ const label =
+ pending.status === 'SCHEDULED'
+ ? t('billing.planChange.pendingDowngrade', {
+ name: targetName ?? t('billing.settings.subscriptionCard.unnamedPlan'),
+ date: effectiveDate,
+ })
+ : pending.status === 'AWAITING_PAYMENT'
+ ? t('billing.planChange.pendingPayment', {
+ name: targetName ?? t('billing.settings.subscriptionCard.unnamedPlan'),
+ })
+ : t('billing.planChange.pendingQuote', {
+ name: targetName ?? t('billing.settings.subscriptionCard.unnamedPlan'),
+ });
+ return (
+ <div className="flex items-center gap-4 border-t border-[var(--border-default)] bg-[var(--surface-chip)] px-5 py-3">
+ <p className="min-w-0 flex-1 text-12 leading-5 text-[var(--text-secondary)]">{label}</p>
+ {pending.status === 'SCHEDULED' ? (
+ <button
+ type="button"
+ onClick={onUndo}
+ className="h-8 shrink-0 rounded-full border border-[var(--border-default)] px-3.5 text-12 font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover-soft)]"
+ >
+ {t('billing.planChange.undo')}
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={onResume}
+ className="h-8 shrink-0 rounded-full border border-[var(--border-default)] px-3.5 text-12 font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover-soft)]"
+ >
+ {t('billing.planChange.resume')}
+ </button>
+ )}
+ </div>
+ );
+}
+
+function BillingUsageSummary({
+ usage,
+ balance,
+ issue,
+ loading,
+ detailsUnavailable,
+}: {
+ usage: ModelAccessCreditUsage | null;
+ balance: ModelAccessBalance | null;
+ issue: BalanceIssue;
+ loading: boolean;
+ detailsUnavailable: boolean;
+}) {
+ const { t } = useTranslation();
+ const currency = CURRENT_CINDY_REGION === 'global' ? 'usd' : 'cny';
+ const legacyPools = balance
+ ? [
+ { key: 'plan', label: t('billing.balance.plan'), amount: balance.planCredits },
+ {
+ key: 'purchased',
+ label: t('billing.balance.purchased'),
+ amount: balance.purchasedCredits,
+ },
+ {
+ key: 'promotional',
+ label: t('billing.balance.promotional'),
+ amount: balance.promotionalCredits,
+ },
+ ]
+ : [];
+ const usagePools = usage
+ ? [
+ { key: 'plan', label: t('billing.balance.plan'), pool: usage.plan },
+ { key: 'purchased', label: t('billing.balance.purchased'), pool: usage.purchased },
+ { key: 'promotional', label: t('billing.balance.promotional'), pool: usage.promotional },
+ ]
+ : [];
+ const issueDescription =
+ issue === 'NOT_PROVISIONED'
+ ? t('billing.balance.notProvisioned')
+ : issue === 'NOT_SUPPORTED'
+ ? t('billing.balance.notSupported')
+ : t('billing.balance.unavailable');
+
+ return (
+ <section
+ className="px-5 py-5"
+ aria-labelledby="billing-balance-title"
+ aria-live="polite"
+ aria-busy={loading}
+ >
+ {loading ? (
+ <div className="flex h-[118px] items-center px-5">
+ <Spinner size={15} />
+ </div>
+ ) : usage ? (
+ <>
+ <div className="px-5 py-5">
+ <p
+ id="billing-balance-title"
+ className="text-11 font-medium text-[var(--text-tertiary)]"
+ >
+ {t('billing.balance.title')}
+ </p>
+ <p className="mt-1 text-[28px] font-medium leading-9 tracking-[-0.03em] tabular-nums text-[var(--text-primary)]">
+ {formatMoney(usage.available, currency)}
+ </p>
+ <p className="mt-1 text-11 text-[var(--text-tertiary)]">
+ {t('billing.usage.observedAt', {
+ date: formatLedgerTimestamp(usage.observedAt),
+ })}
+ </p>
+ </div>
+ <div className="border-t border-[var(--border-default)] px-5 py-5">
+ <div className="grid grid-cols-1 gap-3 lg:grid-cols-3">
+ {usagePools.map(({ key, label, pool }) => (
+ <CreditPoolCard key={key} label={label} pool={pool} currency={currency} />
+ ))}
+ </div>
+ </div>
+ <PromotionalGrantLedger usage={usage} currency={currency} />
+ </>
+ ) : balance ? (
+ <div className="px-5 py-5">
+ <p id="billing-balance-title" className="text-11 font-medium text-[var(--text-tertiary)]">
+ {t('billing.balance.title')}
+ </p>
+ <p className="mt-1 text-[28px] font-medium leading-9 tracking-[-0.03em] tabular-nums text-[var(--text-primary)]">
+ {formatMoney(balance.available, currency)}
+ </p>
+ <div className="mt-4 grid grid-cols-3 divide-x divide-[var(--border-default)] rounded-xl bg-[var(--surface-chip)] px-1 py-2.5">
+ {legacyPools.map(({ key, label, amount }) => (
+ <div key={key} className="min-w-0 px-3">
+ <p className="truncate text-11 text-[var(--text-tertiary)]">{label}</p>
+ <p className="mt-1 truncate text-13 font-medium tabular-nums text-[var(--text-primary)]">
+ {formatMoney(amount, currency)}
+ </p>
+ </div>
+ ))}
+ </div>
+ {detailsUnavailable && (
+ <p className="mt-3 text-11 leading-4 text-[var(--text-secondary)]">
+ {t('billing.usage.detailsUnavailable')}
+ </p>
+ )}
+ </div>
+ ) : (
+ <div
+ role="status"
+ className="flex min-h-[118px] items-center px-5 text-12 leading-5 text-[var(--text-secondary)]"
+ >
+ {issueDescription}
+ </div>
+ )}
+ </section>
+ );
+}
+
+function CreditPoolCard({
+ label,
+ pool,
+ currency,
+}: {
+ label: string;
+ pool: ModelAccessCreditPoolUsage;
+ currency: string;
+}) {
+ const { t } = useTranslation();
+ const percent = usagePercent(pool);
+ const stats = [
+ { key: 'used', label: t('billing.usage.used'), amount: pool.used },
+ { key: 'total', label: t('billing.usage.total'), amount: pool.total },
+ { key: 'remaining', label: t('billing.usage.remaining'), amount: pool.remaining },
+ ];
+ return (
+ <article className="min-w-0 rounded-xl border border-[var(--border-default)] bg-[var(--surface)] p-4">
+ <p className="truncate text-12 font-medium text-[var(--text-primary)]">{label}</p>
+ <p className="mt-3 text-11 text-[var(--text-tertiary)]">{t('billing.usage.remaining')}</p>
+ <p className="mt-0.5 truncate text-lg font-medium tracking-[-0.02em] tabular-nums text-[var(--text-primary)]">
+ {formatMoney(pool.remaining, currency)}
+ </p>
+ <div
+ className="mt-3 h-1.5 overflow-hidden rounded-full bg-[var(--surface-chip)]"
+ role={percent === null ? undefined : 'progressbar'}
+ aria-label={t('billing.usage.progressLabel', { label })}
+ aria-valuemin={percent === null ? undefined : 0}
+ aria-valuemax={percent === null ? undefined : 100}
+ aria-valuenow={percent ?? undefined}
+ >
+ {percent !== null && (
+ <div
+ className="h-full rounded-full bg-[var(--text-primary)]"
+ style={{ width: `${percent}%` }}
+ />
+ )}
+ </div>
+ {percent === null ? (
+ <p className="mt-2 min-h-8 text-10 leading-4 text-[var(--text-tertiary)]">
+ {t('billing.usage.historyUnavailable')}
+ </p>
+ ) : (
+ <p className="mt-2 min-h-8 text-10 leading-4 text-[var(--text-tertiary)]">
+ {t('billing.usage.percentUsed', {
+ percent: new Intl.NumberFormat(undefined, {
+ maximumFractionDigits: 1,
+ }).format(percent),
+ })}
+ </p>
+ )}
+ <dl className="mt-3 grid grid-cols-3 gap-2 border-t border-[var(--border-default)] pt-3">
+ {stats.map(({ key, label: statLabel, amount }) => (
+ <div key={key} className="min-w-0">
+ <dt className="truncate text-10 text-[var(--text-tertiary)]">{statLabel}</dt>
+ <dd className="mt-0.5 truncate text-11 font-medium tabular-nums text-[var(--text-primary)]">
+ {amount === null ? '—' : formatMoney(amount, currency)}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ </article>
+ );
+}
+
+function PromotionalGrantLedger({
+ usage,
+ currency,
+}: {
+ usage: ModelAccessCreditUsage;
+ 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">
+ <div>
+ <h3 className="text-13 font-medium text-[var(--text-primary)]">
+ {t('billing.usage.promotionalDetails.title')}
+ </h3>
+ <p className="mt-1 max-w-[620px] text-11 leading-4 text-[var(--text-secondary)]">
+ {t('billing.usage.promotionalDetails.description')}
+ </p>
+ </div>
+ <span className="shrink-0 rounded-full bg-[var(--surface-chip)] px-2.5 py-1 text-10 font-medium text-[var(--text-secondary)]">
+ {t('billing.usage.promotionalDetails.count', {
+ count: usage.promotionalGrants.length,
+ })}
+ </span>
+ </div>
+
+ {!usage.promotionalGrantsComplete && (
+ <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.incomplete', {
+ count: usage.promotionalGrants.length,
+ })}
+ </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)]">
+ {t('billing.usage.promotionalDetails.empty')}
+ </p>
+ ) : (
+ <div
+ className="mt-4 max-h-[360px] overflow-y-auto rounded-xl border border-[var(--border-default)] [scrollbar-gutter:stable]"
+ role="list"
+ >
+ {usage.promotionalGrants.map((grant, index) => (
+ <div
+ key={grant.grantId}
+ role="listitem"
+ className={cn(
+ 'grid grid-cols-3 gap-x-3 gap-y-2 px-4 py-3 lg:grid-cols-[minmax(0,1.5fr)_repeat(3,minmax(80px,0.7fr))] lg:items-center',
+ index > 0 && 'border-t border-[var(--border-default)]',
+ )}
+ >
+ <div className="col-span-3 min-w-0 lg:col-span-1">
+ <div className="flex min-w-0 items-center gap-2">
+ <p className="truncate text-12 font-medium text-[var(--text-primary)]">
+ {grant.displayName ?? t('billing.usage.promotionalDetails.unnamed')}
+ </p>
+ <PromotionalGrantStatus state={grant.state} />
+ </div>
+ <p className="mt-1 truncate text-10 text-[var(--text-tertiary)]">
+ {t('billing.usage.promotionalDetails.expiresAt', {
+ date: formatLedgerTimestamp(grant.expiresAt),
+ })}
+ </p>
+ </div>
+ <GrantAmount
+ label={t('billing.usage.promotionalDetails.original')}
+ amount={grant.originalAmount}
+ currency={currency}
+ />
+ <GrantAmount
+ label={t('billing.usage.promotionalDetails.used')}
+ amount={grant.usedAmount}
+ currency={currency}
+ />
+ <GrantAmount
+ label={t('billing.usage.promotionalDetails.remaining')}
+ amount={grant.remainingAmount}
+ currency={currency}
+ />
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function PromotionalGrantStatus({ state }: { state: ModelAccessPromotionalGrantState }) {
+ const { t } = useTranslation();
+ return (
+ <span className="shrink-0 rounded-full bg-[var(--surface-chip)] px-2 py-0.5 text-10 text-[var(--text-secondary)]">
+ {t(`billing.usage.promotionalDetails.states.${state}`)}
+ </span>
+ );
+}
+
+function GrantAmount({
+ label,
+ amount,
+ currency,
+}: {
+ label: string;
+ amount: string | null;
+ 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)}
+ </p>
+ </div>
+ );
+}
+
+function BillingSummaryRow({
+ label,
+ title,
+ description,
+ loading = false,
+ disabled = false,
+ actionLabel,
+ onAction,
+}: {
+ label: string;
+ title: string;
+ description: string;
+ loading?: boolean;
+ disabled?: boolean;
+ actionLabel: string;
+ onAction: () => void;
+}) {
+ return (
+ <div className="flex min-h-[112px] items-center gap-6 px-5 py-4">
+ <div className="min-w-0 flex-1">
+ <p className="text-11 font-medium text-[var(--text-tertiary)]">{label}</p>
+ <p className="mt-1 text-sm font-medium text-[var(--text-primary)]">{title}</p>
+ <div className="mt-1 min-h-5 text-12 leading-5 text-[var(--text-secondary)]">
+ {loading ? <Spinner size={13} /> : description}
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={onAction}
+ disabled={disabled}
+ className="h-8 shrink-0 rounded-full border border-[var(--border-default)] px-4 text-12 font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover-soft)] disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ {actionLabel}
+ </button>
+ </div>
+ );
+}
+
+function BillingOfferDialog({
+ open,
+ kind,
+ offers,
+ loading,
+ catalogError,
+ selected,
+ selectedPurchaseOptionId,
+ customAmount,
+ amountError,
+ subscriptionPurchaseBlocked,
+ canCheckout,
+ onClose,
+ onRetry,
+ onSelectOffer,
+ onSelectPurchaseOption,
+ onCustomAmountChange,
+ onSubmit,
+}: {
+ open: boolean;
+ kind: PurchaseKind;
+ offers: PurchasableOffer[];
+ loading: boolean;
+ catalogError: boolean;
+ selected: PurchasableOffer | null;
+ selectedPurchaseOptionId: string | null;
+ customAmount: string;
+ amountError: string | null;
+ subscriptionPurchaseBlocked: boolean;
+ canCheckout: boolean;
+ onClose: () => void;
+ onRetry: () => void;
+ onSelectOffer: (offerCode: string) => void;
+ onSelectPurchaseOption: (optionId: string) => void;
+ onCustomAmountChange: (amount: string) => void;
+ onSubmit: () => void;
+}) {
+ const { t } = useTranslation();
+ const title =
+ kind === 'SUBSCRIPTION'
+ ? t('billing.dialogs.subscription.title')
+ : t('billing.dialogs.topup.title');
+ const description =
+ kind === 'SUBSCRIPTION'
+ ? t('billing.dialogs.subscription.description')
+ : t('billing.dialogs.topup.description');
+
+ return (
+ <Dialog.Root open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
+ <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-[9990] bg-[var(--overlay-modal)]" />
+ <Dialog.Content
+ className={cn(
+ 'fixed left-1/2 top-1/2 z-[9991] flex max-h-[min(720px,calc(100vh-48px))]',
+ 'w-[calc(100vw-48px)] max-w-[680px] -translate-x-1/2 -translate-y-1/2 flex-col',
+ 'overflow-hidden rounded-xl border border-[var(--border-default)]',
+ 'bg-[var(--surface-elevated)] text-[var(--text-primary)] focus:outline-none',
+ )}
+ >
+ <div className="flex items-start justify-between gap-4 px-6 pb-4 pt-5">
+ <div>
+ <Dialog.Title className="text-16 font-medium tracking-[-0.01em]">
+ {title}
+ </Dialog.Title>
+ <Dialog.Description className="mt-1.5 max-w-[520px] text-12 leading-5 text-[var(--text-secondary)]">
+ {description}
+ </Dialog.Description>
+ </div>
+ <Dialog.Close asChild>
+ <button
+ type="button"
+ className="grid size-8 shrink-0 place-items-center rounded-full text-[var(--text-tertiary)] transition-colors hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)]"
+ aria-label={t('billing.actions.close')}
+ >
+ <X size={16} />
+ </button>
+ </Dialog.Close>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto border-t border-[var(--border-default)] px-6 py-4 [scrollbar-gutter:stable]">
+ {loading ? (
+ <CatalogSkeleton />
+ ) : catalogError ? (
+ <StateCard
+ icon={<RefreshCcw size={22} />}
+ title={t('billing.catalog.errorTitle')}
+ description={t('billing.catalog.errorDescription')}
+ action={
+ <button
+ type="button"
+ onClick={onRetry}
+ className="mt-4 h-9 rounded-full border border-[var(--border-default)] px-4 text-12 font-medium hover:bg-[var(--surface-hover-soft)]"
+ >
+ {t('billing.actions.retry')}
+ </button>
+ }
+ />
+ ) : offers.length === 0 ? (
+ <StateCard
+ icon={<PackageOpen size={22} />}
+ title={t('billing.catalog.emptyTitle')}
+ description={t('billing.catalog.emptyDescription')}
+ />
+ ) : (
+ <>
+ <div className="space-y-2.5">
+ {offers.map(({ product, offer }) => {
+ const active = selected?.offer.code === offer.code;
+ return (
+ <button
+ key={offer.code}
+ type="button"
+ onClick={() => onSelectOffer(offer.code)}
+ aria-pressed={active}
+ className={cn(
+ 'group relative flex min-h-[88px] w-full items-center gap-5 rounded-xl border px-4 py-3.5 text-left',
+ 'transition-[background-color,border-color,box-shadow] focus-visible:outline-none',
+ 'focus-visible:ring-2 focus-visible:ring-[var(--text-primary)] focus-visible:ring-offset-2',
+ 'focus-visible:ring-offset-[var(--surface-elevated)]',
+ active
+ ? 'border-[var(--text-primary)] bg-[var(--surface)] shadow-[inset_3px_0_0_var(--text-primary)]'
+ : 'border-[var(--border-default)] hover:bg-[var(--surface-hover-soft)]',
+ )}
+ >
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium text-[var(--text-primary)]">
+ {product.name}
+ </p>
+ <p className="mt-1 text-11 text-[var(--text-tertiary)]">
+ {kind === 'SUBSCRIPTION'
+ ? t('billing.offerKinds.subscription')
+ : t('billing.offerKinds.topup')}
+ </p>
+ </div>
+ <div className="flex shrink-0 items-center gap-4">
+ <div className="text-right">
+ <p className="text-lg font-medium tracking-[-0.02em]">
+ {offer.amount
+ ? formatMoney(offer.amount, offer.currency)
+ : t('billing.amount.custom')}
+ {offer.interval && (
+ <span className="ml-1 text-11 font-normal text-[var(--text-tertiary)]">
+ / {t(`billing.intervals.${offer.interval}`)}
+ </span>
+ )}
+ </p>
+ {offer.creditAmount && (
+ <p className="mt-1 text-11 text-[var(--text-secondary)]">
+ {t('billing.credits', { amount: offer.creditAmount })}
+ </p>
+ )}
+ </div>
+ <SelectionMark active={active} />
+ </div>
+ </button>
+ );
+ })}
+ </div>
+
+ {selected && (
+ <div className="mt-5 border-t border-[var(--border-default)] pt-4">
+ <h3 className="text-13 font-medium">{t('billing.steps.channel.title')}</h3>
+ <p className="mt-1 text-12 text-[var(--text-secondary)]">
+ {t('billing.steps.channel.description')}
+ </p>
+ <div className="mt-3 space-y-2">
+ {selected.purchaseOptions.map((option) => (
+ <PaymentOptionCard
+ key={option.id}
+ option={option}
+ active={selectedPurchaseOptionId === option.id}
+ onSelect={() => onSelectPurchaseOption(option.id)}
+ />
+ ))}
+ </div>
+
+ {kind === 'CREDIT_TOPUP' && isCustomTopup(selected.offer) && (
+ <label className="mt-5 block">
+ <span className="text-12 font-medium text-[var(--text-secondary)]">
+ {t('billing.amount.label')}
+ </span>
+ <div className="mt-2 flex h-11 items-center rounded-xl border border-[var(--border-default)] bg-[var(--surface)] px-4 focus-within:border-[var(--text-primary)]">
+ <span className="mr-2 text-sm text-[var(--text-tertiary)]">
+ {selected.offer.currency.toUpperCase()}
+ </span>
+ <input
+ value={customAmount}
+ onChange={(event) => onCustomAmountChange(event.target.value)}
+ inputMode="decimal"
+ placeholder={t('billing.amount.placeholder')}
+ className="min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-[var(--text-tertiary)]"
+ />
+ </div>
+ <p
+ className={cn(
+ 'mt-2 text-11',
+ amountError
+ ? 'text-[var(--text-primary)]'
+ : 'text-[var(--text-tertiary)]',
+ )}
+ >
+ {amountError ??
+ t('billing.amount.rangeHint', {
+ min: formatMoney(selected.offer.minAmount!, selected.offer.currency),
+ max: formatMoney(selected.offer.maxAmount!, selected.offer.currency),
+ })}
+ </p>
+ </label>
+ )}
+
+ {kind === 'SUBSCRIPTION' && subscriptionPurchaseBlocked && (
+ <p className="mt-5 rounded-lg bg-[var(--surface-chip)] px-4 py-3 text-12 leading-5 text-[var(--text-secondary)]">
+ {t('billing.currentSubscription.purchaseBlocked')}
+ </p>
+ )}
+ </div>
+ )}
+ </>
+ )}
+ </div>
+
+ <div className="flex min-h-16 items-center justify-between gap-4 border-t border-[var(--border-default)] px-6 py-3">
+ <div className="flex min-w-0 max-w-[380px] items-start gap-2 text-11 leading-4 text-[var(--text-tertiary)]">
+ <ShieldCheck size={13} className="shrink-0" />
+ <span>{t('billing.securityNotice')}</span>
+ </div>
+ <button
+ type="button"
+ onClick={onSubmit}
+ disabled={!canCheckout}
+ className="inline-flex h-9 shrink-0 items-center gap-2 rounded-full bg-[var(--text-primary)] px-5 text-13 font-medium text-[var(--surface)] transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--text-primary)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface-elevated)] disabled:cursor-not-allowed disabled:opacity-35"
+ >
+ {t('billing.actions.pay')}
+ <ArrowRight size={15} />
+ </button>
+ </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
+
+function CatalogSkeleton() {
+ return (
+ <div className="space-y-2.5" aria-hidden>
+ {[0, 1, 2].map((item) => (
+ <div
+ key={item}
+ className="h-[88px] animate-pulse rounded-xl border border-[var(--border-default)] bg-[var(--surface-chip)] motion-reduce:animate-none"
+ />
+ ))}
+ </div>
+ );
+}
+
+function StateCard({
+ icon,
+ title,
+ description,
+ action,
+}: {
+ icon: React.ReactNode;
+ title: string;
+ description: string;
+ action?: React.ReactNode;
+}) {
+ return (
+ <div className="flex min-h-[184px] flex-col items-center justify-center rounded-xl border border-[var(--border-default)] px-6 text-center">
+ <div className="grid size-11 place-items-center rounded-full bg-[var(--surface-chip)]">
+ {icon}
+ </div>
+ <p className="mt-4 text-sm font-medium">{title}</p>
+ <p className="mt-1 text-12 text-[var(--text-secondary)]">{description}</p>
+ {action}
+ </div>
+ );
+}
+
+function PaymentOptionCard({
+ option,
+ active,
+ onSelect,
+}: {
+ option: SupportedPurchaseOption;
+ active: boolean;
+ onSelect: () => void;
+}) {
+ const { t } = useTranslation();
+ const Icon = option.paymentAction === 'QR_CODE' ? CircleDollarSign : CreditCard;
+ return (
+ <button
+ type="button"
+ onClick={onSelect}
+ aria-pressed={active}
+ className={cn(
+ 'flex min-h-[64px] w-full items-center gap-3 rounded-xl border px-3.5 py-2.5 text-left',
+ 'transition-colors focus-visible:outline-none focus-visible:ring-2',
+ 'focus-visible:ring-[var(--text-primary)] focus-visible:ring-offset-2',
+ 'focus-visible:ring-offset-[var(--surface-elevated)]',
+ active
+ ? 'border-[var(--text-primary)] bg-[var(--surface)]'
+ : 'border-[var(--border-default)] hover:bg-[var(--surface-hover-soft)]',
+ )}
+ >
+ <div className="grid size-9 shrink-0 place-items-center rounded-full bg-[var(--surface-chip)]">
+ <Icon size={16} />
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium">{providerLabel(option.provider, t)}</p>
+ <p className="mt-1 text-11 text-[var(--text-tertiary)]">
+ {option.paymentAction === 'QR_CODE'
+ ? t('billing.paymentActions.QR_CODE')
+ : t('billing.paymentActions.REDIRECT')}
+ </p>
+ </div>
+ <SelectionMark active={active} />
+ </button>
+ );
+}
+
+function SelectionMark({ active }: { active: boolean }) {
+ return (
+ <span
+ className={cn(
+ 'grid size-5 shrink-0 place-items-center rounded-full border',
+ active
+ ? 'border-[var(--text-primary)] bg-[var(--text-primary)] text-[var(--surface)]'
+ : 'border-[var(--border-default)]',
+ )}
+ >
+ {active && <Check size={12} strokeWidth={2.5} />}
+ </span>
+ );
+}
+
+function providerLabel(
+ provider: SupportedBillingProvider,
+ t: ReturnType<typeof useTranslation>['t'],
+): string {
+ return t(`billing.providers.${provider}`);
+}
diff --git a/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx b/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx
new file mode 100644
index 0000000000..3acc4f6433
--- /dev/null
+++ b/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx
@@ -0,0 +1,502 @@
+import { useEffect, useMemo, useState } from 'react';
+import * as Dialog from '@radix-ui/react-dialog';
+import * as QRCode from 'qrcode';
+import {
+ ArrowDownRight,
+ ArrowUpRight,
+ Check,
+ CircleAlert,
+ ExternalLink,
+ LoaderCircle,
+ PackageOpen,
+ RotateCcw,
+ X,
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Spinner } from '@/components/ui/spinner';
+import { cn } from '@/lib/utils';
+import type {
+ BillingCatalogOffer,
+ BillingCatalogProduct,
+ BillingPaymentAction,
+} from '../../../shared/billing';
+import { billingApi } from './api';
+import {
+ formatBillingAmount as formatMoney,
+ formatBillingMinorAmount as formatPlanChangeMinorAmount,
+} from './money';
+import type { PlanChangeState } from './usePlanChange';
+
+export type PlanChangeCandidate = {
+ product: BillingCatalogProduct;
+ offer: BillingCatalogOffer;
+ /** UI hint only; the server quote is the authority on the change type. */
+ direction: 'UPGRADE' | 'DOWNGRADE';
+};
+
+function formatEffectiveDate(iso: string): string {
+ const timestamp = Date.parse(iso);
+ if (!Number.isFinite(timestamp)) return iso;
+ try {
+ return new Intl.DateTimeFormat(undefined, {
+ dateStyle: 'medium',
+ timeStyle: 'short',
+ }).format(timestamp);
+ } catch {
+ return iso;
+ }
+}
+
+export function PlanChangeTargetDialog({
+ open,
+ candidates,
+ currentPlanName,
+ onClose,
+ onSelect,
+}: {
+ open: boolean;
+ candidates: PlanChangeCandidate[];
+ currentPlanName: string | null;
+ onClose: () => void;
+ onSelect: (candidate: PlanChangeCandidate) => void;
+}) {
+ const { t } = useTranslation();
+ return (
+ <Dialog.Root open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
+ <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-[9990] bg-[var(--overlay-modal)]" />
+ <Dialog.Content
+ className={cn(
+ 'fixed left-1/2 top-1/2 z-[9991] flex max-h-[min(640px,calc(100vh-48px))]',
+ 'w-[calc(100vw-48px)] max-w-[640px] -translate-x-1/2 -translate-y-1/2 flex-col',
+ 'overflow-hidden rounded-xl border border-[var(--border-default)]',
+ 'bg-[var(--surface-elevated)] text-[var(--text-primary)] focus:outline-none',
+ )}
+ >
+ <div className="flex items-start justify-between gap-4 px-6 pb-4 pt-5">
+ <div>
+ <Dialog.Title className="text-16 font-medium tracking-[-0.01em]">
+ {t('billing.planChange.targetTitle')}
+ </Dialog.Title>
+ <Dialog.Description className="mt-1.5 max-w-[500px] text-12 leading-5 text-[var(--text-secondary)]">
+ {currentPlanName
+ ? t('billing.planChange.targetDescriptionWithCurrent', {
+ plan: currentPlanName,
+ })
+ : t('billing.planChange.targetDescription')}
+ </Dialog.Description>
+ </div>
+ <Dialog.Close asChild>
+ <button
+ type="button"
+ className="grid size-8 shrink-0 place-items-center rounded-full text-[var(--text-tertiary)] transition-colors hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)]"
+ aria-label={t('billing.actions.close')}
+ >
+ <X size={16} />
+ </button>
+ </Dialog.Close>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto border-t border-[var(--border-default)] px-6 py-4 [scrollbar-gutter:stable]">
+ {candidates.length === 0 ? (
+ <div className="flex min-h-[184px] flex-col items-center justify-center rounded-xl border border-[var(--border-default)] px-6 text-center">
+ <div className="grid size-11 place-items-center rounded-full bg-[var(--surface-chip)]">
+ <PackageOpen size={22} />
+ </div>
+ <p className="mt-4 text-sm font-medium">{t('billing.planChange.emptyTitle')}</p>
+ <p className="mt-1 text-12 text-[var(--text-secondary)]">
+ {t('billing.planChange.emptyDescription')}
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-2.5">
+ {candidates.map((candidate) => {
+ const DirectionIcon =
+ candidate.direction === 'UPGRADE' ? ArrowUpRight : ArrowDownRight;
+ return (
+ <button
+ key={candidate.offer.code}
+ type="button"
+ onClick={() => onSelect(candidate)}
+ className={cn(
+ 'group relative flex min-h-[84px] w-full items-center gap-5 rounded-xl border px-4 py-3.5 text-left',
+ 'border-[var(--border-default)] transition-colors hover:bg-[var(--surface-hover-soft)]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--text-primary)]',
+ 'focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface-elevated)]',
+ )}
+ >
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium text-[var(--text-primary)]">
+ {candidate.product.name}
+ </p>
+ <p className="mt-1 inline-flex items-center gap-1 text-11 text-[var(--text-tertiary)]">
+ <DirectionIcon size={12} />
+ {candidate.direction === 'UPGRADE'
+ ? t('billing.planChange.upgradeBadge')
+ : t('billing.planChange.downgradeBadge')}
+ </p>
+ </div>
+ <div className="shrink-0 text-right">
+ <p className="text-lg font-medium tracking-[-0.02em]">
+ {candidate.offer.amount
+ ? formatMoney(candidate.offer.amount, candidate.offer.currency)
+ : '—'}
+ {candidate.offer.interval && (
+ <span className="ml-1 text-11 font-normal text-[var(--text-tertiary)]">
+ / {t(`billing.intervals.${candidate.offer.interval}`)}
+ </span>
+ )}
+ </p>
+ {candidate.offer.creditAmount && (
+ <p className="mt-1 text-11 text-[var(--text-secondary)]">
+ {t('billing.credits', { amount: candidate.offer.creditAmount })}
+ </p>
+ )}
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
+
+function useCountdownSeconds(expiresAt: string | null): number | null {
+ const [remainingSeconds, setRemainingSeconds] = useState<number | null>(null);
+ useEffect(() => {
+ if (!expiresAt) {
+ setRemainingSeconds(null);
+ return;
+ }
+ const update = () => {
+ setRemainingSeconds(Math.max(0, Math.ceil((Date.parse(expiresAt) - Date.now()) / 1000)));
+ };
+ update();
+ const timer = window.setInterval(update, 1_000);
+ return () => window.clearInterval(timer);
+ }, [expiresAt]);
+ return remainingSeconds;
+}
+
+export function PlanChangeStatusDialog({
+ state,
+ targetName,
+ onClose,
+ onConfirm,
+ onRefresh,
+ onAbandon,
+}: {
+ state: PlanChangeState;
+ targetName: string | null;
+ onClose: () => void;
+ onConfirm: () => void;
+ onRefresh: () => void;
+ onAbandon: () => void;
+}) {
+ const { t } = useTranslation();
+ const change = state.planChange;
+ const action: BillingPaymentAction | null = change?.paymentAction ?? null;
+ const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);
+ const actionSeconds = useCountdownSeconds(
+ state.phase === 'AWAITING_PAYMENT' ? (action?.expiresAt ?? null) : null,
+ );
+ const quoteSeconds = useCountdownSeconds(
+ state.phase === 'QUOTE_READY' ? (change?.quoteExpiresAt ?? null) : null,
+ );
+
+ useEffect(() => {
+ let active = true;
+ setQrDataUrl(null);
+ if (action?.type === 'QR_CODE') {
+ void QRCode.toDataURL(action.value, { width: 1024, margin: 4 })
+ .then((dataUrl) => {
+ if (active) setQrDataUrl(dataUrl);
+ })
+ .catch(() => {
+ if (active) setQrDataUrl(null);
+ });
+ }
+ return () => {
+ active = false;
+ };
+ }, [action]);
+
+ const busy = state.phase === 'QUOTING' || state.phase === 'CONFIRMING';
+ const title = useMemo(() => {
+ switch (state.phase) {
+ case 'QUOTING':
+ return t('billing.planChange.quotingTitle');
+ case 'QUOTE_READY':
+ return t('billing.planChange.quoteTitle');
+ case 'CONFIRMING':
+ return t('billing.planChange.confirmingTitle');
+ case 'PENDING_PROVIDER':
+ return t('billing.planChange.pendingProviderTitle');
+ case 'AWAITING_PAYMENT':
+ return t('billing.planChange.awaitingTitle');
+ case 'SCHEDULED':
+ return t('billing.planChange.scheduledTitle');
+ case 'APPLIED':
+ return t('billing.planChange.appliedTitle');
+ case 'CANCELED':
+ return t('billing.planChange.canceledTitle');
+ case 'EXPIRED':
+ return t('billing.planChange.expiredTitle');
+ default:
+ return t('billing.planChange.failedTitle');
+ }
+ }, [state.phase, t]);
+
+ const isUpgrade = change?.changeType === 'UPGRADE';
+ const quotedAmount =
+ change && change.quotedAmountMinor !== null && change.quotedCurrency
+ ? formatPlanChangeMinorAmount(change.quotedAmountMinor, change.quotedCurrency)
+ : null;
+ const settled =
+ state.phase === 'SCHEDULED' ||
+ state.phase === 'APPLIED' ||
+ state.phase === 'CANCELED' ||
+ state.phase === 'FAILED' ||
+ state.phase === 'EXPIRED';
+
+ return (
+ <Dialog.Root open={state.open} onOpenChange={(open) => !open && !busy && onClose()}>
+ <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-[10000] bg-[var(--overlay-modal)]" />
+ <Dialog.Content
+ className={cn(
+ 'fixed left-1/2 top-1/2 z-[10001] w-[calc(100vw-40px)] max-w-[600px]',
+ '-translate-x-1/2 -translate-y-1/2 overflow-hidden rounded-xl',
+ 'border border-[var(--border-default)] bg-[var(--surface-elevated)]',
+ 'text-[var(--text-primary)] focus:outline-none',
+ )}
+ aria-describedby={undefined}
+ >
+ <div className="flex items-start justify-between gap-4 border-b border-[var(--border-default)] px-6 py-5">
+ <div>
+ <Dialog.Title className="text-lg font-medium">{title}</Dialog.Title>
+ {targetName && (
+ <p className="mt-1 text-12 leading-5 text-[var(--text-secondary)]">
+ {t('billing.planChange.targetLabel', { name: targetName })}
+ </p>
+ )}
+ </div>
+ {!busy && (
+ <Dialog.Close asChild>
+ <button
+ type="button"
+ className="grid size-8 shrink-0 place-items-center rounded-full text-[var(--text-tertiary)] transition-colors hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)]"
+ aria-label={t('billing.actions.close')}
+ >
+ <X size={16} />
+ </button>
+ </Dialog.Close>
+ )}
+ </div>
+
+ <div className="flex min-h-[260px] flex-col items-center justify-center px-6 py-7 text-center">
+ {busy && (
+ <>
+ <Spinner icon={LoaderCircle} size={28} className="text-[var(--text-secondary)]" />
+ <p className="mt-4 text-sm text-[var(--text-secondary)]">
+ {state.phase === 'QUOTING'
+ ? t('billing.planChange.quotingBody')
+ : t('billing.planChange.confirmingBody')}
+ </p>
+ </>
+ )}
+
+ {state.phase === 'PENDING_PROVIDER' && (
+ <>
+ <Spinner icon={LoaderCircle} size={28} className="text-[var(--text-secondary)]" />
+ <p className="mt-4 max-w-[400px] text-sm text-[var(--text-secondary)]">
+ {t('billing.planChange.pendingProviderBody')}
+ </p>
+ </>
+ )}
+
+ {state.phase === 'QUOTE_READY' && change && (
+ <>
+ <p className="text-sm font-medium">
+ {isUpgrade
+ ? quotedAmount
+ ? t('billing.planChange.upgradeDueNow', { amount: quotedAmount })
+ : t('billing.planChange.upgradeNoAmount')
+ : t('billing.planChange.downgradeAt', {
+ date: formatEffectiveDate(change.effectiveAt),
+ })}
+ </p>
+ <p className="mt-2 max-w-[400px] text-12 leading-5 text-[var(--text-secondary)]">
+ {isUpgrade
+ ? t('billing.planChange.upgradeHint')
+ : t('billing.planChange.downgradeHint')}
+ </p>
+ {quoteSeconds !== null && (
+ <p className="mt-3 text-11 text-[var(--text-tertiary)]">
+ {t('billing.planChange.quoteExpiresIn', {
+ minutes: Math.floor(quoteSeconds / 60),
+ seconds: String(quoteSeconds % 60).padStart(2, '0'),
+ })}
+ </p>
+ )}
+ {state.error && (
+ <p className="mt-3 text-12 text-[var(--text-primary)]">
+ {state.stale
+ ? t('billing.planChange.resyncHint')
+ : t('billing.planChange.requestFailed')}
+ </p>
+ )}
+ </>
+ )}
+
+ {state.phase === 'AWAITING_PAYMENT' && action?.type === 'QR_CODE' && (
+ <>
+ <div
+ className="grid place-items-center rounded-xl border border-[var(--border-default)] bg-white p-2"
+ style={{
+ width: 'min(440px, calc(100vw - 96px), calc(100vh - 280px))',
+ height: 'min(440px, calc(100vw - 96px), calc(100vh - 280px))',
+ }}
+ >
+ {qrDataUrl ? (
+ <img src={qrDataUrl} className="size-full" alt={t('billing.checkout.qrAlt')} />
+ ) : (
+ <Spinner size={24} className="text-[var(--text-secondary)]" />
+ )}
+ </div>
+ <p className="mt-4 text-sm font-medium">
+ {quotedAmount
+ ? t('billing.planChange.scanToPay', { amount: quotedAmount })
+ : t('billing.checkout.scanHint')}
+ </p>
+ <p className="mt-1 text-12 text-[var(--text-tertiary)]">
+ {actionSeconds === null
+ ? t('billing.checkout.checkingExpiry')
+ : t('billing.checkout.expiresIn', {
+ minutes: Math.floor(actionSeconds / 60),
+ seconds: String(actionSeconds % 60).padStart(2, '0'),
+ })}
+ </p>
+ </>
+ )}
+
+ {state.phase === 'AWAITING_PAYMENT' && action?.type === 'REDIRECT' && (
+ <>
+ <div className="grid size-14 place-items-center rounded-full bg-[var(--surface-chip)]">
+ <ExternalLink size={22} />
+ </div>
+ <p className="mt-4 text-sm font-medium">{t('billing.checkout.redirectHint')}</p>
+ <button
+ type="button"
+ onClick={() => void billingApi.openPaymentRedirect(action.url)}
+ className="mt-5 inline-flex h-9 items-center gap-2 rounded-full bg-[var(--text-primary)] px-5 text-sm font-medium text-[var(--surface)]"
+ >
+ <ExternalLink size={14} />
+ {t('billing.checkout.openPayment')}
+ </button>
+ </>
+ )}
+
+ {state.phase === 'AWAITING_PAYMENT' && !action && (
+ <>
+ <Spinner size={26} className="text-[var(--text-secondary)]" />
+ <p className="mt-4 text-sm text-[var(--text-secondary)]">
+ {t('billing.checkout.refreshingAction')}
+ </p>
+ </>
+ )}
+
+ {(state.phase === 'SCHEDULED' || state.phase === 'APPLIED') && (
+ <>
+ <div className="grid size-14 place-items-center rounded-full bg-[var(--text-primary)] text-[var(--surface)]">
+ <Check size={24} />
+ </div>
+ <p className="mt-4 text-sm font-medium">
+ {state.phase === 'APPLIED'
+ ? t('billing.planChange.appliedBody')
+ : change
+ ? t('billing.planChange.scheduledBody', {
+ date: formatEffectiveDate(change.effectiveAt),
+ })
+ : t('billing.planChange.scheduledTitle')}
+ </p>
+ </>
+ )}
+
+ {(state.phase === 'FAILED' ||
+ state.phase === 'CANCELED' ||
+ state.phase === 'EXPIRED') && (
+ <>
+ <div className="grid size-14 place-items-center rounded-full bg-[var(--surface-chip)]">
+ <CircleAlert size={23} />
+ </div>
+ <p className="mt-4 max-w-[340px] text-sm text-[var(--text-secondary)]">
+ {state.error
+ ? t('billing.planChange.requestFailed')
+ : state.phase === 'CANCELED'
+ ? t('billing.planChange.canceledBody')
+ : state.phase === 'EXPIRED'
+ ? t('billing.planChange.expiredBody')
+ : t('billing.planChange.failedBody')}
+ </p>
+ </>
+ )}
+ </div>
+
+ <div className="flex min-h-16 items-center justify-between gap-3 border-t border-[var(--border-default)] px-6 py-3">
+ <div>
+ {state.phase === 'QUOTE_READY' && change?.status === 'QUOTED' && !state.stale && (
+ <button
+ type="button"
+ onClick={onAbandon}
+ className="h-9 rounded-full px-3 text-12 text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-hover-soft)]"
+ >
+ {t('billing.planChange.abandon')}
+ </button>
+ )}
+ </div>
+ <div className="flex items-center gap-2">
+ {(state.phase === 'AWAITING_PAYMENT' ||
+ state.phase === 'PENDING_PROVIDER' ||
+ (state.phase === 'QUOTE_READY' && state.stale)) && (
+ <button
+ type="button"
+ onClick={onRefresh}
+ className="inline-flex h-9 items-center gap-2 rounded-full border border-[var(--border-default)] px-4 text-12 font-medium transition-colors hover:bg-[var(--surface-hover-soft)]"
+ >
+ <RotateCcw size={14} />
+ {t('billing.actions.refresh')}
+ </button>
+ )}
+ {/* A stale snapshot must never be confirmable; the refresh action
+ above (plus background polling) re-reads the server first. */}
+ {state.phase === 'QUOTE_READY' && change?.status === 'QUOTED' && !state.stale && (
+ <button
+ type="button"
+ onClick={onConfirm}
+ className="inline-flex h-9 items-center gap-2 rounded-full bg-[var(--text-primary)] px-5 text-13 font-medium text-[var(--surface)]"
+ >
+ {t('billing.planChange.confirm')}
+ </button>
+ )}
+ {settled && (
+ <button
+ type="button"
+ onClick={onClose}
+ className="h-9 rounded-full border border-[var(--border-default)] px-4 text-12 font-medium transition-colors hover:bg-[var(--surface-hover-soft)]"
+ >
+ {t('billing.actions.close')}
+ </button>
+ )}
+ </div>
+ </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
new file mode 100644
index 0000000000..5cc84f22dc
--- /dev/null
+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
@@ -0,0 +1,981 @@
+// @vitest-environment jsdom
+
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const checkout = {
+ state: {
+ open: false,
+ kind: null,
+ phase: 'IDLE',
+ intent: null,
+ order: null,
+ subscription: null,
+ error: false,
+ },
+ recoverables: { topups: [], subscription: null },
+ recovering: false,
+ startTopup: vi.fn(),
+ startSubscription: vi.fn(),
+ refreshActive: vi.fn(),
+ retry: vi.fn(),
+ cancel: vi.fn(),
+ close: vi.fn(),
+ resumeTopup: vi.fn(),
+ resumeSubscription: vi.fn(),
+};
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, params?: Record<string, string>) => {
+ const providerLabels: Record<string, string> = {
+ 'billing.providers.alipay': 'alipay',
+ 'billing.providers.stripe': 'stripe',
+ };
+ if (providerLabels[key]) return providerLabels[key];
+ return params ? `${key}:${JSON.stringify(params)}` : key;
+ },
+ }),
+}));
+vi.mock('@/features/feature-context', () => ({
+ useRegisterSidebarUpper: vi.fn(),
+ useRegisterContentHeader: vi.fn(),
+}));
+vi.mock('@/contexts/AuthContext', () => ({
+ useAuth: () => ({ dataOwnerId: 'account-fixture' }),
+}));
+vi.mock('../useBillingCheckout', () => ({
+ useBillingCheckout: () => checkout,
+}));
+vi.mock('qrcode', () => ({
+ toDataURL: vi.fn(async () => 'data:image/png;base64,fixture'),
+}));
+
+import { BillingPage } from '../BillingPage';
+
+describe('BillingPage remote catalog rendering', () => {
+ beforeEach(() => {
+ Object.assign(checkout.state, {
+ open: false,
+ kind: null,
+ phase: 'IDLE',
+ intent: null,
+ order: null,
+ subscription: null,
+ error: false,
+ });
+ checkout.startTopup.mockClear();
+ checkout.startSubscription.mockClear();
+ checkout.close.mockClear();
+ checkout.recovering = false;
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ billing: {
+ getBalance: vi.fn(async () => ({
+ planCredits: '7.000000001',
+ purchasedCredits: '5.000000002',
+ promotionalCredits: '0.345678898',
+ available: '12.345678901',
+ scale: 9 as const,
+ observedAt: '2026-07-23T12:00:00.000Z',
+ })),
+ getCatalog: vi.fn(async () => ({
+ products: [
+ {
+ code: 'credit_topup',
+ name: 'Configured top-up',
+ kind: 'CREDIT_TOPUP',
+ level: null,
+ sortOrder: 1,
+ offers: [
+ {
+ code: 'credit_topup_custom',
+ interval: null,
+ currency: 'cny',
+ amount: null,
+ minAmount: '1',
+ maxAmount: '100',
+ creditAmount: null,
+ rolloverCap: null,
+ purchaseOptions: [
+ {
+ id: 'listing_alipay',
+ provider: 'alipay',
+ capability: 'ONE_TIME_PAYMENT',
+ paymentAction: 'QR_CODE',
+ },
+ {
+ id: 'listing_unknown',
+ provider: 'unknown_provider',
+ capability: 'ONE_TIME_PAYMENT',
+ paymentAction: 'REDIRECT',
+ },
+ ],
+ },
+ ],
+ },
+ {
+ code: 'plus',
+ name: 'Configured subscription',
+ kind: 'SUBSCRIPTION',
+ level: 1,
+ sortOrder: 2,
+ offers: [
+ {
+ code: 'plus_month',
+ interval: 'MONTH',
+ currency: 'usd',
+ amount: '9',
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: '100',
+ rolloverCap: '0',
+ purchaseOptions: [
+ {
+ id: 'listing_stripe',
+ provider: 'stripe',
+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION',
+ paymentAction: 'REDIRECT',
+ },
+ ],
+ },
+ ],
+ },
+ {
+ code: 'unknown_provider_only',
+ name: 'Unknown-provider offer',
+ kind: 'CREDIT_TOPUP',
+ level: null,
+ sortOrder: 3,
+ offers: [
+ {
+ code: 'unknown_provider_offer',
+ interval: null,
+ currency: 'cny',
+ amount: '10',
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: '10',
+ rolloverCap: null,
+ purchaseOptions: [
+ {
+ id: 'listing_unknown_only',
+ provider: 'unknown_provider',
+ capability: 'ONE_TIME_PAYMENT',
+ paymentAction: 'REDIRECT',
+ },
+ ],
+ },
+ ],
+ },
+ {
+ code: 'hidden',
+ name: 'Unconfigured offer',
+ kind: 'CREDIT_TOPUP',
+ level: null,
+ sortOrder: 4,
+ offers: [
+ {
+ code: 'hidden_offer',
+ interval: null,
+ currency: 'cny',
+ amount: '10',
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: '10',
+ rolloverCap: null,
+ purchaseOptions: [],
+ },
+ ],
+ },
+ {
+ code: 'legacy',
+ name: 'Legacy offer without channel projection',
+ kind: 'CREDIT_TOPUP',
+ level: null,
+ sortOrder: 5,
+ offers: [
+ {
+ code: 'legacy_offer',
+ interval: null,
+ currency: 'cny',
+ amount: '20',
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: '20',
+ rolloverCap: null,
+ },
+ ],
+ },
+ {
+ code: 'unsupported_action',
+ name: 'Unsupported payment action',
+ kind: 'CREDIT_TOPUP',
+ level: null,
+ sortOrder: 6,
+ offers: [
+ {
+ code: 'unsupported_action_offer',
+ interval: null,
+ currency: 'cny',
+ amount: '10',
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: '10',
+ rolloverCap: null,
+ purchaseOptions: [
+ {
+ id: 'listing_future_action',
+ provider: 'alipay',
+ capability: 'ONE_TIME_PAYMENT',
+ paymentAction: 'FUTURE_ACTION' as never,
+ },
+ ],
+ },
+ ],
+ },
+ {
+ code: 'unsupported_capability',
+ name: 'Unsupported payment capability',
+ kind: 'CREDIT_TOPUP',
+ level: null,
+ sortOrder: 7,
+ offers: [
+ {
+ code: 'unsupported_capability_offer',
+ interval: null,
+ currency: 'cny',
+ amount: '10',
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: '10',
+ rolloverCap: null,
+ purchaseOptions: [
+ {
+ id: 'listing_wrong_capability',
+ provider: 'stripe',
+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION',
+ paymentAction: 'REDIRECT',
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ })),
+ getCurrentSubscription: vi.fn(async () => ({ subscription: null })),
+ },
+ openExternal: vi.fn(),
+ },
+ });
+ });
+
+ it('shows the server ledger total and all three balance pools', async () => {
+ render(<BillingPage />);
+
+ expect(await screen.findByText('billing.balance.plan')).toBeTruthy();
+ expect(screen.getByText('billing.balance.purchased')).toBeTruthy();
+ expect(screen.getByText('billing.balance.promotional')).toBeTruthy();
+ expect(
+ screen.getByText(
+ new Intl.NumberFormat(undefined, { style: 'currency', currency: 'CNY' }).format(
+ 12.345678901,
+ ),
+ ),
+ ).toBeTruthy();
+ expect(screen.getByText('billing.usage.detailsUnavailable')).toBeTruthy();
+ });
+
+ it('shows usage progress and each promotional grant with its own state and expiry', async () => {
+ window.electronAPI.billing.getCreditUsage = vi.fn(async () => ({
+ available: '66',
+ plan: { remaining: '40', used: '60', total: '100' },
+ purchased: { remaining: '20', used: '30', total: '50' },
+ promotional: { remaining: '6', used: '4', total: '10' },
+ promotionalGrants: [
+ {
+ grantId: 'welcome',
+ displayName: 'Welcome grant',
+ originalAmount: '10',
+ usedAmount: '4',
+ remainingAmount: '6',
+ expiresAt: '2026-08-01T00:00:00Z',
+ state: 'active' as const,
+ },
+ {
+ grantId: 'expired',
+ displayName: null,
+ originalAmount: '5',
+ usedAmount: null,
+ remainingAmount: '0',
+ expiresAt: '2026-07-01T00:00:00Z',
+ state: 'expired' as const,
+ },
+ ],
+ promotionalGrantsComplete: true,
+ promotionalGrantConsistency: 'LAST_SETTLED' as const,
+ ledgerUpdatedAt: '2026-07-23T12:00:00Z',
+ scale: 9 as const,
+ observedAt: '2026-07-23T12:00:00Z',
+ }));
+
+ render(<BillingPage />);
+
+ 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.expired')).toBeTruthy();
+ expect(
+ screen.getByText('billing.usage.promotionalDetails.historicalUsageUnavailable'),
+ ).toBeTruthy();
+ expect(screen.getAllByRole('progressbar')).toHaveLength(3);
+ expect(window.electronAPI.billing.getBalance).not.toHaveBeenCalled();
+ });
+
+ it('refreshes the balance once when a checkout becomes completed', async () => {
+ const getBalance = window.electronAPI.billing.getBalance;
+ const view = render(<BillingPage />);
+ await waitFor(() => expect(getBalance).toHaveBeenCalledTimes(1));
+
+ Object.assign(checkout.state, { phase: 'AWAITING_PAYMENT' });
+ view.rerender(<BillingPage />);
+ expect(getBalance).toHaveBeenCalledTimes(1);
+
+ Object.assign(checkout.state, { phase: 'COMPLETED' });
+ view.rerender(<BillingPage />);
+ await waitFor(() => expect(getBalance).toHaveBeenCalledTimes(2));
+
+ view.rerender(<BillingPage />);
+ expect(getBalance).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not show zero or block purchases when balance is not provisioned', async () => {
+ window.electronAPI.billing.getBalance = vi.fn(async () => {
+ throw Object.assign(new Error('[NOT_FOUND] balance account is not provisioned'), {
+ code: 'NOT_FOUND' as const,
+ });
+ });
+
+ render(<BillingPage />);
+
+ expect(await screen.findByText('billing.balance.notProvisioned')).toBeTruthy();
+ expect(
+ screen.queryByText(
+ new Intl.NumberFormat(undefined, { style: 'currency', currency: 'CNY' }).format(0),
+ ),
+ ).toBeNull();
+ await waitFor(() =>
+ expect(
+ screen.getByText('billing.settings.subscriptionCard.action').closest('button'),
+ ).toHaveProperty('disabled', false),
+ );
+ expect(screen.getByText('billing.settings.topupCard.action').closest('button')).toHaveProperty(
+ 'disabled',
+ false,
+ );
+ });
+
+ it('does not wait for a slow balance response before enabling purchase entry points', async () => {
+ window.electronAPI.billing.getBalance = vi.fn(() => new Promise<never>(() => undefined));
+
+ render(<BillingPage />);
+
+ await waitFor(() =>
+ expect(
+ screen.getByText('billing.settings.subscriptionCard.action').closest('button'),
+ ).toHaveProperty('disabled', false),
+ );
+ expect(screen.getByText('billing.settings.topupCard.action').closest('button')).toHaveProperty(
+ 'disabled',
+ false,
+ );
+ });
+
+ it('shows only configured offers and only the selected offer channels', async () => {
+ render(<BillingPage />);
+
+ expect(screen.getByText('billing.settings.subscriptionCard.action')).toBeTruthy();
+ expect(screen.getByText('billing.settings.topupCard.action')).toBeTruthy();
+ expect(screen.queryByText('Configured top-up')).toBeNull();
+ expect(screen.queryByText('Configured subscription')).toBeNull();
+
+ fireEvent.click(screen.getByText('billing.settings.topupCard.action'));
+ await screen.findByText('Configured top-up');
+ expect(screen.queryByText('Unknown-provider offer')).toBeNull();
+ expect(screen.queryByText('Unconfigured offer')).toBeNull();
+ expect(screen.queryByText('Legacy offer without channel projection')).toBeNull();
+ expect(screen.queryByText('Unsupported payment action')).toBeNull();
+ expect(screen.queryByText('Unsupported payment capability')).toBeNull();
+ expect(screen.queryByText('Configured subscription')).toBeNull();
+ expect(screen.queryByText('unknown_provider')).toBeNull();
+ expect(screen.queryByText('alipay')).toBeNull();
+ expect(screen.queryByText('stripe')).toBeNull();
+
+ fireEvent.click(screen.getByText('Configured top-up').closest('button')!);
+ expect(await screen.findByText('alipay')).toBeTruthy();
+ expect(screen.queryByText('unknown_provider')).toBeNull();
+ expect(screen.queryByText('stripe')).toBeNull();
+
+ fireEvent.click(screen.getByText('alipay').closest('button')!);
+ fireEvent.change(screen.getByPlaceholderText('billing.amount.placeholder'), {
+ target: { value: '1.001' },
+ });
+ expect(screen.getByText('billing.actions.pay').closest('button')).toHaveProperty(
+ 'disabled',
+ true,
+ );
+ expect(screen.getByText('billing.amount.formatError:{"digits":2}')).toBeTruthy();
+
+ fireEvent.click(screen.getByLabelText('billing.actions.close'));
+ await waitFor(() => expect(screen.queryByText('Configured top-up')).toBeNull());
+
+ fireEvent.click(screen.getByText('billing.settings.subscriptionCard.action'));
+ fireEvent.click((await screen.findByText('Configured subscription')).closest('button')!);
+ expect(screen.getByText('stripe')).toBeTruthy();
+ expect(screen.queryByText('alipay')).toBeNull();
+ fireEvent.click(screen.getByText('stripe').closest('button')!);
+ fireEvent.click(screen.getByText('billing.actions.pay'));
+ expect(checkout.startSubscription).toHaveBeenCalledWith({
+ offerCode: 'plus_month',
+ purchaseOptionId: 'listing_stripe',
+ });
+ });
+
+ it('keeps checkout disabled until startup recovery finishes', async () => {
+ checkout.recovering = true;
+ const view = render(<BillingPage />);
+
+ fireEvent.click(screen.getByText('billing.settings.topupCard.action'));
+ fireEvent.click((await screen.findByText('Configured top-up')).closest('button')!);
+ fireEvent.click((await screen.findByText('alipay')).closest('button')!);
+ fireEvent.change(screen.getByPlaceholderText('billing.amount.placeholder'), {
+ target: { value: '10' },
+ });
+
+ const pay = screen.getByText('billing.actions.pay').closest('button')!;
+ expect(pay).toHaveProperty('disabled', true);
+ fireEvent.click(pay);
+ expect(checkout.startTopup).not.toHaveBeenCalled();
+
+ checkout.recovering = false;
+ view.rerender(<BillingPage />);
+ expect(pay).toHaveProperty('disabled', false);
+ });
+
+ it('does not create a second subscription while one is still live', async () => {
+ window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => ({
+ subscription: {
+ subscriptionId: 'subscription_fixture',
+ status: 'ACTIVE' as const,
+ currentPeriodStartAt: null,
+ currentPeriodEndAt: null,
+ entitlementValidUntil: null,
+ cancelAtPeriodEnd: false,
+ effectivePlan: null,
+ purchaseAttemptId: null,
+ paymentAction: null,
+ },
+ }));
+
+ render(<BillingPage />);
+ const viewPlans = screen
+ .getByText('billing.settings.subscriptionCard.action')
+ .closest('button')!;
+ await waitFor(() => expect(viewPlans).toHaveProperty('disabled', false));
+ fireEvent.click(viewPlans);
+ fireEvent.click((await screen.findByText('Configured subscription')).closest('button')!);
+ fireEvent.click((await screen.findByText('stripe')).closest('button')!);
+
+ expect(screen.getByText('billing.actions.pay').closest('button')).toHaveProperty(
+ 'disabled',
+ true,
+ );
+ expect(screen.getByText('billing.currentSubscription.purchaseBlocked')).toBeTruthy();
+ });
+
+ it('fails closed for subscription purchases when subscription status is unavailable', async () => {
+ window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => {
+ throw new Error('subscription status unavailable');
+ });
+
+ render(<BillingPage />);
+
+ expect(await screen.findByText('billing.settings.subscriptionCard.unavailable')).toBeTruthy();
+ expect(
+ screen.getByText('billing.settings.subscriptionCard.action').closest('button'),
+ ).toHaveProperty('disabled', true);
+ expect(screen.getByText('billing.settings.topupCard.action').closest('button')).toHaveProperty(
+ 'disabled',
+ false,
+ );
+ });
+
+ it('clears a previously loaded subscription when refresh fails', async () => {
+ window.electronAPI.billing.getCurrentSubscription = vi
+ .fn()
+ .mockResolvedValueOnce({
+ subscription: {
+ subscriptionId: 'subscription_fixture',
+ status: 'ACTIVE' as const,
+ currentPeriodStartAt: null,
+ currentPeriodEndAt: null,
+ entitlementValidUntil: null,
+ cancelAtPeriodEnd: false,
+ effectivePlan: {
+ version: 1 as const,
+ product: {
+ code: 'plus',
+ kind: 'SUBSCRIPTION' as const,
+ level: 1,
+ },
+ offer: {
+ code: 'plus_month',
+ interval: 'MONTH' as const,
+ },
+ terms: {
+ amount: '9',
+ currency: 'usd',
+ creditAmount: '100',
+ rolloverCap: '0',
+ },
+ capturedAt: '2026-07-23T12:00:00.000Z',
+ },
+ purchaseAttemptId: null,
+ paymentAction: null,
+ },
+ })
+ .mockRejectedValueOnce(new Error('subscription status unavailable'));
+
+ render(<BillingPage />);
+
+ expect(await screen.findByText('Configured subscription')).toBeTruthy();
+ fireEvent.click(screen.getByText('billing.actions.refreshCatalog'));
+
+ expect(await screen.findByText('billing.settings.subscriptionCard.unavailable')).toBeTruthy();
+ expect(screen.queryByText('Configured subscription')).toBeNull();
+ expect(
+ screen.getByText('billing.settings.subscriptionCard.action').closest('button'),
+ ).toHaveProperty('disabled', true);
+ });
+
+ it('renders multiple remote subscription offers as independent choices', async () => {
+ window.electronAPI.billing.getCatalog = vi.fn(async () => ({
+ products: (['alipay', 'stripe', 'alipay'] as const).map((provider, index) => ({
+ code: `plan_${index + 1}`,
+ name: `Remote plan ${index + 1}`,
+ kind: 'SUBSCRIPTION' as const,
+ level: index + 1,
+ sortOrder: index + 1,
+ offers: [
+ {
+ code: `plan_${index + 1}_month`,
+ interval: 'MONTH' as const,
+ currency: 'cny',
+ amount: String(index + 1),
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: String((index + 1) * 100),
+ rolloverCap: '0',
+ purchaseOptions: [
+ {
+ id: `listing_${provider}_${index + 1}`,
+ provider,
+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,
+ paymentAction: provider === 'alipay' ? ('QR_CODE' as const) : ('REDIRECT' as const),
+ },
+ ],
+ },
+ ],
+ })),
+ }));
+
+ render(<BillingPage />);
+ const viewPlans = screen
+ .getByText('billing.settings.subscriptionCard.action')
+ .closest('button')!;
+ await waitFor(() => expect(viewPlans).toHaveProperty('disabled', false));
+ fireEvent.click(viewPlans);
+
+ const planButtons = await screen.findAllByRole('button', { name: /Remote plan/ });
+ expect(planButtons).toHaveLength(3);
+ expect(planButtons.map((button) => button.getAttribute('aria-pressed'))).toEqual([
+ 'false',
+ 'false',
+ 'false',
+ ]);
+
+ fireEvent.click(planButtons[1]);
+ expect(planButtons[1].getAttribute('aria-pressed')).toBe('true');
+ expect(await screen.findByText('stripe')).toBeTruthy();
+ expect(screen.queryByText('alipay')).toBeNull();
+ });
+
+ it('shows a crediting state until top-up fulfillment succeeds', async () => {
+ Object.assign(checkout.state, {
+ open: true,
+ kind: 'TOPUP',
+ phase: 'FULFILLING',
+ order: {
+ orderId: 'order_paid',
+ productCode: 'credit_topup',
+ offerCode: 'credit_topup_custom',
+ amount: '10',
+ currency: 'cny',
+ status: 'SUCCEEDED',
+ fulfillmentStatus: 'FAILED',
+ paymentAction: null,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:01:00.000Z',
+ },
+ });
+
+ render(<BillingPage />);
+ await screen.findByText('billing.settings.subscriptionCard.empty');
+
+ expect(screen.getByText('billing.checkout.fulfillingTitle')).toBeTruthy();
+ expect(screen.getByText('billing.checkout.creditingBody')).toBeTruthy();
+ expect(screen.queryByText('billing.checkout.completedTitle')).toBeNull();
+ expect(screen.queryByText('billing.checkout.paymentCompleted')).toBeNull();
+ });
+
+ it('allows an uncertain failed checkout to be dismissed for later recovery', async () => {
+ Object.assign(checkout.state, {
+ open: true,
+ kind: 'TOPUP',
+ phase: 'FAILED',
+ intent: {
+ version: 1,
+ kind: 'TOPUP',
+ idempotencyKey: 'desktop:topup:fixture-0001',
+ request: {
+ offerCode: 'credit_topup_custom',
+ amount: '10',
+ purchaseOptionId: 'listing_alipay',
+ },
+ orderId: null,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ },
+ order: null,
+ subscription: null,
+ error: true,
+ });
+
+ render(<BillingPage />);
+ await screen.findByText('billing.checkout.requestFailed');
+ fireEvent.click(screen.getByLabelText('billing.actions.close'));
+
+ expect(checkout.close).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('BillingPage plan change', () => {
+ const subscriptionCatalog = {
+ products: [
+ {
+ code: 'plus',
+ name: 'Plus plan',
+ kind: 'SUBSCRIPTION' as const,
+ level: 1,
+ sortOrder: 1,
+ offers: [
+ {
+ code: 'plus_month',
+ interval: 'MONTH' as const,
+ currency: 'usd',
+ amount: '9',
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: '100',
+ rolloverCap: '0',
+ purchaseOptions: [
+ {
+ id: 'listing_plus_stripe',
+ provider: 'stripe',
+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,
+ paymentAction: 'REDIRECT' as const,
+ },
+ ],
+ },
+ ],
+ },
+ {
+ code: 'max',
+ name: 'Max plan',
+ kind: 'SUBSCRIPTION' as const,
+ level: 2,
+ sortOrder: 2,
+ offers: [
+ {
+ code: 'max_month',
+ interval: 'MONTH' as const,
+ currency: 'usd',
+ amount: '20',
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: '250',
+ rolloverCap: '0',
+ purchaseOptions: [
+ {
+ id: 'listing_max_stripe',
+ provider: 'stripe',
+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,
+ paymentAction: 'REDIRECT' as const,
+ },
+ ],
+ },
+ ],
+ },
+ {
+ code: 'cn_max',
+ name: 'Alipay-only Max',
+ kind: 'SUBSCRIPTION' as const,
+ level: 2,
+ sortOrder: 3,
+ offers: [
+ {
+ code: 'cn_max_month',
+ interval: 'MONTH' as const,
+ currency: 'cny',
+ amount: '140',
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: '250',
+ rolloverCap: '0',
+ purchaseOptions: [
+ {
+ id: 'listing_cn_max_alipay',
+ provider: 'alipay',
+ capability: 'MERCHANT_INITIATED_MANDATE' as const,
+ paymentAction: 'QR_CODE' as const,
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+
+ const activeSubscription = (
+ pendingPlanChange: unknown = null,
+ interval: 'MONTH' | 'YEAR' = 'MONTH',
+ ) => ({
+ subscriptionId: 'subscription_active',
+ status: 'ACTIVE' as const,
+ provider: 'stripe',
+ currentPeriodStartAt: '2026-07-01T00:00:00.000Z',
+ currentPeriodEndAt: '2026-08-01T00:00:00.000Z',
+ entitlementValidUntil: '2026-08-02T00:00:00.000Z',
+ cancelAtPeriodEnd: false,
+ effectivePlan: {
+ version: 1 as const,
+ product: { code: 'plus', kind: 'SUBSCRIPTION' as const, level: 1 },
+ offer: { code: 'plus_month', interval },
+ terms: { amount: '9', currency: 'usd', creditAmount: '100', rolloverCap: '0' },
+ capturedAt: '2026-07-01T00:00:00.000Z',
+ },
+ purchaseAttemptId: null,
+ paymentAction: null,
+ pendingPlanChange,
+ });
+
+ const billingMocks = () => ({
+ getBalance: vi.fn(async () => ({
+ planCredits: '7.000000001',
+ purchasedCredits: '5.000000002',
+ promotionalCredits: '0.345678898',
+ available: '12.345678901',
+ scale: 9 as const,
+ observedAt: '2026-07-23T12:00:00.000Z',
+ })),
+ getCatalog: vi.fn(async () => subscriptionCatalog),
+ getCurrentSubscription: vi.fn(async () => ({ subscription: activeSubscription() })),
+ quotePlanChange: vi.fn(),
+ confirmPlanChange: vi.fn(),
+ refreshPlanChange: vi.fn(),
+ cancelPlanChange: vi.fn(),
+ });
+
+ const install = (billing: ReturnType<typeof billingMocks>) => {
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: { billing, openExternal: vi.fn() },
+ });
+ return billing;
+ };
+
+ beforeEach(() => {
+ localStorage.clear();
+ Object.assign(checkout.state, {
+ open: false,
+ kind: null,
+ phase: 'IDLE',
+ intent: null,
+ order: null,
+ subscription: null,
+ error: false,
+ });
+ vi.stubGlobal('crypto', {
+ randomUUID: () => '00000000-0000-4000-8000-000000000042',
+ });
+ });
+
+ it('offers plan change for an active subscription with same-provider candidates only', async () => {
+ const billing = install(billingMocks());
+ billing.quotePlanChange.mockResolvedValue({
+ planChangeId: 'plan_change_1',
+ changeType: 'UPGRADE',
+ status: 'QUOTED',
+ quotedAmountMinor: 1100,
+ quotedCurrency: 'usd',
+ quoteExpiresAt: '2099-01-01T00:00:00.000Z',
+ effectiveAt: '2026-07-24T00:00:00.000Z',
+ paymentAction: null,
+ });
+
+ render(<BillingPage />);
+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.changeAction'));
+
+ await screen.findByText('billing.planChange.targetTitle');
+ expect(screen.getByText('Max plan')).toBeTruthy();
+ expect(screen.queryByText('Alipay-only Max')).toBeNull();
+ // The current plan renders in the summary card but must not be a candidate.
+ expect(screen.getByText('billing.planChange.upgradeBadge')).toBeTruthy();
+
+ fireEvent.click(screen.getByText('Max plan'));
+ await screen.findByText('billing.planChange.quoteTitle');
+ expect(billing.quotePlanChange).toHaveBeenCalledTimes(1);
+ expect(billing.quotePlanChange).toHaveBeenCalledWith({
+ targetOfferCode: 'max_month',
+ idempotencyKey: 'desktop:plan-change:00000000-0000-4000-8000-000000000042',
+ });
+ expect(
+ screen.getByText((text) => text.startsWith('billing.planChange.upgradeDueNow')),
+ ).toBeTruthy();
+
+ billing.confirmPlanChange.mockResolvedValue({
+ planChangeId: 'plan_change_1',
+ changeType: 'UPGRADE',
+ status: 'APPLIED',
+ quotedAmountMinor: 1100,
+ quotedCurrency: 'usd',
+ quoteExpiresAt: null,
+ effectiveAt: '2026-07-24T00:00:00.000Z',
+ paymentAction: null,
+ });
+ fireEvent.click(screen.getByText('billing.planChange.confirm'));
+ await screen.findByText('billing.planChange.appliedTitle');
+ // APPLIED refreshes subscription, catalog, and balance exactly once more.
+ await waitFor(() => expect(billing.getBalance).toHaveBeenCalledTimes(2));
+ expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not expose plan change for yearly subscriptions while server v1 is monthly-only', async () => {
+ const billing = billingMocks();
+ billing.getCurrentSubscription = vi.fn(async () => ({
+ subscription: activeSubscription(null, 'YEAR'),
+ }));
+ install(billing);
+
+ render(<BillingPage />);
+
+ await screen.findByText('Plus plan');
+ expect(screen.queryByText('billing.settings.subscriptionCard.changeAction')).toBeNull();
+ expect(screen.getByText('billing.settings.subscriptionCard.action')).toBeTruthy();
+ expect(billing.quotePlanChange).not.toHaveBeenCalled();
+ });
+
+ it('shows a scheduled downgrade banner and undoes it through DELETE', async () => {
+ const billing = billingMocks();
+ billing.getCurrentSubscription = vi.fn(async () => ({
+ subscription: activeSubscription({
+ planChangeId: 'plan_change_down',
+ changeType: 'DOWNGRADE',
+ status: 'SCHEDULED',
+ quotedAmountMinor: null,
+ quotedCurrency: null,
+ quoteExpiresAt: null,
+ effectiveAt: '2026-08-01T00:00:00.000Z',
+ paymentAction: null,
+ targetPlan: {
+ product: { code: 'plus', level: 1 },
+ offer: { code: 'plus_month', interval: 'MONTH' },
+ terms: { amount: '9', currency: 'usd', creditAmount: '100' },
+ },
+ }),
+ }));
+ install(billing);
+ billing.cancelPlanChange.mockResolvedValue({
+ planChangeId: 'plan_change_down',
+ changeType: 'DOWNGRADE',
+ status: 'CANCELED',
+ quotedAmountMinor: null,
+ quotedCurrency: null,
+ quoteExpiresAt: null,
+ effectiveAt: '2026-08-01T00:00:00.000Z',
+ paymentAction: null,
+ });
+
+ render(<BillingPage />);
+ await screen.findByText((text) => text.startsWith('billing.planChange.pendingDowngrade'));
+
+ fireEvent.click(screen.getByText('billing.planChange.undo'));
+ await waitFor(() =>
+ expect(billing.cancelPlanChange).toHaveBeenCalledWith({ planChangeId: 'plan_change_down' }),
+ );
+ // The canceled settle re-syncs the subscription projection for the banner.
+ await waitFor(() => expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(2));
+ });
+
+ it('resumes a pending alipay upgrade payment with the server-issued QR action', async () => {
+ const qr = {
+ type: 'QR_CODE' as const,
+ value: 'https://qr.alipay.example/plan-change',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ };
+ const billing = billingMocks();
+ billing.getCurrentSubscription = vi.fn(async () => ({
+ subscription: {
+ ...activeSubscription({
+ planChangeId: 'plan_change_up',
+ changeType: 'UPGRADE',
+ status: 'AWAITING_PAYMENT',
+ quotedAmountMinor: 1500,
+ quotedCurrency: 'cny',
+ quoteExpiresAt: null,
+ effectiveAt: '2026-07-24T00:00:00.000Z',
+ paymentAction: qr,
+ targetPlan: {
+ product: { code: 'cn_max', level: 2 },
+ offer: { code: 'cn_max_month', interval: 'MONTH' },
+ terms: { amount: '140', currency: 'cny', creditAmount: '250' },
+ },
+ }),
+ provider: 'alipay',
+ },
+ }));
+ install(billing);
+ billing.refreshPlanChange.mockResolvedValue({
+ planChangeId: 'plan_change_up',
+ changeType: 'UPGRADE',
+ status: 'AWAITING_PAYMENT',
+ quotedAmountMinor: 1500,
+ quotedCurrency: 'cny',
+ quoteExpiresAt: null,
+ effectiveAt: '2026-07-24T00:00:00.000Z',
+ paymentAction: qr,
+ });
+
+ render(<BillingPage />);
+ await screen.findByText((text) => text.startsWith('billing.planChange.pendingPayment'));
+
+ fireEvent.click(screen.getByText('billing.planChange.resume'));
+ await screen.findByText('billing.planChange.awaitingTitle');
+ expect(
+ await screen.findByText((text) => text.startsWith('billing.planChange.scanToPay')),
+ ).toBeTruthy();
+ await screen.findByAltText('billing.checkout.qrAlt');
+ // Resuming re-displays the stored server action without quoting again.
+ expect(billing.quotePlanChange).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx
new file mode 100644
index 0000000000..7896be8d54
--- /dev/null
+++ b/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx
@@ -0,0 +1,106 @@
+// @vitest-environment jsdom
+
+import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, params?: Record<string, string>) =>
+ params ? `${key}:${JSON.stringify(params)}` : key,
+ }),
+}));
+vi.mock('qrcode', () => ({
+ toDataURL: vi.fn(async () => 'data:image/png;base64,fixture'),
+}));
+
+import { PlanChangeStatusDialog } from '../PlanChangeDialog';
+import type { PlanChangeState } from '../usePlanChange';
+
+function quoteReadyState(overrides: Partial<PlanChangeState> = {}): PlanChangeState {
+ return {
+ open: true,
+ phase: 'QUOTE_READY',
+ planChange: {
+ planChangeId: 'plan_change_1',
+ changeType: 'UPGRADE',
+ status: 'QUOTED',
+ quotedAmountMinor: 1500,
+ quotedCurrency: 'cny',
+ quoteExpiresAt: '2099-01-01T00:00:00.000Z',
+ effectiveAt: '2026-08-01T00:00:00.000Z',
+ paymentAction: null,
+ },
+ targetPlan: null,
+ error: false,
+ stale: false,
+ ...overrides,
+ };
+}
+
+describe('PlanChangeStatusDialog stale snapshot handling', () => {
+ it('lets a fresh quote be confirmed or abandoned', () => {
+ render(
+ <PlanChangeStatusDialog
+ state={quoteReadyState()}
+ targetName={null}
+ onClose={vi.fn()}
+ onConfirm={vi.fn()}
+ onRefresh={vi.fn()}
+ onAbandon={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByText('billing.planChange.confirm')).toBeTruthy();
+ expect(screen.getByText('billing.planChange.abandon')).toBeTruthy();
+ expect(screen.queryByText('billing.actions.refresh')).toBeNull();
+ });
+
+ it('never offers confirm or abandon on a stale snapshot, only resync', () => {
+ const onRefresh = vi.fn();
+ render(
+ <PlanChangeStatusDialog
+ state={quoteReadyState({ error: true, stale: true })}
+ targetName={null}
+ onClose={vi.fn()}
+ onConfirm={vi.fn()}
+ onRefresh={onRefresh}
+ onAbandon={vi.fn()}
+ />,
+ );
+
+ expect(screen.queryByText('billing.planChange.confirm')).toBeNull();
+ expect(screen.queryByText('billing.planChange.abandon')).toBeNull();
+ expect(screen.getByText('billing.planChange.resyncHint')).toBeTruthy();
+
+ fireEvent.click(screen.getByText('billing.actions.refresh'));
+ expect(onRefresh).toHaveBeenCalledTimes(1);
+ });
+
+ it('shows provider-pending progress without offering another confirm', () => {
+ const onRefresh = vi.fn();
+ render(
+ <PlanChangeStatusDialog
+ state={quoteReadyState({
+ phase: 'PENDING_PROVIDER',
+ planChange: {
+ ...quoteReadyState().planChange!,
+ status: 'PENDING_PROVIDER',
+ },
+ })}
+ targetName={null}
+ onClose={vi.fn()}
+ onConfirm={vi.fn()}
+ onRefresh={onRefresh}
+ onAbandon={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByText('billing.planChange.pendingProviderTitle')).toBeTruthy();
+ expect(screen.getByText('billing.planChange.pendingProviderBody')).toBeTruthy();
+ expect(screen.queryByText('billing.planChange.confirm')).toBeNull();
+ expect(screen.queryByText('billing.planChange.abandon')).toBeNull();
+
+ fireEvent.click(screen.getByText('billing.actions.refresh'));
+ expect(onRefresh).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/api.test.ts b/apps/desktop/src/renderer/features/billing/__tests__/api.test.ts
new file mode 100644
index 0000000000..702abd0ad1
--- /dev/null
+++ b/apps/desktop/src/renderer/features/billing/__tests__/api.test.ts
@@ -0,0 +1,61 @@
+// @vitest-environment jsdom
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { billingApi } from '../api';
+
+describe('billing renderer API', () => {
+ const billing = {
+ getBalance: vi.fn(),
+ getCreditUsage: vi.fn(),
+ listOrders: vi.fn(),
+ createTopup: vi.fn(),
+ openPaymentRedirect: vi.fn(),
+ };
+
+ beforeEach(() => {
+ billing.getBalance.mockReset().mockResolvedValue({ available: '12.34' });
+ billing.getCreditUsage.mockReset().mockResolvedValue({ available: '12.34' });
+ billing.listOrders.mockReset().mockResolvedValue({ orders: [], nextCursor: null });
+ billing.createTopup.mockReset().mockResolvedValue({ orderId: 'order_fixture' });
+ billing.openPaymentRedirect.mockReset().mockResolvedValue({ success: true });
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: { billing },
+ });
+ });
+
+ it('queries the current account balance without accepting renderer parameters', async () => {
+ await billingApi.getBalance();
+ expect(billing.getBalance).toHaveBeenCalledWith();
+ });
+
+ it('queries current account credit usage without accepting renderer parameters', async () => {
+ await billingApi.getCreditUsage();
+ expect(billing.getCreditUsage).toHaveBeenCalledWith();
+ });
+
+ it('uses the bounded default order page size', async () => {
+ await billingApi.listOrders();
+ expect(billing.listOrders).toHaveBeenCalledWith({ limit: 20 });
+ });
+
+ it('keeps the request and idempotency key inside the fixed create method', async () => {
+ const request = {
+ offerCode: 'credit_topup_custom',
+ amount: '20.00',
+ purchaseOptionId: 'listing_alipay',
+ };
+ await billingApi.createTopup(request, 'desktop:topup:fixture-0001');
+ expect(billing.createTopup).toHaveBeenCalledWith({
+ request,
+ idempotencyKey: 'desktop:topup:fixture-0001',
+ });
+ });
+
+ it('uses the dedicated billing redirect method', async () => {
+ const url = 'https://checkout.stripe.com/c/pay/session_fixture';
+ await billingApi.openPaymentRedirect(url);
+ expect(billing.openPaymentRedirect).toHaveBeenCalledWith({ url });
+ });
+});
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/checkoutIntent.test.ts b/apps/desktop/src/renderer/features/billing/__tests__/checkoutIntent.test.ts
new file mode 100644
index 0000000000..0782b78e3d
--- /dev/null
+++ b/apps/desktop/src/renderer/features/billing/__tests__/checkoutIntent.test.ts
@@ -0,0 +1,164 @@
+// @vitest-environment jsdom
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ billingCheckoutIntentKey,
+ billingPlanChangeIntentKey,
+ clearBillingCheckoutIntent,
+ clearBillingPlanChangeIntent,
+ newBillingIdempotencyKey,
+ readBillingCheckoutIntent,
+ readBillingPlanChangeIntent,
+ writeBillingCheckoutIntent,
+ writeBillingPlanChangeIntent,
+} from '../checkoutIntent';
+
+const ACCOUNT_A = 'account-a';
+const ACCOUNT_B = 'account-b';
+
+describe('billing checkout intent', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ });
+
+ it('round-trips a valid top-up intent', () => {
+ const intent = {
+ version: 1 as const,
+ kind: 'TOPUP' as const,
+ idempotencyKey: 'desktop:topup:fixture-0001',
+ request: {
+ offerCode: 'credit_topup_custom',
+ amount: '20.00',
+ purchaseOptionId: 'listing_alipay',
+ },
+ orderId: null,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ };
+ writeBillingCheckoutIntent(ACCOUNT_A, intent);
+ expect(readBillingCheckoutIntent(ACCOUNT_A)).toEqual(intent);
+ clearBillingCheckoutIntent(ACCOUNT_A);
+ expect(readBillingCheckoutIntent(ACCOUNT_A)).toBeNull();
+ });
+
+ it('removes malformed or future-version storage', () => {
+ localStorage.setItem(
+ billingCheckoutIntentKey(ACCOUNT_A),
+ JSON.stringify({ version: 2, kind: 'TOPUP' }),
+ );
+ expect(readBillingCheckoutIntent(ACCOUNT_A)).toBeNull();
+ expect(localStorage.getItem(billingCheckoutIntentKey(ACCOUNT_A))).toBeNull();
+ });
+
+ it('removes intents containing undeclared response or payment fields', () => {
+ localStorage.setItem(
+ billingCheckoutIntentKey(ACCOUNT_A),
+ JSON.stringify({
+ version: 1,
+ kind: 'TOPUP_RETRY',
+ idempotencyKey: 'desktop:retry:fixture-0001',
+ orderId: 'order_fixture',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ paymentUrl: 'https://pay.example.test/should-not-persist',
+ }),
+ );
+ expect(readBillingCheckoutIntent(ACCOUNT_A)).toBeNull();
+ expect(localStorage.getItem(billingCheckoutIntentKey(ACCOUNT_A))).toBeNull();
+ });
+
+ it('creates a fresh namespaced idempotency key per user action', () => {
+ vi.stubGlobal('crypto', { randomUUID: () => '00000000-0000-4000-8000-000000000001' });
+ expect(newBillingIdempotencyKey('subscription')).toBe(
+ 'desktop:subscription:00000000-0000-4000-8000-000000000001',
+ );
+ vi.unstubAllGlobals();
+ });
+
+ it('round-trips a retry intent without storing catalog or provider data', () => {
+ const intent = {
+ version: 1 as const,
+ kind: 'TOPUP_RETRY' as const,
+ idempotencyKey: 'desktop:retry:fixture-0001',
+ orderId: 'order_fixture',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ };
+ writeBillingCheckoutIntent(ACCOUNT_A, intent);
+ expect(readBillingCheckoutIntent(ACCOUNT_A)).toEqual(intent);
+ });
+
+ it('keeps checkout recovery isolated between accounts', () => {
+ const intent = {
+ version: 1 as const,
+ kind: 'TOPUP_RETRY' as const,
+ idempotencyKey: 'desktop:retry:fixture-0001',
+ orderId: 'order_fixture',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ };
+ writeBillingCheckoutIntent(ACCOUNT_A, intent);
+
+ expect(readBillingCheckoutIntent(ACCOUNT_B)).toBeNull();
+ expect(readBillingCheckoutIntent(ACCOUNT_A)).toEqual(intent);
+ });
+
+ it('drops legacy unscoped recovery instead of assigning it to the active account', () => {
+ localStorage.setItem(
+ 'cindy.billing.checkout-intent.v1',
+ JSON.stringify({
+ version: 1,
+ kind: 'TOPUP_RETRY',
+ idempotencyKey: 'desktop:retry:fixture-0001',
+ orderId: 'order_fixture',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ }),
+ );
+
+ expect(readBillingCheckoutIntent(ACCOUNT_A)).toBeNull();
+ expect(localStorage.getItem('cindy.billing.checkout-intent.v1')).toBeNull();
+ });
+});
+
+describe('billing plan change intent persistence', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ });
+
+ const intent = {
+ version: 1 as const,
+ targetOfferCode: 'max_month',
+ idempotencyKey: 'desktop:plan-change:fixture-0001',
+ planChangeId: 'plan_change_1',
+ createdAt: '2026-07-24T00:00:00.000Z',
+ };
+
+ it('round-trips a valid intent per account', () => {
+ writeBillingPlanChangeIntent(ACCOUNT_A, intent);
+
+ expect(readBillingPlanChangeIntent(ACCOUNT_A)).toEqual(intent);
+ expect(readBillingPlanChangeIntent(ACCOUNT_B)).toBeNull();
+ });
+
+ it('drops a tampered or extended intent instead of replaying it', () => {
+ localStorage.setItem(
+ billingPlanChangeIntentKey(ACCOUNT_A),
+ JSON.stringify({ ...intent, provider: 'alipay' }),
+ );
+ expect(readBillingPlanChangeIntent(ACCOUNT_A)).toBeNull();
+
+ localStorage.setItem(
+ billingPlanChangeIntentKey(ACCOUNT_A),
+ JSON.stringify({ ...intent, targetOfferCode: 'Bad Code!' }),
+ );
+ expect(readBillingPlanChangeIntent(ACCOUNT_A)).toBeNull();
+ expect(localStorage.getItem(billingPlanChangeIntentKey(ACCOUNT_A))).toBeNull();
+ });
+
+ it('clears only the requested account intent', () => {
+ writeBillingPlanChangeIntent(ACCOUNT_A, intent);
+ writeBillingPlanChangeIntent(ACCOUNT_B, { ...intent, planChangeId: null });
+
+ clearBillingPlanChangeIntent(ACCOUNT_A);
+
+ expect(readBillingPlanChangeIntent(ACCOUNT_A)).toBeNull();
+ expect(readBillingPlanChangeIntent(ACCOUNT_B)).toEqual({ ...intent, planChangeId: null });
+ });
+});
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/money.test.ts b/apps/desktop/src/renderer/features/billing/__tests__/money.test.ts
new file mode 100644
index 0000000000..5539a72e0f
--- /dev/null
+++ b/apps/desktop/src/renderer/features/billing/__tests__/money.test.ts
@@ -0,0 +1,72 @@
+// @vitest-environment jsdom
+
+import { describe, expect, it } from 'vitest';
+
+import { formatBillingAmount, formatBillingMinorAmount } from '../money';
+
+const usd = (value: number) =>
+ new Intl.NumberFormat(undefined, { style: 'currency', currency: 'USD' }).format(value);
+const jpy = (value: number) =>
+ new Intl.NumberFormat(undefined, { style: 'currency', currency: 'JPY' }).format(value);
+const exactUsd = (whole: bigint, fraction: bigint) => {
+ const formatter = new Intl.NumberFormat(undefined, {
+ style: 'currency',
+ currency: 'USD',
+ });
+ const resolved = formatter.resolvedOptions();
+ const localizedFraction = new Intl.NumberFormat(resolved.locale, {
+ numberingSystem: resolved.numberingSystem,
+ useGrouping: false,
+ minimumIntegerDigits: 2,
+ maximumFractionDigits: 0,
+ }).format(fraction);
+ return formatter
+ .formatToParts(whole)
+ .map((part) => (part.type === 'fraction' ? localizedFraction : part.value))
+ .join('');
+};
+
+describe('formatBillingAmount', () => {
+ it('rounds decimal midpoints half away from zero without IEEE 754 drift', () => {
+ expect(formatBillingAmount('1.005', 'usd')).toBe(usd(1.01));
+ expect(formatBillingAmount('2.675', 'usd')).toBe(usd(2.68));
+ });
+
+ it('rounds negative midpoints symmetrically', () => {
+ expect(formatBillingAmount('-1.005', 'usd')).toBe(usd(-1.01));
+ expect(formatBillingAmount('-2.675', 'usd')).toBe(usd(-2.68));
+ });
+
+ it('never renders negative zero', () => {
+ expect(formatBillingAmount('-0.001', 'usd')).toBe(usd(0));
+ });
+
+ it('preserves cents when the currency-scaled value exceeds Number.MAX_SAFE_INTEGER', () => {
+ const amount = '999999999999999.94';
+ expect(formatBillingAmount(amount, 'usd')).toBe(exactUsd(999999999999999n, 94n));
+ expect(formatBillingAmount(amount, 'usd')).not.toBe(usd(Number(amount)));
+ });
+
+ it('falls back to the raw amount when the value is not numeric', () => {
+ expect(formatBillingAmount('not-a-number', 'usd')).toBe('not-a-number USD');
+ });
+});
+
+describe('formatBillingMinorAmount', () => {
+ it('converts minor units through an exact decimal string', () => {
+ expect(formatBillingMinorAmount(1105, 'usd')).toBe(usd(11.05));
+ expect(formatBillingMinorAmount(1500, 'cny')).toBe(
+ new Intl.NumberFormat(undefined, { style: 'currency', currency: 'CNY' }).format(15),
+ );
+ });
+
+ it('handles zero-decimal currencies', () => {
+ expect(formatBillingMinorAmount(120, 'jpy')).toBe(jpy(120));
+ });
+
+ it('preserves every minor unit up to Number.MAX_SAFE_INTEGER', () => {
+ expect(formatBillingMinorAmount(Number.MAX_SAFE_INTEGER, 'usd')).toBe(
+ exactUsd(90071992547409n, 91n),
+ );
+ });
+});
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.ts b/apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.ts
new file mode 100644
index 0000000000..eb5254e299
--- /dev/null
+++ b/apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.ts
@@ -0,0 +1,489 @@
+// @vitest-environment jsdom
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const api = vi.hoisted(() => ({
+ listOrders: vi.fn(),
+ getCurrentSubscription: vi.fn(),
+ createTopup: vi.fn(),
+ createSubscription: vi.fn(),
+ retryTopup: vi.fn(),
+ refreshTopup: vi.fn(),
+ refreshSubscriptionPurchase: vi.fn(),
+ getOrder: vi.fn(),
+}));
+
+vi.mock('../api', () => ({ billingApi: api }));
+
+import {
+ isRecoverableTopup,
+ phaseForOrder,
+ phaseForSubscription,
+ useBillingCheckout,
+} from '../useBillingCheckout';
+import { readBillingCheckoutIntent, writeBillingCheckoutIntent } from '../checkoutIntent';
+
+const ACCOUNT_ID = 'account-fixture';
+
+describe('billing checkout phase projection', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ api.listOrders.mockReset().mockResolvedValue({ orders: [], nextCursor: null });
+ api.getCurrentSubscription.mockReset().mockResolvedValue({ subscription: null });
+ api.createTopup.mockReset();
+ api.createSubscription.mockReset();
+ api.retryTopup.mockReset();
+ api.refreshTopup.mockReset();
+ api.refreshSubscriptionPurchase.mockReset();
+ api.getOrder.mockReset();
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ value: 'visible',
+ });
+ vi.stubGlobal('crypto', {
+ randomUUID: () => '00000000-0000-4000-8000-000000000001',
+ });
+ });
+
+ it('keeps paid top-ups crediting until fulfillment succeeds', () => {
+ const base = {
+ orderId: 'order_fixture',
+ productCode: 'credit_topup',
+ offerCode: 'credit_topup_20',
+ amount: '20',
+ currency: 'cny',
+ status: 'SUCCEEDED' as const,
+ paymentAction: null,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:01:00.000Z',
+ };
+ expect(phaseForOrder(base)).toBe('FULFILLING');
+ expect(phaseForOrder({ ...base, fulfillmentStatus: 'PENDING' })).toBe('FULFILLING');
+ expect(phaseForOrder({ ...base, fulfillmentStatus: 'SUCCEEDED' })).toBe('COMPLETED');
+ expect(phaseForOrder({ ...base, fulfillmentStatus: 'FAILED' })).toBe('FULFILLING');
+ });
+
+ it('shows active subscriptions as paid without exposing entitlement state', () => {
+ const base = {
+ subscriptionId: 'subscription_fixture',
+ status: 'ACTIVE' as const,
+ currentPeriodStartAt: null,
+ currentPeriodEndAt: null,
+ entitlementValidUntil: null,
+ cancelAtPeriodEnd: false,
+ effectivePlan: null,
+ purchaseAttemptId: null,
+ paymentAction: null,
+ };
+ expect(phaseForSubscription(base)).toBe('COMPLETED');
+ expect(phaseForSubscription({ ...base, entitlementStatus: 'SUCCEEDED' })).toBe('COMPLETED');
+ expect(phaseForSubscription({ ...base, entitlementStatus: 'FAILED' })).toBe('COMPLETED');
+ });
+
+ it('lets the server confirm expiry instead of trusting the client clock', () => {
+ expect(
+ isRecoverableTopup({
+ status: 'PENDING',
+ paymentAction: {
+ expiresAt: '2000-01-01T00:00:00.000Z',
+ },
+ }),
+ ).toBe(true);
+ });
+
+ it('keeps created top-ups with a payment action recoverable', () => {
+ expect(
+ isRecoverableTopup({
+ status: 'CREATED',
+ paymentAction: {
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ },
+ }),
+ ).toBe(true);
+ });
+
+ it('keeps pending top-ups recoverable before a payment action is projected', () => {
+ expect(
+ isRecoverableTopup({
+ status: 'CREATED',
+ paymentAction: null,
+ }),
+ ).toBe(true);
+ expect(
+ isRecoverableTopup({
+ status: 'PENDING',
+ paymentAction: null,
+ }),
+ ).toBe(true);
+ });
+
+ it('keeps paid but unfulfilled top-ups recoverable without a payment action', () => {
+ expect(
+ isRecoverableTopup({
+ status: 'SUCCEEDED',
+ fulfillmentStatus: 'PENDING',
+ paymentAction: null,
+ }),
+ ).toBe(true);
+ expect(
+ isRecoverableTopup({
+ status: 'SUCCEEDED',
+ fulfillmentStatus: 'SUCCEEDED',
+ paymentAction: null,
+ }),
+ ).toBe(false);
+ });
+
+ it('keeps the checkout intent until paid top-up fulfillment succeeds', async () => {
+ const paidOrder = {
+ orderId: 'order_paid',
+ productCode: 'credit_topup',
+ offerCode: 'credit_topup_20',
+ amount: '20',
+ currency: 'cny',
+ status: 'SUCCEEDED' as const,
+ fulfillmentStatus: 'PENDING' as const,
+ paymentAction: null,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:01:00.000Z',
+ };
+ api.createTopup.mockResolvedValue(paidOrder);
+ api.getOrder.mockResolvedValue({
+ ...paidOrder,
+ fulfillmentStatus: 'SUCCEEDED',
+ });
+ const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
+ await waitFor(() => expect(result.current.recovering).toBe(false));
+
+ await act(() =>
+ result.current.startTopup({
+ offerCode: 'credit_topup_20',
+ purchaseOptionId: 'listing_alipay',
+ }),
+ );
+
+ expect(result.current.state.phase).toBe('FULFILLING');
+ expect(readBillingCheckoutIntent(ACCOUNT_ID)).not.toBeNull();
+
+ await act(() => result.current.refreshActive());
+
+ expect(api.getOrder).toHaveBeenCalledWith('order_paid');
+ expect(result.current.state.phase).toBe('COMPLETED');
+ expect(readBillingCheckoutIntent(ACCOUNT_ID)).toBeNull();
+ });
+
+ it('replays an unresolved persisted purchase with the original request and key', async () => {
+ const pending = {
+ subscriptionId: 'subscription_pending',
+ status: 'INCOMPLETE' as const,
+ currentPeriodStartAt: null,
+ currentPeriodEndAt: null,
+ entitlementValidUntil: null,
+ cancelAtPeriodEnd: false,
+ effectivePlan: null,
+ purchaseAttemptId: 'purchase_pending',
+ paymentAction: {
+ type: 'QR_CODE' as const,
+ value: 'alipays://pending',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ },
+ };
+ api.createSubscription.mockResolvedValue(pending);
+ writeBillingCheckoutIntent(ACCOUNT_ID, {
+ version: 1,
+ kind: 'SUBSCRIPTION',
+ idempotencyKey: 'desktop:subscription:stale-intent',
+ request: {
+ offerCode: 'retired_plus_month',
+ purchaseOptionId: 'listing_alipay',
+ },
+ subscriptionId: null,
+ purchaseAttemptId: null,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ });
+
+ const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
+ await waitFor(() => expect(result.current.recovering).toBe(false));
+
+ expect(api.listOrders).toHaveBeenCalledTimes(1);
+ expect(api.getCurrentSubscription).toHaveBeenCalledTimes(1);
+ expect(api.createTopup).not.toHaveBeenCalled();
+ expect(api.createSubscription).toHaveBeenCalledWith(
+ {
+ offerCode: 'retired_plus_month',
+ purchaseOptionId: 'listing_alipay',
+ },
+ 'desktop:subscription:stale-intent',
+ );
+ expect(result.current.state.open).toBe(true);
+ expect(result.current.state.phase).toBe('AWAITING_PAYMENT');
+ expect(readBillingCheckoutIntent(ACCOUNT_ID)).toEqual({
+ version: 1,
+ kind: 'SUBSCRIPTION',
+ idempotencyKey: 'desktop:subscription:stale-intent',
+ request: {
+ offerCode: 'retired_plus_month',
+ purchaseOptionId: 'listing_alipay',
+ },
+ subscriptionId: 'subscription_pending',
+ purchaseAttemptId: 'purchase_pending',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ });
+ });
+
+ it('does not replace a persisted subscription intent with another current subscription', async () => {
+ const intent = {
+ version: 1 as const,
+ kind: 'SUBSCRIPTION' as const,
+ idempotencyKey: 'desktop:subscription:pending-intent',
+ request: {
+ offerCode: 'plus_month',
+ purchaseOptionId: 'listing_alipay',
+ },
+ subscriptionId: 'subscription_expected',
+ purchaseAttemptId: 'purchase_expected',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ };
+ const unrelated = {
+ subscriptionId: 'subscription_other',
+ status: 'ACTIVE' as const,
+ currentPeriodStartAt: null,
+ currentPeriodEndAt: null,
+ entitlementValidUntil: null,
+ cancelAtPeriodEnd: false,
+ effectivePlan: null,
+ purchaseAttemptId: 'purchase_other',
+ paymentAction: null,
+ };
+ writeBillingCheckoutIntent(ACCOUNT_ID, intent);
+ api.getCurrentSubscription.mockResolvedValue({ subscription: unrelated });
+ api.refreshSubscriptionPurchase.mockResolvedValue(unrelated);
+
+ const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
+ await waitFor(() => expect(result.current.recovering).toBe(false));
+
+ expect(api.refreshSubscriptionPurchase).toHaveBeenCalledWith('purchase_expected');
+ expect(result.current.state).toMatchObject({
+ phase: 'FAILED',
+ intent,
+ subscription: null,
+ error: true,
+ });
+ expect(readBillingCheckoutIntent(ACCOUNT_ID)).toEqual(intent);
+ });
+
+ it('accepts a terminal same-subscription result after its purchase attempt is cleared', async () => {
+ const intent = {
+ version: 1 as const,
+ kind: 'SUBSCRIPTION' as const,
+ idempotencyKey: 'desktop:subscription:completed-intent',
+ request: {
+ offerCode: 'plus_month',
+ purchaseOptionId: 'listing_alipay',
+ },
+ subscriptionId: 'subscription_expected',
+ purchaseAttemptId: 'purchase_expected',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ };
+ const completed = {
+ subscriptionId: 'subscription_expected',
+ status: 'ACTIVE' as const,
+ currentPeriodStartAt: '2026-01-01T00:00:00.000Z',
+ currentPeriodEndAt: '2026-02-01T00:00:00.000Z',
+ entitlementValidUntil: '2026-02-01T00:00:00.000Z',
+ cancelAtPeriodEnd: false,
+ effectivePlan: null,
+ purchaseAttemptId: null,
+ paymentAction: null,
+ };
+ writeBillingCheckoutIntent(ACCOUNT_ID, intent);
+ api.getCurrentSubscription.mockResolvedValue({ subscription: completed });
+ api.refreshSubscriptionPurchase.mockResolvedValue(completed);
+
+ const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
+ await waitFor(() => expect(result.current.recovering).toBe(false));
+
+ expect(api.refreshSubscriptionPurchase).toHaveBeenCalledWith('purchase_expected');
+ expect(result.current.state).toMatchObject({
+ phase: 'COMPLETED',
+ subscription: completed,
+ error: false,
+ });
+ expect(readBillingCheckoutIntent(ACCOUNT_ID)).toBeNull();
+ });
+
+ it('keeps an unresolved persisted purchase retryable when recovery fails', async () => {
+ const intent = {
+ version: 1 as const,
+ kind: 'TOPUP' as const,
+ idempotencyKey: 'desktop:topup:unresolved-intent',
+ request: {
+ offerCode: 'credit_topup_custom',
+ amount: '20',
+ purchaseOptionId: 'listing_alipay',
+ },
+ orderId: null,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ };
+ writeBillingCheckoutIntent(ACCOUNT_ID, intent);
+ api.createTopup.mockRejectedValue(new Error('network result unknown'));
+
+ const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
+ await waitFor(() => expect(result.current.recovering).toBe(false));
+
+ expect(result.current.state).toMatchObject({
+ open: true,
+ kind: 'TOPUP',
+ phase: 'FAILED',
+ intent,
+ error: true,
+ });
+ expect(readBillingCheckoutIntent(ACCOUNT_ID)).toEqual(intent);
+ act(() => result.current.close());
+ expect(result.current.state.open).toBe(false);
+ expect(readBillingCheckoutIntent(ACCOUNT_ID)).toEqual(intent);
+ });
+
+ it('does not bind an unidentified intent to another pending subscription', async () => {
+ const unrelated = {
+ subscriptionId: 'subscription_other',
+ status: 'INCOMPLETE' as const,
+ currentPeriodStartAt: null,
+ currentPeriodEndAt: null,
+ entitlementValidUntil: null,
+ cancelAtPeriodEnd: false,
+ effectivePlan: null,
+ purchaseAttemptId: 'purchase_other',
+ paymentAction: {
+ type: 'QR_CODE' as const,
+ value: 'alipays://pending',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ },
+ };
+ api.createSubscription.mockRejectedValue(new Error('SUBSCRIPTION_NOT_MANAGEABLE'));
+ api.getCurrentSubscription
+ .mockResolvedValueOnce({ subscription: null })
+ .mockResolvedValueOnce({ subscription: unrelated });
+
+ const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
+ await waitFor(() => expect(result.current.recovering).toBe(false));
+
+ await act(async () =>
+ result.current.startSubscription({
+ offerCode: 'plus_month',
+ purchaseOptionId: 'listing_alipay',
+ }),
+ );
+
+ expect(api.getCurrentSubscription).toHaveBeenCalledTimes(1);
+ expect(result.current.state).toMatchObject({
+ phase: 'FAILED',
+ subscription: null,
+ error: true,
+ });
+ expect(result.current.state.intent).toMatchObject({
+ subscriptionId: null,
+ purchaseAttemptId: null,
+ });
+ });
+
+ it('reuses the same retry key while the retry result is unknown', async () => {
+ const failedOrder = {
+ orderId: 'order_fixture',
+ productCode: 'credit_topup',
+ offerCode: 'credit_topup_20',
+ amount: '20',
+ currency: 'cny',
+ status: 'FAILED' as const,
+ paymentAction: null,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:01:00.000Z',
+ };
+ api.retryTopup.mockRejectedValue(new Error('network result unknown'));
+
+ const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
+ await waitFor(() => expect(result.current.recovering).toBe(false));
+
+ act(() => result.current.resumeTopup(failedOrder));
+ await act(async () => result.current.retry());
+ await act(async () => result.current.retry());
+
+ expect(api.retryTopup).toHaveBeenCalledTimes(2);
+ expect(api.retryTopup.mock.calls[0]).toEqual(api.retryTopup.mock.calls[1]);
+ expect(api.retryTopup.mock.calls[0]).toEqual([
+ 'order_fixture',
+ 'desktop:retry:00000000-0000-4000-8000-000000000001',
+ ]);
+ });
+
+ it('refreshes on focus without allowing concurrent status requests', async () => {
+ const pendingOrder = {
+ orderId: 'order_fixture',
+ productCode: 'credit_topup',
+ offerCode: 'credit_topup_20',
+ amount: '20',
+ currency: 'cny',
+ status: 'PENDING' as const,
+ paymentAction: {
+ type: 'QR_CODE' as const,
+ value: 'https://pay.example.test/checkout/fixture',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ },
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:01:00.000Z',
+ };
+ let resolveRefresh: ((value: typeof pendingOrder) => void) | null = null;
+ api.refreshTopup.mockImplementation(
+ () =>
+ new Promise<typeof pendingOrder>((resolve) => {
+ resolveRefresh = resolve;
+ }),
+ );
+
+ const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
+ await waitFor(() => expect(result.current.recovering).toBe(false));
+ act(() => result.current.resumeTopup(pendingOrder));
+ await waitFor(() => expect(result.current.state.phase).toBe('AWAITING_PAYMENT'));
+
+ act(() => {
+ window.dispatchEvent(new Event('focus'));
+ window.dispatchEvent(new Event('focus'));
+ });
+ await waitFor(() => expect(api.refreshTopup).toHaveBeenCalledTimes(1));
+
+ await act(async () => resolveRefresh?.(pendingOrder));
+ expect(api.refreshTopup).toHaveBeenCalledWith('order_fixture');
+ });
+
+ it('keeps a pending checkout recoverable after its dialog is closed', async () => {
+ const pendingOrder = {
+ orderId: 'order_pending',
+ productCode: 'credit_topup',
+ offerCode: 'credit_topup_20',
+ amount: '20',
+ currency: 'cny',
+ status: 'PENDING' as const,
+ paymentAction: {
+ type: 'QR_CODE' as const,
+ value: 'https://pay.example.test/checkout/pending',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ },
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:01:00.000Z',
+ };
+
+ const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
+ await waitFor(() => expect(result.current.recovering).toBe(false));
+
+ act(() => result.current.resumeTopup(pendingOrder));
+ act(() => result.current.close());
+
+ expect(result.current.state.open).toBe(false);
+ expect(result.current.recoverables.topups).toEqual([pendingOrder]);
+
+ act(() => result.current.resumeTopup(result.current.recoverables.topups[0]));
+ expect(result.current.state.open).toBe(true);
+ expect(result.current.state.order).toEqual(pendingOrder);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/usePlanChange.test.ts b/apps/desktop/src/renderer/features/billing/__tests__/usePlanChange.test.ts
new file mode 100644
index 0000000000..ae75bcd52e
--- /dev/null
+++ b/apps/desktop/src/renderer/features/billing/__tests__/usePlanChange.test.ts
@@ -0,0 +1,360 @@
+// @vitest-environment jsdom
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const api = vi.hoisted(() => ({
+ getCurrentSubscription: vi.fn(),
+ quotePlanChange: vi.fn(),
+ confirmPlanChange: vi.fn(),
+ refreshPlanChange: vi.fn(),
+ cancelPlanChange: vi.fn(),
+}));
+
+vi.mock('../api', () => ({ billingApi: api }));
+
+import { usePlanChange } from '../usePlanChange';
+import {
+ billingPlanChangeIntentKey,
+ readBillingPlanChangeIntent,
+ writeBillingPlanChangeIntent,
+} from '../checkoutIntent';
+import type { BillingPlanChange } from '../../../../shared/billing';
+
+const ACCOUNT_ID = 'account-fixture';
+
+function change(overrides: Partial<BillingPlanChange> = {}): BillingPlanChange {
+ return {
+ planChangeId: 'plan_change_1',
+ changeType: 'UPGRADE',
+ status: 'QUOTED',
+ quotedAmountMinor: 1500,
+ quotedCurrency: 'cny',
+ quoteExpiresAt: '2099-01-01T00:00:00.000Z',
+ effectiveAt: '2026-08-01T00:00:00.000Z',
+ paymentAction: null,
+ ...overrides,
+ };
+}
+
+const TARGET_PLAN = {
+ product: { code: 'max', level: 300 },
+ offer: { code: 'max_month', interval: 'MONTH' as const },
+ terms: { amount: '50', currency: 'cny', creditAmount: '50' },
+};
+
+describe('usePlanChange', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ for (const mock of Object.values(api)) mock.mockReset();
+ api.getCurrentSubscription.mockResolvedValue({ subscription: null });
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ value: 'visible',
+ });
+ let uuid = 0;
+ vi.stubGlobal('crypto', {
+ randomUUID: () => `00000000-0000-4000-8000-${String(++uuid).padStart(12, '0')}`,
+ });
+ });
+
+ it('runs quote → confirm → applied and settles exactly once', async () => {
+ const onSettled = vi.fn();
+ api.quotePlanChange.mockResolvedValue(change());
+ api.confirmPlanChange.mockResolvedValue(change({ status: 'AWAITING_PAYMENT' }));
+ api.refreshPlanChange.mockResolvedValue(change({ status: 'APPLIED' }));
+ const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, onSettled));
+
+ await act(() => result.current.startQuote('max_month', TARGET_PLAN));
+ expect(result.current.state).toMatchObject({
+ open: true,
+ phase: 'QUOTE_READY',
+ targetPlan: TARGET_PLAN,
+ });
+ expect(readBillingPlanChangeIntent(ACCOUNT_ID)).toMatchObject({
+ targetOfferCode: 'max_month',
+ planChangeId: 'plan_change_1',
+ });
+
+ await act(() => result.current.confirm());
+ expect(result.current.state.phase).toBe('AWAITING_PAYMENT');
+
+ await act(() => result.current.refresh());
+ await act(() => result.current.refresh());
+ expect(result.current.state.phase).toBe('APPLIED');
+ expect(onSettled).toHaveBeenCalledTimes(1);
+ expect(onSettled).toHaveBeenCalledWith('APPLIED');
+ expect(readBillingPlanChangeIntent(ACCOUNT_ID)).toBeNull();
+ });
+
+ it.each(['FAILED', 'EXPIRED'] as const)(
+ 'notifies the parent when a pending plan change becomes %s',
+ async (status) => {
+ const onSettled = vi.fn();
+ api.quotePlanChange.mockResolvedValue(change());
+ api.confirmPlanChange.mockResolvedValue(change({ status: 'AWAITING_PAYMENT' }));
+ api.refreshPlanChange.mockResolvedValue(change({ status }));
+ const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, onSettled));
+
+ await act(() => result.current.startQuote('max_month', TARGET_PLAN));
+ await act(() => result.current.confirm());
+ await act(() => result.current.refresh());
+
+ expect(result.current.state.phase).toBe(status);
+ expect(onSettled).toHaveBeenCalledWith(status);
+ },
+ );
+
+ it('keeps the alipay QR from confirm and does not re-quote on refresh', async () => {
+ const qr = {
+ type: 'QR_CODE' as const,
+ value: 'https://qr.alipay.example/pay',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ };
+ api.quotePlanChange.mockResolvedValue(change());
+ api.confirmPlanChange.mockResolvedValue(
+ change({ status: 'AWAITING_PAYMENT', paymentAction: qr }),
+ );
+ api.refreshPlanChange.mockResolvedValue(
+ change({ status: 'AWAITING_PAYMENT', paymentAction: qr }),
+ );
+ const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, vi.fn()));
+
+ await act(() => result.current.startQuote('max_month', TARGET_PLAN));
+ await act(() => result.current.confirm());
+ await act(() => result.current.refresh());
+
+ expect(result.current.state.planChange?.paymentAction).toEqual(qr);
+ expect(api.quotePlanChange).toHaveBeenCalledTimes(1);
+ expect(api.refreshPlanChange).toHaveBeenCalledWith('plan_change_1');
+ });
+
+ it('polls a provider-pending change without confirming it again', async () => {
+ const onSettled = vi.fn();
+ api.quotePlanChange.mockResolvedValue(change());
+ api.confirmPlanChange.mockResolvedValue(change({ status: 'PENDING_PROVIDER' }));
+ api.refreshPlanChange.mockResolvedValue(change({ status: 'APPLIED' }));
+ const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, onSettled));
+
+ await act(() => result.current.startQuote('max_month', TARGET_PLAN));
+ await act(() => result.current.confirm());
+ expect(result.current.state.phase).toBe('PENDING_PROVIDER');
+
+ await act(() => result.current.confirm());
+ expect(api.confirmPlanChange).toHaveBeenCalledTimes(1);
+
+ act(() => window.dispatchEvent(new Event('focus')));
+ await waitFor(() => expect(result.current.state.phase).toBe('APPLIED'));
+ expect(api.refreshPlanChange).toHaveBeenCalledWith('plan_change_1');
+ expect(onSettled).toHaveBeenCalledWith('APPLIED');
+ });
+
+ it('schedules a downgrade and notifies so the pending banner can refresh', async () => {
+ const onSettled = vi.fn();
+ api.quotePlanChange.mockResolvedValue(
+ change({ changeType: 'DOWNGRADE', quotedAmountMinor: null, quotedCurrency: null }),
+ );
+ api.confirmPlanChange.mockResolvedValue(
+ change({ changeType: 'DOWNGRADE', status: 'SCHEDULED', quotedAmountMinor: null }),
+ );
+ const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, onSettled));
+
+ await act(() => result.current.startQuote('plus_month', null));
+ await act(() => result.current.confirm());
+
+ expect(result.current.state.phase).toBe('SCHEDULED');
+ expect(onSettled).toHaveBeenCalledWith('SCHEDULED');
+ expect(readBillingPlanChangeIntent(ACCOUNT_ID)).toBeNull();
+ });
+
+ it('cancels a scheduled downgrade (undo)', async () => {
+ const onSettled = vi.fn();
+ api.cancelPlanChange.mockResolvedValue(change({ changeType: 'DOWNGRADE', status: 'CANCELED' }));
+ const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, onSettled));
+
+ await act(() => result.current.cancelChange('plan_change_1'));
+
+ expect(api.cancelPlanChange).toHaveBeenCalledWith('plan_change_1');
+ expect(onSettled).toHaveBeenCalledWith('CANCELED');
+ });
+
+ it('ignores duplicate confirm clicks while a request is in flight', async () => {
+ api.quotePlanChange.mockResolvedValue(change());
+ let release!: (value: BillingPlanChange) => void;
+ api.confirmPlanChange.mockImplementation(
+ () => new Promise<BillingPlanChange>((resolve) => (release = resolve)),
+ );
+ const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, vi.fn()));
+
+ await act(() => result.current.startQuote('max_month', TARGET_PLAN));
+ let first!: Promise<void>;
+ act(() => {
+ first = result.current.confirm();
+ void result.current.confirm();
+ });
+ release(change({ status: 'AWAITING_PAYMENT' }));
+ await act(() => first);
+
+ expect(api.confirmPlanChange).toHaveBeenCalledTimes(1);
+ });
+
+ it('re-reads the server state when confirm fails, instead of restoring a stale quote', async () => {
+ const onSettled = vi.fn();
+ api.quotePlanChange.mockResolvedValue(
+ change({ changeType: 'DOWNGRADE', quotedAmountMinor: null }),
+ );
+ api.confirmPlanChange.mockRejectedValue(new Error('network'));
+ api.refreshPlanChange.mockResolvedValue(
+ change({ changeType: 'DOWNGRADE', status: 'SCHEDULED', quotedAmountMinor: null }),
+ );
+ const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, onSettled));
+
+ await act(() => result.current.startQuote('plus_month', null));
+ await act(() => result.current.confirm());
+
+ expect(api.refreshPlanChange).toHaveBeenCalledWith('plan_change_1');
+ expect(result.current.state).toMatchObject({ phase: 'SCHEDULED', error: false });
+ expect(onSettled).toHaveBeenCalledWith('SCHEDULED');
+ });
+
+ it('flags an error but keeps the quote when confirm fails and the change did not progress', async () => {
+ api.quotePlanChange.mockResolvedValue(change());
+ api.confirmPlanChange.mockRejectedValue(new Error('network'));
+ api.refreshPlanChange.mockResolvedValue(change());
+ const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, vi.fn()));
+
+ await act(() => result.current.startQuote('max_month', TARGET_PLAN));
+ await act(() => result.current.confirm());
+
+ expect(result.current.state).toMatchObject({
+ phase: 'QUOTE_READY',
+ error: true,
+ stale: false,
+ });
+ });
+
+ it('marks the snapshot stale when the recovery read also fails, then resyncs', async () => {
+ api.quotePlanChange.mockResolvedValue(change());
+ api.confirmPlanChange.mockRejectedValue(new Error('network'));
+ api.refreshPlanChange.mockRejectedValue(new Error('network'));
+ const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, vi.fn()));
+
+ await act(() => result.current.startQuote('max_month', TARGET_PLAN));
+ await act(() => result.current.confirm());
+
+ expect(result.current.state).toMatchObject({
+ phase: 'QUOTE_READY',
+ error: true,
+ stale: true,
+ });
+
+ // Connectivity returns: the next read swaps in the server truth and clears
+ // the stale flag, so the change becomes actionable again.
+ api.refreshPlanChange.mockResolvedValue(change({ status: 'AWAITING_PAYMENT' }));
+ await act(() => result.current.refresh());
+ expect(result.current.state).toMatchObject({
+ phase: 'AWAITING_PAYMENT',
+ error: false,
+ stale: false,
+ });
+ });
+
+ it('adopts the server pending projection when the quote request fails', async () => {
+ api.quotePlanChange.mockRejectedValue(new Error('conflict'));
+ api.getCurrentSubscription.mockResolvedValue({
+ subscription: {
+ subscriptionId: 'subscription_1',
+ status: 'ACTIVE',
+ currentPeriodStartAt: null,
+ currentPeriodEndAt: null,
+ entitlementValidUntil: null,
+ cancelAtPeriodEnd: false,
+ effectivePlan: null,
+ purchaseAttemptId: null,
+ paymentAction: null,
+ pendingPlanChange: {
+ ...change({ status: 'SCHEDULED', changeType: 'DOWNGRADE' }),
+ targetPlan: TARGET_PLAN,
+ },
+ },
+ });
+ const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, vi.fn()));
+
+ await act(() => result.current.startQuote('plus_month', null));
+
+ expect(result.current.state).toMatchObject({
+ open: true,
+ phase: 'SCHEDULED',
+ targetPlan: TARGET_PLAN,
+ });
+ });
+
+ it('reuses the same idempotency key when retrying the same target after a failure', async () => {
+ api.quotePlanChange.mockRejectedValueOnce(new Error('network'));
+ api.quotePlanChange.mockResolvedValueOnce(change());
+ const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, vi.fn()));
+
+ await act(() => result.current.startQuote('max_month', TARGET_PLAN));
+ await act(() => result.current.startQuote('max_month', TARGET_PLAN));
+
+ expect(api.quotePlanChange).toHaveBeenCalledTimes(2);
+ expect(api.quotePlanChange.mock.calls[0]![1]).toBe(api.quotePlanChange.mock.calls[1]![1]);
+ });
+
+ it('recovers a persisted in-flight change on restart and reopens the payment step', async () => {
+ writeBillingPlanChangeIntent(ACCOUNT_ID, {
+ version: 1,
+ targetOfferCode: 'max_month',
+ idempotencyKey: 'desktop:plan-change:12345678',
+ planChangeId: 'plan_change_1',
+ createdAt: '2026-07-24T00:00:00.000Z',
+ });
+ api.refreshPlanChange.mockResolvedValue(
+ change({
+ status: 'AWAITING_PAYMENT',
+ paymentAction: {
+ type: 'QR_CODE',
+ value: 'https://qr.alipay.example/pay',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ },
+ }),
+ );
+ const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, vi.fn()));
+
+ await waitFor(() => expect(result.current.state.phase).toBe('AWAITING_PAYMENT'));
+ expect(result.current.state.open).toBe(true);
+ expect(api.refreshPlanChange).toHaveBeenCalledWith('plan_change_1');
+ expect(api.quotePlanChange).not.toHaveBeenCalled();
+ });
+
+ it('clears a keyed intent that never produced a plan change instead of re-quoting', async () => {
+ writeBillingPlanChangeIntent(ACCOUNT_ID, {
+ version: 1,
+ targetOfferCode: 'max_month',
+ idempotencyKey: 'desktop:plan-change:12345678',
+ planChangeId: null,
+ createdAt: '2026-07-24T00:00:00.000Z',
+ });
+ renderHook(() => usePlanChange(ACCOUNT_ID, vi.fn()));
+
+ await waitFor(() => expect(readBillingPlanChangeIntent(ACCOUNT_ID)).toBeNull());
+ expect(api.quotePlanChange).not.toHaveBeenCalled();
+ expect(api.refreshPlanChange).not.toHaveBeenCalled();
+ });
+
+ it("never reads another account's intent", async () => {
+ writeBillingPlanChangeIntent('other-account', {
+ version: 1,
+ targetOfferCode: 'max_month',
+ idempotencyKey: 'desktop:plan-change:12345678',
+ planChangeId: 'plan_change_other',
+ createdAt: '2026-07-24T00:00:00.000Z',
+ });
+ const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, vi.fn()));
+
+ await Promise.resolve();
+ expect(api.refreshPlanChange).not.toHaveBeenCalled();
+ expect(result.current.state.phase).toBe('IDLE');
+ expect(localStorage.getItem(billingPlanChangeIntentKey('other-account'))).not.toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/billing/api.ts b/apps/desktop/src/renderer/features/billing/api.ts
new file mode 100644
index 0000000000..8e1cf43be7
--- /dev/null
+++ b/apps/desktop/src/renderer/features/billing/api.ts
@@ -0,0 +1,71 @@
+import type {
+ BillingCatalog,
+ BillingCurrentSubscription,
+ BillingOrderList,
+ BillingPaymentOrder,
+ BillingPlanChange,
+ BillingSubscription,
+ CreateBillingSubscriptionRequest,
+ CreateBillingTopupRequest,
+} from '../../../shared/billing';
+import type { ModelAccessBalance, ModelAccessCreditUsage } from '../../../shared/modelAccess';
+
+export const billingApi = {
+ getBalance(): Promise<ModelAccessBalance> {
+ return window.electronAPI.billing.getBalance();
+ },
+ getCreditUsage(): Promise<ModelAccessCreditUsage> {
+ return window.electronAPI.billing.getCreditUsage();
+ },
+ getCatalog(): Promise<BillingCatalog> {
+ return window.electronAPI.billing.getCatalog();
+ },
+ listOrders(limit = 20): Promise<BillingOrderList> {
+ return window.electronAPI.billing.listOrders({ limit });
+ },
+ getOrder(orderId: string): Promise<BillingPaymentOrder> {
+ return window.electronAPI.billing.getOrder({ orderId });
+ },
+ createTopup(
+ request: CreateBillingTopupRequest,
+ idempotencyKey: string,
+ ): Promise<BillingPaymentOrder> {
+ return window.electronAPI.billing.createTopup({ request, idempotencyKey });
+ },
+ refreshTopup(orderId: string): Promise<BillingPaymentOrder> {
+ return window.electronAPI.billing.refreshTopup({ orderId });
+ },
+ cancelTopup(orderId: string): Promise<BillingPaymentOrder> {
+ return window.electronAPI.billing.cancelTopup({ orderId });
+ },
+ retryTopup(orderId: string, idempotencyKey: string): Promise<BillingPaymentOrder> {
+ return window.electronAPI.billing.retryTopup({ orderId, idempotencyKey });
+ },
+ createSubscription(
+ request: CreateBillingSubscriptionRequest,
+ idempotencyKey: string,
+ ): Promise<BillingSubscription> {
+ return window.electronAPI.billing.createSubscription({ request, idempotencyKey });
+ },
+ getCurrentSubscription(): Promise<BillingCurrentSubscription> {
+ return window.electronAPI.billing.getCurrentSubscription();
+ },
+ refreshSubscriptionPurchase(purchaseAttemptId: string): Promise<BillingSubscription> {
+ return window.electronAPI.billing.refreshSubscriptionPurchase({ purchaseAttemptId });
+ },
+ quotePlanChange(targetOfferCode: string, idempotencyKey: string): Promise<BillingPlanChange> {
+ return window.electronAPI.billing.quotePlanChange({ targetOfferCode, idempotencyKey });
+ },
+ confirmPlanChange(planChangeId: string): Promise<BillingPlanChange> {
+ return window.electronAPI.billing.confirmPlanChange({ planChangeId });
+ },
+ refreshPlanChange(planChangeId: string): Promise<BillingPlanChange> {
+ return window.electronAPI.billing.refreshPlanChange({ planChangeId });
+ },
+ cancelPlanChange(planChangeId: string): Promise<BillingPlanChange> {
+ return window.electronAPI.billing.cancelPlanChange({ planChangeId });
+ },
+ openPaymentRedirect(url: string): Promise<{ success: boolean }> {
+ return window.electronAPI.billing.openPaymentRedirect({ url });
+ },
+};
diff --git a/apps/desktop/src/renderer/features/billing/checkoutIntent.ts b/apps/desktop/src/renderer/features/billing/checkoutIntent.ts
new file mode 100644
index 0000000000..30560f556f
--- /dev/null
+++ b/apps/desktop/src/renderer/features/billing/checkoutIntent.ts
@@ -0,0 +1,233 @@
+import type {
+ CreateBillingSubscriptionRequest,
+ CreateBillingTopupRequest,
+} from '../../../shared/billing';
+
+const LEGACY_BILLING_CHECKOUT_INTENT_KEY = 'cindy.billing.checkout-intent.v1';
+const BILLING_CHECKOUT_INTENT_KEY_PREFIX = 'cindy.billing.checkout-intent.v2';
+
+export type BillingCheckoutIntentV1 =
+ | {
+ version: 1;
+ kind: 'TOPUP';
+ idempotencyKey: string;
+ request: CreateBillingTopupRequest;
+ orderId: string | null;
+ createdAt: string;
+ }
+ | {
+ version: 1;
+ kind: 'SUBSCRIPTION';
+ idempotencyKey: string;
+ request: CreateBillingSubscriptionRequest;
+ subscriptionId: string | null;
+ purchaseAttemptId: string | null;
+ createdAt: string;
+ }
+ | {
+ version: 1;
+ kind: 'TOPUP_RETRY';
+ idempotencyKey: string;
+ orderId: string;
+ createdAt: string;
+ };
+
+const KEY_PATTERN = /^[A-Za-z0-9._:-]{8,128}$/;
+const CODE_PATTERN = /^[a-z][a-z0-9_]{1,63}$/;
+const AMOUNT_PATTERN = /^(0|[1-9]\d{0,14})(?:\.\d{1,9})?$/;
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
+}
+
+function isRequiredString(value: unknown): value is string {
+ return typeof value === 'string' && value.length > 0 && value.length <= 128;
+}
+
+function hasOnlyKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {
+ return Object.keys(value).every((key) => keys.includes(key));
+}
+
+function isTopupRequest(value: unknown): value is CreateBillingTopupRequest {
+ if (!isRecord(value)) return false;
+ return (
+ hasOnlyKeys(value, ['offerCode', 'amount', 'purchaseOptionId']) &&
+ typeof value.offerCode === 'string' &&
+ CODE_PATTERN.test(value.offerCode) &&
+ isRequiredString(value.purchaseOptionId) &&
+ (value.amount === undefined ||
+ (typeof value.amount === 'string' && AMOUNT_PATTERN.test(value.amount)))
+ );
+}
+
+function isSubscriptionRequest(value: unknown): value is CreateBillingSubscriptionRequest {
+ if (!isRecord(value)) return false;
+ return (
+ hasOnlyKeys(value, ['offerCode', 'purchaseOptionId']) &&
+ typeof value.offerCode === 'string' &&
+ CODE_PATTERN.test(value.offerCode) &&
+ isRequiredString(value.purchaseOptionId)
+ );
+}
+
+export function isBillingCheckoutIntent(value: unknown): value is BillingCheckoutIntentV1 {
+ if (
+ !isRecord(value) ||
+ value.version !== 1 ||
+ typeof value.idempotencyKey !== 'string' ||
+ !KEY_PATTERN.test(value.idempotencyKey) ||
+ typeof value.createdAt !== 'string' ||
+ !Number.isFinite(Date.parse(value.createdAt))
+ )
+ return false;
+ if (value.kind === 'TOPUP') {
+ return (
+ hasOnlyKeys(value, [
+ 'version',
+ 'kind',
+ 'idempotencyKey',
+ 'request',
+ 'orderId',
+ 'createdAt',
+ ]) &&
+ isTopupRequest(value.request) &&
+ (value.orderId === null || isRequiredString(value.orderId))
+ );
+ }
+ if (value.kind === 'SUBSCRIPTION') {
+ return (
+ hasOnlyKeys(value, [
+ 'version',
+ 'kind',
+ 'idempotencyKey',
+ 'request',
+ 'subscriptionId',
+ 'purchaseAttemptId',
+ 'createdAt',
+ ]) &&
+ isSubscriptionRequest(value.request) &&
+ (value.subscriptionId === null || isRequiredString(value.subscriptionId)) &&
+ (value.purchaseAttemptId === null || isRequiredString(value.purchaseAttemptId))
+ );
+ }
+ if (value.kind === 'TOPUP_RETRY') {
+ return (
+ hasOnlyKeys(value, ['version', 'kind', 'idempotencyKey', 'orderId', 'createdAt']) &&
+ isRequiredString(value.orderId)
+ );
+ }
+ return false;
+}
+
+export function billingCheckoutIntentKey(accountId: string): string {
+ return `${BILLING_CHECKOUT_INTENT_KEY_PREFIX}:${encodeURIComponent(accountId)}`;
+}
+
+export function readBillingCheckoutIntent(accountId: string): BillingCheckoutIntentV1 | null {
+ const storageKey = billingCheckoutIntentKey(accountId);
+ try {
+ // A v1 intent has no account identity and must never be replayed after an
+ // account switch. Drop it instead of guessing who created it.
+ localStorage.removeItem(LEGACY_BILLING_CHECKOUT_INTENT_KEY);
+ const raw = localStorage.getItem(storageKey);
+ if (!raw) return null;
+ const parsed: unknown = JSON.parse(raw);
+ if (isBillingCheckoutIntent(parsed)) return parsed;
+ localStorage.removeItem(storageKey);
+ } catch {
+ try {
+ localStorage.removeItem(storageKey);
+ } catch {
+ // Storage is unavailable; checkout remains server-recoverable.
+ }
+ }
+ return null;
+}
+
+export function writeBillingCheckoutIntent(
+ accountId: string,
+ intent: BillingCheckoutIntentV1,
+): void {
+ localStorage.removeItem(LEGACY_BILLING_CHECKOUT_INTENT_KEY);
+ localStorage.setItem(billingCheckoutIntentKey(accountId), JSON.stringify(intent));
+}
+
+export function clearBillingCheckoutIntent(accountId: string): void {
+ localStorage.removeItem(LEGACY_BILLING_CHECKOUT_INTENT_KEY);
+ localStorage.removeItem(billingCheckoutIntentKey(accountId));
+}
+
+export function newBillingIdempotencyKey(
+ kind: 'topup' | 'subscription' | 'retry' | 'plan-change',
+): string {
+ return `desktop:${kind}:${crypto.randomUUID()}`;
+}
+
+const BILLING_PLAN_CHANGE_INTENT_KEY_PREFIX = 'cindy.billing.plan-change-intent.v1';
+
+/**
+ * Request-level recovery only. The server's `pendingPlanChange` projection is
+ * the source of truth for what is actually open; a stored intent must never
+ * override it.
+ */
+export type BillingPlanChangeIntentV1 = {
+ version: 1;
+ targetOfferCode: string;
+ idempotencyKey: string;
+ planChangeId: string | null;
+ createdAt: string;
+};
+
+export function isBillingPlanChangeIntent(value: unknown): value is BillingPlanChangeIntentV1 {
+ return (
+ isRecord(value) &&
+ value.version === 1 &&
+ hasOnlyKeys(value, [
+ 'version',
+ 'targetOfferCode',
+ 'idempotencyKey',
+ 'planChangeId',
+ 'createdAt',
+ ]) &&
+ typeof value.targetOfferCode === 'string' &&
+ CODE_PATTERN.test(value.targetOfferCode) &&
+ typeof value.idempotencyKey === 'string' &&
+ KEY_PATTERN.test(value.idempotencyKey) &&
+ (value.planChangeId === null || isRequiredString(value.planChangeId)) &&
+ typeof value.createdAt === 'string' &&
+ Number.isFinite(Date.parse(value.createdAt))
+ );
+}
+
+export function billingPlanChangeIntentKey(accountId: string): string {
+ return `${BILLING_PLAN_CHANGE_INTENT_KEY_PREFIX}:${encodeURIComponent(accountId)}`;
+}
+
+export function readBillingPlanChangeIntent(accountId: string): BillingPlanChangeIntentV1 | null {
+ const storageKey = billingPlanChangeIntentKey(accountId);
+ try {
+ const raw = localStorage.getItem(storageKey);
+ if (!raw) return null;
+ const parsed: unknown = JSON.parse(raw);
+ if (isBillingPlanChangeIntent(parsed)) return parsed;
+ localStorage.removeItem(storageKey);
+ } catch {
+ try {
+ localStorage.removeItem(storageKey);
+ } catch {
+ // Storage is unavailable; the server projection still recovers state.
+ }
+ }
+ return null;
+}
+
+export function writeBillingPlanChangeIntent(
+ accountId: string,
+ intent: BillingPlanChangeIntentV1,
+): void {
+ localStorage.setItem(billingPlanChangeIntentKey(accountId), JSON.stringify(intent));
+}
+
+export function clearBillingPlanChangeIntent(accountId: string): void {
+ localStorage.removeItem(billingPlanChangeIntentKey(accountId));
+}
diff --git a/apps/desktop/src/renderer/features/billing/money.ts b/apps/desktop/src/renderer/features/billing/money.ts
new file mode 100644
index 0000000000..ea811d80bb
--- /dev/null
+++ b/apps/desktop/src/renderer/features/billing/money.ts
@@ -0,0 +1,79 @@
+/**
+ * Currency display helpers shared by the billing surfaces. Amounts arrive as
+ * exact decimal strings (or integer minor units) from the server; formatting
+ * must not re-introduce binary floating point rounding artifacts.
+ */
+
+const DECIMAL_PATTERN = /^([+-]?)(\d+)(?:\.(\d+))?$/;
+
+function roundToMinorUnits(amount: string, digits: number): bigint | null {
+ const matched = DECIMAL_PATTERN.exec(amount.trim());
+ if (!matched) return null;
+
+ const [, sign, whole, fraction = ''] = matched;
+ const scale = 10n ** BigInt(digits);
+ const keptFraction = fraction.slice(0, digits).padEnd(digits, '0');
+ let minor = BigInt(whole) * scale + BigInt(keptFraction || '0');
+ if ((fraction[digits] ?? '0') >= '5') minor += 1n;
+ return sign === '-' && minor !== 0n ? -minor : minor;
+}
+
+function formatMinorUnits(
+ minor: bigint,
+ formatter: Intl.NumberFormat,
+ digits: number,
+): string {
+ const scale = 10n ** BigInt(digits);
+ const negative = minor < 0n;
+ const magnitude = negative ? -minor : minor;
+ const whole = magnitude / scale;
+ const fraction = magnitude % scale;
+ // BigInt has no negative zero, so use Number -0 only as a locale-layout
+ // sentinel when a negative amount rounds to a magnitude below one unit.
+ const formattedWhole = negative ? (whole === 0n ? -0 : -whole) : whole;
+ const resolved = formatter.resolvedOptions();
+ const localizedFraction =
+ digits === 0
+ ? ''
+ : new Intl.NumberFormat(resolved.locale, {
+ numberingSystem: resolved.numberingSystem,
+ useGrouping: false,
+ minimumIntegerDigits: digits,
+ maximumFractionDigits: 0,
+ }).format(fraction);
+
+ return formatter
+ .formatToParts(formattedWhole)
+ .map((part) => (part.type === 'fraction' ? localizedFraction : part.value))
+ .join('');
+}
+
+export function formatBillingAmount(amount: string, currency: string): string {
+ try {
+ const fmt = new Intl.NumberFormat(undefined, {
+ style: 'currency',
+ currency: currency.toUpperCase(),
+ });
+ const digits = fmt.resolvedOptions().maximumFractionDigits ?? 2;
+ const minor = roundToMinorUnits(amount, digits);
+ return minor === null
+ ? `${amount} ${currency.toUpperCase()}`
+ : formatMinorUnits(minor, fmt, digits);
+ } catch {
+ return `${amount} ${currency.toUpperCase()}`;
+ }
+}
+
+export function formatBillingMinorAmount(minor: number, currency: string): string {
+ try {
+ if (!Number.isSafeInteger(minor)) return `${minor} ${currency.toUpperCase()}`;
+ const fmt = new Intl.NumberFormat(undefined, {
+ style: 'currency',
+ currency: currency.toUpperCase(),
+ });
+ const digits = fmt.resolvedOptions().maximumFractionDigits ?? 2;
+ return formatMinorUnits(BigInt(minor), fmt, digits);
+ } catch {
+ return `${minor} ${currency.toUpperCase()}`;
+ }
+}
diff --git a/apps/desktop/src/renderer/features/billing/useBillingCheckout.ts b/apps/desktop/src/renderer/features/billing/useBillingCheckout.ts
new file mode 100644
index 0000000000..64c84a0341
--- /dev/null
+++ b/apps/desktop/src/renderer/features/billing/useBillingCheckout.ts
@@ -0,0 +1,574 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import type {
+ BillingPaymentOrder,
+ BillingSubscription,
+ CreateBillingSubscriptionRequest,
+ CreateBillingTopupRequest,
+} from '../../../shared/billing';
+import { billingApi } from './api';
+import {
+ clearBillingCheckoutIntent,
+ newBillingIdempotencyKey,
+ readBillingCheckoutIntent,
+ writeBillingCheckoutIntent,
+ type BillingCheckoutIntentV1,
+} from './checkoutIntent';
+
+export type BillingCheckoutPhase =
+ | 'IDLE'
+ | 'CREATING'
+ | 'AWAITING_PAYMENT'
+ | 'FULFILLING'
+ | 'COMPLETED'
+ | 'FAILED'
+ | 'EXPIRED'
+ | 'CANCELED';
+
+export type BillingCheckoutState = {
+ open: boolean;
+ kind: 'TOPUP' | 'SUBSCRIPTION' | null;
+ phase: BillingCheckoutPhase;
+ intent: BillingCheckoutIntentV1 | null;
+ order: BillingPaymentOrder | null;
+ subscription: BillingSubscription | null;
+ error: boolean;
+};
+
+export type BillingRecoverables = {
+ topups: BillingPaymentOrder[];
+ subscription: BillingSubscription | null;
+};
+
+const INITIAL_STATE: BillingCheckoutState = {
+ open: false,
+ kind: null,
+ phase: 'IDLE',
+ intent: null,
+ order: null,
+ subscription: null,
+ error: false,
+};
+
+function phaseForOrder(order: BillingPaymentOrder): BillingCheckoutPhase {
+ if (order.status === 'FAILED') return 'FAILED';
+ if (order.status === 'EXPIRED') return 'EXPIRED';
+ if (order.status === 'CANCELED') return 'CANCELED';
+ if (order.status === 'SUCCEEDED') {
+ return order.fulfillmentStatus === 'SUCCEEDED' ? 'COMPLETED' : 'FULFILLING';
+ }
+ return 'AWAITING_PAYMENT';
+}
+
+function phaseForSubscription(subscription: BillingSubscription): BillingCheckoutPhase {
+ if (subscription.status === 'INCOMPLETE') return 'AWAITING_PAYMENT';
+ if (subscription.status === 'INCOMPLETE_EXPIRED') return 'EXPIRED';
+ if (subscription.status === 'CANCELED') return 'CANCELED';
+ if (subscription.status === 'TRIALING' || subscription.status === 'ACTIVE') return 'COMPLETED';
+ return 'FAILED';
+}
+
+function isTerminal(phase: BillingCheckoutPhase): boolean {
+ return ['COMPLETED', 'FAILED', 'EXPIRED', 'CANCELED'].includes(phase);
+}
+
+function isRecoverableTopup(value: {
+ status: string;
+ fulfillmentStatus?: string;
+ paymentAction: { expiresAt: string } | null;
+}): boolean {
+ return (
+ value.status === 'CREATED' ||
+ value.status === 'PENDING' ||
+ (value.status === 'SUCCEEDED' && value.fulfillmentStatus !== 'SUCCEEDED')
+ );
+}
+
+function persistIntent(accountId: string | null, intent: BillingCheckoutIntentV1 | null): void {
+ if (!accountId) return;
+ try {
+ if (intent) writeBillingCheckoutIntent(accountId, intent);
+ else clearBillingCheckoutIntent(accountId);
+ } catch {
+ // Server recovery remains available when browser storage is unavailable.
+ }
+}
+
+function matchesSubscriptionIntent(
+ subscription: BillingSubscription,
+ intent: Extract<BillingCheckoutIntentV1, { kind: 'SUBSCRIPTION' }>,
+): boolean {
+ if (intent.subscriptionId && subscription.subscriptionId !== intent.subscriptionId) return false;
+ if (intent.purchaseAttemptId && subscription.purchaseAttemptId !== intent.purchaseAttemptId) {
+ const terminalSameSubscription =
+ intent.subscriptionId !== null &&
+ subscription.subscriptionId === intent.subscriptionId &&
+ subscription.status !== 'INCOMPLETE' &&
+ subscription.purchaseAttemptId === null;
+ if (!terminalSameSubscription) return false;
+ }
+ return true;
+}
+
+export function useBillingCheckout(accountId: string | null) {
+ const [state, setState] = useState<BillingCheckoutState>(INITIAL_STATE);
+ const [recoverables, setRecoverables] = useState<BillingRecoverables>({
+ topups: [],
+ subscription: null,
+ });
+ const [recovering, setRecovering] = useState(true);
+ const stateRef = useRef(state);
+ const mountedRef = useRef(true);
+ const inFlightRef = useRef(false);
+ stateRef.current = state;
+
+ const applyOrder = useCallback(
+ (order: BillingPaymentOrder, intent: BillingCheckoutIntentV1 | null) => {
+ const nextIntent =
+ intent?.kind === 'TOPUP' && intent.orderId !== order.orderId
+ ? { ...intent, orderId: order.orderId }
+ : intent;
+ const phase = phaseForOrder(order);
+ if (nextIntent && !isTerminal(phase)) persistIntent(accountId, nextIntent);
+ if (isTerminal(phase)) persistIntent(accountId, null);
+ if (!mountedRef.current) return;
+ setRecoverables((current) => ({
+ ...current,
+ topups: isRecoverableTopup(order)
+ ? [order, ...current.topups.filter((item) => item.orderId !== order.orderId)]
+ : current.topups.filter((item) => item.orderId !== order.orderId),
+ }));
+ setState({
+ open: true,
+ kind: 'TOPUP',
+ phase,
+ intent: nextIntent,
+ order,
+ subscription: null,
+ error: false,
+ });
+ },
+ [accountId],
+ );
+
+ const applySubscription = useCallback(
+ (subscription: BillingSubscription, intent: BillingCheckoutIntentV1 | null) => {
+ if (intent?.kind === 'SUBSCRIPTION' && !matchesSubscriptionIntent(subscription, intent))
+ return false;
+ const nextIntent =
+ intent?.kind === 'SUBSCRIPTION'
+ ? {
+ ...intent,
+ subscriptionId: subscription.subscriptionId,
+ purchaseAttemptId: subscription.purchaseAttemptId,
+ }
+ : intent;
+ const phase = phaseForSubscription(subscription);
+ if (nextIntent && !isTerminal(phase)) persistIntent(accountId, nextIntent);
+ if (isTerminal(phase)) persistIntent(accountId, null);
+ if (!mountedRef.current) return true;
+ setRecoverables((current) => ({
+ ...current,
+ subscription: subscription.status === 'INCOMPLETE' ? subscription : null,
+ }));
+ setState({
+ open: true,
+ kind: 'SUBSCRIPTION',
+ phase,
+ intent: nextIntent,
+ order: null,
+ subscription,
+ error: false,
+ });
+ return true;
+ },
+ [accountId],
+ );
+
+ const failCurrentOperation = useCallback(() => {
+ if (!mountedRef.current) return;
+ setState((current) => ({ ...current, phase: 'FAILED', error: true }));
+ }, []);
+
+ const withRequestLock = useCallback(async (request: () => Promise<void>) => {
+ if (inFlightRef.current) return;
+ inFlightRef.current = true;
+ try {
+ await request();
+ } finally {
+ inFlightRef.current = false;
+ }
+ }, []);
+
+ const startTopup = useCallback(
+ async (request: CreateBillingTopupRequest) => {
+ if (!accountId || inFlightRef.current) return;
+ const intent: BillingCheckoutIntentV1 = {
+ version: 1,
+ kind: 'TOPUP',
+ idempotencyKey: newBillingIdempotencyKey('topup'),
+ request,
+ orderId: null,
+ createdAt: new Date().toISOString(),
+ };
+ persistIntent(accountId, intent);
+ setState({
+ open: true,
+ kind: 'TOPUP',
+ phase: 'CREATING',
+ intent,
+ order: null,
+ subscription: null,
+ error: false,
+ });
+ await withRequestLock(async () => {
+ try {
+ applyOrder(await billingApi.createTopup(request, intent.idempotencyKey), intent);
+ } catch {
+ failCurrentOperation();
+ }
+ });
+ },
+ [accountId, applyOrder, failCurrentOperation, withRequestLock],
+ );
+
+ const recoverPendingSubscription = useCallback(
+ async (intent: Extract<BillingCheckoutIntentV1, { kind: 'SUBSCRIPTION' }>) => {
+ if (!intent.subscriptionId && !intent.purchaseAttemptId) return false;
+ try {
+ const current = (await billingApi.getCurrentSubscription()).subscription;
+ if (current?.status !== 'INCOMPLETE') return false;
+ return applySubscription(current, intent);
+ } catch {
+ return false;
+ }
+ },
+ [applySubscription],
+ );
+
+ const startSubscription = useCallback(
+ async (request: CreateBillingSubscriptionRequest) => {
+ if (!accountId || inFlightRef.current) return;
+ const intent: BillingCheckoutIntentV1 = {
+ version: 1,
+ kind: 'SUBSCRIPTION',
+ idempotencyKey: newBillingIdempotencyKey('subscription'),
+ request,
+ subscriptionId: null,
+ purchaseAttemptId: null,
+ createdAt: new Date().toISOString(),
+ };
+ persistIntent(accountId, intent);
+ setState({
+ open: true,
+ kind: 'SUBSCRIPTION',
+ phase: 'CREATING',
+ intent,
+ order: null,
+ subscription: null,
+ error: false,
+ });
+ await withRequestLock(async () => {
+ try {
+ applySubscription(
+ await billingApi.createSubscription(request, intent.idempotencyKey),
+ intent,
+ );
+ } catch {
+ if (!(await recoverPendingSubscription(intent))) failCurrentOperation();
+ }
+ });
+ },
+ [
+ accountId,
+ applySubscription,
+ failCurrentOperation,
+ recoverPendingSubscription,
+ withRequestLock,
+ ],
+ );
+
+ const refreshActive = useCallback(async () => {
+ await withRequestLock(async () => {
+ const current = stateRef.current;
+ try {
+ if (current.kind === 'TOPUP' && current.order) {
+ const order =
+ current.phase === 'AWAITING_PAYMENT'
+ ? await billingApi.refreshTopup(current.order.orderId)
+ : await billingApi.getOrder(current.order.orderId);
+ applyOrder(order, current.intent);
+ return;
+ }
+ if (current.kind === 'SUBSCRIPTION' && current.subscription) {
+ const subscription =
+ current.phase === 'AWAITING_PAYMENT' && current.subscription.purchaseAttemptId
+ ? await billingApi.refreshSubscriptionPurchase(current.subscription.purchaseAttemptId)
+ : (await billingApi.getCurrentSubscription()).subscription;
+ if (subscription && !applySubscription(subscription, current.intent)) {
+ failCurrentOperation();
+ }
+ }
+ } catch {
+ if (mountedRef.current) setState((value) => ({ ...value, error: true }));
+ }
+ });
+ }, [applyOrder, applySubscription, failCurrentOperation, withRequestLock]);
+
+ const retry = useCallback(async () => {
+ if (inFlightRef.current) return;
+ const current = stateRef.current;
+ if (current.error && current.intent?.kind === 'TOPUP_RETRY') {
+ await startTopupRetryWithIntent(current.intent);
+ return;
+ }
+ if (current.kind === 'TOPUP' && current.order) {
+ const intent: Extract<BillingCheckoutIntentV1, { kind: 'TOPUP_RETRY' }> = {
+ version: 1,
+ kind: 'TOPUP_RETRY',
+ idempotencyKey: newBillingIdempotencyKey('retry'),
+ orderId: current.order.orderId,
+ createdAt: new Date().toISOString(),
+ };
+ persistIntent(accountId, intent);
+ await startTopupRetryWithIntent(intent);
+ return;
+ }
+ if (current.intent && !current.order && !current.subscription) {
+ if (current.intent.kind === 'TOPUP') {
+ await startTopupWithIntent(current.intent);
+ } else if (current.intent.kind === 'SUBSCRIPTION') {
+ await startSubscriptionWithIntent(current.intent);
+ } else {
+ await startTopupRetryWithIntent(current.intent);
+ }
+ }
+ }, [accountId, applyOrder, failCurrentOperation, withRequestLock]);
+
+ async function startTopupWithIntent(intent: Extract<BillingCheckoutIntentV1, { kind: 'TOPUP' }>) {
+ setState({
+ open: true,
+ kind: 'TOPUP',
+ phase: 'CREATING',
+ intent,
+ order: null,
+ subscription: null,
+ error: false,
+ });
+ await withRequestLock(async () => {
+ try {
+ const order = intent.orderId
+ ? await billingApi.getOrder(intent.orderId)
+ : await billingApi.createTopup(intent.request, intent.idempotencyKey);
+ applyOrder(order, intent);
+ } catch {
+ failCurrentOperation();
+ }
+ });
+ }
+
+ async function startSubscriptionWithIntent(
+ intent: Extract<BillingCheckoutIntentV1, { kind: 'SUBSCRIPTION' }>,
+ ) {
+ setState({
+ open: true,
+ kind: 'SUBSCRIPTION',
+ phase: 'CREATING',
+ intent,
+ order: null,
+ subscription: null,
+ error: false,
+ });
+ await withRequestLock(async () => {
+ try {
+ const subscription = intent.purchaseAttemptId
+ ? await billingApi.refreshSubscriptionPurchase(intent.purchaseAttemptId)
+ : intent.subscriptionId
+ ? (await billingApi.getCurrentSubscription()).subscription
+ : await billingApi.createSubscription(intent.request, intent.idempotencyKey);
+ if (!subscription || !applySubscription(subscription, intent)) failCurrentOperation();
+ } catch {
+ if (!(await recoverPendingSubscription(intent))) failCurrentOperation();
+ }
+ });
+ }
+
+ async function startTopupRetryWithIntent(
+ intent: Extract<BillingCheckoutIntentV1, { kind: 'TOPUP_RETRY' }>,
+ ) {
+ const previousOrder =
+ stateRef.current.order?.orderId === intent.orderId ? stateRef.current.order : null;
+ setState({
+ open: true,
+ kind: 'TOPUP',
+ phase: 'CREATING',
+ intent,
+ order: previousOrder,
+ subscription: null,
+ error: false,
+ });
+ await withRequestLock(async () => {
+ try {
+ applyOrder(await billingApi.retryTopup(intent.orderId, intent.idempotencyKey), intent);
+ } catch {
+ failCurrentOperation();
+ }
+ });
+ }
+
+ const cancel = useCallback(async () => {
+ const current = stateRef.current;
+ if (current.kind !== 'TOPUP' || !current.order) return;
+ await withRequestLock(async () => {
+ try {
+ applyOrder(await billingApi.cancelTopup(current.order!.orderId), current.intent);
+ } catch {
+ if (mountedRef.current) setState((value) => ({ ...value, error: true }));
+ }
+ });
+ }, [applyOrder, withRequestLock]);
+
+ const close = useCallback(() => {
+ setState((current) => ({ ...current, open: false }));
+ }, []);
+
+ const resumeTopup = useCallback(
+ (order: BillingPaymentOrder) => {
+ applyOrder(order, null);
+ },
+ [applyOrder],
+ );
+
+ const resumeSubscription = useCallback(
+ (subscription: BillingSubscription) => {
+ applySubscription(subscription, null);
+ },
+ [applySubscription],
+ );
+
+ useEffect(() => {
+ mountedRef.current = true;
+ if (!accountId) {
+ setState(INITIAL_STATE);
+ setRecoverables({ topups: [], subscription: null });
+ setRecovering(false);
+ return () => {
+ mountedRef.current = false;
+ };
+ }
+ const restore = async () => {
+ const intent = readBillingCheckoutIntent(accountId);
+ inFlightRef.current = true;
+ try {
+ const [ordersResult, subscriptionResult] = await Promise.allSettled([
+ billingApi.listOrders(),
+ billingApi.getCurrentSubscription(),
+ ]);
+ if (!mountedRef.current) return;
+ setRecoverables({
+ topups:
+ ordersResult.status === 'fulfilled'
+ ? ordersResult.value.orders.filter(isRecoverableTopup)
+ : [],
+ subscription:
+ subscriptionResult.status === 'fulfilled' &&
+ subscriptionResult.value.subscription?.status === 'INCOMPLETE'
+ ? subscriptionResult.value.subscription
+ : null,
+ });
+
+ if (!intent) return;
+ setState({
+ open: true,
+ kind: intent.kind === 'SUBSCRIPTION' ? 'SUBSCRIPTION' : 'TOPUP',
+ phase: 'CREATING',
+ intent,
+ order: null,
+ subscription: null,
+ error: false,
+ });
+ try {
+ if (intent.kind === 'TOPUP') {
+ const listedOrder =
+ intent.orderId && ordersResult.status === 'fulfilled'
+ ? ordersResult.value.orders.find((order) => order.orderId === intent.orderId)
+ : null;
+ const order =
+ listedOrder ??
+ (intent.orderId
+ ? await billingApi.getOrder(intent.orderId)
+ : await billingApi.createTopup(intent.request, intent.idempotencyKey));
+ applyOrder(order, intent);
+ return;
+ }
+
+ if (intent.kind === 'TOPUP_RETRY') {
+ applyOrder(await billingApi.retryTopup(intent.orderId, intent.idempotencyKey), intent);
+ return;
+ }
+
+ if (
+ intent.subscriptionId &&
+ !intent.purchaseAttemptId &&
+ subscriptionResult.status === 'rejected'
+ ) {
+ failCurrentOperation();
+ return;
+ }
+ const currentSubscription =
+ subscriptionResult.status === 'fulfilled'
+ ? subscriptionResult.value.subscription
+ : null;
+ const subscription = intent.purchaseAttemptId
+ ? await billingApi.refreshSubscriptionPurchase(intent.purchaseAttemptId)
+ : intent.subscriptionId
+ ? currentSubscription
+ : await billingApi.createSubscription(intent.request, intent.idempotencyKey);
+ if (!subscription || !applySubscription(subscription, intent)) failCurrentOperation();
+ } catch {
+ failCurrentOperation();
+ }
+ } finally {
+ inFlightRef.current = false;
+ if (mountedRef.current) setRecovering(false);
+ }
+ };
+ void restore();
+ return () => {
+ mountedRef.current = false;
+ };
+ }, [accountId, applyOrder, applySubscription, failCurrentOperation]);
+
+ useEffect(() => {
+ if (!state.open || (state.phase !== 'AWAITING_PAYMENT' && state.phase !== 'FULFILLING')) return;
+ const timer = window.setInterval(() => {
+ if (document.visibilityState === 'visible') void refreshActive();
+ }, 3_000);
+ const onVisible = () => {
+ if (document.visibilityState === 'visible') void refreshActive();
+ };
+ window.addEventListener('focus', onVisible);
+ document.addEventListener('visibilitychange', onVisible);
+ return () => {
+ window.clearInterval(timer);
+ window.removeEventListener('focus', onVisible);
+ document.removeEventListener('visibilitychange', onVisible);
+ };
+ }, [refreshActive, state.open, state.phase]);
+
+ return {
+ state,
+ recoverables,
+ recovering,
+ startTopup,
+ startSubscription,
+ refreshActive,
+ retry,
+ cancel,
+ close,
+ resumeTopup,
+ resumeSubscription,
+ };
+}
+
+export { isRecoverableTopup, phaseForOrder, phaseForSubscription };
diff --git a/apps/desktop/src/renderer/features/billing/usePlanChange.ts b/apps/desktop/src/renderer/features/billing/usePlanChange.ts
new file mode 100644
index 0000000000..75d537c487
--- /dev/null
+++ b/apps/desktop/src/renderer/features/billing/usePlanChange.ts
@@ -0,0 +1,377 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import type {
+ BillingPendingPlanChange,
+ BillingPlanChange,
+ BillingPlanChangeTargetPlan,
+} from '../../../shared/billing';
+import { billingApi } from './api';
+import {
+ clearBillingPlanChangeIntent,
+ newBillingIdempotencyKey,
+ readBillingPlanChangeIntent,
+ writeBillingPlanChangeIntent,
+ type BillingPlanChangeIntentV1,
+} from './checkoutIntent';
+
+export type PlanChangePhase =
+ | 'IDLE'
+ | 'QUOTING'
+ | 'QUOTE_READY'
+ | 'CONFIRMING'
+ | 'PENDING_PROVIDER'
+ | 'AWAITING_PAYMENT'
+ | 'SCHEDULED'
+ | 'APPLIED'
+ | 'CANCELED'
+ | 'FAILED'
+ | 'EXPIRED';
+
+export type PlanChangeState = {
+ open: boolean;
+ phase: PlanChangePhase;
+ planChange: BillingPlanChange | null;
+ targetPlan: BillingPlanChangeTargetPlan | null;
+ error: boolean;
+ /**
+ * True when the rendered change is a pre-request snapshot that could not be
+ * re-read from the server (confirm and the recovery read both failed). A
+ * stale quote must not be confirmable until a fresh read succeeds.
+ */
+ stale: boolean;
+};
+
+export type PlanChangeSettledKind = 'APPLIED' | 'CANCELED' | 'SCHEDULED' | 'FAILED' | 'EXPIRED';
+
+const INITIAL_STATE: PlanChangeState = {
+ open: false,
+ phase: 'IDLE',
+ planChange: null,
+ targetPlan: null,
+ error: false,
+ stale: false,
+};
+
+/**
+ * Every phase is derived from the server status. Unknown statuses can never
+ * reach here: the main-process projection rejects them, so the renderer only
+ * sees the closed enum.
+ */
+function phaseForPlanChange(change: BillingPlanChange): PlanChangePhase {
+ switch (change.status) {
+ case 'QUOTED':
+ return 'QUOTE_READY';
+ case 'PENDING_PROVIDER':
+ return 'PENDING_PROVIDER';
+ case 'AWAITING_PAYMENT':
+ return 'AWAITING_PAYMENT';
+ case 'SCHEDULED':
+ return 'SCHEDULED';
+ case 'APPLIED':
+ return 'APPLIED';
+ case 'CANCELED':
+ return 'CANCELED';
+ case 'EXPIRED':
+ return 'EXPIRED';
+ default:
+ return 'FAILED';
+ }
+}
+
+function isSettledPhase(phase: PlanChangePhase): boolean {
+ return (
+ phase === 'APPLIED' ||
+ phase === 'CANCELED' ||
+ phase === 'FAILED' ||
+ phase === 'EXPIRED' ||
+ phase === 'SCHEDULED'
+ );
+}
+
+export function usePlanChange(
+ accountId: string | null,
+ onSettled: (kind: PlanChangeSettledKind) => void,
+) {
+ const [state, setState] = useState<PlanChangeState>(INITIAL_STATE);
+ const stateRef = useRef(state);
+ const mountedRef = useRef(true);
+ const inFlightRef = useRef(false);
+ const settledNotifiedRef = useRef(new Set<string>());
+ const onSettledRef = useRef(onSettled);
+ stateRef.current = state;
+ onSettledRef.current = onSettled;
+
+ const persistIntent = useCallback(
+ (intent: BillingPlanChangeIntentV1 | null) => {
+ if (!accountId) return;
+ try {
+ if (intent) writeBillingPlanChangeIntent(accountId, intent);
+ else clearBillingPlanChangeIntent(accountId);
+ } catch {
+ // Server projection still recovers state without local storage.
+ }
+ },
+ [accountId],
+ );
+
+ const notifySettled = useCallback((change: BillingPlanChange) => {
+ if (
+ change.status !== 'APPLIED' &&
+ change.status !== 'CANCELED' &&
+ change.status !== 'SCHEDULED' &&
+ change.status !== 'FAILED' &&
+ change.status !== 'EXPIRED'
+ )
+ return;
+ const settleKey = `${change.planChangeId}:${change.status}`;
+ if (settledNotifiedRef.current.has(settleKey)) return;
+ settledNotifiedRef.current.add(settleKey);
+ onSettledRef.current(change.status);
+ }, []);
+
+ const applyChange = useCallback(
+ (
+ change: BillingPlanChange,
+ options?: { targetPlan?: BillingPlanChangeTargetPlan | null; open?: boolean },
+ ) => {
+ const phase = phaseForPlanChange(change);
+ if (phase !== 'QUOTE_READY' && phase !== 'AWAITING_PAYMENT') {
+ persistIntent(null);
+ }
+ notifySettled(change);
+ if (!mountedRef.current) return;
+ setState((current) => ({
+ open: options?.open ?? current.open,
+ phase,
+ planChange: change,
+ targetPlan: options?.targetPlan !== undefined ? options.targetPlan : current.targetPlan,
+ error: false,
+ stale: false,
+ }));
+ },
+ [notifySettled, persistIntent],
+ );
+
+ const withRequestLock = useCallback(async (request: () => Promise<void>) => {
+ if (inFlightRef.current) return;
+ inFlightRef.current = true;
+ try {
+ await request();
+ } finally {
+ inFlightRef.current = false;
+ }
+ }, []);
+
+ /** Adopt whatever the server says is open; never trust local state over it. */
+ const adoptServerPending = useCallback(async (): Promise<boolean> => {
+ try {
+ const pending = (await billingApi.getCurrentSubscription()).subscription?.pendingPlanChange;
+ if (!pending) return false;
+ applyChange(pending, { targetPlan: pending.targetPlan, open: true });
+ return true;
+ } catch {
+ return false;
+ }
+ }, [applyChange]);
+
+ const startQuote = useCallback(
+ async (targetOfferCode: string, targetPlan: BillingPlanChangeTargetPlan | null) => {
+ if (!accountId || inFlightRef.current) return;
+ const previous = readBillingPlanChangeIntent(accountId);
+ const intent: BillingPlanChangeIntentV1 =
+ previous && previous.targetOfferCode === targetOfferCode && !previous.planChangeId
+ ? previous
+ : {
+ version: 1,
+ targetOfferCode,
+ idempotencyKey: newBillingIdempotencyKey('plan-change'),
+ planChangeId: null,
+ createdAt: new Date().toISOString(),
+ };
+ persistIntent(intent);
+ setState({
+ open: true,
+ phase: 'QUOTING',
+ planChange: null,
+ targetPlan,
+ error: false,
+ stale: false,
+ });
+ await withRequestLock(async () => {
+ try {
+ const change = await billingApi.quotePlanChange(targetOfferCode, intent.idempotencyKey);
+ persistIntent({ ...intent, planChangeId: change.planChangeId });
+ applyChange(change, { targetPlan });
+ } catch {
+ if (await adoptServerPending()) return;
+ if (mountedRef.current) {
+ setState((current) => ({ ...current, phase: 'FAILED', error: true }));
+ }
+ }
+ });
+ },
+ [accountId, adoptServerPending, applyChange, persistIntent, withRequestLock],
+ );
+
+ const confirm = useCallback(async () => {
+ const current = stateRef.current;
+ if (!current.planChange || current.planChange.status !== 'QUOTED' || inFlightRef.current)
+ return;
+ const change = current.planChange;
+ setState((value) => ({ ...value, phase: 'CONFIRMING', error: false }));
+ await withRequestLock(async () => {
+ try {
+ applyChange(await billingApi.confirmPlanChange(change.planChangeId));
+ } catch {
+ // The confirm may have landed server-side even though the response was
+ // lost. Re-read the change before restoring anything local, so a
+ // progressed change is never re-rendered as a confirmable quote.
+ let latest: BillingPlanChange | null = null;
+ try {
+ latest = await billingApi.refreshPlanChange(change.planChangeId);
+ } catch {
+ // Fall back to the pre-request snapshot below.
+ }
+ if (!mountedRef.current) return;
+ if (latest) {
+ applyChange(latest);
+ if (latest.status === change.status) {
+ setState((value) => ({ ...value, error: true }));
+ }
+ } else {
+ // Offline fallback: the snapshot may lag the server. Mark it stale so
+ // the dialog swaps confirm for a resync action, and let the poll
+ // effect keep retrying the read until connectivity returns.
+ setState((value) => ({
+ ...value,
+ phase: phaseForPlanChange(change),
+ error: true,
+ stale: true,
+ }));
+ }
+ }
+ });
+ }, [applyChange, withRequestLock]);
+
+ const refresh = useCallback(async () => {
+ const current = stateRef.current;
+ if (!current.planChange) return;
+ const planChangeId = current.planChange.planChangeId;
+ await withRequestLock(async () => {
+ try {
+ applyChange(await billingApi.refreshPlanChange(planChangeId));
+ } catch {
+ if (mountedRef.current) setState((value) => ({ ...value, error: true }));
+ }
+ });
+ }, [applyChange, withRequestLock]);
+
+ /** Cancels a quoted change or a scheduled downgrade (撤销). */
+ const cancelChange = useCallback(
+ async (planChangeId: string) => {
+ if (inFlightRef.current) return;
+ await withRequestLock(async () => {
+ try {
+ applyChange(await billingApi.cancelPlanChange(planChangeId));
+ } catch {
+ if (mountedRef.current) setState((value) => ({ ...value, error: true }));
+ }
+ });
+ },
+ [applyChange, withRequestLock],
+ );
+
+ /** Re-enter a server-reported open change (e.g. resume an alipay QR). */
+ const resumePending = useCallback(
+ (pending: BillingPendingPlanChange) => {
+ applyChange(pending, { targetPlan: pending.targetPlan, open: true });
+ },
+ [applyChange],
+ );
+
+ const close = useCallback(() => {
+ setState((current) =>
+ current.phase === 'QUOTING' || current.phase === 'CONFIRMING'
+ ? current
+ : { ...current, open: false },
+ );
+ }, []);
+
+ useEffect(() => {
+ mountedRef.current = true;
+ settledNotifiedRef.current = new Set();
+ setState(INITIAL_STATE);
+ if (!accountId) {
+ return () => {
+ mountedRef.current = false;
+ };
+ }
+ const intent = readBillingPlanChangeIntent(accountId);
+ if (intent?.planChangeId) {
+ const planChangeId = intent.planChangeId;
+ void withRequestLock(async () => {
+ try {
+ const change = await billingApi.refreshPlanChange(planChangeId);
+ if (!mountedRef.current) return;
+ const phase = phaseForPlanChange(change);
+ applyChange(change, {
+ // The catalog-side target label is rebuilt from the server pending
+ // projection when present; a bare refresh keeps it unknown.
+ targetPlan: null,
+ open:
+ phase === 'AWAITING_PAYMENT' ||
+ phase === 'PENDING_PROVIDER' ||
+ phase === 'QUOTE_READY',
+ });
+ if (isSettledPhase(phase)) persistIntent(null);
+ } catch {
+ // The pendingPlanChange banner remains the recovery entry point.
+ }
+ });
+ } else if (intent) {
+ // The quote request never resolved locally. If it landed server-side the
+ // pendingPlanChange projection will surface it; the stored key alone must
+ // not trigger a new quote on startup.
+ persistIntent(null);
+ }
+ return () => {
+ mountedRef.current = false;
+ };
+ }, [accountId, applyChange, persistIntent, withRequestLock]);
+
+ useEffect(() => {
+ // Poll while waiting for a payment, and also while showing a stale
+ // snapshot so the dialog resynchronizes on its own once the server is
+ // reachable again.
+ if (
+ !state.open ||
+ (state.phase !== 'AWAITING_PAYMENT' && state.phase !== 'PENDING_PROVIDER' && !state.stale)
+ )
+ return;
+ const timer = window.setInterval(() => {
+ if (document.visibilityState === 'visible') void refresh();
+ }, 3_000);
+ const onVisible = () => {
+ if (document.visibilityState === 'visible') void refresh();
+ };
+ window.addEventListener('focus', onVisible);
+ document.addEventListener('visibilitychange', onVisible);
+ return () => {
+ window.clearInterval(timer);
+ window.removeEventListener('focus', onVisible);
+ document.removeEventListener('visibilitychange', onVisible);
+ };
+ }, [refresh, state.open, state.phase, state.stale]);
+
+ return {
+ state,
+ startQuote,
+ confirm,
+ refresh,
+ cancelChange,
+ resumePending,
+ close,
+ };
+}
+
+export { phaseForPlanChange };
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index d237fcfb7e..f360a8cb5b 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -78,6 +78,7 @@
},
"tabs": {
"general": "General",
+ "billing": "Usage and billing",
"personalization": "Personalization",
"apiKeys": "Tool Keys",
"voiceInput": "Voice Input",
@@ -99,6 +100,7 @@
},
"sections": {
"user": "User",
+ "billing": "Usage and billing",
"appearance": "Appearance",
"notifications": "Notifications",
"agentIsland": "Agent Island",
@@ -6827,6 +6829,229 @@
"workdirKeyInexact": "The chosen directory path is too long to place transcripts; downgraded to chat history only."
}
},
+ "billing": {
+ "sidebar": "Credits & plans",
+ "settings": {
+ "title": "Usage and billing",
+ "subtitle": "Review your current subscription or purchase server-provided plans and credits.",
+ "loading": "Loading subscription status…",
+ "subscriptionCard": {
+ "title": "Current plan",
+ "empty": "No active subscription",
+ "emptyTitle": "No subscription plan",
+ "unnamedPlan": "Subscription plan",
+ "unavailable": "Subscription status is temporarily unavailable. Refresh to try again.",
+ "action": "View plans",
+ "changeAction": "Change plan"
+ },
+ "topupCard": {
+ "title": "Credits",
+ "description": "Purchase credits for usage-based models and features.",
+ "cardTitle": "Buy credits as needed",
+ "cardDescription": "Available credit products are configured by the server.",
+ "action": "Buy credits"
+ }
+ },
+ "balance": {
+ "title": "Available balance",
+ "plan": "Plan credits",
+ "purchased": "Purchased credits",
+ "promotional": "Promotional credits",
+ "notProvisioned": "Credits have not been enabled for this account.",
+ "notSupported": "Balance lookup is not supported for this account.",
+ "unavailable": "Balance is temporarily unavailable. Refresh to try again."
+ },
+ "usage": {
+ "observedAt": "Balance updated {{date}}",
+ "used": "Used",
+ "total": "Total",
+ "remaining": "Remaining",
+ "progressLabel": "{{label}} usage",
+ "historyUnavailable": "Usage history is incomplete. Only the remaining balance is available.",
+ "percentUsed": "{{percent}}% used",
+ "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.",
+ "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",
+ "remaining": "Remaining",
+ "expiresAt": "Expires {{date}}",
+ "states": {
+ "active": "Active",
+ "depleted": "Depleted",
+ "expired": "Expired",
+ "voided": "Voided"
+ }
+ }
+ },
+ "dialogs": {
+ "subscription": {
+ "title": "Choose a subscription plan",
+ "description": "Only currently configured server plans are shown. Choose a plan before selecting its payment method."
+ },
+ "topup": {
+ "title": "Buy credits",
+ "description": "Only currently configured server credit products are shown. Choose a product before selecting its payment method."
+ }
+ },
+ "eyebrow": "Account & usage",
+ "title": "Choose the plan that fits",
+ "subtitle": "Plans and payment methods are delivered by the server. Choose a plan first to see its currently supported payment methods.",
+ "steps": {
+ "offer": {
+ "title": "Choose a plan",
+ "description": "Only currently purchasable credit and subscription offers are shown."
+ },
+ "channel": {
+ "title": "Choose a payment method",
+ "description": "Supported payment methods can differ by plan.",
+ "selectOfferFirst": "Choose a plan to see its supported payment methods"
+ },
+ "confirm": {
+ "title": "Review and pay",
+ "description": "Review the plan and payment method before creating payment.",
+ "selectChannelFirst": "Choose a payment method to continue"
+ }
+ },
+ "actions": {
+ "refreshCatalog": "Refresh",
+ "retry": "Retry",
+ "pay": "Review and pay",
+ "refresh": "Refresh status",
+ "cancelPayment": "Cancel payment",
+ "close": "Close"
+ },
+ "catalog": {
+ "errorTitle": "Plans are temporarily unavailable",
+ "errorDescription": "Check your connection and retry. Local fallback plans will not be used.",
+ "emptyTitle": "No plans are available",
+ "emptyDescription": "The server has not configured a purchasable plan and payment method yet."
+ },
+ "offerKinds": {
+ "topup": "Credit top-up",
+ "subscription": "Subscription"
+ },
+ "amount": {
+ "custom": "Custom amount",
+ "label": "Top-up amount",
+ "placeholder": "Enter an amount",
+ "rangeHint": "Enter between {{min}} and {{max}}",
+ "rangeError": "Amount must be between {{min}} and {{max}}",
+ "formatError": "Enter a valid amount with no more than {{digits}} decimal places"
+ },
+ "intervals": {
+ "MONTH": "month",
+ "YEAR": "year"
+ },
+ "credits": "{{amount}} credits",
+ "confirm": {
+ "channel": "Pay with {{provider}}"
+ },
+ "paymentActions": {
+ "QR_CODE": "Scan to pay",
+ "REDIRECT": "Open payment page"
+ },
+ "providers": {
+ "alipay": "Alipay",
+ "stripe": "Card"
+ },
+ "securityNotice": "Payments are securely handled by the selected provider; Cindy does not store payment credentials",
+ "currentSubscription": {
+ "title": "Current subscription",
+ "purchaseBlocked": "You already have an unfinished subscription. Manage it before purchasing another plan."
+ },
+ "subscriptionStatus": {
+ "INCOMPLETE": "Awaiting payment",
+ "INCOMPLETE_EXPIRED": "Payment expired",
+ "TRIALING": "Trial",
+ "ACTIVE": "Active",
+ "PAST_DUE": "Past due",
+ "UNPAID": "Unpaid",
+ "CANCELED": "Canceled",
+ "PAUSED": "Paused"
+ },
+ "recovery": {
+ "title": "Unfinished payment found",
+ "description": "Continue the previous payment and confirm its latest state with the server.",
+ "continueTopup": "Continue {{amount}} payment",
+ "continueSubscription": "Continue subscription payment"
+ },
+ "checkout": {
+ "creatingTitle": "Creating payment",
+ "awaitingTitle": "Awaiting payment",
+ "fulfillingTitle": "Crediting your account",
+ "completedTitle": "Payment successful",
+ "failedTitle": "Unable to complete",
+ "expiredTitle": "Payment expired",
+ "canceledTitle": "Payment canceled",
+ "topupSubtitle": "Credit top-up",
+ "subscriptionSubtitle": "Subscription",
+ "creatingBody": "Confirming the order with the payment service…",
+ "qrAlt": "Payment QR code",
+ "scanHint": "Scan with the corresponding payment app",
+ "checkingExpiry": "Checking expiration…",
+ "expiresIn": "QR code expires in {{minutes}}:{{seconds}}",
+ "redirectHint": "Complete payment on the provider page, then return to Cindy.",
+ "openPayment": "Open payment page",
+ "refreshingAction": "Loading payment instructions…",
+ "creditingBody": "Payment succeeded. Waiting for the credits to be applied…",
+ "paymentCompleted": "Your payment was completed.",
+ "requestFailed": "The request failed. Retry safely; an uncertain create result keeps the original idempotency key.",
+ "expiredBody": "This payment link expired. Create a new payment to continue.",
+ "canceledBody": "This payment was canceled.",
+ "failedBody": "Payment failed. Try again later or contact support."
+ },
+ "planChange": {
+ "targetTitle": "Change subscription plan",
+ "targetDescription": "Plan changes keep your current payment method. The final price and effective time are confirmed on the next step.",
+ "targetDescriptionWithCurrent": "Current plan: {{plan}}. Plan changes keep your current payment method; the final price and effective time are confirmed on the next step.",
+ "upgradeBadge": "Upgrade",
+ "downgradeBadge": "Downgrade",
+ "emptyTitle": "No plans available to switch to",
+ "emptyDescription": "The server has not configured another plan for your current payment method.",
+ "quotingTitle": "Preparing plan change",
+ "quotingBody": "Fetching the price and effective time from the server…",
+ "quoteTitle": "Confirm plan change",
+ "confirmingTitle": "Submitting plan change",
+ "confirmingBody": "Submitting your plan change to the server…",
+ "pendingProviderTitle": "Processing plan change",
+ "pendingProviderBody": "The payment provider is processing this change. Cindy will keep checking the result…",
+ "awaitingTitle": "Pay the difference",
+ "scheduledTitle": "Downgrade scheduled",
+ "scheduledBody": "The new plan takes effect on {{date}}. Your current plan stays active until then.",
+ "appliedTitle": "Plan change applied",
+ "appliedBody": "Your new plan is now active.",
+ "canceledTitle": "Plan change canceled",
+ "canceledBody": "The plan change was canceled. Your current plan is unchanged.",
+ "expiredTitle": "Quote expired",
+ "expiredBody": "The quote expired. Start the plan change again to get a new quote.",
+ "failedTitle": "Plan change failed",
+ "failedBody": "The plan change did not complete. Your current plan is unchanged.",
+ "requestFailed": "The request failed. Please try again.",
+ "resyncHint": "The confirmation result could not be verified. Syncing the latest status from the server…",
+ "upgradeDueNow": "Pay {{amount}} now for the remainder of this period",
+ "upgradeNoAmount": "The upgrade takes effect immediately after confirmation.",
+ "upgradeHint": "The upgrade takes effect immediately after payment. The renewal price becomes the new plan price.",
+ "downgradeAt": "Takes effect on {{date}}",
+ "downgradeHint": "Your current plan stays active until the end of this billing period. No refund is issued now.",
+ "quoteExpiresIn": "Quote expires in {{minutes}}:{{seconds}}",
+ "scanToPay": "Scan to pay {{amount}}",
+ "confirm": "Confirm change",
+ "abandon": "Discard",
+ "targetLabel": "Target plan: {{name}}",
+ "pendingDowngrade": "Downgrade to {{name}} is scheduled for {{date}}.",
+ "pendingPayment": "The upgrade to {{name}} is waiting for payment.",
+ "pendingQuote": "A plan change to {{name}} is in progress.",
+ "resume": "Continue",
+ "undo": "Undo downgrade"
+ }
+ },
"fileAccess": {
"epermGuidance": {
"title": "macOS folder access denied",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index e89c8aa583..0c328f3c41 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -78,6 +78,7 @@
},
"tabs": {
"general": "一般",
+ "billing": "使用状況と請求",
"personalization": "パーソナライズ",
"apiKeys": "ツールキー",
"voiceInput": "音声入力",
@@ -99,6 +100,7 @@
},
"sections": {
"user": "ユーザー",
+ "billing": "使用状況と請求",
"appearance": "外観",
"notifications": "通知",
"agentIsland": "Agent Island",
@@ -6816,6 +6818,229 @@
"workdirKeyInexact": "選択したディレクトリのパスが長すぎるためトランスクリプトを配置できず、チャット履歴のみに切り替えました。"
}
},
+ "billing": {
+ "sidebar": "クレジットとプラン",
+ "settings": {
+ "title": "使用状況と請求",
+ "subtitle": "現在のサブスクリプションを確認し、サーバーから提供されるプランやクレジットを購入できます。",
+ "loading": "サブスクリプションの状態を取得中…",
+ "subscriptionCard": {
+ "title": "現在のプラン",
+ "empty": "有効なサブスクリプションはありません",
+ "emptyTitle": "サブスクリプションなし",
+ "unnamedPlan": "サブスクリプションプラン",
+ "unavailable": "サブスクリプションの状態を取得できません。更新してもう一度お試しください。",
+ "action": "プランを見る",
+ "changeAction": "プラン変更"
+ },
+ "topupCard": {
+ "title": "クレジット",
+ "description": "従量制のモデルや機能で使うクレジットを購入します。",
+ "cardTitle": "必要に応じてクレジットを購入",
+ "cardDescription": "購入可能なクレジット商品はサーバーで設定されます。",
+ "action": "クレジットを購入"
+ }
+ },
+ "balance": {
+ "title": "利用可能残高",
+ "plan": "プランクレジット",
+ "purchased": "購入済みクレジット",
+ "promotional": "特典クレジット",
+ "notProvisioned": "このアカウントではクレジットがまだ有効になっていません。",
+ "notSupported": "このアカウントでは残高照会を利用できません。",
+ "unavailable": "残高を取得できません。更新してもう一度お試しください。"
+ },
+ "usage": {
+ "observedAt": "クレジット更新: {{date}}",
+ "used": "使用済み",
+ "total": "合計",
+ "remaining": "残り",
+ "progressLabel": "{{label}}の使用状況",
+ "historyUnavailable": "使用履歴が完全ではないため、残りのクレジットのみ表示しています。",
+ "percentUsed": "{{percent}}% 使用済み",
+ "detailsUnavailable": "使用量の詳細を取得できないため、現在の残高のみ表示しています。",
+ "promotionalDetails": {
+ "title": "特典クレジット明細",
+ "description": "付与ごとに状態と有効期限が異なります。残量は前回の台帳精算時点の値で、反映が少し遅れる場合があります。",
+ "count": "{{count}}件",
+ "empty": "特典クレジットの付与履歴はありません。",
+ "incomplete": "付与履歴が多いため、最新の{{count}}件のみ表示しています。",
+ "historicalUsageUnavailable": "期限切れまたは無効化された付与の実使用量は現在 Gateway から復元できないため、「—」で表示します。",
+ "unnamed": "特典クレジット",
+ "original": "付与額",
+ "used": "使用済み",
+ "remaining": "残り",
+ "expiresAt": "有効期限 {{date}}",
+ "states": {
+ "active": "利用可能",
+ "depleted": "使用済み",
+ "expired": "期限切れ",
+ "voided": "無効"
+ }
+ }
+ },
+ "dialogs": {
+ "subscription": {
+ "title": "サブスクリプションプランを選択",
+ "description": "サーバーで現在設定されているプランのみ表示します。プランを選択すると支払い方法が表示されます。"
+ },
+ "topup": {
+ "title": "クレジットを購入",
+ "description": "サーバーで現在設定されているクレジット商品のみ表示します。商品を選択すると支払い方法が表示されます。"
+ }
+ },
+ "eyebrow": "アカウントと使用量",
+ "title": "最適なプランを選択",
+ "subtitle": "プランと支払い方法はサーバーから配信されます。先にプランを選ぶと、現在利用可能な支払い方法が表示されます。",
+ "steps": {
+ "offer": {
+ "title": "プランを選択",
+ "description": "現在購入できるチャージとサブスクリプションのみ表示します。"
+ },
+ "channel": {
+ "title": "支払い方法を選択",
+ "description": "利用できる支払い方法はプランごとに異なります。",
+ "selectOfferFirst": "プランを選ぶと、対応する支払い方法が表示されます"
+ },
+ "confirm": {
+ "title": "確認して支払う",
+ "description": "プランと支払い方法を確認して決済を作成します。",
+ "selectChannelFirst": "支払い方法を選択してください"
+ }
+ },
+ "actions": {
+ "refreshCatalog": "更新",
+ "retry": "再試行",
+ "pay": "確認して支払う",
+ "refresh": "状態を更新",
+ "cancelPayment": "支払いをキャンセル",
+ "close": "閉じる"
+ },
+ "catalog": {
+ "errorTitle": "プランを取得できません",
+ "errorDescription": "接続を確認して再試行してください。ローカルの代替プランは表示しません。",
+ "emptyTitle": "利用可能なプランはありません",
+ "emptyDescription": "購入可能なプランと支払い方法がまだ設定されていません。"
+ },
+ "offerKinds": {
+ "topup": "クレジットチャージ",
+ "subscription": "サブスクリプション"
+ },
+ "amount": {
+ "custom": "金額を指定",
+ "label": "チャージ金額",
+ "placeholder": "金額を入力",
+ "rangeHint": "{{min}}〜{{max}}を入力",
+ "rangeError": "金額は{{min}}〜{{max}}の範囲で入力してください",
+ "formatError": "有効な金額を小数点以下{{digits}}桁以内で入力してください"
+ },
+ "intervals": {
+ "MONTH": "月",
+ "YEAR": "年"
+ },
+ "credits": "{{amount}} クレジット",
+ "confirm": {
+ "channel": "{{provider}}で支払う"
+ },
+ "paymentActions": {
+ "QR_CODE": "QRコードで支払う",
+ "REDIRECT": "支払いページを開く"
+ },
+ "providers": {
+ "alipay": "Alipay",
+ "stripe": "カード"
+ },
+ "securityNotice": "支払いは選択した事業者が安全に処理し、Cindyは支払い認証情報を保存しません",
+ "currentSubscription": {
+ "title": "現在のサブスクリプション",
+ "purchaseBlocked": "未終了のサブスクリプションがあります。既存のサブスクリプションを処理してから新しいプランを購入してください。"
+ },
+ "subscriptionStatus": {
+ "INCOMPLETE": "支払い待ち",
+ "INCOMPLETE_EXPIRED": "支払い期限切れ",
+ "TRIALING": "トライアル中",
+ "ACTIVE": "有効",
+ "PAST_DUE": "支払い遅延",
+ "UNPAID": "未払い",
+ "CANCELED": "キャンセル済み",
+ "PAUSED": "一時停止"
+ },
+ "recovery": {
+ "title": "未完了の支払いがあります",
+ "description": "前回の支払いを続け、最新状態をサーバーで確認できます。",
+ "continueTopup": "{{amount}}の支払いを続ける",
+ "continueSubscription": "サブスクリプションの支払いを続ける"
+ },
+ "checkout": {
+ "creatingTitle": "支払いを作成中",
+ "awaitingTitle": "支払い待ち",
+ "fulfillingTitle": "クレジットを反映中",
+ "completedTitle": "支払い完了",
+ "failedTitle": "完了できませんでした",
+ "expiredTitle": "支払い期限切れ",
+ "canceledTitle": "支払いキャンセル済み",
+ "topupSubtitle": "クレジットチャージ",
+ "subscriptionSubtitle": "サブスクリプション",
+ "creatingBody": "支払いサービスで注文を確認しています…",
+ "qrAlt": "支払いQRコード",
+ "scanHint": "対応する支払いアプリでスキャンしてください",
+ "checkingExpiry": "有効期限を確認中…",
+ "expiresIn": "QRコードの有効期限 {{minutes}}:{{seconds}}",
+ "redirectHint": "支払いページで完了後、Cindyに戻ってください。",
+ "openPayment": "支払いページを開く",
+ "refreshingAction": "支払い情報を取得中…",
+ "creditingBody": "支払いが完了しました。クレジットの反映を待っています…",
+ "paymentCompleted": "支払いが完了しました。",
+ "requestFailed": "リクエストに失敗しました。不明な作成結果では同じ冪等キーで安全に再試行します。",
+ "expiredBody": "支払いリンクの期限が切れました。新しい支払いを作成してください。",
+ "canceledBody": "この支払いはキャンセルされました。",
+ "failedBody": "支払いに失敗しました。しばらくしてからもう一度お試しください。"
+ },
+ "planChange": {
+ "targetTitle": "サブスクリプションプランの変更",
+ "targetDescription": "プラン変更は現在の支払い方法を引き継ぎます。最終的な金額と適用時期は次のステップで確認します。",
+ "targetDescriptionWithCurrent": "現在のプラン:{{plan}}。変更は現在の支払い方法を引き継ぎ、最終的な金額と適用時期は次のステップで確認します。",
+ "upgradeBadge": "アップグレード",
+ "downgradeBadge": "ダウングレード",
+ "emptyTitle": "切り替え可能なプランがありません",
+ "emptyDescription": "現在の支払い方法で切り替え可能なプランがまだ設定されていません。",
+ "quotingTitle": "プラン変更を準備中",
+ "quotingBody": "サーバーから金額と適用時期を取得しています…",
+ "quoteTitle": "プラン変更の確認",
+ "confirmingTitle": "変更を送信中",
+ "confirmingBody": "プラン変更をサーバーに送信しています…",
+ "pendingProviderTitle": "プラン変更を処理中",
+ "pendingProviderBody": "決済プロバイダーが変更を処理しています。Cindy が結果を確認し続けます…",
+ "awaitingTitle": "差額のお支払い",
+ "scheduledTitle": "ダウングレードを予約しました",
+ "scheduledBody": "新しいプランは {{date}} に適用されます。それまで現在のプランが継続します。",
+ "appliedTitle": "プラン変更が完了しました",
+ "appliedBody": "新しいプランが有効になりました。",
+ "canceledTitle": "変更を取り消しました",
+ "canceledBody": "プラン変更は取り消され、現在のプランは変わりません。",
+ "expiredTitle": "見積もりの期限切れ",
+ "expiredBody": "見積もりの有効期限が切れました。もう一度プラン変更を開始してください。",
+ "failedTitle": "プラン変更に失敗しました",
+ "failedBody": "プラン変更は完了しませんでした。現在のプランは変わりません。",
+ "requestFailed": "リクエストに失敗しました。もう一度お試しください。",
+ "resyncHint": "確認結果を検証できませんでした。サーバーから最新の状態を同期しています…",
+ "upgradeDueNow": "今期の差額 {{amount}} をお支払いください",
+ "upgradeNoAmount": "確認後、アップグレードは即時適用されます。",
+ "upgradeHint": "お支払い完了後にアップグレードが即時適用され、以降は新プランの価格で更新されます。",
+ "downgradeAt": "{{date}} に適用されます",
+ "downgradeHint": "現在のプランは今の請求期間の終了まで維持され、返金は発生しません。",
+ "quoteExpiresIn": "見積もりは {{minutes}}:{{seconds}} 後に失効します",
+ "scanToPay": "スキャンして {{amount}} を支払う",
+ "confirm": "変更を確定",
+ "abandon": "破棄",
+ "targetLabel": "変更先プラン:{{name}}",
+ "pendingDowngrade": "{{name}} へのダウングレードが {{date}} に予約されています。",
+ "pendingPayment": "{{name}} へのアップグレードは差額のお支払い待ちです。",
+ "pendingQuote": "{{name}} へのプラン変更が進行中です。",
+ "resume": "続行",
+ "undo": "ダウングレードを取り消す"
+ }
+ },
"fileAccess": {
"epermGuidance": {
"title": "macOS のフォルダアクセスが拒否されました",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 1c194273cb..60988d20d2 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -78,6 +78,7 @@
},
"tabs": {
"general": "일반",
+ "billing": "사용량 및 결제",
"personalization": "개인화",
"apiKeys": "도구 키",
"voiceInput": "음성 입력",
@@ -99,6 +100,7 @@
},
"sections": {
"user": "사용자",
+ "billing": "사용량 및 결제",
"appearance": "외관",
"notifications": "알림",
"agentIsland": "Agent Island",
@@ -6816,6 +6818,229 @@
"workdirKeyInexact": "선택한 디렉터리 경로가 너무 길어 트랜스크립트를 배치할 수 없어 채팅 기록만 가져왔습니다."
}
},
+ "billing": {
+ "sidebar": "크레딧 및 요금제",
+ "settings": {
+ "title": "사용량 및 결제",
+ "subtitle": "현재 구독을 확인하거나 서버에서 제공하는 구독 상품과 크레딧을 구매할 수 있습니다.",
+ "loading": "구독 상태를 불러오는 중…",
+ "subscriptionCard": {
+ "title": "현재 요금제",
+ "empty": "활성 구독이 없습니다",
+ "emptyTitle": "구독 요금제 없음",
+ "unnamedPlan": "구독 요금제",
+ "unavailable": "구독 상태를 불러올 수 없습니다. 새로고침 후 다시 시도하세요.",
+ "action": "요금제 보기",
+ "changeAction": "플랜 변경"
+ },
+ "topupCard": {
+ "title": "크레딧",
+ "description": "사용량 기반 모델과 기능을 위한 크레딧을 구매합니다.",
+ "cardTitle": "필요할 때 크레딧 구매",
+ "cardDescription": "구매 가능한 크레딧 상품은 서버에서 설정됩니다.",
+ "action": "크레딧 구매"
+ }
+ },
+ "balance": {
+ "title": "사용 가능 잔액",
+ "plan": "요금제 크레딧",
+ "purchased": "구매한 크레딧",
+ "promotional": "프로모션 크레딧",
+ "notProvisioned": "이 계정에는 아직 크레딧이 활성화되지 않았습니다.",
+ "notSupported": "이 계정에서는 잔액 조회를 지원하지 않습니다.",
+ "unavailable": "잔액을 불러올 수 없습니다. 새로고침 후 다시 시도하세요."
+ },
+ "usage": {
+ "observedAt": "크레딧 업데이트: {{date}}",
+ "used": "사용",
+ "total": "전체",
+ "remaining": "잔여",
+ "progressLabel": "{{label}} 사용량",
+ "historyUnavailable": "사용 기록이 완전하지 않아 잔여 크레딧만 표시합니다.",
+ "percentUsed": "{{percent}}% 사용",
+ "detailsUnavailable": "사용량 상세를 불러올 수 없어 현재 잔액만 표시합니다.",
+ "promotionalDetails": {
+ "title": "프로모션 크레딧 상세",
+ "description": "각 지급 건은 상태와 만료 시간이 서로 다릅니다. 잔여 금액은 마지막 원장 정산 기준이며 반영이 조금 늦을 수 있습니다.",
+ "count": "{{count}}건",
+ "empty": "프로모션 크레딧 지급 내역이 없습니다.",
+ "incomplete": "지급 내역이 많아 최근 {{count}}건만 표시합니다.",
+ "historicalUsageUnavailable": "만료되었거나 무효화된 지급분의 실제 사용량은 현재 Gateway에서 복원할 수 없어 '—'로 표시됩니다.",
+ "unnamed": "프로모션 크레딧",
+ "original": "지급액",
+ "used": "사용",
+ "remaining": "잔여",
+ "expiresAt": "{{date}} 만료",
+ "states": {
+ "active": "사용 중",
+ "depleted": "소진됨",
+ "expired": "만료됨",
+ "voided": "무효"
+ }
+ }
+ },
+ "dialogs": {
+ "subscription": {
+ "title": "구독 요금제 선택",
+ "description": "서버에 현재 설정된 구독 요금제만 표시합니다. 요금제를 선택하면 결제 수단이 표시됩니다."
+ },
+ "topup": {
+ "title": "크레딧 구매",
+ "description": "서버에 현재 설정된 크레딧 상품만 표시합니다. 상품을 선택하면 결제 수단이 표시됩니다."
+ }
+ },
+ "eyebrow": "계정 및 사용량",
+ "title": "알맞은 요금제 선택",
+ "subtitle": "요금제와 결제 수단은 서버에서 실시간으로 제공됩니다. 요금제를 먼저 선택하면 현재 지원되는 결제 수단을 볼 수 있습니다.",
+ "steps": {
+ "offer": {
+ "title": "요금제 선택",
+ "description": "현재 구매 가능한 충전 및 구독만 표시합니다."
+ },
+ "channel": {
+ "title": "결제 수단 선택",
+ "description": "지원되는 결제 수단은 요금제마다 다를 수 있습니다.",
+ "selectOfferFirst": "요금제를 선택하면 지원되는 결제 수단이 표시됩니다"
+ },
+ "confirm": {
+ "title": "확인 및 결제",
+ "description": "요금제와 결제 수단을 확인한 뒤 결제를 생성합니다.",
+ "selectChannelFirst": "계속하려면 결제 수단을 선택하세요"
+ }
+ },
+ "actions": {
+ "refreshCatalog": "새로고침",
+ "retry": "다시 시도",
+ "pay": "확인 및 결제",
+ "refresh": "상태 새로고침",
+ "cancelPayment": "결제 취소",
+ "close": "닫기"
+ },
+ "catalog": {
+ "errorTitle": "요금제를 불러올 수 없습니다",
+ "errorDescription": "네트워크를 확인하고 다시 시도하세요. 로컬 대체 요금제는 표시하지 않습니다.",
+ "emptyTitle": "사용 가능한 요금제가 없습니다",
+ "emptyDescription": "서버에 구매 가능한 요금제와 결제 수단이 아직 설정되지 않았습니다."
+ },
+ "offerKinds": {
+ "topup": "크레딧 충전",
+ "subscription": "구독"
+ },
+ "amount": {
+ "custom": "금액 직접 입력",
+ "label": "충전 금액",
+ "placeholder": "금액 입력",
+ "rangeHint": "{{min}}~{{max}} 입력",
+ "rangeError": "금액은 {{min}}~{{max}} 사이여야 합니다",
+ "formatError": "유효한 금액을 소수점 이하 {{digits}}자리 이내로 입력하세요"
+ },
+ "intervals": {
+ "MONTH": "월",
+ "YEAR": "년"
+ },
+ "credits": "{{amount}} 크레딧",
+ "confirm": {
+ "channel": "{{provider}}로 결제"
+ },
+ "paymentActions": {
+ "QR_CODE": "QR 코드 결제",
+ "REDIRECT": "결제 페이지 열기"
+ },
+ "providers": {
+ "alipay": "Alipay",
+ "stripe": "카드"
+ },
+ "securityNotice": "결제는 선택한 결제사에서 안전하게 처리하며 Cindy는 결제 인증 정보를 저장하지 않습니다",
+ "currentSubscription": {
+ "title": "현재 구독",
+ "purchaseBlocked": "종료되지 않은 구독이 있습니다. 기존 구독을 처리한 후 새 요금제를 구매하세요."
+ },
+ "subscriptionStatus": {
+ "INCOMPLETE": "결제 대기",
+ "INCOMPLETE_EXPIRED": "결제 만료",
+ "TRIALING": "체험 중",
+ "ACTIVE": "사용 중",
+ "PAST_DUE": "결제 연체",
+ "UNPAID": "미결제",
+ "CANCELED": "취소됨",
+ "PAUSED": "일시 중지"
+ },
+ "recovery": {
+ "title": "완료되지 않은 결제가 있습니다",
+ "description": "이전 결제를 계속하고 서버에서 최신 상태를 확인할 수 있습니다.",
+ "continueTopup": "{{amount}} 결제 계속",
+ "continueSubscription": "구독 결제 계속"
+ },
+ "checkout": {
+ "creatingTitle": "결제 생성 중",
+ "awaitingTitle": "결제 대기",
+ "fulfillingTitle": "크레딧 반영 중",
+ "completedTitle": "결제 완료",
+ "failedTitle": "완료할 수 없음",
+ "expiredTitle": "결제 만료",
+ "canceledTitle": "결제 취소됨",
+ "topupSubtitle": "크레딧 충전",
+ "subscriptionSubtitle": "구독",
+ "creatingBody": "결제 서비스에서 주문을 확인하고 있습니다…",
+ "qrAlt": "결제 QR 코드",
+ "scanHint": "해당 결제 앱으로 스캔하세요",
+ "checkingExpiry": "유효 시간을 확인하는 중…",
+ "expiresIn": "QR 코드 만료까지 {{minutes}}:{{seconds}}",
+ "redirectHint": "결제 페이지에서 완료한 뒤 Cindy로 돌아오세요.",
+ "openPayment": "결제 페이지 열기",
+ "refreshingAction": "결제 정보를 불러오는 중…",
+ "creditingBody": "결제가 완료되었습니다. 크레딧이 반영되기를 기다리는 중입니다…",
+ "paymentCompleted": "결제가 완료되었습니다.",
+ "requestFailed": "요청에 실패했습니다. 결과가 불확실한 생성 요청은 같은 멱등성 키로 안전하게 재시도합니다.",
+ "expiredBody": "결제 링크가 만료되었습니다. 새 결제를 생성하세요.",
+ "canceledBody": "이 결제가 취소되었습니다.",
+ "failedBody": "결제에 실패했습니다. 나중에 다시 시도하세요."
+ },
+ "planChange": {
+ "targetTitle": "구독 플랜 변경",
+ "targetDescription": "플랜 변경은 현재 결제 수단을 그대로 사용합니다. 최종 금액과 적용 시점은 다음 단계에서 확인합니다.",
+ "targetDescriptionWithCurrent": "현재 플랜: {{plan}}. 변경은 현재 결제 수단을 그대로 사용하며, 최종 금액과 적용 시점은 다음 단계에서 확인합니다.",
+ "upgradeBadge": "업그레이드",
+ "downgradeBadge": "다운그레이드",
+ "emptyTitle": "전환 가능한 플랜이 없습니다",
+ "emptyDescription": "현재 결제 수단으로 전환할 수 있는 다른 플랜이 아직 설정되지 않았습니다.",
+ "quotingTitle": "플랜 변경 준비 중",
+ "quotingBody": "서버에서 금액과 적용 시점을 가져오는 중…",
+ "quoteTitle": "플랜 변경 확인",
+ "confirmingTitle": "변경 제출 중",
+ "confirmingBody": "플랜 변경을 서버에 제출하는 중…",
+ "pendingProviderTitle": "요금제 변경 처리 중",
+ "pendingProviderBody": "결제 제공업체에서 변경을 처리하고 있습니다. Cindy가 결과를 계속 확인합니다…",
+ "awaitingTitle": "차액 결제",
+ "scheduledTitle": "다운그레이드 예약됨",
+ "scheduledBody": "새 플랜은 {{date}}에 적용됩니다. 그때까지 현재 플랜이 유지됩니다.",
+ "appliedTitle": "플랜 변경 완료",
+ "appliedBody": "새 플랜이 적용되었습니다.",
+ "canceledTitle": "변경 취소됨",
+ "canceledBody": "플랜 변경이 취소되었고 현재 플랜은 그대로 유지됩니다.",
+ "expiredTitle": "견적 만료",
+ "expiredBody": "견적이 만료되었습니다. 플랜 변경을 다시 시작해 주세요.",
+ "failedTitle": "플랜 변경 실패",
+ "failedBody": "플랜 변경이 완료되지 않았습니다. 현재 플랜은 그대로 유지됩니다.",
+ "requestFailed": "요청에 실패했습니다. 다시 시도해 주세요.",
+ "resyncHint": "확인 결과를 검증할 수 없습니다. 서버에서 최신 상태를 동기화하는 중…",
+ "upgradeDueNow": "이번 기간 차액 {{amount}}을(를) 결제하세요",
+ "upgradeNoAmount": "확인 후 업그레이드가 즉시 적용됩니다.",
+ "upgradeHint": "결제 완료 후 업그레이드가 즉시 적용되며 이후 새 플랜 가격으로 갱신됩니다.",
+ "downgradeAt": "{{date}}에 적용됩니다",
+ "downgradeHint": "현재 플랜은 이번 결제 주기 종료 시점까지 유지되며 환불은 발생하지 않습니다.",
+ "quoteExpiresIn": "견적은 {{minutes}}:{{seconds}} 후 만료됩니다",
+ "scanToPay": "스캔하여 {{amount}} 결제",
+ "confirm": "변경 확정",
+ "abandon": "취소",
+ "targetLabel": "대상 플랜: {{name}}",
+ "pendingDowngrade": "{{name}}(으)로의 다운그레이드가 {{date}}에 예약되어 있습니다.",
+ "pendingPayment": "{{name}}(으)로의 업그레이드가 차액 결제를 기다리고 있습니다.",
+ "pendingQuote": "{{name}}(으)로의 플랜 변경이 진행 중입니다.",
+ "resume": "계속",
+ "undo": "다운그레이드 취소"
+ }
+ },
"fileAccess": {
"epermGuidance": {
"title": "macOS 폴더 접근이 거부되었습니다",
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 175b1e772c..1fc9a2d786 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -78,6 +78,7 @@
},
"tabs": {
"general": "通用",
+ "billing": "使用情况和计费",
"personalization": "个性化",
"apiKeys": "工具密钥",
"voiceInput": "语音输入",
@@ -99,6 +100,7 @@
},
"sections": {
"user": "用户",
+ "billing": "使用情况和计费",
"appearance": "外观",
"notifications": "通知",
"agentIsland": "灵动岛",
@@ -6816,6 +6818,229 @@
"workdirKeyInexact": "所选目录路径过长,无法放置历史转录,已降级为仅聊天记录。"
}
},
+ "billing": {
+ "sidebar": "点数与订阅",
+ "settings": {
+ "title": "使用情况和计费",
+ "subtitle": "查看当前订阅,或按需购买由服务端提供的订阅套餐和点数。",
+ "loading": "正在获取订阅状态…",
+ "subscriptionCard": {
+ "title": "当前套餐",
+ "empty": "当前没有生效中的订阅",
+ "emptyTitle": "无订阅套餐",
+ "unnamedPlan": "订阅套餐",
+ "unavailable": "暂时无法获取订阅状态,请刷新后重试。",
+ "action": "查看套餐",
+ "changeAction": "更改套餐"
+ },
+ "topupCard": {
+ "title": "点数",
+ "description": "购买点数,为按量使用的模型和功能充值。",
+ "cardTitle": "按需购买点数",
+ "cardDescription": "可购买的点数商品由服务端配置。",
+ "action": "购买点数"
+ }
+ },
+ "balance": {
+ "title": "可用额度",
+ "plan": "订阅额度",
+ "purchased": "已购额度",
+ "promotional": "赠送额度",
+ "notProvisioned": "当前账户尚未开通额度。",
+ "notSupported": "当前账户暂不支持额度查询。",
+ "unavailable": "暂时无法获取额度,请刷新后重试。"
+ },
+ "usage": {
+ "observedAt": "额度更新于 {{date}}",
+ "used": "已用",
+ "total": "总额",
+ "remaining": "剩余",
+ "progressLabel": "{{label}}使用进度",
+ "historyUnavailable": "历史记录不完整,暂时仅显示剩余额度。",
+ "percentUsed": "已使用 {{percent}}%",
+ "detailsUnavailable": "用量明细暂时不可用,当前仅显示各类余额。",
+ "promotionalDetails": {
+ "title": "赠送额度明细",
+ "description": "每笔赠送拥有独立有效期和状态。剩余额度来自上次账本结算,可能稍有延迟。",
+ "count": "{{count}} 笔",
+ "empty": "当前没有赠送额度记录。",
+ "incomplete": "赠送记录较多,当前仅显示最近的 {{count}} 笔。",
+ "historicalUsageUnavailable": "已过期或作废记录的真实已用额度当前无法由 Gateway 还原,以“—”显示。",
+ "unnamed": "赠送额度",
+ "original": "原始额度",
+ "used": "已用",
+ "remaining": "剩余",
+ "expiresAt": "有效期至 {{date}}",
+ "states": {
+ "active": "生效中",
+ "depleted": "已用完",
+ "expired": "已过期",
+ "voided": "已作废"
+ }
+ }
+ },
+ "dialogs": {
+ "subscription": {
+ "title": "选择订阅套餐",
+ "description": "仅展示服务端当前配置且可用的订阅套餐。选择套餐后再选择支付方式。"
+ },
+ "topup": {
+ "title": "购买点数",
+ "description": "仅展示服务端当前配置且可用的点数商品。选择商品后再选择支付方式。"
+ }
+ },
+ "eyebrow": "账户与用量",
+ "title": "选择适合你的方案",
+ "subtitle": "套餐和支付方式均由服务端实时下发。先选择方案,再查看该方案当前支持的支付方式。",
+ "steps": {
+ "offer": {
+ "title": "选择套餐",
+ "description": "仅展示当前可购买的充值和订阅方案。"
+ },
+ "channel": {
+ "title": "选择支付方式",
+ "description": "不同套餐支持的支付方式可能不同。",
+ "selectOfferFirst": "选择套餐后,这里会显示该套餐支持的支付方式"
+ },
+ "confirm": {
+ "title": "确认并支付",
+ "description": "核对方案与支付方式后创建支付。",
+ "selectChannelFirst": "选择支付方式后即可确认订单"
+ }
+ },
+ "actions": {
+ "refreshCatalog": "刷新",
+ "retry": "重试",
+ "pay": "确认并支付",
+ "refresh": "刷新状态",
+ "cancelPayment": "取消支付",
+ "close": "关闭"
+ },
+ "catalog": {
+ "errorTitle": "暂时无法获取套餐",
+ "errorDescription": "请检查网络后重试。不会使用本地套餐替代。",
+ "emptyTitle": "当前暂无可用套餐",
+ "emptyDescription": "服务端尚未配置可购买的套餐和支付方式。"
+ },
+ "offerKinds": {
+ "topup": "点数充值",
+ "subscription": "订阅套餐"
+ },
+ "amount": {
+ "custom": "自定义金额",
+ "label": "充值金额",
+ "placeholder": "输入金额",
+ "rangeHint": "可输入 {{min}} 至 {{max}}",
+ "rangeError": "金额需在 {{min}} 至 {{max}} 之间",
+ "formatError": "请输入有效金额,最多保留 {{digits}} 位小数"
+ },
+ "intervals": {
+ "MONTH": "月",
+ "YEAR": "年"
+ },
+ "credits": "{{amount}} 点数",
+ "confirm": {
+ "channel": "通过 {{provider}} 支付"
+ },
+ "paymentActions": {
+ "QR_CODE": "扫码支付",
+ "REDIRECT": "跳转支付页面"
+ },
+ "providers": {
+ "alipay": "支付宝",
+ "stripe": "银行卡"
+ },
+ "securityNotice": "支付由所选渠道安全处理,Cindy 不保存你的支付凭证",
+ "currentSubscription": {
+ "title": "当前订阅",
+ "purchaseBlocked": "当前已有未结束的订阅,请先处理现有订阅后再购买新套餐。"
+ },
+ "subscriptionStatus": {
+ "INCOMPLETE": "等待完成支付",
+ "INCOMPLETE_EXPIRED": "支付已过期",
+ "TRIALING": "试用中",
+ "ACTIVE": "生效中",
+ "PAST_DUE": "付款逾期",
+ "UNPAID": "待付款",
+ "CANCELED": "已取消",
+ "PAUSED": "已暂停"
+ },
+ "recovery": {
+ "title": "发现未完成的支付",
+ "description": "你可以继续上次的支付,状态将从服务端重新确认。",
+ "continueTopup": "继续支付 {{amount}}",
+ "continueSubscription": "继续订阅支付"
+ },
+ "checkout": {
+ "creatingTitle": "正在创建支付",
+ "awaitingTitle": "等待支付",
+ "fulfillingTitle": "正在发放点数",
+ "completedTitle": "支付成功",
+ "failedTitle": "暂时无法完成",
+ "expiredTitle": "支付已过期",
+ "canceledTitle": "支付已取消",
+ "topupSubtitle": "点数充值",
+ "subscriptionSubtitle": "订阅套餐",
+ "creatingBody": "正在向支付服务确认订单…",
+ "qrAlt": "支付二维码",
+ "scanHint": "请使用对应支付应用扫码",
+ "checkingExpiry": "正在确认有效时间…",
+ "expiresIn": "二维码将在 {{minutes}}:{{seconds}} 后过期",
+ "redirectHint": "请在支付页面完成操作,完成后返回 Cindy。",
+ "openPayment": "打开支付页面",
+ "refreshingAction": "正在获取支付方式…",
+ "creditingBody": "支付已完成,正在等待点数到账…",
+ "paymentCompleted": "支付已完成。",
+ "requestFailed": "请求失败。可以重试;结果不确定时会继续复用原幂等请求。",
+ "expiredBody": "支付链接已过期,请重新创建支付。",
+ "canceledBody": "本次支付已取消。",
+ "failedBody": "支付失败,请稍后重试或联系支持。"
+ },
+ "planChange": {
+ "targetTitle": "更改订阅套餐",
+ "targetDescription": "套餐变更沿用当前支付方式,最终价格与生效时间以下一步确认为准。",
+ "targetDescriptionWithCurrent": "当前套餐:{{plan}}。变更沿用当前支付方式,最终价格与生效时间以下一步确认为准。",
+ "upgradeBadge": "升级",
+ "downgradeBadge": "降级",
+ "emptyTitle": "暂无可切换的套餐",
+ "emptyDescription": "服务端尚未为当前支付方式配置其他可切换套餐。",
+ "quotingTitle": "正在准备套餐变更",
+ "quotingBody": "正在向服务端获取价格与生效时间…",
+ "quoteTitle": "确认套餐变更",
+ "confirmingTitle": "正在提交变更",
+ "confirmingBody": "正在向服务端提交套餐变更…",
+ "pendingProviderTitle": "正在处理套餐变更",
+ "pendingProviderBody": "支付渠道正在处理本次变更,Cindy 会持续确认最新结果…",
+ "awaitingTitle": "支付差价",
+ "scheduledTitle": "降级已排期",
+ "scheduledBody": "新套餐将于 {{date}} 生效,当前套餐在此之前保持不变。",
+ "appliedTitle": "套餐变更已生效",
+ "appliedBody": "新套餐已生效。",
+ "canceledTitle": "变更已撤销",
+ "canceledBody": "套餐变更已撤销,当前套餐保持不变。",
+ "expiredTitle": "报价已过期",
+ "expiredBody": "报价已过期,请重新发起套餐变更获取新报价。",
+ "failedTitle": "套餐变更失败",
+ "failedBody": "套餐变更未完成,当前套餐保持不变。",
+ "requestFailed": "请求失败,请重试。",
+ "resyncHint": "确认结果暂时无法核实,正在从服务端同步最新状态…",
+ "upgradeDueNow": "本期需支付差价 {{amount}}",
+ "upgradeNoAmount": "确认后升级立即生效。",
+ "upgradeHint": "支付完成后升级立即生效,后续按新套餐价格续费。",
+ "downgradeAt": "将于 {{date}} 生效",
+ "downgradeHint": "当前套餐将保留至本计费周期结束,期间不产生退款。",
+ "quoteExpiresIn": "报价将在 {{minutes}}:{{seconds}} 后失效",
+ "scanToPay": "扫码支付 {{amount}}",
+ "confirm": "确认变更",
+ "abandon": "放弃",
+ "targetLabel": "目标套餐:{{name}}",
+ "pendingDowngrade": "已排期降级至 {{name}},{{date}} 生效。",
+ "pendingPayment": "升级到 {{name}} 的差价待支付。",
+ "pendingQuote": "有一笔切换到 {{name}} 的套餐变更进行中。",
+ "resume": "继续",
+ "undo": "撤销降级"
+ }
+ },
"fileAccess": {
"epermGuidance": {
"title": "macOS 文件夹访问被拒绝",
diff --git a/apps/desktop/src/renderer/lib/tabLabels.ts b/apps/desktop/src/renderer/lib/tabLabels.ts
index 2cf73d3767..1cc2043111 100644
--- a/apps/desktop/src/renderer/lib/tabLabels.ts
+++ b/apps/desktop/src/renderer/lib/tabLabels.ts
@@ -6,6 +6,7 @@
export type SettingsTab =
| 'general'
+ | 'billing'
| 'personalization'
| 'providers'
| 'api-keys'
@@ -24,6 +25,7 @@ export type SettingsTab =
export const TAB_IDS: ReadonlyArray<SettingsTab> = [
'general',
+ 'billing',
'personalization',
'providers',
// 「工具密钥」(api-keys)已于 2026-07-13 下架:面板里最后一把 mivo key 随
@@ -47,6 +49,7 @@ export const TAB_IDS: ReadonlyArray<SettingsTab> = [
export const TAB_LABEL_KEY: Record<SettingsTab, string> = {
general: 'settings.tabs.general',
+ billing: 'settings.tabs.billing',
personalization: 'settings.tabs.personalization',
'api-keys': 'settings.tabs.apiKeys',
'voice-input': 'settings.tabs.voiceInput',
diff --git a/apps/desktop/src/renderer/router.tsx b/apps/desktop/src/renderer/router.tsx
index ff2e7b508e..e184c7902e 100644
--- a/apps/desktop/src/renderer/router.tsx
+++ b/apps/desktop/src/renderer/router.tsx
@@ -145,6 +145,10 @@ export const router = createHashRouter([
},
{ path: 'settings', element: <SettingsView /> },
{ path: 'plugins', element: <GhostPluginPage /> },
+ {
+ path: 'billing',
+ element: <Navigate to="/settings?tab=billing" replace />,
+ },
// Maker IPC / agent event 链路诊断页(独立路由,不影响标准 chat)。
{ path: 'maker-experimental', element: <MakerExperimentalView /> },
],
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 357a3a9f07..06c2cef2c3 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -935,6 +935,7 @@ interface ElectronAPI {
pageZoomReset: () => Promise<{ ok: true; zoomLevel: number }>;
onApplicationMenuCommand: (callback: (command: ApplicationMenuCommand) => void) => () => void;
setApplicationMenuLocale: (locale: ApplicationMenuLocale) => Promise<{ ok: true }>;
+ billing: import('../shared/billing').BillingRendererApi;
// lifecycle 兜底 catch 到瞬时网络错误时推一次。renderer 收到后由
// systemNetworkErrorToast.ts 负责节流 + 多语言 toast。
diff --git a/apps/desktop/src/shared/billing.ts b/apps/desktop/src/shared/billing.ts
new file mode 100644
index 0000000000..373bddec57
--- /dev/null
+++ b/apps/desktop/src/shared/billing.ts
@@ -0,0 +1,228 @@
+/**
+ * Billing desktop wire contract.
+ *
+ * Renderer only receives fixed business methods through preload. It cannot choose
+ * an HTTP path, target service, or arbitrary headers.
+ */
+
+import type { ModelAccessBalance, ModelAccessCreditUsage } from './modelAccess';
+
+export const BILLING_INVOKE = {
+ GET_BALANCE: 'billing:get-balance',
+ GET_CREDIT_USAGE: 'billing:get-credit-usage',
+ GET_CATALOG: 'billing:get-catalog',
+ LIST_ORDERS: 'billing:list-orders',
+ GET_ORDER: 'billing:get-order',
+ CREATE_TOPUP: 'billing:create-topup',
+ REFRESH_TOPUP: 'billing:refresh-topup',
+ CANCEL_TOPUP: 'billing:cancel-topup',
+ RETRY_TOPUP: 'billing:retry-topup',
+ CREATE_SUBSCRIPTION: 'billing:create-subscription',
+ GET_CURRENT_SUBSCRIPTION: 'billing:get-current-subscription',
+ REFRESH_SUBSCRIPTION_PURCHASE: 'billing:refresh-subscription-purchase',
+ QUOTE_PLAN_CHANGE: 'billing:quote-plan-change',
+ CONFIRM_PLAN_CHANGE: 'billing:confirm-plan-change',
+ REFRESH_PLAN_CHANGE: 'billing:refresh-plan-change',
+ CANCEL_PLAN_CHANGE: 'billing:cancel-plan-change',
+ OPEN_PAYMENT_REDIRECT: 'billing:open-payment-redirect',
+} as const;
+
+export type BillingPaymentAction =
+ | { type: 'QR_CODE'; value: string; expiresAt: string }
+ | { type: 'REDIRECT'; url: string; expiresAt: string };
+
+export type BillingFulfillmentStatus = 'NOT_STARTED' | 'PENDING' | 'SUCCEEDED' | 'FAILED';
+
+export type BillingPurchaseOption = {
+ id: string;
+ provider: string;
+ capability: 'ONE_TIME_PAYMENT' | 'MERCHANT_INITIATED_MANDATE' | 'PROVIDER_MANAGED_SUBSCRIPTION';
+ paymentAction: BillingPaymentAction['type'];
+};
+
+export type BillingCatalogOffer = {
+ code: string;
+ interval: 'MONTH' | 'YEAR' | null;
+ currency: string;
+ amount: string | null;
+ minAmount: string | null;
+ maxAmount: string | null;
+ creditAmount: string | null;
+ rolloverCap: string | null;
+ purchaseOptions: BillingPurchaseOption[];
+};
+
+export type BillingCatalogProduct = {
+ code: string;
+ name: string;
+ kind: 'CREDIT_TOPUP' | 'SUBSCRIPTION';
+ level: number | null;
+ sortOrder: number;
+ offers: BillingCatalogOffer[];
+};
+
+export type BillingCatalog = {
+ products: BillingCatalogProduct[];
+};
+
+export type BillingPaymentOrderStatus =
+ 'CREATED' | 'PENDING' | 'SUCCEEDED' | 'FAILED' | 'CANCELED' | 'EXPIRED';
+
+export type BillingPaymentOrder = {
+ orderId: string;
+ productCode: string;
+ offerCode: string;
+ amount: string;
+ currency: string;
+ status: BillingPaymentOrderStatus;
+ paymentAction: BillingPaymentAction | null;
+ /**
+ * Added by the fulfillment projection. Older servers may omit it; the client
+ * must then stay in "crediting" and never infer delivery from payment alone.
+ */
+ fulfillmentStatus?: BillingFulfillmentStatus;
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type BillingSubscriptionStatus =
+ | 'INCOMPLETE'
+ | 'INCOMPLETE_EXPIRED'
+ | 'TRIALING'
+ | 'ACTIVE'
+ | 'PAST_DUE'
+ | 'UNPAID'
+ | 'CANCELED'
+ | 'PAUSED';
+
+export type BillingPlanChangeType = 'UPGRADE' | 'DOWNGRADE';
+
+/**
+ * Open plan-change states the client may act on. Terminal states (APPLIED /
+ * CANCELED / FAILED / EXPIRED) are also part of the wire enum because the
+ * plan-change endpoints echo them back after confirm/refresh/cancel.
+ */
+export type BillingPlanChangeStatus =
+ | 'QUOTED'
+ | 'PENDING_PROVIDER'
+ | 'AWAITING_PAYMENT'
+ | 'SCHEDULED'
+ | 'APPLIED'
+ | 'CANCELED'
+ | 'FAILED'
+ | 'EXPIRED';
+
+export type BillingPlanChange = {
+ planChangeId: string;
+ changeType: BillingPlanChangeType;
+ status: BillingPlanChangeStatus;
+ quotedAmountMinor: number | null;
+ quotedCurrency: string | null;
+ quoteExpiresAt: string | null;
+ effectiveAt: string;
+ paymentAction: BillingPaymentAction | null;
+};
+
+export type BillingPlanChangeTargetPlan = {
+ product: { code: string; level: number };
+ offer: { code: string; interval: 'MONTH' | 'YEAR' };
+ terms: { amount: string; currency: string; creditAmount: string };
+};
+
+export type BillingPendingPlanChange = BillingPlanChange & {
+ /** Null when the server could not safely parse the historical snapshot. */
+ targetPlan: BillingPlanChangeTargetPlan | null;
+};
+
+export type BillingSubscription = {
+ subscriptionId: string;
+ status: BillingSubscriptionStatus;
+ provider?: string;
+ managementAction?: 'API_CANCEL' | 'PORTAL';
+ entitlementStatus?: BillingFulfillmentStatus;
+ currentPeriodStartAt: string | null;
+ currentPeriodEndAt: string | null;
+ entitlementValidUntil: string | null;
+ cancelAtPeriodEnd: boolean;
+ effectivePlan: {
+ version: 1;
+ product: {
+ code: string;
+ kind: 'SUBSCRIPTION';
+ level: number;
+ };
+ offer: {
+ code: string;
+ interval: 'MONTH' | 'YEAR';
+ };
+ terms: {
+ amount: string;
+ currency: string;
+ creditAmount: string;
+ rolloverCap: string;
+ };
+ capturedAt: string;
+ } | null;
+ purchaseAttemptId: string | null;
+ paymentAction: BillingPaymentAction | null;
+ /**
+ * Server-owned recovery projection of the newest open plan change. `null`
+ * means "no open change"; `undefined` means the server (or endpoint) does
+ * not emit the field, so the client must not treat it as a denial.
+ */
+ pendingPlanChange?: BillingPendingPlanChange | null;
+};
+
+export type BillingOrderList = {
+ orders: BillingPaymentOrder[];
+ nextCursor: string | null;
+};
+
+export type BillingCurrentSubscription = {
+ subscription: BillingSubscription | null;
+};
+
+export type CreateBillingTopupRequest = {
+ offerCode: string;
+ amount?: string;
+ purchaseOptionId: string;
+};
+
+export type CreateBillingSubscriptionRequest = {
+ offerCode: string;
+ purchaseOptionId: string;
+};
+
+export interface BillingRendererApi {
+ getBalance: () => Promise<ModelAccessBalance>;
+ getCreditUsage: () => Promise<ModelAccessCreditUsage>;
+ getCatalog: () => Promise<BillingCatalog>;
+ listOrders: (payload: { limit: number }) => Promise<BillingOrderList>;
+ getOrder: (payload: { orderId: string }) => Promise<BillingPaymentOrder>;
+ createTopup: (payload: {
+ request: CreateBillingTopupRequest;
+ idempotencyKey: string;
+ }) => Promise<BillingPaymentOrder>;
+ refreshTopup: (payload: { orderId: string }) => Promise<BillingPaymentOrder>;
+ cancelTopup: (payload: { orderId: string }) => Promise<BillingPaymentOrder>;
+ retryTopup: (payload: {
+ orderId: string;
+ idempotencyKey: string;
+ }) => Promise<BillingPaymentOrder>;
+ createSubscription: (payload: {
+ request: CreateBillingSubscriptionRequest;
+ idempotencyKey: string;
+ }) => Promise<BillingSubscription>;
+ getCurrentSubscription: () => Promise<BillingCurrentSubscription>;
+ refreshSubscriptionPurchase: (payload: {
+ purchaseAttemptId: string;
+ }) => Promise<BillingSubscription>;
+ quotePlanChange: (payload: {
+ targetOfferCode: string;
+ idempotencyKey: string;
+ }) => Promise<BillingPlanChange>;
+ confirmPlanChange: (payload: { planChangeId: string }) => Promise<BillingPlanChange>;
+ refreshPlanChange: (payload: { planChangeId: string }) => Promise<BillingPlanChange>;
+ cancelPlanChange: (payload: { planChangeId: string }) => Promise<BillingPlanChange>;
+ openPaymentRedirect: (payload: { url: string }) => Promise<{ success: boolean }>;
+}
diff --git a/apps/desktop/src/shared/modelAccess.ts b/apps/desktop/src/shared/modelAccess.ts
index b5e46738fb..0f338fef6d 100644
--- a/apps/desktop/src/shared/modelAccess.ts
+++ b/apps/desktop/src/shared/modelAccess.ts
@@ -35,6 +35,51 @@ export interface ModelAccessStatus {
endpoint: string | null;
}
+/** 当前登录身份在 AIGateway Credit Ledger 中的同一时点余额快照。 */
+export interface ModelAccessBalance {
+ planCredits: string;
+ purchasedCredits: string;
+ promotionalCredits: string;
+ available: string;
+ scale: 9;
+ observedAt: string;
+}
+
+export interface ModelAccessCreditPoolUsage {
+ remaining: string;
+ used: string | null;
+ total: string | null;
+}
+
+export type ModelAccessPromotionalGrantState = 'active' | 'depleted' | 'expired' | 'voided';
+
+export interface ModelAccessPromotionalGrantUsage {
+ grantId: string;
+ displayName: string | null;
+ originalAmount: string;
+ /** expired / voided 时 Gateway 当前 contract 无法还原真实已用量。 */
+ usedAmount: string | null;
+ remainingAmount: string;
+ expiresAt: string;
+ state: ModelAccessPromotionalGrantState;
+}
+
+/** Gateway 账本的当前额度、三类用量和逐笔赠送只读投影。 */
+export interface ModelAccessCreditUsage {
+ available: string;
+ plan: ModelAccessCreditPoolUsage;
+ purchased: ModelAccessCreditPoolUsage;
+ promotional: ModelAccessCreditPoolUsage;
+ promotionalGrants: ModelAccessPromotionalGrantUsage[];
+ /** false 表示 Gateway 历史超过 Server 的安全分页上限,列表只含最近记录。 */
+ promotionalGrantsComplete: boolean;
+ /** 逐笔 remainingAmount 来自 Gateway 上次持久化结算,不是实时扣减值。 */
+ promotionalGrantConsistency: 'LAST_SETTLED';
+ ledgerUpdatedAt: string | null;
+ scale: 9;
+ observedAt: string;
+}
+
/** main → renderer 的状态推送通道。 */
export const MODEL_ACCESS_STATUS_CHANNEL = 'model-access:status-change';