Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(billing): add Stripe subscription management (#923)
GaoWei Liu9f67c10296e0
diff --git a/apps/desktop/src/main/billing/__tests__/index.test.ts b/apps/desktop/src/main/billing/__tests__/index.test.tsindex 576759a42b..aa0204b4e3 100644--- a/apps/desktop/src/main/billing/__tests__/index.test.ts+++ b/apps/desktop/src/main/billing/__tests__/index.test.ts@@ -5,6 +5,20 @@ import { BILLING_INVOKE } from '../../../shared/billing.js';import { ServerApiError } from '../../serverApiClient.js';import { createBillingHandlers } from '../index.js';+vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: vi.fn() }));+vi.mock('../../serverApiClient.js', () => {+ class ServerApiError extends Error {+ constructor(+ public readonly code: string,+ public readonly statusCode: number,+ message: string,+ ) {+ super(message);+ }+ }+ return { ServerApiError, serverApiFetch: vi.fn() };+});+function harness() {const mainFrame = { routingId: 1 };const mainWebContents = { id: 1, mainFrame };@@ -166,6 +180,7 @@ describe('billing IPC', () => {BILLING_INVOKE.GET_CATALOG,BILLING_INVOKE.GET_CURRENT_SUBSCRIPTION,BILLING_INVOKE.CANCEL_CURRENT_SUBSCRIPTION,+ BILLING_INVOKE.OPEN_SUBSCRIPTION_PORTAL,])('rejects any payload on the no-payload channel %s before network access', async (channel) => {const { call, fetch } = harness();@@ -476,6 +491,51 @@ describe('billing IPC', () => {});});+ it('creates and opens a Stripe portal session only in the main process', async () => {+ const { call, fetch, openExternal } = harness();+ const url = 'https://billing.stripe.com/p/session/session_fixture';+ fetch.mockResolvedValueOnce({ url });++ await expect(call(BILLING_INVOKE.OPEN_SUBSCRIPTION_PORTAL)).resolves.toEqual({+ success: true,+ });+ expect(fetch).toHaveBeenCalledWith('/api/billing/subscription/portal', {+ baseUrl: expect.any(Function),+ timeoutMs: 20_000,+ redactErrorDetails: true,+ method: 'POST',+ });+ expect(openExternal).toHaveBeenCalledWith(url);+ });++ it('releases a stalled Stripe portal browser launch', async () => {+ vi.useFakeTimers();+ try {+ const { call, fetch, openExternal } = harness();+ const url = 'https://billing.stripe.com/p/session/session_fixture';+ fetch.mockResolvedValueOnce({ url });+ openExternal.mockImplementationOnce(() => new Promise<undefined>(() => {}));++ const pending = call(BILLING_INVOKE.OPEN_SUBSCRIPTION_PORTAL);+ await vi.advanceTimersByTimeAsync(10_000);++ await expect(pending).resolves.toEqual({ success: false, timedOut: true });+ expect(openExternal).toHaveBeenCalledWith(url);+ } finally {+ vi.useRealTimers();+ }+ });++ it('fails closed when the portal endpoint does not return a Stripe portal URL', async () => {+ const { call, fetch, openExternal } = harness();+ fetch.mockResolvedValueOnce({ url: 'https://checkout.stripe.com/c/pay/session_fixture' });++ await expect(call(BILLING_INVOKE.OPEN_SUBSCRIPTION_PORTAL)).rejects.toMatchObject({+ code: 'INTERNAL',+ });+ expect(openExternal).not.toHaveBeenCalled();+ });+it.each(['https://checkout.stripe.com/c/pay/session_fixture#fragment','https://invoice.stripe.com/i/acct_fixture/test_fixture',diff --git a/apps/desktop/src/main/billing/index.ts b/apps/desktop/src/main/billing/index.tsindex 96f4624326..e6f3c3644d 100644--- a/apps/desktop/src/main/billing/index.ts+++ b/apps/desktop/src/main/billing/index.ts@@ -2,6 +2,7 @@ import { ipcMain, shell, type BrowserWindow, type IpcMainInvokeEvent } from 'eleimport {BILLING_INVOKE,+ type BillingSubscriptionPortalResult,type CreateBillingSubscriptionRequest,type CreateBillingTopupRequest,} from '../../shared/billing.js';@@ -13,6 +14,7 @@ import {projectBillingCatalog,projectBillingCurrentSubscription,projectBillingOrderList,+ projectBillingPortalSession,projectBillingPaymentOrder,projectBillingPlanChange,projectBillingSubscription,@@ -25,6 +27,7 @@ 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;+const EXTERNAL_BROWSER_LAUNCH_TIMEOUT_MS = 10_000;type ServerFetch = <T>(path: string, options: ApiFetchOptions) => Promise<T>;@@ -98,6 +101,35 @@ function projectResponse<T>(value: unknown, projector: (input: unknown) => T): T}}+function openExternalWithTimeout(+ openExternal: (url: string) => Promise<void>,+ url: string,+): Promise<BillingSubscriptionPortalResult> {+ return new Promise((resolve) => {+ let settled = false;+ let timeout: ReturnType<typeof setTimeout>;+ const finish = (result: BillingSubscriptionPortalResult) => {+ if (settled) return;+ settled = true;+ clearTimeout(timeout);+ resolve(result);+ };++ timeout = setTimeout(+ () => finish({ success: false, timedOut: true }),+ EXTERNAL_BROWSER_LAUNCH_TIMEOUT_MS,+ );+ try {+ void openExternal(url).then(+ () => finish({ success: true }),+ () => finish({ success: false }),+ );+ } catch {+ finish({ success: false });+ }+ });+}+function assertOnlyKeys(value: Record<string, unknown>,allowed: readonly string[],@@ -388,6 +420,16 @@ export function createBillingHandlers(projectBillingPlanChange,);}),+ [BILLING_INVOKE.OPEN_SUBSCRIPTION_PORTAL]: protect(async (raw) => {+ if (raw !== undefined) {+ throwIpcError('INVALID_PARAMS', 'subscription portal does not accept a payload');+ }+ const session = projectResponse(+ await invoke<unknown>('/api/billing/subscription/portal', { method: 'POST' }),+ projectBillingPortalSession,+ );+ return openExternalWithTimeout(openExternal, session.url);+ }),[BILLING_INVOKE.OPEN_PAYMENT_REDIRECT]: protect(async (raw) => {const payload = requireObject(raw);assertOnlyKeys(payload, ['url'], 'payload');diff --git a/apps/desktop/src/main/billing/paymentRedirect.ts b/apps/desktop/src/main/billing/paymentRedirect.tsindex 72237ce3cf..a747dffa62 100644--- a/apps/desktop/src/main/billing/paymentRedirect.ts+++ b/apps/desktop/src/main/billing/paymentRedirect.ts@@ -6,8 +6,9 @@ const ALLOWED_BILLING_REDIRECT_HOSTS = new Set(['checkout.stripe.com','invoice.stripe.com',]);+const ALLOWED_STRIPE_PORTAL_HOSTS = new Set(['billing.stripe.com']);-export function isAllowedBillingRedirectUrl(value: unknown): value is string {+function isAllowedStripeUrl(value: unknown, allowedHosts: ReadonlySet<string>): value is string {if (typeof value !== 'string' ||value.length === 0 ||@@ -22,9 +23,17 @@ export function isAllowedBillingRedirectUrl(value: unknown): value is string {parsed.username === '' &&parsed.password === '' &&parsed.port === '' &&- ALLOWED_BILLING_REDIRECT_HOSTS.has(parsed.hostname)+ allowedHosts.has(parsed.hostname));} catch {return false;}}++export function isAllowedBillingRedirectUrl(value: unknown): value is string {+ return isAllowedStripeUrl(value, ALLOWED_BILLING_REDIRECT_HOSTS);+}++export function isAllowedStripeBillingPortalUrl(value: unknown): value is string {+ return isAllowedStripeUrl(value, ALLOWED_STRIPE_PORTAL_HOSTS);+}diff --git a/apps/desktop/src/main/billing/projection.ts b/apps/desktop/src/main/billing/projection.tsindex d31c3953c7..2e65ccd0bc 100644--- a/apps/desktop/src/main/billing/projection.ts+++ b/apps/desktop/src/main/billing/projection.ts@@ -23,7 +23,7 @@ import type {ModelAccessPromotionalGrantState,ModelAccessPromotionalGrantUsage,} from '../../shared/modelAccess.js';-import { isAllowedBillingRedirectUrl } from './paymentRedirect.js';+import { isAllowedBillingRedirectUrl, isAllowedStripeBillingPortalUrl } from './paymentRedirect.js';const MAX_ID_LENGTH = 128;const MAX_NAME_LENGTH = 128;@@ -364,6 +364,13 @@ function projectPaymentAction(value: unknown): BillingPaymentAction | null {return null;}+export function projectBillingPortalSession(value: unknown): { url: string } {+ if (!isRecord(value)) invalidResponse();+ const url = value.url;+ if (!isAllowedStripeBillingPortalUrl(url)) invalidResponse();+ return { url };+}+function projectPurchaseOption(value: unknown,productKind: BillingCatalogProduct['kind'],diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 2a836ae89c..11e58024c6 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1691,6 +1691,7 @@ contextBridge.exposeInMainWorld('electronAPI', {refreshPlanChange: (payload) =>ipcRenderer.invoke(BILLING_INVOKE.REFRESH_PLAN_CHANGE, payload),cancelPlanChange: (payload) => ipcRenderer.invoke(BILLING_INVOKE.CANCEL_PLAN_CHANGE, payload),+ openSubscriptionPortal: () => ipcRenderer.invoke(BILLING_INVOKE.OPEN_SUBSCRIPTION_PORTAL),openPaymentRedirect: (payload) =>ipcRenderer.invoke(BILLING_INVOKE.OPEN_PAYMENT_REDIRECT, payload),} satisfies BillingRendererApi,diff --git a/apps/desktop/src/renderer/features/billing/BillingPage.tsx b/apps/desktop/src/renderer/features/billing/BillingPage.tsxindex b9a89a2be0..c4a5f0a3a9 100644--- a/apps/desktop/src/renderer/features/billing/BillingPage.tsx+++ b/apps/desktop/src/renderer/features/billing/BillingPage.tsx@@ -3,8 +3,10 @@ import * as Dialog from '@radix-ui/react-dialog';import {ArrowRight,Check,+ ChevronDown,CircleDollarSign,CreditCard,+ ExternalLink,PackageOpen,RefreshCcw,X,@@ -12,6 +14,13 @@ import {import { useTranslation } from 'react-i18next';import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';import { toast } from '@/lib/toast';import { Spinner } from '@/components/ui/spinner';import { useAuth } from '@/contexts/AuthContext';@@ -233,6 +242,7 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullconst [loadingSubscription, setLoadingSubscription] = useState(true);const [subscriptionError, setSubscriptionError] = useState(false);const [cancelingSubscription, setCancelingSubscription] = useState(false);+ const [openingSubscriptionPortal, setOpeningSubscriptionPortal] = useState(false);const [creditUsage, setCreditUsage] = useState<ModelAccessCreditUsage | null>(null);const [balance, setBalance] = useState<ModelAccessBalance | null>(null);const [usageDetailsUnavailable, setUsageDetailsUnavailable] = useState(false);@@ -247,6 +257,8 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullconst checkout = useBillingCheckout(accountId);const previousCheckoutPhaseRef = useRef(checkout.state.phase);const cancelSubscriptionLockRef = useRef(false);+ const subscriptionPortalLockRef = useRef(false);+ const subscriptionPortalRefreshPendingRef = useRef(false);// 取消订阅的 DELETE 不带 subscriptionId,服务端按「请求时已认证的账号」执行。// ConfirmDialogProvider 挂在 AuthProvider 之外(见 App.tsx),弹窗会活过本 section// 因 dataOwnerId 变化而发生的卸载,所以必须记住确认时的账号与挂载态。@@ -334,6 +346,23 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullvoid loadBillingState();}, [loadBillingState]);+ useEffect(() => {+ const refreshAfterPortal = () => {+ if (!subscriptionPortalRefreshPendingRef.current) return;+ subscriptionPortalRefreshPendingRef.current = false;+ void loadBillingState();+ };+ const onVisible = () => {+ if (document.visibilityState === 'visible') refreshAfterPortal();+ };+ window.addEventListener('focus', refreshAfterPortal);+ document.addEventListener('visibilitychange', onVisible);+ return () => {+ window.removeEventListener('focus', refreshAfterPortal);+ document.removeEventListener('visibilitychange', onVisible);+ };+ }, [loadBillingState]);+const closeCheckout = useCallback(() => {const abandonedIncomplete = checkout.state.subscription?.status === 'INCOMPLETE';checkout.close();@@ -541,6 +570,28 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null};}, [billingLocale, currentSubscription, planNameOf, t]);+ const openSubscriptionPortal = useCallback(async () => {+ if (subscriptionPortalLockRef.current || currentSubscription?.provider !== 'stripe') return;+ subscriptionPortalLockRef.current = true;+ setOpeningSubscriptionPortal(true);+ subscriptionPortalRefreshPendingRef.current = true;+ try {+ const result = await billingApi.openSubscriptionPortal();+ if (!result.success && !result.timedOut) {+ subscriptionPortalRefreshPendingRef.current = false;+ }+ if (!result.success) {+ toast.error(t('billing.settings.subscriptionCard.portalFailed'));+ }+ } catch {+ subscriptionPortalRefreshPendingRef.current = false;+ toast.error(t('billing.settings.subscriptionCard.portalFailed'));+ } finally {+ setOpeningSubscriptionPortal(false);+ subscriptionPortalLockRef.current = false;+ }+ }, [currentSubscription?.provider, t]);+const cancelCurrentSubscription = useCallback(async () => {if (cancelSubscriptionLockRef.current ||@@ -734,7 +785,11 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nulltype="button"onClick={() => void loadBillingState()}disabled={- loadingCatalog || loadingSubscription || loadingBalance || cancelingSubscription+ loadingCatalog ||+ loadingSubscription ||+ loadingBalance ||+ cancelingSubscription ||+ openingSubscriptionPortal}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">@@ -754,11 +809,19 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullloading={loadingSubscription}error={subscriptionError}showPlanChangeEntry={showPlanChangeEntry}+ showPortalEntry={currentSubscription?.provider === 'stripe'}canceling={cancelingSubscription}- actionDisabled={loadingSubscription || subscriptionError || cancelingSubscription}+ openingPortal={openingSubscriptionPortal}+ actionDisabled={+ loadingSubscription ||+ subscriptionError ||+ cancelingSubscription ||+ openingSubscriptionPortal+ }pendingPlanChange={pendingPlanChange}pendingTargetName={planNameOf(pendingPlanChange?.targetPlan?.product.code)}onCancelSubscription={() => void cancelCurrentSubscription()}+ onOpenPortal={() => void openSubscriptionPortal()}onChangePlan={openPlanChange}onPurchase={() => openPurchaseDialog('SUBSCRIPTION')}onCancelPending={() => {@@ -897,11 +960,14 @@ function SubscriptionOverviewCard({loading,error,showPlanChangeEntry,+ showPortalEntry,canceling,+ openingPortal,actionDisabled,pendingPlanChange,pendingTargetName,onCancelSubscription,+ onOpenPortal,onChangePlan,onPurchase,onCancelPending,@@ -910,11 +976,14 @@ function SubscriptionOverviewCard({loading: boolean;error: boolean;showPlanChangeEntry: boolean;+ showPortalEntry: boolean;canceling: boolean;+ openingPortal: boolean;actionDisabled: boolean;pendingPlanChange: BillingPendingPlanChange | null;pendingTargetName: string | null;onCancelSubscription: () => void;+ onOpenPortal: () => void;onChangePlan: () => void;onPurchase: () => void;onCancelPending: () => void;@@ -987,33 +1056,80 @@ function SubscriptionOverviewCard({)}</div><div className="flex shrink-0 items-center gap-2.5">- {facts &&- !facts.cancelAtPeriodEnd &&- SUBSCRIPTION_CANCELLABLE_STATUSES.includes(facts.status) && (- <button- type="button"- onClick={onCancelSubscription}- disabled={actionDisabled}- aria-label={t('billing.settings.subscriptionCard.cancelAction')}- className="inline-flex h-8 select-none items-center justify-center rounded-full border border-[var(--border-default)] px-3.5 text-12 font-medium text-[var(--error-fg)] transition-colors hover:bg-[var(--error-bg)] disabled:cursor-not-allowed disabled:opacity-40"+ {facts ? (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ disabled={actionDisabled}+ className="group inline-flex h-8 min-w-[9.5rem] select-none items-center justify-center gap-1.5 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)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] data-[state=open]:bg-[var(--surface-chip)] disabled:cursor-not-allowed disabled:opacity-40"+ >+ {t('billing.settings.subscriptionCard.manageAction')}+ {canceling || openingPortal ? (+ <Spinner size={13} />+ ) : (+ <ChevronDown+ size={13}+ strokeWidth={1.75}+ className="transition-transform duration-150 group-data-[state=open]:rotate-180 motion-reduce:transition-none"+ aria-hidden="true"+ />+ )}+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ sideOffset={8}+ className="w-[var(--radix-dropdown-menu-trigger-width)] rounded-[12px] border border-[var(--border-default)] bg-[var(--surface-elevated)] p-1.5 text-[var(--text-primary)] shadow-none">- {canceling ? (- <Spinner size={13} />- ) : (- t('billing.settings.subscriptionCard.cancelAction')+ <DropdownMenuItem+ onSelect={showPlanChangeEntry ? onChangePlan : onPurchase}+ disabled={actionDisabled}+ className="h-9 rounded-lg px-3 text-12 focus:bg-[var(--surface-hover)] focus:text-[var(--text-primary)]"+ >+ {showPlanChangeEntry+ ? t('billing.settings.subscriptionCard.changeAction')+ : t('billing.settings.subscriptionCard.action')}+ </DropdownMenuItem>+ {showPortalEntry && (+ <DropdownMenuItem+ onSelect={onOpenPortal}+ disabled={actionDisabled}+ className="h-9 gap-2 rounded-lg px-3 text-12 focus:bg-[var(--surface-hover)] focus:text-[var(--text-primary)]"+ >+ <ExternalLink size={14} aria-hidden="true" />+ {t('billing.settings.subscriptionCard.portalAction')}+ </DropdownMenuItem>)}- </button>- )}- <button- type="button"- onClick={showPlanChangeEntry ? onChangePlan : onPurchase}- disabled={actionDisabled}- className="h-8 select-none 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)] disabled:cursor-not-allowed disabled:opacity-40"- >- {showPlanChangeEntry- ? t('billing.settings.subscriptionCard.changeAction')- : t('billing.settings.subscriptionCard.action')}- </button>+ {!facts.cancelAtPeriodEnd &&+ SUBSCRIPTION_CANCELLABLE_STATUSES.includes(facts.status) && (+ <>+ <DropdownMenuSeparator className="mx-2 my-1 h-px bg-[var(--border-default)]" />+ <DropdownMenuItem+ onSelect={onCancelSubscription}+ disabled={actionDisabled}+ className="h-9 rounded-lg px-3 text-12 text-[var(--error-fg)] focus:bg-[var(--error-bg)] focus:text-[var(--error-fg)]"+ >+ {canceling ? (+ <Spinner size={13} />+ ) : (+ t('billing.settings.subscriptionCard.cancelAction')+ )}+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ ) : (+ <button+ type="button"+ onClick={onPurchase}+ disabled={actionDisabled}+ className="h-8 select-none 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)] disabled:cursor-not-allowed disabled:opacity-40"+ >+ {t('billing.settings.subscriptionCard.action')}+ </button>+ )}</div></div>{pendingPlanChange?.status === 'SCHEDULED' && (diff --git a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsxindex 1908229bc9..c74e0ae317 100644--- a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx@@ -2,7 +2,10 @@import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';-import type { BillingSubscription } from '../../../../shared/billing';+import type {+ BillingSubscription,+ BillingSubscriptionPortalResult,+} from '../../../../shared/billing';const i18n = {language: 'en',@@ -85,6 +88,20 @@ beforeEach(() => {authState.dataOwnerId = 'account-fixture';});+async function openSubscriptionManagementMenu() {+ const trigger = await screen.findByText('billing.settings.subscriptionCard.manageAction');+ fireEvent.pointerDown(+ trigger.closest('button')!,+ { button: 0, ctrlKey: false },+ );+ await screen.findByRole('menu');+}++async function selectSubscriptionManagementAction(action: string) {+ await openSubscriptionManagementMenu();+ fireEvent.click(await screen.findByRole('menuitem', { name: action }));+}+describe('BillingPage remote catalog rendering', () => {beforeEach(() => {i18n.language = 'en';@@ -444,7 +461,10 @@ describe('BillingPage remote catalog rendering', () => {expect(screen.getByText('billing.settings.subscriptionCard.renewsAt:{"date":"2026/08/01"}'),).toBeTruthy();- expect(screen.getByText('billing.settings.subscriptionCard.changeAction')).toBeTruthy();+ await openSubscriptionManagementMenu();+ expect(+ screen.getByRole('menuitem', { name: 'billing.settings.subscriptionCard.changeAction' }),+ ).toBeTruthy();});it('preserves the server order for offers within the same product', async () => {@@ -879,8 +899,13 @@ describe('BillingPage remote catalog rendering', () => {render(<BillingPage />);- expect(await screen.findByText('billing.settings.subscriptionCard.action')).toBeTruthy();- expect(screen.queryByText('billing.settings.subscriptionCard.changeAction')).toBeNull();+ await openSubscriptionManagementMenu();+ expect(+ await screen.findByRole('menuitem', { name: 'billing.settings.subscriptionCard.action' }),+ ).toBeTruthy();+ expect(+ screen.queryByRole('menuitem', { name: 'billing.settings.subscriptionCard.changeAction' }),+ ).toBeNull();expect(checkout.startSubscription).not.toHaveBeenCalled();});@@ -911,7 +936,7 @@ describe('BillingPage remote catalog rendering', () => {}));render(<BillingPage />);- fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));+ await selectSubscriptionManagementAction('billing.settings.subscriptionCard.action');const dialog = await screen.findByRole('dialog');const currentPlan = within(dialog).getByRole('button', { name: /Configured subscription/ });@@ -1354,6 +1379,7 @@ describe('BillingPage plan change', () => {refreshPlanChange: vi.fn(),cancelPlanChange: vi.fn(),openPaymentRedirect: vi.fn(async () => ({ success: true })),+ openSubscriptionPortal: vi.fn(),});const install = (billing: ReturnType<typeof billingMocks>) => {@@ -1380,6 +1406,90 @@ describe('BillingPage plan change', () => {});});+ it('refreshes when Cindy regains focus before the Stripe portal launch resolves', async () => {+ const billing = install(billingMocks());+ let resolvePortal!: (result: BillingSubscriptionPortalResult) => void;+ billing.openSubscriptionPortal.mockImplementation(+ () => new Promise<BillingSubscriptionPortalResult>((resolve) => {+ resolvePortal = resolve;+ }),+ );++ render(<BillingPage />);+ await openSubscriptionManagementMenu();+ expect(+ screen.getByRole('menuitem', { name: 'billing.settings.subscriptionCard.changeAction' }),+ ).toBeTruthy();+ expect(+ screen.getByRole('menuitem', { name: 'billing.settings.subscriptionCard.portalAction' }),+ ).toBeTruthy();+ expect(+ screen.getByRole('menuitem', { name: 'billing.settings.subscriptionCard.cancelAction' }),+ ).toBeTruthy();+ const portalAction = screen.getByRole('menuitem', {+ name: 'billing.settings.subscriptionCard.portalAction',+ });+ await act(async () => {+ fireEvent.click(portalAction);+ fireEvent.click(portalAction);+ });++ expect(billing.openSubscriptionPortal).toHaveBeenCalledWith();+ expect(billing.openSubscriptionPortal).toHaveBeenCalledTimes(1);++ const catalogCalls = billing.getCatalog.mock.calls.length;+ const subscriptionCalls = billing.getCurrentSubscription.mock.calls.length;+ const balanceCalls = billing.getBalance.mock.calls.length;+ await act(async () => window.dispatchEvent(new Event('focus')));+ await waitFor(() => {+ expect(billing.getCatalog).toHaveBeenCalledTimes(catalogCalls + 1);+ expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(subscriptionCalls + 1);+ expect(billing.getBalance).toHaveBeenCalledTimes(balanceCalls + 1);+ });++ await act(async () => resolvePortal({ success: true }));+ await act(async () => window.dispatchEvent(new Event('focus')));+ expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(subscriptionCalls + 1);+ });++ it('refreshes billing after a timed-out Stripe portal launch', async () => {+ const billing = install(billingMocks());+ billing.openSubscriptionPortal.mockResolvedValue({ success: false, timedOut: true });++ render(<BillingPage />);+ await selectSubscriptionManagementAction('billing.settings.subscriptionCard.portalAction');+ await waitFor(() => {+ expect(uiMocks.toastError).toHaveBeenCalledWith('billing.settings.subscriptionCard.portalFailed');+ });++ const catalogCalls = billing.getCatalog.mock.calls.length;+ const subscriptionCalls = billing.getCurrentSubscription.mock.calls.length;+ const balanceCalls = billing.getBalance.mock.calls.length;+ await act(async () => window.dispatchEvent(new Event('focus')));+ await waitFor(() => {+ expect(billing.getCatalog).toHaveBeenCalledTimes(catalogCalls + 1);+ expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(subscriptionCalls + 1);+ expect(billing.getBalance).toHaveBeenCalledTimes(balanceCalls + 1);+ });+ });++ it('does not show Stripe management in the menu for an Alipay subscription', async () => {+ const billing = billingMocks();+ billing.getCurrentSubscription = vi.fn(async () => ({+ subscription: { ...activeSubscription(), provider: 'alipay' },+ }));+ install(billing);++ render(<BillingPage />);++ await screen.findByText('Plus plan');+ await openSubscriptionManagementMenu();+ expect(+ screen.queryByRole('menuitem', { name: 'billing.settings.subscriptionCard.portalAction' }),+ ).toBeNull();+ expect(billing.openSubscriptionPortal).not.toHaveBeenCalled();+ });+it('confirms provider-neutral cancellation and keeps credits unchanged until period end', async () => {const billing = install(billingMocks());billing.cancelCurrentSubscription.mockResolvedValue({@@ -1390,7 +1500,7 @@ describe('BillingPage plan change', () => {uiMocks.confirm.mockResolvedValueOnce(true);render(<BillingPage />);- fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.cancelAction'));+ await selectSubscriptionManagementAction('billing.settings.subscriptionCard.cancelAction');await waitFor(() => expect(billing.cancelCurrentSubscription).toHaveBeenCalledWith());expect(uiMocks.confirm).toHaveBeenCalledWith(@@ -1406,7 +1516,10 @@ describe('BillingPage plan change', () => {expect(screen.getByText((text) => text.startsWith('billing.settings.subscriptionCard.endsAt')),).toBeTruthy();- expect(screen.queryByText('billing.settings.subscriptionCard.cancelAction')).toBeNull();+ await openSubscriptionManagementMenu();+ expect(+ screen.queryByRole('menuitem', { name: 'billing.settings.subscriptionCard.cancelAction' }),+ ).toBeNull();});it.each(['INCOMPLETE', 'CANCELED', 'INCOMPLETE_EXPIRED'] as const)(@@ -1450,7 +1563,7 @@ describe('BillingPage plan change', () => {view.rerender(<BillingPage />);await waitFor(() => expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(2));- fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.changeAction'));+ await selectSubscriptionManagementAction('billing.settings.subscriptionCard.changeAction');expect(await screen.findByText('Alipay-only Max')).toBeTruthy();expect(screen.queryByText('Max plan')).toBeNull();});@@ -1481,7 +1594,10 @@ describe('BillingPage plan change', () => {await waitFor(() => expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(2));expect(await screen.findByText('billing.subscriptionStatus.ACTIVE')).toBeTruthy();expect(screen.queryByText('billing.settings.subscriptionCard.unavailable')).toBeNull();- expect(screen.getByText('billing.settings.subscriptionCard.changeAction')).toBeTruthy();+ await openSubscriptionManagementMenu();+ expect(+ screen.getByRole('menuitem', { name: 'billing.settings.subscriptionCard.changeAction' }),+ ).toBeTruthy();});it('locks cancellation before confirmation resolves', async () => {@@ -1494,9 +1610,8 @@ describe('BillingPage plan change', () => {);render(<BillingPage />);- const cancelButton = await screen.findByText('billing.settings.subscriptionCard.cancelAction');- fireEvent.click(cancelButton);- fireEvent.click(cancelButton);+ await selectSubscriptionManagementAction('billing.settings.subscriptionCard.cancelAction');+ await selectSubscriptionManagementAction('billing.settings.subscriptionCard.cancelAction');expect(uiMocks.confirm).toHaveBeenCalledTimes(1);expect(billing.cancelCurrentSubscription).not.toHaveBeenCalled();@@ -1514,21 +1629,24 @@ describe('BillingPage plan change', () => {);const view = render(<BillingPage />);- fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.cancelAction'));+ await selectSubscriptionManagementAction('billing.settings.subscriptionCard.cancelAction');expect(uiMocks.confirm).toHaveBeenCalledTimes(1);// 弹窗还开着时账号被换掉:section 按 dataOwnerId 重挂,但弹窗挂在 AuthProvider// 之外仍然存活。此时确认不能落到新账号的订阅上。authState.dataOwnerId = 'account-switched';view.rerender(<BillingPage />);- await screen.findByText('billing.settings.subscriptionCard.cancelAction');+ await openSubscriptionManagementMenu();+ expect(+ screen.getByRole('menuitem', { name: 'billing.settings.subscriptionCard.cancelAction' }),+ ).toBeTruthy();await act(async () => resolveConfirm(true));expect(billing.cancelCurrentSubscription).not.toHaveBeenCalled();});- it('keeps the loading cancellation accessible and disables competing actions', async () => {+ it('disables subscription management while cancellation is pending', async () => {const billing = billingMocks();billing.getCurrentSubscription = vi.fn(async () => ({subscription: activeSubscription({@@ -1554,12 +1672,12 @@ describe('BillingPage plan change', () => {uiMocks.confirm.mockResolvedValueOnce(true);render(<BillingPage />);- fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.cancelAction'));+ await selectSubscriptionManagementAction('billing.settings.subscriptionCard.cancelAction');await waitFor(() => expect(billing.cancelCurrentSubscription).toHaveBeenCalledTimes(1));expect(screen- .getByRole('button', { name: 'billing.settings.subscriptionCard.cancelAction' })+ .getByRole('button', { name: 'billing.settings.subscriptionCard.manageAction' }).hasAttribute('disabled'),).toBe(true);const refreshButton = screen.getByRole('button', { name: 'billing.actions.refreshCatalog' });@@ -1582,7 +1700,7 @@ describe('BillingPage plan change', () => {uiMocks.confirm.mockResolvedValueOnce(true);render(<BillingPage />);- fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.cancelAction'));+ await selectSubscriptionManagementAction('billing.settings.subscriptionCard.cancelAction');await waitFor(() =>expect(uiMocks.toastError).toHaveBeenCalledWith(@@ -1591,7 +1709,10 @@ describe('BillingPage plan change', () => {);expect(billing.cancelCurrentSubscription).toHaveBeenCalledWith();expect(billing.getBalance).toHaveBeenCalledTimes(1);- expect(screen.getByText('billing.settings.subscriptionCard.cancelAction')).toBeTruthy();+ await openSubscriptionManagementMenu();+ expect(+ screen.getByRole('menuitem', { name: 'billing.settings.subscriptionCard.cancelAction' }),+ ).toBeTruthy();});it('offers same-provider monthly plans in upgrade, same-tier, downgrade order', async () => {@@ -1608,7 +1729,7 @@ describe('BillingPage plan change', () => {});render(<BillingPage />);- fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.changeAction'));+ await selectSubscriptionManagementAction('billing.settings.subscriptionCard.changeAction');await screen.findByText('billing.planChange.targetTitle');const dialog = screen.getByRole('dialog');@@ -1689,7 +1810,7 @@ describe('BillingPage plan change', () => {});render(<BillingPage />);- fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.changeAction'));+ await selectSubscriptionManagementAction('billing.settings.subscriptionCard.changeAction');fireEvent.click((await screen.findByText('Max plan')).closest('button')!);fireEvent.click(await screen.findByText('billing.planChange.confirm'));@@ -1717,7 +1838,7 @@ describe('BillingPage plan change', () => {install(billing);render(<BillingPage />);- fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.changeAction'));+ await selectSubscriptionManagementAction('billing.settings.subscriptionCard.changeAction');const dialog = await screen.findByRole('dialog');const currentButton = within(dialog)@@ -1740,8 +1861,13 @@ describe('BillingPage plan change', () => {render(<BillingPage />);await screen.findByText('Plus plan');- expect(screen.queryByText('billing.settings.subscriptionCard.changeAction')).toBeNull();- expect(screen.getByText('billing.settings.subscriptionCard.action')).toBeTruthy();+ await openSubscriptionManagementMenu();+ expect(+ screen.queryByRole('menuitem', { name: 'billing.settings.subscriptionCard.changeAction' }),+ ).toBeNull();+ expect(+ screen.getByRole('menuitem', { name: 'billing.settings.subscriptionCard.action' }),+ ).toBeTruthy();expect(billing.quotePlanChange).not.toHaveBeenCalled();});@@ -1754,7 +1880,7 @@ describe('BillingPage plan change', () => {render(<BillingPage />);- fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.changeAction'));+ await selectSubscriptionManagementAction('billing.settings.subscriptionCard.changeAction');expect(await screen.findByText('billing.planChange.emptyTitle')).toBeTruthy();expect(screen.queryByText('Max plan')).toBeNull();expect(billing.quotePlanChange).not.toHaveBeenCalled();@@ -1772,8 +1898,13 @@ describe('BillingPage plan change', () => {render(<BillingPage />);await screen.findByText('Plus plan');- expect(screen.queryByText('billing.settings.subscriptionCard.changeAction')).toBeNull();- expect(screen.getByText('billing.settings.subscriptionCard.action')).toBeTruthy();+ await openSubscriptionManagementMenu();+ expect(+ screen.queryByRole('menuitem', { name: 'billing.settings.subscriptionCard.changeAction' }),+ ).toBeNull();+ expect(+ screen.getByRole('menuitem', { name: 'billing.settings.subscriptionCard.action' }),+ ).toBeTruthy();},);@@ -1787,8 +1918,13 @@ describe('BillingPage plan change', () => {render(<BillingPage />);await screen.findByText('Plus plan');- expect(screen.queryByText('billing.settings.subscriptionCard.changeAction')).toBeNull();- expect(screen.getByText('billing.settings.subscriptionCard.action')).toBeTruthy();+ await openSubscriptionManagementMenu();+ expect(+ screen.queryByRole('menuitem', { name: 'billing.settings.subscriptionCard.changeAction' }),+ ).toBeNull();+ expect(+ screen.getByRole('menuitem', { name: 'billing.settings.subscriptionCard.action' }),+ ).toBeTruthy();});it('keeps new selection enabled when no current subscription exists (no INCOMPLETE task)', async () => {@@ -1863,7 +1999,7 @@ describe('BillingPage plan change', () => {render(<BillingPage />);- fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));+ await selectSubscriptionManagementAction('billing.settings.subscriptionCard.action');fireEvent.click((await screen.findAllByText('Plus plan'))[0].closest('button')!);fireEvent.click(screen.getByText('stripe').closest('button')!);expect(screen.getByText('billing.actions.pay').closest('button')).toHaveProperty(@@ -1880,7 +2016,7 @@ describe('BillingPage plan change', () => {);render(<BillingPage />);- fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.changeAction'));+ await selectSubscriptionManagementAction('billing.settings.subscriptionCard.changeAction');fireEvent.click(await screen.findByText('Max plan'));expect(await screen.findByText('billing.planChange.quoteRejected')).toBeTruthy();@@ -1969,7 +2105,7 @@ describe('BillingPage plan change', () => {).toBeNull();expect(screen.queryByText('billing.planChange.undo')).toBeNull();- fireEvent.click(screen.getByText('billing.settings.subscriptionCard.changeAction'));+ await selectSubscriptionManagementAction('billing.settings.subscriptionCard.changeAction');expect(await screen.findByText('billing.planChange.targetTitle')).toBeTruthy();expect(billing.refreshPlanChange).not.toHaveBeenCalled();});diff --git a/apps/desktop/src/renderer/features/billing/__tests__/api.test.ts b/apps/desktop/src/renderer/features/billing/__tests__/api.test.tsindex 9550031ce5..15daf34936 100644--- a/apps/desktop/src/renderer/features/billing/__tests__/api.test.ts+++ b/apps/desktop/src/renderer/features/billing/__tests__/api.test.ts@@ -11,6 +11,7 @@ describe('billing renderer API', () => {listOrders: vi.fn(),createTopup: vi.fn(),cancelCurrentSubscription: vi.fn(),+ openSubscriptionPortal: vi.fn(),openPaymentRedirect: vi.fn(),};@@ -23,6 +24,7 @@ describe('billing renderer API', () => {subscriptionId: 'subscription_fixture',cancelAtPeriodEnd: true,});+ billing.openSubscriptionPortal.mockReset().mockResolvedValue({ success: true });billing.openPaymentRedirect.mockReset().mockResolvedValue({ success: true });Object.defineProperty(window, 'electronAPI', {configurable: true,@@ -63,6 +65,11 @@ describe('billing renderer API', () => {expect(billing.cancelCurrentSubscription).toHaveBeenCalledWith();});+ it('opens the subscription portal without exposing a provider URL or request parameters', async () => {+ await billingApi.openSubscriptionPortal();+ expect(billing.openSubscriptionPortal).toHaveBeenCalledWith();+ });+it('uses the dedicated billing redirect method', async () => {const url = 'https://checkout.stripe.com/c/pay/session_fixture';await billingApi.openPaymentRedirect(url);diff --git a/apps/desktop/src/renderer/features/billing/api.ts b/apps/desktop/src/renderer/features/billing/api.tsindex c4a8303de0..ffc1b7a40e 100644--- a/apps/desktop/src/renderer/features/billing/api.ts+++ b/apps/desktop/src/renderer/features/billing/api.ts@@ -4,6 +4,7 @@ import type {BillingOrderList,BillingPaymentOrder,BillingPlanChange,+ BillingSubscriptionPortalResult,BillingSubscription,CreateBillingSubscriptionRequest,CreateBillingTopupRequest,@@ -68,6 +69,9 @@ export const billingApi = {cancelPlanChange(planChangeId: string): Promise<BillingPlanChange> {return window.electronAPI.billing.cancelPlanChange({ planChangeId });},+ openSubscriptionPortal(): Promise<BillingSubscriptionPortalResult> {+ return window.electronAPI.billing.openSubscriptionPortal();+ },openPaymentRedirect(url: string): Promise<{ success: boolean }> {return window.electronAPI.billing.openPaymentRedirect({ url });},diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex f2f4fadb80..40a9ba5d78 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -7559,6 +7559,9 @@"unavailable": "Subscription status is temporarily unavailable. Refresh to try again.","action": "View plans","changeAction": "Change plan",+ "manageAction": "Manage subscription",+ "portalAction": "Manage in Stripe",+ "portalFailed": "Couldn't open Stripe subscription management. Try again later.","priceInterval": "{{price}} / {{interval}}","includedCredits": "Includes {{amount}} credits per {{interval}}","renewsAt": "Renews {{date}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex fe94e1c723..04a84f8f3e 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -7548,6 +7548,9 @@"unavailable": "サブスクリプションの状態を取得できません。更新してもう一度お試しください。","action": "プランを見る","changeAction": "プランを変更",+ "manageAction": "サブスクリプションを管理",+ "portalAction": "Stripe で管理",+ "portalFailed": "Stripeのサブスクリプション管理を開けませんでした。しばらくしてからもう一度お試しください。","priceInterval": "{{price}} / {{interval}}","includedCredits": "毎{{interval}} {{amount}} クレジットを付与","renewsAt": "次回更新日: {{date}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 1889aa3e1b..f520aeda83 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -7548,6 +7548,9 @@"unavailable": "구독 상태를 불러올 수 없습니다. 새로고침 후 다시 시도하세요.","action": "요금제 보기","changeAction": "요금제 변경",+ "manageAction": "구독 관리",+ "portalAction": "Stripe에서 관리",+ "portalFailed": "Stripe 구독 관리 페이지를 열 수 없습니다. 잠시 후 다시 시도하세요.","priceInterval": "{{price}} / {{interval}}","includedCredits": "매{{interval}} {{amount}} 크레딧 포함","renewsAt": "다음 갱신일 {{date}}",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 4d81f7c1af..6c6125336c 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -7548,6 +7548,9 @@"unavailable": "暂时无法获取订阅状态,请刷新后重试。","action": "查看套餐","changeAction": "更改套餐",+ "manageAction": "管理订阅",+ "portalAction": "Stripe 管理",+ "portalFailed": "无法打开 Stripe 订阅管理页,请稍后重试。","priceInterval": "{{price}} / {{interval}}","includedCredits": "每{{interval}}包含 {{amount}} 点数","renewsAt": "下次续费 {{date}}",diff --git a/apps/desktop/src/shared/billing.ts b/apps/desktop/src/shared/billing.tsindex b95016f80d..f9b8320750 100644--- a/apps/desktop/src/shared/billing.ts+++ b/apps/desktop/src/shared/billing.ts@@ -25,6 +25,7 @@ export const BILLING_INVOKE = {CONFIRM_PLAN_CHANGE: 'billing:confirm-plan-change',REFRESH_PLAN_CHANGE: 'billing:refresh-plan-change',CANCEL_PLAN_CHANGE: 'billing:cancel-plan-change',+ OPEN_SUBSCRIPTION_PORTAL: 'billing:open-subscription-portal',OPEN_PAYMENT_REDIRECT: 'billing:open-payment-redirect',} as const;@@ -32,6 +33,10 @@ export type BillingPaymentAction =| { type: 'QR_CODE'; value: string; expiresAt: string }| { type: 'REDIRECT'; url: string; expiresAt: string };+export type BillingSubscriptionPortalResult =+ | { success: true }+ | { success: false; timedOut?: true };+export type BillingFulfillmentStatus = 'NOT_STARTED' | 'PENDING' | 'SUCCEEDED' | 'FAILED';export type BillingPurchaseOption = {@@ -236,5 +241,6 @@ export interface BillingRendererApi {confirmPlanChange: (payload: { planChangeId: string }) => Promise<BillingPlanChange>;refreshPlanChange: (payload: { planChangeId: string }) => Promise<BillingPlanChange>;cancelPlanChange: (payload: { planChangeId: string }) => Promise<BillingPlanChange>;+ openSubscriptionPortal: () => Promise<BillingSubscriptionPortalResult>;openPaymentRedirect: (payload: { url: string }) => Promise<{ success: boolean }>;}