Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 优化计费概览与支付恢复体验
liugaowei531087d5b9be
diff --git a/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsx b/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsxindex 02a7634e2d..700b995f70 100644--- a/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsx+++ b/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsx@@ -4,9 +4,11 @@ import * as QRCode from 'qrcode';import { Check, CircleAlert, ExternalLink, LoaderCircle, RotateCcw, X } from 'lucide-react';import { useTranslation } from 'react-i18next';+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import { Spinner } from '@/components/ui/spinner';import { cn } from '@/lib/utils';import { billingApi } from './api';+import { formatBillingAmount as formatMoney } from './money';import type { BillingCheckoutState } from './useBillingCheckout';interface BillingCheckoutDialogProps {@@ -29,6 +31,7 @@ export function BillingCheckoutDialog({onCancel,}: BillingCheckoutDialogProps) {const { t } = useTranslation();+ const { confirm } = useConfirmDialog();const action = actionOf(state);const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);const [remainingSeconds, setRemainingSeconds] = useState<number | null>(null);@@ -90,6 +93,32 @@ export function BillingCheckoutDialog({state.kind === 'TOPUP' &&state.order !== null &&(state.order.status === 'CREATED' || state.order.status === 'PENDING');+ const confirmCancel = async () => {+ if (!state.order) return;+ const accepted = await confirm({+ title: t('billing.confirmActions.cancelPaymentTitle'),+ description: t('billing.confirmActions.cancelPaymentDescription', {+ amount: formatMoney(state.order.amount, state.order.currency),+ }),+ confirmText: t('billing.confirmActions.cancelPayment'),+ cancelText: t('billing.confirmActions.back'),+ });+ if (accepted) onCancel();+ };+ const confirmRetry = async () => {+ const accepted = await confirm({+ title: t('billing.confirmActions.retryPaymentTitle'),+ description: state.order+ ? t('billing.confirmActions.retryPaymentDescription', {+ amount: formatMoney(state.order.amount, state.order.currency),+ })+ : t('billing.confirmActions.retryUnknownPaymentDescription'),+ confirmText: t('billing.confirmActions.retryPayment'),+ cancelText: t('billing.confirmActions.back'),+ autoFocusConfirm: true,+ });+ if (accepted) onRetry();+ };return (<Dialog.Root@@ -97,10 +126,10 @@ export function BillingCheckoutDialog({onOpenChange={(open) => !open && state.phase !== 'CREATING' && onClose()}><Dialog.Portal>- <Dialog.Overlay className="fixed inset-0 z-[10000] bg-[var(--overlay-modal)]" />+ <Dialog.Overlay className="fixed inset-0 z-[9990] bg-[var(--overlay-modal)]" /><Dialog.ContentclassName={cn(- 'fixed left-1/2 top-1/2 z-[10001] w-[calc(100vw-40px)] max-w-[620px]',+ 'fixed left-1/2 top-1/2 z-[9991] 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',@@ -235,7 +264,7 @@ export function BillingCheckoutDialog({{canCancel && (<buttontype="button"- onClick={onCancel}+ onClick={() => void confirmCancel()}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')}@@ -256,7 +285,7 @@ export function BillingCheckoutDialog({{(state.phase === 'FAILED' || state.phase === 'EXPIRED') && canRetry && (<buttontype="button"- onClick={onRetry}+ onClick={() => void confirmRetry()}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} />diff --git a/apps/desktop/src/renderer/features/billing/BillingPage.tsx b/apps/desktop/src/renderer/features/billing/BillingPage.tsxindex 205400b909..7ae192782b 100644--- a/apps/desktop/src/renderer/features/billing/BillingPage.tsx+++ b/apps/desktop/src/renderer/features/billing/BillingPage.tsx@@ -12,6 +12,7 @@ import {} from 'lucide-react';import { useTranslation } from 'react-i18next';+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import { Spinner } from '@/components/ui/spinner';import { useAuth } from '@/contexts/AuthContext';import { cn } from '@/lib/utils';@@ -21,6 +22,7 @@ import type {BillingCatalogOffer,BillingCatalogProduct,BillingPendingPlanChange,+ BillingPaymentOrder,BillingPurchaseOption,BillingSubscription,} from '../../../shared/billing';@@ -55,6 +57,15 @@ type SupportedPurchaseOption = BillingPurchaseOption & {type PurchaseKind = BillingCatalogProduct['kind'];type BalanceIssue = 'NOT_PROVISIONED' | 'NOT_SUPPORTED' | 'UNAVAILABLE' | null;+type CurrentPlanFacts = {+ name: string;+ status: BillingSubscription['status'];+ price: string | null;+ interval: BillingCatalogOffer['interval'];+ includedCredits: string | null;+ periodEndAt: string | null;+ cancelAtPeriodEnd: boolean;+};const SUPPORTED_BILLING_PROVIDERS = new Set<SupportedBillingProvider>(['alipay', 'stripe']);const SUPPORTED_PAYMENT_ACTIONS = new Set<BillingPurchaseOption['paymentAction']>([@@ -66,15 +77,6 @@ const SUPPORTED_SUBSCRIPTION_CAPABILITIES = new Set<BillingPurchaseOption['capab'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;@@ -126,6 +128,17 @@ function formatLedgerTimestamp(value: string): string {}}+function formatBillingDate(value: string | null): string | null {+ if (!value) return null;+ const timestamp = Date.parse(value);+ if (!Number.isFinite(timestamp)) return null;+ try {+ return new Intl.DateTimeFormat(undefined, { dateStyle: 'medium' }).format(timestamp);+ } catch {+ return null;+ }+}+function isCustomTopup(offer: BillingCatalogOffer): boolean {return offer.amount === null && offer.minAmount !== null && offer.maxAmount !== null;}@@ -174,6 +187,7 @@ export function BillingPage() {export function BillingSettingsSection({ accountId }: { accountId: string | null }) {const { t } = useTranslation();+ const { confirm } = useConfirmDialog();const [catalog, setCatalog] = useState<BillingCatalog | null>(null);const [catalogError, setCatalogError] = useState(false);const [loadingCatalog, setLoadingCatalog] = useState(true);@@ -295,12 +309,7 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null: [],})),)- .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);- });+ .filter(({ purchaseOptions }) => purchaseOptions.length > 0);}, [catalog]);const subscriptionOffers = useMemo(@@ -362,17 +371,10 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullreturn 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(@@ -390,36 +392,31 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullconst 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 currentPlanFacts = useMemo(() => {+ if (!currentSubscription) return null;+ const plan = currentSubscription.effectivePlan;+ return {+ name: planNameOf(plan?.product.code) ?? t('billing.settings.subscriptionCard.unnamedPlan'),+ status: currentSubscription.status,+ price: plan ? formatMoney(plan.terms.amount, plan.terms.currency) : null,+ interval: plan?.offer.interval ?? null,+ includedCredits: plan?.terms.creditAmount ?? null,+ periodEndAt: formatBillingDate(currentSubscription.currentPeriodEndAt),+ cancelAtPeriodEnd: currentSubscription.cancelAtPeriodEnd,+ };+ }, [currentSubscription, planNameOf, t]);++ // The server quote owns reachability and direction. The renderer only removes+ // the exact current offer because selecting it cannot express a change.const planChangeCandidates = useMemo<PlanChangeCandidate[]>(() => {- if (!planChangeable || !currentPlan) return [];- const currentProvider = currentSubscription?.provider ?? null;+ if (!currentSubscription) return [];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)),- )+ .filter(({ offer }) => offer.code !== currentPlan?.offer.code).map(({ product, offer }) => ({product,offer,- direction:- (product.level ?? 0) > currentPlan.product.level- ? ('UPGRADE' as const)- : ('DOWNGRADE' as const),}));- }, [subscriptionOffers, planChangeable, currentPlan, currentSubscription?.provider]);+ }, [currentPlan?.offer.code, currentSubscription, subscriptionOffers]);const openPurchaseDialog = (kind: PurchaseKind) => {resetSelection();@@ -437,8 +434,41 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullsetCustomAmount('');};- const submit = () => {+ const submit = async () => {if (!selected || !selectedOption || !canCheckout) return;+ const amount = formatMoney(+ isCustomTopup(selected.offer) ? customAmount.trim() : selected.offer.amount!,+ selected.offer.currency,+ );+ const accepted =+ selected.product.kind === 'CREDIT_TOPUP'+ ? await confirm({+ title: t('billing.confirmActions.purchaseTopupTitle'),+ description: t('billing.confirmActions.purchaseTopupDescription', {+ product: selected.product.name,+ amount,+ provider: providerLabel(selectedOption.provider, t),+ }),+ confirmText: t('billing.confirmActions.purchaseTopup'),+ cancelText: t('billing.confirmActions.back'),+ autoFocusConfirm: true,+ })+ : await confirm({+ title: t('billing.confirmActions.purchaseSubscriptionTitle', {+ plan: selected.product.name,+ }),+ description: t('billing.confirmActions.purchaseSubscriptionDescription', {+ price: amount,+ interval: selected.offer.interval+ ? t(`billing.intervals.${selected.offer.interval}`)+ : '',+ provider: providerLabel(selectedOption.provider, t),+ }),+ confirmText: t('billing.confirmActions.purchaseSubscription'),+ cancelText: t('billing.confirmActions.back'),+ autoFocusConfirm: true,+ });+ if (!accepted) return;setSubscriptionDialogOpen(false);setTopupDialogOpen(false);if (selected.product.kind === 'CREDIT_TOPUP') {@@ -473,8 +503,19 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null}};- const selectPlanChangeTarget = (candidate: PlanChangeCandidate) => {+ const selectPlanChangeTarget = async (candidate: PlanChangeCandidate) => {if (candidate.offer.interval === null) return;+ const accepted = await confirm({+ title: t('billing.confirmActions.quotePlanChangeTitle'),+ description: t('billing.confirmActions.quotePlanChangeDescription', {+ current: currentPlanName ?? t('billing.settings.subscriptionCard.unnamedPlan'),+ target: candidate.product.name,+ }),+ confirmText: t('billing.confirmActions.quotePlanChange'),+ cancelText: t('billing.confirmActions.back'),+ autoFocusConfirm: true,+ });+ if (!accepted) return;setPlanChangeTargetOpen(false);void planChange.startQuote(candidate.offer.code, {product: { code: candidate.product.code, level: candidate.product.level ?? 0 },@@ -487,6 +528,20 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null});};+ const cancelPendingPlanChange = async (pending: BillingPendingPlanChange) => {+ const accepted = await confirm({+ title: t('billing.confirmActions.cancelPlanChangeTitle'),+ description: t('billing.confirmActions.cancelPlanChangeDescription', {+ target:+ planNameOf(pending.targetPlan?.product.code) ??+ t('billing.settings.subscriptionCard.unnamedPlan'),+ }),+ confirmText: t('billing.confirmActions.cancelPlanChange'),+ cancelText: t('billing.confirmActions.back'),+ });+ if (accepted) await planChange.cancelChange(pending.planChangeId);+ };+const closePlanChangeStatus = () => {const phase = planChange.state.phase;planChange.close();@@ -523,7 +578,18 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null</button></div>- <div className="mt-8 overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)]">+ {!checkout.recovering &&+ (checkout.recoverables.topups.length > 0 ||+ checkout.recoverables.subscription !== null) && (+ <BillingRecoveryNotice+ topups={checkout.recoverables.topups}+ subscription={checkout.recoverables.subscription}+ onResumeTopup={checkout.resumeTopup}+ onResumeSubscription={checkout.resumeSubscription}+ />+ )}++ <div className="mt-5 overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)]"><BillingUsageSummaryusage={creditUsage}balance={balance}@@ -531,89 +597,26 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullloading={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 className="mt-4 grid grid-cols-1 gap-4 lg:grid-cols-2">+ <SubscriptionOverviewCard+ facts={currentPlanFacts}+ loading={loadingSubscription}+ error={subscriptionError}+ pendingPlanChange={pendingPlanChange}+ pendingTargetName={planNameOf(pendingPlanChange?.targetPlan?.product.code)}+ onChangePlan={openPlanChange}+ onPurchase={() => openPurchaseDialog('SUBSCRIPTION')}+ onResumePending={() => {+ if (pendingPlanChange) planChange.resumePending(pendingPlanChange);+ }}+ onCancelPending={() => {+ if (pendingPlanChange) void cancelPendingPlanChange(pendingPlanChange);+ }}+ />+ <TopupOverviewCard onPurchase={() => openPurchaseDialog('CREDIT_TOPUP')} />+ </div></div><BillingOfferDialog@@ -626,14 +629,13 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullselectedPurchaseOptionId={selectedPurchaseOptionId}customAmount={customAmount}amountError={amountError}- subscriptionPurchaseBlocked={subscriptionPurchaseBlocked}canCheckout={canCheckout}onClose={closeSubscriptionDialog}onRetry={() => void loadBillingState()}onSelectOffer={selectOffer}onSelectPurchaseOption={setSelectedPurchaseOptionId}onCustomAmountChange={setCustomAmount}- onSubmit={submit}+ onSubmit={() => void submit()}/><BillingOfferDialog@@ -646,14 +648,13 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullselectedPurchaseOptionId={selectedPurchaseOptionId}customAmount={customAmount}amountError={amountError}- subscriptionPurchaseBlocked={false}canCheckout={canCheckout}onClose={closeTopupDialog}onRetry={() => void loadBillingState()}onSelectOffer={selectOffer}onSelectPurchaseOption={setSelectedPurchaseOptionId}onCustomAmountChange={setCustomAmount}- onSubmit={submit}+ onSubmit={() => void submit()}/><BillingCheckoutDialog@@ -687,6 +688,196 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null);}+function BillingRecoveryNotice({+ topups,+ subscription,+ onResumeTopup,+ onResumeSubscription,+}: {+ topups: BillingPaymentOrder[];+ subscription: BillingSubscription | null;+ onResumeTopup: (order: BillingPaymentOrder) => void;+ onResumeSubscription: (subscription: BillingSubscription) => void;+}) {+ const { t } = useTranslation();+ return (+ <section className="mt-5 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-5 py-4">+ <p className="text-sm font-medium text-[var(--text-primary)]">+ {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">+ {topups.map((order) => (+ <button+ key={order.orderId}+ type="button"+ onClick={() => onResumeTopup(order)}+ className="select-none rounded-full border border-[var(--border-default)] px-3 py-1.5 text-12 font-medium transition-colors hover:bg-[var(--surface-hover-soft)]"+ >+ {t('billing.recovery.continueTopup', {+ amount: formatMoney(order.amount, order.currency),+ })}+ </button>+ ))}+ {subscription && (+ <button+ type="button"+ onClick={() => onResumeSubscription(subscription)}+ className="select-none rounded-full border border-[var(--border-default)] px-3 py-1.5 text-12 font-medium transition-colors hover:bg-[var(--surface-hover-soft)]"+ >+ {t('billing.recovery.continueSubscription')}+ </button>+ )}+ </div>+ </section>+ );+}++function SubscriptionOverviewCard({+ facts,+ loading,+ error,+ pendingPlanChange,+ pendingTargetName,+ onChangePlan,+ onPurchase,+ onResumePending,+ onCancelPending,+}: {+ facts: CurrentPlanFacts | null;+ loading: boolean;+ error: boolean;+ pendingPlanChange: BillingPendingPlanChange | null;+ pendingTargetName: string | null;+ onChangePlan: () => void;+ onPurchase: () => void;+ onResumePending: () => void;+ onCancelPending: () => void;+}) {+ const { t } = useTranslation();+ const showPeriodDate =+ facts?.periodEndAt &&+ (facts.cancelAtPeriodEnd || facts.status === 'ACTIVE' || facts.status === 'TRIALING');++ return (+ <section className="flex min-h-[220px] flex-col rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-5">+ <p className="text-11 font-medium text-[var(--text-tertiary)]">+ {t('billing.settings.subscriptionCard.title')}+ </p>+ <div className="mt-3 min-h-0 flex-1">+ {loading ? (+ <Spinner size={15} />+ ) : error ? (+ <p className="text-12 leading-5 text-[var(--text-secondary)]">+ {t('billing.settings.subscriptionCard.unavailable')}+ </p>+ ) : facts ? (+ <>+ <div className="flex flex-wrap items-center gap-2">+ <h3 className="text-16 font-medium text-[var(--text-primary)]">{facts.name}</h3>+ <span className="select-none rounded-full bg-[var(--surface-chip)] px-2.5 py-1 text-10 font-medium text-[var(--text-secondary)]">+ {t(`billing.subscriptionStatus.${facts.status}`)}+ </span>+ </div>+ {facts.price && facts.interval && (+ <p className="mt-3 text-13 text-[var(--text-primary)]">+ {t('billing.settings.subscriptionCard.priceInterval', {+ price: facts.price,+ interval: t(`billing.intervals.${facts.interval}`),+ })}+ </p>+ )}+ {facts.includedCredits && facts.interval && (+ <p className="mt-1 text-12 text-[var(--text-secondary)]">+ {t('billing.settings.subscriptionCard.includedCredits', {+ amount: facts.includedCredits,+ interval: t(`billing.intervals.${facts.interval}`),+ })}+ </p>+ )}+ {showPeriodDate && (+ <p className="mt-3 text-12 text-[var(--text-secondary)]">+ {facts.cancelAtPeriodEnd+ ? t('billing.settings.subscriptionCard.endsAt', {+ date: facts.periodEndAt,+ })+ : t('billing.settings.subscriptionCard.renewsAt', {+ date: facts.periodEndAt,+ })}+ </p>+ )}+ </>+ ) : (+ <>+ <h3 className="text-16 font-medium text-[var(--text-primary)]">+ {t('billing.settings.subscriptionCard.emptyTitle')}+ </h3>+ <p className="mt-2 text-12 leading-5 text-[var(--text-secondary)]">+ {t('billing.settings.subscriptionCard.empty')}+ </p>+ </>+ )}+ </div>+ <div className="mt-5 flex flex-wrap gap-2">+ {facts && (+ <button+ type="button"+ onClick={onChangePlan}+ 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)]"+ >+ {t('billing.settings.subscriptionCard.changeAction')}+ </button>+ )}+ <button+ type="button"+ onClick={onPurchase}+ 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)]"+ >+ {facts+ ? t('billing.settings.subscriptionCard.purchaseAnother')+ : t('billing.settings.subscriptionCard.action')}+ </button>+ </div>+ {pendingPlanChange && (+ <PendingPlanChangeBanner+ pending={pendingPlanChange}+ targetName={pendingTargetName}+ onResume={onResumePending}+ onUndo={onCancelPending}+ />+ )}+ </section>+ );+}++function TopupOverviewCard({ onPurchase }: { onPurchase: () => void }) {+ const { t } = useTranslation();+ return (+ <section className="flex min-h-[220px] flex-col rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-5">+ <p className="text-11 font-medium text-[var(--text-tertiary)]">+ {t('billing.settings.topupCard.title')}+ </p>+ <div className="mt-3 flex-1">+ <h3 className="text-16 font-medium text-[var(--text-primary)]">+ {t('billing.settings.topupCard.cardTitle')}+ </h3>+ <p className="mt-2 max-w-[420px] text-12 leading-5 text-[var(--text-secondary)]">+ {t('billing.settings.topupCard.cardDescription')}+ </p>+ </div>+ <button+ type="button"+ onClick={onPurchase}+ className="mt-5 h-8 w-fit 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)]"+ >+ {t('billing.settings.topupCard.action')}+ </button>+ </section>+ );+}+function PendingPlanChangeBanner({pending,targetName,@@ -722,13 +913,13 @@ function PendingPlanChangeBanner({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">+ <div className="mt-5 flex flex-wrap items-center gap-3 rounded-xl border border-[var(--border-default)] bg-[var(--surface-chip)] px-4 py-3"><p className="min-w-0 flex-1 text-12 leading-5 text-[var(--text-secondary)]">{label}</p>{pending.status === 'SCHEDULED' ? (<buttontype="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)]"+ className="h-8 shrink-0 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)]">{t('billing.planChange.undo')}</button>@@ -736,7 +927,7 @@ function PendingPlanChangeBanner({<buttontype="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)]"+ className="h-8 shrink-0 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)]">{t('billing.planChange.resume')}</button>@@ -790,14 +981,9 @@ function BillingUsageSummary({: t('billing.balance.unavailable');return (- <section- className="px-5 py-5"- aria-labelledby="billing-balance-title"- aria-live="polite"- aria-busy={loading}- >+ <section aria-labelledby="billing-balance-title" aria-live="polite" aria-busy={loading}>{loading ? (- <div className="flex h-[118px] items-center px-5">+ <div className="flex h-[118px] items-center px-5 py-5"><Spinner size={15} /></div>) : usage ? (@@ -1052,44 +1238,6 @@ function GrantAmount({);}-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,@@ -1100,7 +1248,6 @@ function BillingOfferDialog({selectedPurchaseOptionId,customAmount,amountError,- subscriptionPurchaseBlocked,canCheckout,onClose,onRetry,@@ -1118,7 +1265,6 @@ function BillingOfferDialog({selectedPurchaseOptionId: string | null;customAmount: string;amountError: string | null;- subscriptionPurchaseBlocked: boolean;canCheckout: boolean;onClose: () => void;onRetry: () => void;@@ -1299,12 +1445,6 @@ function BillingOfferDialog({</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>)}</>diff --git a/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx b/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsxindex 3acc4f6433..15599432e9 100644--- a/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx+++ b/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx@@ -2,8 +2,6 @@ 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,@@ -14,6 +12,7 @@ import {} from 'lucide-react';import { useTranslation } from 'react-i18next';+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import { Spinner } from '@/components/ui/spinner';import { cn } from '@/lib/utils';import type {@@ -31,8 +30,6 @@ 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 {@@ -112,8 +109,6 @@ export function PlanChangeTargetDialog({) : (<div className="space-y-2.5">{candidates.map((candidate) => {- const DirectionIcon =- candidate.direction === 'UPGRADE' ? ArrowUpRight : ArrowDownRight;return (<buttonkey={candidate.offer.code}@@ -131,10 +126,7 @@ export function PlanChangeTargetDialog({{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')}+ {t('billing.planChange.serverDecisionHint')}</p></div><div className="shrink-0 text-right">@@ -199,6 +191,7 @@ export function PlanChangeStatusDialog({onAbandon: () => void;}) {const { t } = useTranslation();+ const { confirm } = useConfirmDialog();const change = state.planChange;const action: BillingPaymentAction | null = change?.paymentAction ?? null;const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);@@ -263,14 +256,47 @@ export function PlanChangeStatusDialog({state.phase === 'CANCELED' ||state.phase === 'FAILED' ||state.phase === 'EXPIRED';+ const confirmPlanChange = async () => {+ if (!change) return;+ const impact =+ change.changeType === 'UPGRADE'+ ? quotedAmount+ ? t('billing.planChange.upgradeDueNow', { amount: quotedAmount })+ : t('billing.planChange.upgradeNoAmount')+ : t('billing.planChange.downgradeAt', {+ date: formatEffectiveDate(change.effectiveAt),+ });+ const accepted = await confirm({+ title: t('billing.confirmActions.confirmPlanChangeTitle'),+ description: t('billing.confirmActions.confirmPlanChangeDescription', {+ target: targetName ?? t('billing.settings.subscriptionCard.unnamedPlan'),+ impact,+ }),+ confirmText: t('billing.confirmActions.confirmPlanChange'),+ cancelText: t('billing.confirmActions.back'),+ autoFocusConfirm: true,+ });+ if (accepted) onConfirm();+ };+ const abandonPlanChange = async () => {+ const accepted = await confirm({+ title: t('billing.confirmActions.cancelPlanChangeTitle'),+ description: t('billing.confirmActions.cancelPlanChangeDescription', {+ target: targetName ?? t('billing.settings.subscriptionCard.unnamedPlan'),+ }),+ confirmText: t('billing.confirmActions.cancelPlanChange'),+ cancelText: t('billing.confirmActions.back'),+ });+ if (accepted) onAbandon();+ };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.Overlay className="fixed inset-0 z-[9990] bg-[var(--overlay-modal)]" /><Dialog.ContentclassName={cn(- 'fixed left-1/2 top-1/2 z-[10001] w-[calc(100vw-40px)] max-w-[600px]',+ 'fixed left-1/2 top-1/2 z-[9991] 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',@@ -453,7 +479,7 @@ export function PlanChangeStatusDialog({{state.phase === 'QUOTE_READY' && change?.status === 'QUOTED' && !state.stale && (<buttontype="button"- onClick={onAbandon}+ onClick={() => void abandonPlanChange()}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')}@@ -478,7 +504,7 @@ export function PlanChangeStatusDialog({{state.phase === 'QUOTE_READY' && change?.status === 'QUOTED' && !state.stale && (<buttontype="button"- onClick={onConfirm}+ onClick={() => void confirmPlanChange()}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')}diff --git a/apps/desktop/src/renderer/features/billing/__tests__/BillingCheckoutDialog.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/BillingCheckoutDialog.test.tsxnew file mode 100644index 0000000000..4c4ad56ef1--- /dev/null+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingCheckoutDialog.test.tsx@@ -0,0 +1,124 @@+// @vitest-environment jsdom++import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const confirm = vi.hoisted(() => vi.fn());++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'),+}));+vi.mock('@/components/ui/confirm-dialog-provider', () => ({+ useConfirmDialog: () => ({ confirm }),+}));++import { BillingCheckoutDialog } from '../BillingCheckoutDialog';+import type { BillingCheckoutState } from '../useBillingCheckout';++function topupState(overrides: Partial<BillingCheckoutState> = {}): BillingCheckoutState {+ return {+ open: true,+ kind: 'TOPUP',+ phase: 'AWAITING_PAYMENT',+ intent: null,+ order: {+ orderId: 'order_fixture',+ productCode: 'credit_topup',+ offerCode: 'credit_topup_20',+ amount: '20',+ currency: 'cny',+ status: 'PENDING',+ fulfillmentStatus: 'NOT_STARTED',+ paymentAction: null,+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:01:00.000Z',+ },+ subscription: null,+ error: false,+ ...overrides,+ };+}++describe('BillingCheckoutDialog confirmations', () => {+ beforeEach(() => {+ confirm.mockReset().mockResolvedValue(true);+ });++ it('cancels a pending payment only after confirmation is accepted', async () => {+ confirm.mockResolvedValueOnce(false).mockResolvedValueOnce(true);+ const onCancel = vi.fn();+ render(+ <BillingCheckoutDialog+ state={topupState()}+ onClose={vi.fn()}+ onRefresh={vi.fn()}+ onRetry={vi.fn()}+ onCancel={onCancel}+ />,+ );++ fireEvent.click(screen.getByText('billing.actions.cancelPayment'));+ await waitFor(() => expect(confirm).toHaveBeenCalledTimes(1));+ expect(onCancel).not.toHaveBeenCalled();++ fireEvent.click(screen.getByText('billing.actions.cancelPayment'));+ await waitFor(() => expect(onCancel).toHaveBeenCalledTimes(1));+ expect(confirm).toHaveBeenLastCalledWith(+ expect.objectContaining({+ confirmText: 'billing.confirmActions.cancelPayment',+ }),+ );+ });++ it('retries an expired payment only after confirmation is accepted', async () => {+ const onRetry = vi.fn();+ render(+ <BillingCheckoutDialog+ state={topupState({+ phase: 'EXPIRED',+ order: {+ ...topupState().order!,+ status: 'EXPIRED',+ },+ })}+ onClose={vi.fn()}+ onRefresh={vi.fn()}+ onRetry={onRetry}+ onCancel={vi.fn()}+ />,+ );++ fireEvent.click(screen.getByText('billing.actions.retry'));+ expect(onRetry).not.toHaveBeenCalled();+ await waitFor(() => expect(onRetry).toHaveBeenCalledTimes(1));+ expect(confirm).toHaveBeenCalledWith(+ expect.objectContaining({+ confirmText: 'billing.confirmActions.retryPayment',+ autoFocusConfirm: true,+ }),+ );+ });++ it('refreshes payment status without confirmation', () => {+ const onRefresh = vi.fn();+ render(+ <BillingCheckoutDialog+ state={topupState()}+ onClose={vi.fn()}+ onRefresh={onRefresh}+ onRetry={vi.fn()}+ onCancel={vi.fn()}+ />,+ );++ fireEvent.click(screen.getByText('billing.actions.refresh'));+ expect(onRefresh).toHaveBeenCalledTimes(1);+ expect(confirm).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsxindex 5cc84f22dc..a23ff44ed6 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,9 @@import { fireEvent, render, screen, waitFor } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { BillingPaymentOrder, BillingSubscription } from '../../../../shared/billing';+const confirm = vi.hoisted(() => vi.fn());const checkout = {state: {open: false,@@ -13,7 +15,10 @@ const checkout = {subscription: null,error: false,},- recoverables: { topups: [], subscription: null },+ recoverables: {+ topups: [] as BillingPaymentOrder[],+ subscription: null as BillingSubscription | null,+ },recovering: false,startTopup: vi.fn(),startSubscription: vi.fn(),@@ -44,6 +49,9 @@ vi.mock('@/features/feature-context', () => ({vi.mock('@/contexts/AuthContext', () => ({useAuth: () => ({ dataOwnerId: 'account-fixture' }),}));+vi.mock('@/components/ui/confirm-dialog-provider', () => ({+ useConfirmDialog: () => ({ confirm }),+}));vi.mock('../useBillingCheckout', () => ({useBillingCheckout: () => checkout,}));@@ -53,6 +61,10 @@ vi.mock('qrcode', () => ({import { BillingPage } from '../BillingPage';+beforeEach(() => {+ confirm.mockReset().mockResolvedValue(true);+});+describe('BillingPage remote catalog rendering', () => {beforeEach(() => {Object.assign(checkout.state, {@@ -67,6 +79,10 @@ describe('BillingPage remote catalog rendering', () => {checkout.startTopup.mockClear();checkout.startSubscription.mockClear();checkout.close.mockClear();+ checkout.resumeTopup.mockClear();+ checkout.resumeSubscription.mockClear();+ checkout.recoverables.topups = [];+ checkout.recoverables.subscription = null;checkout.recovering = false;Object.defineProperty(window, 'electronAPI', {configurable: true,@@ -287,6 +303,111 @@ describe('BillingPage remote catalog rendering', () => {expect(screen.getByText('billing.usage.detailsUnavailable')).toBeTruthy();});+ it('shows current plan price, included credits, status, and renewal date', async () => {+ window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => ({+ subscription: {+ subscriptionId: 'subscription_fixture',+ status: 'ACTIVE' as const,+ 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: 'MONTH' as const },+ terms: { amount: '9', currency: 'usd', creditAmount: '100', rolloverCap: '0' },+ capturedAt: '2026-07-01T00:00:00.000Z',+ },+ purchaseAttemptId: null,+ paymentAction: null,+ },+ }));++ render(<BillingPage />);++ expect(await screen.findByText('Configured subscription')).toBeTruthy();+ expect(screen.getByText('billing.subscriptionStatus.ACTIVE')).toBeTruthy();+ expect(+ screen.getByText((text) =>+ text.startsWith('billing.settings.subscriptionCard.priceInterval'),+ ),+ ).toBeTruthy();+ expect(+ screen.getByText((text) =>+ text.startsWith('billing.settings.subscriptionCard.includedCredits'),+ ),+ ).toBeTruthy();+ expect(+ screen.getByText((text) => text.startsWith('billing.settings.subscriptionCard.renewsAt')),+ ).toBeTruthy();+ expect(screen.getByText('billing.settings.subscriptionCard.changeAction')).toBeTruthy();+ expect(screen.getByText('billing.settings.subscriptionCard.purchaseAnother')).toBeTruthy();+ });++ it('shows an end date for period-end cancellation and omits invalid dates', async () => {+ const subscription = {+ subscriptionId: 'subscription_fixture',+ status: 'ACTIVE' as const,+ currentPeriodStartAt: null,+ currentPeriodEndAt: '2026-08-01T00:00:00.000Z',+ entitlementValidUntil: null,+ cancelAtPeriodEnd: true,+ effectivePlan: null,+ purchaseAttemptId: null,+ paymentAction: null,+ };+ window.electronAPI.billing.getCurrentSubscription = vi+ .fn()+ .mockResolvedValueOnce({ subscription })+ .mockResolvedValueOnce({+ subscription: { ...subscription, currentPeriodEndAt: 'not-a-date' },+ });++ render(<BillingPage />);+ expect(+ await screen.findByText((text) =>+ text.startsWith('billing.settings.subscriptionCard.endsAt'),+ ),+ ).toBeTruthy();++ fireEvent.click(screen.getByText('billing.actions.refreshCatalog'));+ await waitFor(() =>+ expect(+ screen.queryByText((text) => text.startsWith('billing.settings.subscriptionCard.endsAt')),+ ).toBeNull(),+ );+ expect(+ screen.queryByText((text) => text.startsWith('billing.settings.subscriptionCard.renewsAt')),+ ).toBeNull();+ });++ it('places recoverable checkout actions before the balance overview', async () => {+ const order = {+ orderId: 'order_pending',+ productCode: 'credit_topup',+ offerCode: 'credit_topup_custom',+ amount: '10',+ currency: 'cny',+ status: 'PENDING' as const,+ fulfillmentStatus: 'NOT_STARTED' as const,+ paymentAction: null,+ createdAt: '2026-07-24T00:00:00.000Z',+ updatedAt: '2026-07-24T00:00:00.000Z',+ };+ checkout.recoverables.topups = [order];++ render(<BillingPage />);++ const recovery = screen.getByText('billing.recovery.title');+ const balanceTitle = await screen.findByText('billing.balance.title');+ expect(recovery.compareDocumentPosition(balanceTitle) & Node.DOCUMENT_POSITION_FOLLOWING).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ fireEvent.click(screen.getByText((text) => text.startsWith('billing.recovery.continueTopup')));+ expect(checkout.resumeTopup).toHaveBeenCalledWith(order);+ });+it('shows usage progress and each promotional grant with its own state and expiry', async () => {window.electronAPI.billing.getCreditUsage = vi.fn(async () => ({available: '66',@@ -436,10 +557,44 @@ describe('BillingPage remote catalog rendering', () => {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',+ await waitFor(() =>+ expect(checkout.startSubscription).toHaveBeenCalledWith({+ offerCode: 'plus_month',+ purchaseOptionId: 'listing_stripe',+ }),+ );+ expect(confirm).toHaveBeenCalledWith(+ expect.objectContaining({+ confirmText: 'billing.confirmActions.purchaseSubscription',+ autoFocusConfirm: true,+ }),+ );+ });++ it('does not create a top-up when its confirmation is canceled', async () => {+ confirm.mockResolvedValue(false);+ 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' },});+ fireEvent.click(screen.getByText('billing.actions.pay'));++ await waitFor(() => expect(confirm).toHaveBeenCalledTimes(1));+ expect(checkout.startTopup).not.toHaveBeenCalled();+ expect(screen.getByText('Configured top-up')).toBeTruthy();+ });++ it('does not confirm read-only refresh actions', async () => {+ render(<BillingPage />);+ await screen.findByText('billing.balance.title');++ fireEvent.click(screen.getByText('billing.actions.refreshCatalog'));+ await waitFor(() => expect(window.electronAPI.billing.getCatalog).toHaveBeenCalledTimes(2));+ expect(confirm).not.toHaveBeenCalled();});it('keeps checkout disabled until startup recovery finishes', async () => {@@ -463,7 +618,7 @@ describe('BillingPage remote catalog rendering', () => {expect(pay).toHaveProperty('disabled', false);});- it('does not create a second subscription while one is still live', async () => {+ it('keeps new subscription purchase available while one is still live', async () => {window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => ({subscription: {subscriptionId: 'subscription_fixture',@@ -479,22 +634,25 @@ describe('BillingPage remote catalog rendering', () => {}));render(<BillingPage />);- const viewPlans = screen- .getByText('billing.settings.subscriptionCard.action')- .closest('button')!;- await waitFor(() => expect(viewPlans).toHaveProperty('disabled', false));- fireEvent.click(viewPlans);+ const purchaseAnother = await screen.findByText(+ 'billing.settings.subscriptionCard.purchaseAnother',+ );+ fireEvent.click(purchaseAnother);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,+ const pay = screen.getByText('billing.actions.pay').closest('button')!;+ expect(pay).toHaveProperty('disabled', false);+ fireEvent.click(pay);+ await waitFor(() =>+ expect(checkout.startSubscription).toHaveBeenCalledWith({+ offerCode: 'plus_month',+ purchaseOptionId: 'listing_stripe',+ }),);- expect(screen.getByText('billing.currentSubscription.purchaseBlocked')).toBeTruthy();});- it('fails closed for subscription purchases when subscription status is unavailable', async () => {+ it('keeps subscription purchases available when subscription status is unavailable', async () => {window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => {throw new Error('subscription status unavailable');});@@ -504,7 +662,7 @@ describe('BillingPage remote catalog rendering', () => {expect(await screen.findByText('billing.settings.subscriptionCard.unavailable')).toBeTruthy();expect(screen.getByText('billing.settings.subscriptionCard.action').closest('button'),- ).toHaveProperty('disabled', true);+ ).toHaveProperty('disabled', false);expect(screen.getByText('billing.settings.topupCard.action').closest('button')).toHaveProperty('disabled',false,@@ -556,7 +714,7 @@ describe('BillingPage remote catalog rendering', () => {expect(screen.queryByText('Configured subscription')).toBeNull();expect(screen.getByText('billing.settings.subscriptionCard.action').closest('button'),- ).toHaveProperty('disabled', true);+ ).toHaveProperty('disabled', false);});it('renders multiple remote subscription offers as independent choices', async () => {@@ -806,6 +964,9 @@ describe('BillingPage plan change', () => {beforeEach(() => {localStorage.clear();+ checkout.recoverables.topups = [];+ checkout.recoverables.subscription = null;+ checkout.recovering = false;Object.assign(checkout.state, {open: false,kind: null,@@ -820,7 +981,7 @@ describe('BillingPage plan change', () => {});});- it('offers plan change for an active subscription with same-provider candidates only', async () => {+ it('offers cross-provider plan targets and lets the server decide', async () => {const billing = install(billingMocks());billing.quotePlanChange.mockResolvedValue({planChangeId: 'plan_change_1',@@ -838,12 +999,18 @@ describe('BillingPage plan change', () => {await screen.findByText('billing.planChange.targetTitle');expect(screen.getByText('Max plan')).toBeTruthy();- expect(screen.queryByText('Alipay-only Max')).toBeNull();+ expect(screen.getByText('Alipay-only Max')).toBeTruthy();// The current plan renders in the summary card but must not be a candidate.- expect(screen.getByText('billing.planChange.upgradeBadge')).toBeTruthy();+ expect(screen.getAllByText('billing.planChange.serverDecisionHint')).toHaveLength(2);fireEvent.click(screen.getByText('Max plan'));await screen.findByText('billing.planChange.quoteTitle');+ expect(confirm).toHaveBeenCalledWith(+ expect.objectContaining({+ confirmText: 'billing.confirmActions.quotePlanChange',+ autoFocusConfirm: true,+ }),+ );expect(billing.quotePlanChange).toHaveBeenCalledTimes(1);expect(billing.quotePlanChange).toHaveBeenCalledWith({targetOfferCode: 'max_month',@@ -865,12 +1032,18 @@ describe('BillingPage plan change', () => {});fireEvent.click(screen.getByText('billing.planChange.confirm'));await screen.findByText('billing.planChange.appliedTitle');+ expect(confirm).toHaveBeenLastCalledWith(+ expect.objectContaining({+ confirmText: 'billing.confirmActions.confirmPlanChange',+ autoFocusConfirm: true,+ }),+ );// 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 () => {+ it('offers plan change for yearly subscriptions and lets the server decide', async () => {const billing = billingMocks();billing.getCurrentSubscription = vi.fn(async () => ({subscription: activeSubscription(null, 'YEAR'),@@ -880,8 +1053,9 @@ 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();+ fireEvent.click(screen.getByText('billing.settings.subscriptionCard.changeAction'));+ expect(await screen.findByText('Max plan')).toBeTruthy();+ expect(screen.getByText('Alipay-only Max')).toBeTruthy();expect(billing.quotePlanChange).not.toHaveBeenCalled();});@@ -923,6 +1097,11 @@ describe('BillingPage plan change', () => {await waitFor(() =>expect(billing.cancelPlanChange).toHaveBeenCalledWith({ planChangeId: 'plan_change_down' }),);+ expect(confirm).toHaveBeenCalledWith(+ expect.objectContaining({+ confirmText: 'billing.confirmActions.cancelPlanChange',+ }),+ );// The canceled settle re-syncs the subscription projection for the banner.await waitFor(() => expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(2));});diff --git a/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsxindex 7896be8d54..97fd0435bc 100644--- a/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx+++ b/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx@@ -1,8 +1,9 @@// @vitest-environment jsdom-import { fireEvent, render, screen } from '@testing-library/react';-import { describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';+const confirm = vi.hoisted(() => vi.fn());vi.mock('react-i18next', () => ({useTranslation: () => ({t: (key: string, params?: Record<string, string>) =>@@ -12,6 +13,9 @@ vi.mock('react-i18next', () => ({vi.mock('qrcode', () => ({toDataURL: vi.fn(async () => 'data:image/png;base64,fixture'),}));+vi.mock('@/components/ui/confirm-dialog-provider', () => ({+ useConfirmDialog: () => ({ confirm }),+}));import { PlanChangeStatusDialog } from '../PlanChangeDialog';import type { PlanChangeState } from '../usePlanChange';@@ -38,6 +42,10 @@ function quoteReadyState(overrides: Partial<PlanChangeState> = {}): PlanChangeSt}describe('PlanChangeStatusDialog stale snapshot handling', () => {+ beforeEach(() => {+ confirm.mockReset().mockResolvedValue(true);+ });+it('lets a fresh quote be confirmed or abandoned', () => {render(<PlanChangeStatusDialog@@ -103,4 +111,47 @@ describe('PlanChangeStatusDialog stale snapshot handling', () => {fireEvent.click(screen.getByText('billing.actions.refresh'));expect(onRefresh).toHaveBeenCalledTimes(1);});++ it('does not submit the final change until confirmation is accepted', async () => {+ const onConfirm = vi.fn();+ render(+ <PlanChangeStatusDialog+ state={quoteReadyState()}+ targetName="Plus"+ onClose={vi.fn()}+ onConfirm={onConfirm}+ onRefresh={vi.fn()}+ onAbandon={vi.fn()}+ />,+ );++ fireEvent.click(screen.getByText('billing.planChange.confirm'));+ expect(onConfirm).not.toHaveBeenCalled();+ await waitFor(() => expect(onConfirm).toHaveBeenCalledTimes(1));+ expect(confirm).toHaveBeenCalledWith(+ expect.objectContaining({+ confirmText: 'billing.confirmActions.confirmPlanChange',+ autoFocusConfirm: true,+ }),+ );+ });++ it('keeps the quote when cancel-plan-change confirmation is declined', async () => {+ confirm.mockResolvedValue(false);+ const onAbandon = vi.fn();+ render(+ <PlanChangeStatusDialog+ state={quoteReadyState()}+ targetName="Plus"+ onClose={vi.fn()}+ onConfirm={vi.fn()}+ onRefresh={vi.fn()}+ onAbandon={onAbandon}+ />,+ );++ fireEvent.click(screen.getByText('billing.planChange.abandon'));+ await waitFor(() => expect(confirm).toHaveBeenCalledTimes(1));+ expect(onAbandon).not.toHaveBeenCalled();+ });});diff --git a/apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.ts b/apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.tsindex eb5254e299..c5c5706fe3 100644--- a/apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.ts+++ b/apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.ts@@ -173,7 +173,7 @@ describe('billing checkout phase projection', () => {expect(readBillingCheckoutIntent(ACCOUNT_ID)).toBeNull();});- it('replays an unresolved persisted purchase with the original request and key', async () => {+ it('replays an unresolved persisted purchase in the background without opening it', async () => {const pending = {subscriptionId: 'subscription_pending',status: 'INCOMPLETE' as const,@@ -216,8 +216,9 @@ describe('billing checkout phase projection', () => {},'desktop:subscription:stale-intent',);- expect(result.current.state.open).toBe(true);+ expect(result.current.state.open).toBe(false);expect(result.current.state.phase).toBe('AWAITING_PAYMENT');+ expect(result.current.recoverables.subscription).toEqual(pending);expect(readBillingCheckoutIntent(ACCOUNT_ID)).toEqual({version: 1,kind: 'SUBSCRIPTION',@@ -230,6 +231,10 @@ describe('billing checkout phase projection', () => {purchaseAttemptId: 'purchase_pending',createdAt: '2026-01-01T00:00:00.000Z',});++ act(() => result.current.resumeSubscription(result.current.recoverables.subscription!));+ expect(result.current.state.open).toBe(true);+ expect(result.current.state.subscription).toEqual(pending);});it('does not replace a persisted subscription intent with another current subscription', async () => {@@ -265,6 +270,7 @@ describe('billing checkout phase projection', () => {expect(api.refreshSubscriptionPurchase).toHaveBeenCalledWith('purchase_expected');expect(result.current.state).toMatchObject({+ open: false,phase: 'FAILED',intent,subscription: null,@@ -306,6 +312,7 @@ describe('billing checkout phase projection', () => {expect(api.refreshSubscriptionPurchase).toHaveBeenCalledWith('purchase_expected');expect(result.current.state).toMatchObject({+ open: false,phase: 'COMPLETED',subscription: completed,error: false,@@ -313,6 +320,112 @@ describe('billing checkout phase projection', () => {expect(readBillingCheckoutIntent(ACCOUNT_ID)).toBeNull();});+ it('clears an expired persisted top-up without opening a dialog', async () => {+ const intent = {+ version: 1 as const,+ kind: 'TOPUP' as const,+ idempotencyKey: 'desktop:topup:expired-intent',+ request: {+ offerCode: 'credit_topup_20',+ purchaseOptionId: 'listing_alipay',+ },+ orderId: 'order_expired',+ createdAt: '2026-01-01T00:00:00.000Z',+ };+ const expiredOrder = {+ orderId: 'order_expired',+ productCode: 'credit_topup',+ offerCode: 'credit_topup_20',+ amount: '20',+ currency: 'cny',+ status: 'EXPIRED' as const,+ paymentAction: null,+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:01:00.000Z',+ };+ writeBillingCheckoutIntent(ACCOUNT_ID, intent);+ api.listOrders.mockResolvedValue({ orders: [expiredOrder], nextCursor: null });++ const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));+ await waitFor(() => expect(result.current.recovering).toBe(false));++ expect(result.current.state).toMatchObject({+ open: false,+ phase: 'EXPIRED',+ order: expiredOrder,+ });+ expect(result.current.recoverables.topups).toEqual([]);+ expect(readBillingCheckoutIntent(ACCOUNT_ID)).toBeNull();+ });++ it('clears an expired persisted subscription purchase without opening a dialog', async () => {+ const intent = {+ version: 1 as const,+ kind: 'SUBSCRIPTION' as const,+ idempotencyKey: 'desktop:subscription:expired-intent',+ request: {+ offerCode: 'plus_month',+ purchaseOptionId: 'listing_alipay',+ },+ subscriptionId: 'subscription_expired',+ purchaseAttemptId: 'purchase_expired',+ createdAt: '2026-01-01T00:00:00.000Z',+ };+ const expiredSubscription = {+ subscriptionId: 'subscription_expired',+ status: 'INCOMPLETE_EXPIRED' as const,+ currentPeriodStartAt: null,+ currentPeriodEndAt: null,+ entitlementValidUntil: null,+ cancelAtPeriodEnd: false,+ effectivePlan: null,+ purchaseAttemptId: 'purchase_expired',+ paymentAction: null,+ };+ writeBillingCheckoutIntent(ACCOUNT_ID, intent);+ api.getCurrentSubscription.mockResolvedValue({ subscription: expiredSubscription });+ api.refreshSubscriptionPurchase.mockResolvedValue(expiredSubscription);++ const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));+ await waitFor(() => expect(result.current.recovering).toBe(false));++ expect(result.current.state).toMatchObject({+ open: false,+ phase: 'EXPIRED',+ subscription: expiredSubscription,+ });+ expect(result.current.recoverables.subscription).toBeNull();+ expect(readBillingCheckoutIntent(ACCOUNT_ID)).toBeNull();+ });++ it('lists a pending top-up as recoverable without opening it, then opens on resume', async () => {+ const pendingOrder = {+ orderId: 'order_pending',+ productCode: 'credit_topup',+ offerCode: 'credit_topup_20',+ amount: '20',+ currency: 'cny',+ status: 'PENDING' as const,+ paymentAction: null,+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:01:00.000Z',+ };+ api.listOrders.mockResolvedValue({ orders: [pendingOrder], nextCursor: null });++ const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));+ await waitFor(() => expect(result.current.recovering).toBe(false));++ 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).toMatchObject({+ open: true,+ phase: 'AWAITING_PAYMENT',+ order: pendingOrder,+ });+ });+it('keeps an unresolved persisted purchase retryable when recovery fails', async () => {const intent = {version: 1 as const,@@ -333,15 +446,13 @@ describe('billing checkout phase projection', () => {await waitFor(() => expect(result.current.recovering).toBe(false));expect(result.current.state).toMatchObject({- open: true,+ open: false,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);});@@ -456,6 +567,35 @@ describe('billing checkout phase projection', () => {expect(api.refreshTopup).toHaveBeenCalledWith('order_fixture');});+ it('keeps a visible checkout open when refresh reports it expired', async () => {+ const pendingOrder = {+ orderId: 'order_fixture',+ productCode: 'credit_topup',+ offerCode: 'credit_topup_20',+ amount: '20',+ currency: 'cny',+ status: 'PENDING' as const,+ paymentAction: null,+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:01:00.000Z',+ };+ api.refreshTopup.mockResolvedValue({+ ...pendingOrder,+ status: 'EXPIRED',+ });++ const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));+ await waitFor(() => expect(result.current.recovering).toBe(false));+ act(() => result.current.resumeTopup(pendingOrder));++ await act(() => result.current.refreshActive());++ expect(result.current.state).toMatchObject({+ open: true,+ phase: 'EXPIRED',+ });+ });+it('keeps a pending checkout recoverable after its dialog is closed', async () => {const pendingOrder = {orderId: 'order_pending',diff --git a/apps/desktop/src/renderer/features/billing/useBillingCheckout.ts b/apps/desktop/src/renderer/features/billing/useBillingCheckout.tsindex 64c84a0341..3496a2045e 100644--- a/apps/desktop/src/renderer/features/billing/useBillingCheckout.ts+++ b/apps/desktop/src/renderer/features/billing/useBillingCheckout.ts@@ -40,6 +40,8 @@ export type BillingRecoverables = {subscription: BillingSubscription | null;};+type CheckoutPresentation = 'VISIBLE' | 'BACKGROUND';+const INITIAL_STATE: BillingCheckoutState = {open: false,kind: null,@@ -123,7 +125,11 @@ export function useBillingCheckout(accountId: string | null) {stateRef.current = state;const applyOrder = useCallback(- (order: BillingPaymentOrder, intent: BillingCheckoutIntentV1 | null) => {+ (+ order: BillingPaymentOrder,+ intent: BillingCheckoutIntentV1 | null,+ presentation: CheckoutPresentation = 'VISIBLE',+ ) => {const nextIntent =intent?.kind === 'TOPUP' && intent.orderId !== order.orderId? { ...intent, orderId: order.orderId }@@ -139,7 +145,7 @@ export function useBillingCheckout(accountId: string | null) {: current.topups.filter((item) => item.orderId !== order.orderId),}));setState({- open: true,+ open: presentation === 'VISIBLE',kind: 'TOPUP',phase,intent: nextIntent,@@ -152,7 +158,11 @@ export function useBillingCheckout(accountId: string | null) {);const applySubscription = useCallback(- (subscription: BillingSubscription, intent: BillingCheckoutIntentV1 | null) => {+ (+ subscription: BillingSubscription,+ intent: BillingCheckoutIntentV1 | null,+ presentation: CheckoutPresentation = 'VISIBLE',+ ) => {if (intent?.kind === 'SUBSCRIPTION' && !matchesSubscriptionIntent(subscription, intent))return false;const nextIntent =@@ -172,7 +182,7 @@ export function useBillingCheckout(accountId: string | null) {subscription: subscription.status === 'INCOMPLETE' ? subscription : null,}));setState({- open: true,+ open: presentation === 'VISIBLE',kind: 'SUBSCRIPTION',phase,intent: nextIntent,@@ -185,9 +195,14 @@ export function useBillingCheckout(accountId: string | null) {[accountId],);- const failCurrentOperation = useCallback(() => {+ const failCurrentOperation = useCallback((presentation: CheckoutPresentation = 'VISIBLE') => {if (!mountedRef.current) return;- setState((current) => ({ ...current, phase: 'FAILED', error: true }));+ setState((current) => ({+ ...current,+ open: presentation === 'VISIBLE',+ phase: 'FAILED',+ error: true,+ }));}, []);const withRequestLock = useCallback(async (request: () => Promise<void>) => {@@ -479,7 +494,7 @@ export function useBillingCheckout(accountId: string | null) {if (!intent) return;setState({- open: true,+ open: false,kind: intent.kind === 'SUBSCRIPTION' ? 'SUBSCRIPTION' : 'TOPUP',phase: 'CREATING',intent,@@ -498,12 +513,16 @@ export function useBillingCheckout(accountId: string | null) {(intent.orderId? await billingApi.getOrder(intent.orderId): await billingApi.createTopup(intent.request, intent.idempotencyKey));- applyOrder(order, intent);+ applyOrder(order, intent, 'BACKGROUND');return;}if (intent.kind === 'TOPUP_RETRY') {- applyOrder(await billingApi.retryTopup(intent.orderId, intent.idempotencyKey), intent);+ applyOrder(+ await billingApi.retryTopup(intent.orderId, intent.idempotencyKey),+ intent,+ 'BACKGROUND',+ );return;}@@ -512,7 +531,7 @@ export function useBillingCheckout(accountId: string | null) {!intent.purchaseAttemptId &&subscriptionResult.status === 'rejected') {- failCurrentOperation();+ failCurrentOperation('BACKGROUND');return;}const currentSubscription =@@ -524,9 +543,11 @@ export function useBillingCheckout(accountId: string | null) {: intent.subscriptionId? currentSubscription: await billingApi.createSubscription(intent.request, intent.idempotencyKey);- if (!subscription || !applySubscription(subscription, intent)) failCurrentOperation();+ if (!subscription || !applySubscription(subscription, intent, 'BACKGROUND')) {+ failCurrentOperation('BACKGROUND');+ }} catch {- failCurrentOperation();+ failCurrentOperation('BACKGROUND');}} finally {inFlightRef.current = false;diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex b564f7eb6e..97cabddf57 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -6928,7 +6928,7 @@"sidebar": "Credits & plans","settings": {"title": "Usage and billing",- "subtitle": "Review your current subscription or purchase server-provided plans and credits.",+ "subtitle": "Review your available credits and current plan, or buy more credits as needed.","loading": "Loading subscription status…","subscriptionCard": {"title": "Current plan",@@ -6937,13 +6937,18 @@"unnamedPlan": "Subscription plan","unavailable": "Subscription status is temporarily unavailable. Refresh to try again.","action": "View plans",- "changeAction": "Change plan"+ "changeAction": "Change Plan",+ "purchaseAnother": "Buy New Subscription",+ "priceInterval": "{{price}} / {{interval}}",+ "includedCredits": "Includes {{amount}} credits per {{interval}}",+ "renewsAt": "Renews {{date}}",+ "endsAt": "Plan ends {{date}}"},"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.",+ "cardDescription": "Add to your available credits as needed. The checkout page shows the final amount.","action": "Buy credits"}},@@ -7048,6 +7053,31 @@"confirm": {"channel": "Pay with {{provider}}"},+ "confirmActions": {+ "back": "Back to Review",+ "purchaseTopupTitle": "Buy Credits?",+ "purchaseTopupDescription": "{{product}} · {{amount}} · Pay with {{provider}}",+ "purchaseTopup": "Buy Credits",+ "purchaseSubscriptionTitle": "Buy {{plan}}?",+ "purchaseSubscriptionDescription": "{{price}} / {{interval}} · Pay with {{provider}}",+ "purchaseSubscription": "Buy Plan",+ "quotePlanChangeTitle": "Get a Plan Change Quote?",+ "quotePlanChangeDescription": "{{current}} → {{target}}. The next step shows the actual price difference and effective time.",+ "quotePlanChange": "Get Change Quote",+ "confirmPlanChangeTitle": "Apply This Plan Change?",+ "confirmPlanChangeDescription": "{{target}} · {{impact}}",+ "confirmPlanChange": "Apply Plan Change",+ "cancelPaymentTitle": "Cancel This Payment?",+ "cancelPaymentDescription": "The {{amount}} payment will be canceled. You will need to create a new payment.",+ "cancelPayment": "Cancel Payment",+ "cancelPlanChangeTitle": "Cancel This Plan Change?",+ "cancelPlanChangeDescription": "Target plan: {{target}}. Your current plan remains unchanged.",+ "cancelPlanChange": "Cancel Plan Change",+ "retryPaymentTitle": "Retry This Payment?",+ "retryPaymentDescription": "The {{amount}} payment will retry with the original idempotent intent.",+ "retryUnknownPaymentDescription": "This payment will retry with the original idempotent intent.",+ "retryPayment": "Retry Payment"+ },"paymentActions": {"QR_CODE": "Scan to pay","REDIRECT": "Open payment page"@@ -7106,6 +7136,7 @@"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.",+ "serverDecisionHint": "Price and timing are confirmed by the next quote","upgradeBadge": "Upgrade","downgradeBadge": "Downgrade","emptyTitle": "No plans available to switch to",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 210734577e..3067f7a876 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -6917,7 +6917,7 @@"sidebar": "クレジットとプラン","settings": {"title": "使用状況と請求",- "subtitle": "現在のサブスクリプションを確認し、サーバーから提供されるプランやクレジットを購入できます。",+ "subtitle": "利用可能なクレジットと現在のプランを確認し、必要に応じてクレジットを購入できます。","loading": "サブスクリプションの状態を取得中…","subscriptionCard": {"title": "現在のプラン",@@ -6926,13 +6926,18 @@"unnamedPlan": "サブスクリプションプラン","unavailable": "サブスクリプションの状態を取得できません。更新してもう一度お試しください。","action": "プランを見る",- "changeAction": "プラン変更"+ "changeAction": "プランを変更",+ "purchaseAnother": "新しいサブスクリプションを購入",+ "priceInterval": "{{price}} / {{interval}}",+ "includedCredits": "毎{{interval}} {{amount}} クレジットを付与",+ "renewsAt": "次回更新日: {{date}}",+ "endsAt": "{{date}} にプラン終了"},"topupCard": {"title": "クレジット","description": "従量制のモデルや機能で使うクレジットを購入します。","cardTitle": "必要に応じてクレジットを購入",- "cardDescription": "購入可能なクレジット商品はサーバーで設定されます。",+ "cardDescription": "必要に応じて利用可能なクレジットを追加できます。最終金額は決済ページに表示されます。","action": "クレジットを購入"}},@@ -7037,6 +7042,31 @@"confirm": {"channel": "{{provider}}で支払う"},+ "confirmActions": {+ "back": "内容を確認",+ "purchaseTopupTitle": "クレジットを購入しますか?",+ "purchaseTopupDescription": "{{product}} · {{amount}} · {{provider}}で支払う",+ "purchaseTopup": "クレジットを購入",+ "purchaseSubscriptionTitle": "{{plan}}を購入しますか?",+ "purchaseSubscriptionDescription": "{{price}} / {{interval}} · {{provider}}で支払う",+ "purchaseSubscription": "プランを購入",+ "quotePlanChangeTitle": "プラン変更の見積もりを取得しますか?",+ "quotePlanChangeDescription": "{{current}} → {{target}}。次のステップで実際の差額と適用時期を表示します。",+ "quotePlanChange": "変更見積もりを取得",+ "confirmPlanChangeTitle": "プラン変更を確定しますか?",+ "confirmPlanChangeDescription": "{{target}} · {{impact}}",+ "confirmPlanChange": "プラン変更を確定",+ "cancelPaymentTitle": "この支払いをキャンセルしますか?",+ "cancelPaymentDescription": "{{amount}}の支払いをキャンセルします。続行するには新しい支払いの作成が必要です。",+ "cancelPayment": "この支払いをキャンセル",+ "cancelPlanChangeTitle": "プラン変更を取り消しますか?",+ "cancelPlanChangeDescription": "変更先プラン: {{target}}。取り消しても現在のプランは変わりません。",+ "cancelPlanChange": "プラン変更を取り消す",+ "retryPaymentTitle": "この支払いを再試行しますか?",+ "retryPaymentDescription": "{{amount}}の支払いを元の冪等な処理で再試行します。",+ "retryUnknownPaymentDescription": "この支払いを元の冪等な処理で再試行します。",+ "retryPayment": "この支払いを再試行"+ },"paymentActions": {"QR_CODE": "QRコードで支払う","REDIRECT": "支払いページを開く"@@ -7095,6 +7125,7 @@"targetTitle": "サブスクリプションプランの変更","targetDescription": "プラン変更は現在の支払い方法を引き継ぎます。最終的な金額と適用時期は次のステップで確認します。","targetDescriptionWithCurrent": "現在のプラン:{{plan}}。変更は現在の支払い方法を引き継ぎ、最終的な金額と適用時期は次のステップで確認します。",+ "serverDecisionHint": "金額と適用時期は次の見積もりで確定します","upgradeBadge": "アップグレード","downgradeBadge": "ダウングレード","emptyTitle": "切り替え可能なプランがありません",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 36413e4345..e490e382a0 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -6917,7 +6917,7 @@"sidebar": "크레딧 및 요금제","settings": {"title": "사용량 및 결제",- "subtitle": "현재 구독을 확인하거나 서버에서 제공하는 구독 상품과 크레딧을 구매할 수 있습니다.",+ "subtitle": "사용 가능한 크레딧과 현재 요금제를 확인하거나 필요할 때 크레딧을 구매할 수 있습니다.","loading": "구독 상태를 불러오는 중…","subscriptionCard": {"title": "현재 요금제",@@ -6926,13 +6926,18 @@"unnamedPlan": "구독 요금제","unavailable": "구독 상태를 불러올 수 없습니다. 새로고침 후 다시 시도하세요.","action": "요금제 보기",- "changeAction": "플랜 변경"+ "changeAction": "요금제 변경",+ "purchaseAnother": "새 구독 구매",+ "priceInterval": "{{price}} / {{interval}}",+ "includedCredits": "매{{interval}} {{amount}} 크레딧 포함",+ "renewsAt": "다음 갱신일 {{date}}",+ "endsAt": "{{date}}에 요금제 종료"},"topupCard": {"title": "크레딧","description": "사용량 기반 모델과 기능을 위한 크레딧을 구매합니다.","cardTitle": "필요할 때 크레딧 구매",- "cardDescription": "구매 가능한 크레딧 상품은 서버에서 설정됩니다.",+ "cardDescription": "필요할 때 사용 가능한 크레딧을 추가할 수 있습니다. 최종 금액은 결제 페이지에서 확인하세요.","action": "크레딧 구매"}},@@ -7037,6 +7042,31 @@"confirm": {"channel": "{{provider}}로 결제"},+ "confirmActions": {+ "back": "내용 다시 보기",+ "purchaseTopupTitle": "크레딧을 구매할까요?",+ "purchaseTopupDescription": "{{product}} · {{amount}} · {{provider}}로 결제",+ "purchaseTopup": "크레딧 구매",+ "purchaseSubscriptionTitle": "{{plan}}을(를) 구매할까요?",+ "purchaseSubscriptionDescription": "{{price}} / {{interval}} · {{provider}}로 결제",+ "purchaseSubscription": "요금제 구매",+ "quotePlanChangeTitle": "요금제 변경 견적을 받을까요?",+ "quotePlanChangeDescription": "{{current}} → {{target}}. 다음 단계에서 실제 차액과 적용 시점을 확인할 수 있습니다.",+ "quotePlanChange": "변경 견적 받기",+ "confirmPlanChangeTitle": "요금제 변경을 확정할까요?",+ "confirmPlanChangeDescription": "{{target}} · {{impact}}",+ "confirmPlanChange": "요금제 변경 확정",+ "cancelPaymentTitle": "이 결제를 취소할까요?",+ "cancelPaymentDescription": "{{amount}} 결제가 취소됩니다. 계속하려면 새 결제를 만들어야 합니다.",+ "cancelPayment": "이 결제 취소",+ "cancelPlanChangeTitle": "요금제 변경을 취소할까요?",+ "cancelPlanChangeDescription": "대상 요금제: {{target}}. 취소해도 현재 요금제는 유지됩니다.",+ "cancelPlanChange": "요금제 변경 취소",+ "retryPaymentTitle": "이 결제를 다시 시도할까요?",+ "retryPaymentDescription": "{{amount}} 결제를 기존 멱등 요청으로 다시 시도합니다.",+ "retryUnknownPaymentDescription": "이 결제를 기존 멱등 요청으로 다시 시도합니다.",+ "retryPayment": "이 결제 다시 시도"+ },"paymentActions": {"QR_CODE": "QR 코드 결제","REDIRECT": "결제 페이지 열기"@@ -7095,6 +7125,7 @@"targetTitle": "구독 플랜 변경","targetDescription": "플랜 변경은 현재 결제 수단을 그대로 사용합니다. 최종 금액과 적용 시점은 다음 단계에서 확인합니다.","targetDescriptionWithCurrent": "현재 플랜: {{plan}}. 변경은 현재 결제 수단을 그대로 사용하며, 최종 금액과 적용 시점은 다음 단계에서 확인합니다.",+ "serverDecisionHint": "금액과 적용 시점은 다음 견적에서 확정됩니다","upgradeBadge": "업그레이드","downgradeBadge": "다운그레이드","emptyTitle": "전환 가능한 플랜이 없습니다",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 2145db306f..be170e0cc0 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -6917,7 +6917,7 @@"sidebar": "点数与订阅","settings": {"title": "使用情况和计费",- "subtitle": "查看当前订阅,或按需购买由服务端提供的订阅套餐和点数。",+ "subtitle": "查看可用额度与当前套餐,或按需购买点数。","loading": "正在获取订阅状态…","subscriptionCard": {"title": "当前套餐",@@ -6926,13 +6926,18 @@"unnamedPlan": "订阅套餐","unavailable": "暂时无法获取订阅状态,请刷新后重试。","action": "查看套餐",- "changeAction": "更改套餐"+ "changeAction": "更改套餐",+ "purchaseAnother": "购买新订阅",+ "priceInterval": "{{price}} / {{interval}}",+ "includedCredits": "每{{interval}}包含 {{amount}} 点数",+ "renewsAt": "下次续费 {{date}}",+ "endsAt": "套餐将于 {{date}} 结束"},"topupCard": {"title": "点数","description": "购买点数,为按量使用的模型和功能充值。","cardTitle": "按需购买点数",- "cardDescription": "可购买的点数商品由服务端配置。",+ "cardDescription": "按需补充可用额度,购买金额以结算页为准。","action": "购买点数"}},@@ -7037,6 +7042,31 @@"confirm": {"channel": "通过 {{provider}} 支付"},+ "confirmActions": {+ "back": "返回检查",+ "purchaseTopupTitle": "购买点数?",+ "purchaseTopupDescription": "{{product}} · {{amount}} · 通过 {{provider}} 支付",+ "purchaseTopup": "确认购买点数",+ "purchaseSubscriptionTitle": "购买 {{plan}}?",+ "purchaseSubscriptionDescription": "{{price}} / {{interval}} · 通过 {{provider}} 支付",+ "purchaseSubscription": "确认购买套餐",+ "quotePlanChangeTitle": "获取套餐变更报价?",+ "quotePlanChangeDescription": "{{current}} → {{target}}。下一步将显示实际差价和生效时间。",+ "quotePlanChange": "获取变更报价",+ "confirmPlanChangeTitle": "确认套餐变更?",+ "confirmPlanChangeDescription": "{{target}} · {{impact}}",+ "confirmPlanChange": "确认套餐变更",+ "cancelPaymentTitle": "取消本次支付?",+ "cancelPaymentDescription": "{{amount}} 的支付将被取消,之后需要重新创建支付。",+ "cancelPayment": "取消本次支付",+ "cancelPlanChangeTitle": "撤销套餐变更?",+ "cancelPlanChangeDescription": "目标套餐:{{target}}。撤销后当前套餐保持不变。",+ "cancelPlanChange": "撤销套餐变更",+ "retryPaymentTitle": "重试本次支付?",+ "retryPaymentDescription": "{{amount}} 的支付将复用原幂等意图重试。",+ "retryUnknownPaymentDescription": "本次支付将复用原幂等意图重试。",+ "retryPayment": "重试本次支付"+ },"paymentActions": {"QR_CODE": "扫码支付","REDIRECT": "跳转支付页面"@@ -7095,6 +7125,7 @@"targetTitle": "更改订阅套餐","targetDescription": "套餐变更沿用当前支付方式,最终价格与生效时间以下一步确认为准。","targetDescriptionWithCurrent": "当前套餐:{{plan}}。变更沿用当前支付方式,最终价格与生效时间以下一步确认为准。",+ "serverDecisionHint": "价格与生效方式以下一步报价为准","upgradeBadge": "升级","downgradeBadge": "降级","emptyTitle": "暂无可切换的套餐",