Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(billing): 优化套餐对比、支付确认与余额展示 (#4651)
GaoWei Liue3cca481c115
diff --git a/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsx b/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsxindex 4406adca9b..995fb350f3 100644--- a/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsx+++ b/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsx@@ -128,15 +128,16 @@ export function BillingCheckoutDialog({<Dialog.Portal><Dialog.Overlay className="fixed inset-0 z-[10000] bg-[var(--overlay-modal)]" /><Dialog.Content+ onPointerDownOutside={(event) => event.preventDefault()}className={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-[10001] flex max-h-[calc(100dvh-40px)] w-[calc(100vw-40px)] max-w-[620px] flex-col','-translate-x-1/2 -translate-y-1/2 overflow-hidden rounded-xl','border border-[var(--border-default)] bg-[var(--surface-elevated)]','text-[var(--text-primary)] focus:outline-none',)}aria-describedby={undefined}>- <div className="flex items-start justify-between gap-4 border-b border-[var(--border-default)] px-6 py-5">+ <div className="flex shrink-0 items-start justify-between gap-4 border-b border-[var(--border-default)] px-6 py-5"><div><Dialog.Title className="text-lg font-medium">{title}</Dialog.Title><p className="mt-1 text-12 leading-5 text-[var(--text-secondary)]">@@ -158,119 +159,131 @@ export function BillingCheckoutDialog({)}</div>- <div className="flex min-h-[300px] flex-col items-center justify-center px-6 py-7 text-center">- {state.phase === 'CREATING' && (- <>- <Spinner icon={LoaderCircle} size={28} className="text-[var(--text-secondary)]" />- <p className="mt-4 text-sm text-[var(--text-secondary)]">- {t('billing.checkout.creatingBody')}- </p>- </>- )}+ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-7 text-center">+ <div className="flex min-h-[244px] flex-col items-center justify-center">+ {state.phase === 'CREATING' && (+ <>+ <Spinner icon={LoaderCircle} size={28} className="text-[var(--text-secondary)]" />+ <p className="mt-4 text-sm text-[var(--text-secondary)]">+ {t('billing.checkout.creatingBody')}+ </p>+ </>+ )}- {state.phase === 'AWAITING_PAYMENT' && actionExpired && (- <>- <div className="grid size-14 place-items-center rounded-full bg-[var(--surface-chip)]">- <CircleAlert size={23} />- </div>- <p className="mt-4 max-w-[320px] text-sm text-[var(--text-secondary)]">- {t('billing.checkout.actionExpiredBody')}- </p>- </>- )}+ {state.phase === 'AWAITING_PAYMENT' && actionExpired && (+ <>+ <div className="grid size-14 place-items-center rounded-full bg-[var(--surface-chip)]">+ <CircleAlert size={23} />+ </div>+ <p className="mt-4 max-w-[320px] text-sm text-[var(--text-secondary)]">+ {t('billing.checkout.actionExpiredBody')}+ </p>+ </>+ )}- {state.phase === 'AWAITING_PAYMENT' && !actionExpired && action?.type === 'QR_CODE' && (- <>- <div- className="relative grid place-items-center rounded-xl border border-[var(--border-default)] bg-white p-2"- style={{- width: 'min(280px, calc(100vw - 96px), calc(100vh - 260px))',- height: 'min(280px, calc(100vw - 96px), calc(100vh - 260px))',- }}- >- {qrDataUrl ? (- <>- <img src={qrDataUrl} className="size-full" alt={t('billing.checkout.qrAlt')} />- <span- aria-hidden="true"- className="pointer-events-none absolute grid size-10 place-items-center rounded-lg bg-white p-1"- >- <img src={cindyIconUrl} className="size-8 rounded-md" alt="" />- </span>- </>- ) : (- <Spinner size={24} className="text-[var(--text-secondary)]" />- )}- </div>- <p className="mt-4 text-sm font-medium">{t('billing.checkout.scanHint')}</p>- <p className="mt-1 text-12 text-[var(--text-tertiary)]">- {remainingSeconds === null- ? t('billing.checkout.checkingExpiry')- : t('billing.checkout.expiresIn', {- minutes: Math.floor(remainingSeconds / 60),- seconds: String(remainingSeconds % 60).padStart(2, '0'),- })}- </p>- </>- )}+ {state.phase === 'AWAITING_PAYMENT' &&+ !actionExpired &&+ action?.type === 'QR_CODE' && (+ <>+ <div+ className="relative grid place-items-center rounded-xl border border-[var(--border-default)] bg-white p-2"+ style={{+ width: 'min(280px, calc(100vw - 96px))',+ height: 'min(280px, calc(100vw - 96px))',+ }}+ >+ {qrDataUrl ? (+ <>+ <img+ src={qrDataUrl}+ className="size-full"+ alt={t('billing.checkout.qrAlt')}+ />+ <span+ aria-hidden="true"+ className="pointer-events-none absolute grid size-10 place-items-center rounded-lg bg-white p-1"+ >+ <img src={cindyIconUrl} className="size-8 rounded-md" alt="" />+ </span>+ </>+ ) : (+ <Spinner size={24} className="text-[var(--text-secondary)]" />+ )}+ </div>+ <p className="mt-4 text-sm font-medium">{t('billing.checkout.scanHint')}</p>+ <p className="mt-1 text-12 text-[var(--text-tertiary)]">+ {remainingSeconds === null+ ? t('billing.checkout.checkingExpiry')+ : t('billing.checkout.expiresIn', {+ minutes: Math.floor(remainingSeconds / 60),+ seconds: String(remainingSeconds % 60).padStart(2, '0'),+ })}+ </p>+ </>+ )}- {state.phase === 'AWAITING_PAYMENT' && !actionExpired && action?.type === 'REDIRECT' && (- <>- <div className="grid size-14 place-items-center rounded-full bg-[var(--surface-chip)]">- <ExternalLink size={22} />- </div>- <p className="mt-4 text-sm font-medium">{t('billing.checkout.redirectHint')}</p>- <button- type="button"- onClick={openRedirect}- className="mt-5 inline-flex h-9 items-center gap-2 rounded-full bg-[var(--text-primary)] px-5 text-sm font-medium text-[var(--surface)]"- >- <ExternalLink size={14} />- {t('billing.checkout.openPayment')}- </button>- </>- )}+ {state.phase === 'AWAITING_PAYMENT' &&+ !actionExpired &&+ action?.type === 'REDIRECT' && (+ <>+ <div className="grid size-14 place-items-center rounded-full bg-[var(--surface-chip)]">+ <ExternalLink size={22} />+ </div>+ <p className="mt-4 text-sm font-medium">{t('billing.checkout.redirectHint')}</p>+ <button+ type="button"+ onClick={openRedirect}+ className="mt-5 inline-flex h-9 items-center gap-2 rounded-full bg-[var(--text-primary)] px-5 text-sm font-medium text-[var(--surface)]"+ >+ <ExternalLink size={14} />+ {t('billing.checkout.openPayment')}+ </button>+ </>+ )}- {state.phase === 'AWAITING_PAYMENT' && !action && !actionExpired && (- <>- <Spinner size={26} className="text-[var(--text-secondary)]" />- <p className="mt-4 text-sm text-[var(--text-secondary)]">- {t('billing.checkout.refreshingAction')}- </p>- </>- )}+ {state.phase === 'AWAITING_PAYMENT' && !action && !actionExpired && (+ <>+ <Spinner size={26} className="text-[var(--text-secondary)]" />+ <p className="mt-4 text-sm text-[var(--text-secondary)]">+ {t('billing.checkout.refreshingAction')}+ </p>+ </>+ )}- {state.phase === 'COMPLETED' && (- <>- <div className="grid size-14 place-items-center rounded-full bg-[var(--text-primary)] text-[var(--surface)]">- <Check size={24} />- </div>- <p className="mt-4 text-sm font-medium">{t('billing.checkout.paymentCompleted')}</p>- </>- )}+ {state.phase === 'COMPLETED' && (+ <>+ <div className="grid size-14 place-items-center rounded-full bg-[var(--text-primary)] text-[var(--surface)]">+ <Check size={24} />+ </div>+ <p className="mt-4 text-sm font-medium">+ {t('billing.checkout.paymentCompleted')}+ </p>+ </>+ )}- {(state.phase === 'FAILED' ||- state.phase === 'EXPIRED' ||- state.phase === 'CANCELED') && (- <>- <div className="grid size-14 place-items-center rounded-full bg-[var(--surface-chip)]">- <CircleAlert size={23} />- </div>- <p className="mt-4 max-w-[320px] text-sm text-[var(--text-secondary)]">- {state.error- ? t('billing.checkout.requestFailed')- : state.phase === 'EXPIRED'- ? t('billing.checkout.expiredBody')- : state.phase === 'CANCELED'- ? t('billing.checkout.canceledBody')- : t('billing.checkout.failedBody')}- </p>- </>- )}+ {(state.phase === 'FAILED' ||+ state.phase === 'EXPIRED' ||+ state.phase === 'CANCELED') && (+ <>+ <div className="grid size-14 place-items-center rounded-full bg-[var(--surface-chip)]">+ <CircleAlert size={23} />+ </div>+ <p className="mt-4 max-w-[320px] text-sm text-[var(--text-secondary)]">+ {state.error+ ? t('billing.checkout.requestFailed')+ : state.phase === 'EXPIRED'+ ? t('billing.checkout.expiredBody')+ : state.phase === 'CANCELED'+ ? t('billing.checkout.canceledBody')+ : t('billing.checkout.failedBody')}+ </p>+ </>+ )}+ </div></div>- <div className="flex min-h-16 items-center justify-end gap-3 border-t border-[var(--border-default)] px-6 py-3">- <div className="flex items-center gap-2">+ <div className="flex min-h-16 shrink-0 flex-wrap items-center justify-end gap-3 border-t border-[var(--border-default)] px-6 py-3">+ <div className="flex flex-wrap items-center justify-end gap-2">{state.phase === 'AWAITING_PAYMENT' && (<buttontype="button"diff --git a/apps/desktop/src/renderer/features/billing/BillingPage.tsx b/apps/desktop/src/renderer/features/billing/BillingPage.tsxindex eebbdc76ec..fcadd0b7a4 100644--- a/apps/desktop/src/renderer/features/billing/BillingPage.tsx+++ b/apps/desktop/src/renderer/features/billing/BillingPage.tsx@@ -1,12 +1,10 @@-import { type RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import * as Dialog from '@radix-ui/react-dialog';import {- ArrowRight,Check,CircleDollarSign,ChevronDown,- ChevronRight,- ChevronUp,+ ChevronLeft,Copy,CreditCard,ExternalLink,@@ -18,6 +16,7 @@ import {import { useTranslation } from 'react-i18next';import { useSearchParams } from 'react-router-dom';+import { Button } from '@/components/ui/button';import { ConfirmDialog } from '@/components/ui/confirm-dialog';import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import {@@ -41,7 +40,6 @@ import {type BillingCatalogProduct,type BillingPaymentOrder,type BillingPendingPlanChange,- type BillingPurchaseOption,type BillingSubscription,} from '../../../shared/billing';import type {@@ -50,6 +48,7 @@ import type {ModelAccessCreditUsage,ModelAccessPromotionalGrantState,} from '../../../shared/modelAccess';+import { PlanComparison } from './PlanComparison';import { AlipayIcon } from './AlipayIcon';import { billingApi } from './api';import {@@ -167,13 +166,13 @@ function ledgerUnits(value: string): bigint | null {return match[1] === '-' ? -units : units;}-function usagePercent(pool: ModelAccessCreditPoolUsage): number | null {+function remainingPercent(pool: ModelAccessCreditPoolUsage): number | null {if (pool.used === null || pool.total === null) return null;- const used = ledgerUnits(pool.used);+ const remaining = ledgerUnits(pool.remaining);const total = ledgerUnits(pool.total);- if (used === null || total === null || used < 0n || total < 0n) return null;- if (total === 0n) return used === 0n ? 0 : null;- const tenths = (used * 1_000n) / total;+ if (remaining === null || total === null || remaining < 0n || total < 0n) return null;+ if (total === 0n) return remaining === 0n ? 0 : null;+ const tenths = (remaining * 1_000n) / total;return Number(tenths > 1_000n ? 1_000n : tenths) / 10;}@@ -243,9 +242,20 @@ function groupSubscriptionProducts(}}return Array.from(groups.values()).flatMap(({ product, offers }) => {+ const selectableOffers = offers.filter((entry) =>+ isSubscriptionOfferSelectable(entry, currentSubscriptionOfferCode),+ );const defaultOffer =- offers.find((entry) => isSubscriptionOfferSelectable(entry, currentSubscriptionOfferCode)) ??- offers[0];+ selectableOffers.reduce<CatalogOfferEntry | undefined>((lowest, entry) => {+ if (!lowest) return entry;+ const offer = entry.offer;+ return offer.currency === lowest.offer.currency &&+ offer.interval === lowest.offer.interval &&+ offer.amount !== null &&+ (lowest.offer.amount === null || Number(offer.amount) < Number(lowest.offer.amount))+ ? entry+ : lowest;+ }, undefined) ?? offers[0];return defaultOffer ? [{ product, offers, defaultOffer }] : [];});}@@ -677,6 +687,8 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null}, [billingLocale, customAmount, selected, t]);const canCheckout =+ !loadingCatalog &&+ !catalogError &&selected !== null &&isCatalogOfferPurchasable(selected) &&selectedOption !== null &&@@ -733,7 +745,10 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullcurrentPlan !== null &¤tSubscription !== null &&PLAN_CHANGE_ENTRY_STATUSES.includes(currentSubscription.status) &&- !currentSubscription.cancelAtPeriodEnd &&+ (!currentSubscription.cancelAtPeriodEnd ||+ (currentProvider === 'alipay' &&+ currentSubscription.currentPeriodEndAt !== null &&+ Date.parse(currentSubscription.currentPeriodEndAt) > Date.now())) &¤tPlan.offer.interval === 'MONTH';const currentPlanFacts = useMemo(() => {if (!currentSubscription) return null;@@ -889,25 +904,40 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullentry.offer.code !== currentPlan.offer.code &&entry.purchaseOptions.some((option) => option.provider === currentProvider),)- .map(({ product, offer }) => ({- product,- offer,+ .map((entry) => ({+ product: entry.product,+ offer: entry.offer,+ unavailableReason: catalogOfferUnavailableReason(entry),+ available:+ entry.product.level !== currentPlan.product.level &&+ (!currentSubscription?.cancelAtPeriodEnd ||+ (entry.product.level !== null && entry.product.level > currentPlan.product.level)),providers: [currentProvider],direction:- product.level === null+ entry.product.level === null? null- : product.level > currentPlan.product.level+ : entry.product.level > currentPlan.product.level? ('UPGRADE' as const)- : product.level < currentPlan.product.level+ : entry.product.level < currentPlan.product.level? ('DOWNGRADE' as const): ('SAME_LEVEL' as const),}));- }, [subscriptionOffers, showPlanChangeEntry, currentPlan, currentProvider]);+ }, [+ subscriptionOffers,+ showPlanChangeEntry,+ currentPlan,+ currentProvider,+ currentSubscription?.cancelAtPeriodEnd,+ ]);const openPurchaseDialog = useCallback((kind: PurchaseKind) => {resetSelection();if (kind === 'SUBSCRIPTION') {+ if (showPlanChangeEntry) {+ setPlanChangeTargetOpen(true);+ return;+ }const defaultProduct =subscriptionProducts.find((product) =>isSubscriptionOfferSelectable(product.defaultOffer, currentSubscriptionOfferCode),@@ -924,7 +954,13 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullsetTopupDialogOpen(true);}},- [currentSubscriptionOfferCode, resetSelection, selectSubscriptionOffer, subscriptionProducts],+ [+ currentSubscriptionOfferCode,+ resetSelection,+ selectSubscriptionOffer,+ subscriptionProducts,+ showPlanChangeEntry,+ ],);useEffect(() => {@@ -961,7 +997,7 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullconst entry = offers.find(({ offer }) => offer.code === offerCode);if (!entry) return;if (entry.product.kind === 'SUBSCRIPTION') {- if (entry.product.code !== selectedProductCode) return;+ setSelectedProductCode(entry.product.code);selectSubscriptionOffer(entry);return;}@@ -974,13 +1010,6 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullsetCustomAmount('');};- const selectSubscriptionProduct = (productCode: string) => {- const product = subscriptionProducts.find((entry) => entry.product.code === productCode);- if (!product) return;- setSelectedProductCode(productCode);- selectSubscriptionOffer(product.defaultOffer);- };-const submit = () => {if (!selected || !selectedOption || !canCheckout) return;setSubscriptionDialogOpen(false);@@ -1009,12 +1038,21 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null};const openPlanChange = () => {- // 服务端在新报价时自动撤销旧未完成变更;这里总是重新选择目标。+ // 已排期变更可替换;付款处理中仍由服务端保留原单并复核。setPlanChangeTargetOpen(true);};const selectPlanChangeTarget = (candidate: PlanChangeCandidate) => {- if (candidate.offer.interval === null) return;+ if (+ candidate.offer.interval === null ||+ candidate.available === false ||+ loadingCatalog ||+ catalogError ||+ loadingSubscription ||+ subscriptionError ||+ !showPlanChangeEntry+ )+ return;setPlanChangeTargetOpen(false);void planChange.startQuote(candidate.offer.code, {product: { code: candidate.product.code, level: candidate.product.level },@@ -1167,8 +1205,9 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nulloffers={subscriptionOffers}subscriptionProducts={subscriptionProducts}selectedProductCode={selectedProductCode}- loading={loadingCatalog}+ loading={loadingCatalog || loadingSubscription}catalogError={catalogError}+ subscriptionError={subscriptionError}selected={selected?.product.kind === 'SUBSCRIPTION' ? selected : null}selectedPurchaseOptionId={selectedPurchaseOptionId}customAmount={customAmount}@@ -1180,11 +1219,14 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullcanCheckout={canCheckout}onClose={closeSubscriptionDialog}onRetry={() => void loadBillingState()}- onSelectProduct={selectSubscriptionProduct}onSelectOffer={selectOffer}onSelectPurchaseOption={setSelectedPurchaseOptionId}onCustomAmountChange={setCustomAmount}onSubmit={submit}+ onTopup={() => {+ closeSubscriptionDialog();+ openPurchaseDialog('CREDIT_TOPUP');+ }}/><BillingOfferDialog@@ -1206,7 +1248,6 @@ export function BillingSettingsSection({ accountId }: { accountId: string | nullcanCheckout={canCheckout}onClose={closeTopupDialog}onRetry={() => void loadBillingState()}- onSelectProduct={() => undefined}onSelectOffer={selectOffer}onSelectPurchaseOption={setSelectedPurchaseOptionId}onCustomAmountChange={setCustomAmount}@@ -1223,7 +1264,22 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null<PlanChangeTargetDialogopen={planChangeTargetOpen}currentPlan={currentPlanCandidate}+ disabled={+ loadingCatalog ||+ catalogError ||+ loadingSubscription ||+ subscriptionError ||+ !showPlanChangeEntry ||+ cancelingSubscription ||+ resumingSubscription ||+ openingSubscriptionPortal+ }candidates={planChangeCandidates}+ topupDisabled={loadingCatalog || catalogError}+ onTopup={() => {+ setPlanChangeTargetOpen(false);+ openPurchaseDialog('CREDIT_TOPUP');+ }}onClose={() => setPlanChangeTargetOpen(false)}onSelect={selectPlanChangeTarget}/>@@ -1658,7 +1714,7 @@ function CreditPoolRow({}) {const { t, i18n } = useTranslation();const billingLocale = i18n.resolvedLanguage ?? i18n.language;- const percent = usagePercent(pool);+ const percent = remainingPercent(pool);const detail =pool.used !== null && pool.total !== null? t('billing.usage.poolDetail', {@@ -1669,33 +1725,29 @@ function CreditPoolRow({? t('billing.usage.noPlanCredits'): t('billing.usage.historyUnavailable');return (- <div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-2 px-5 py-3.5">- <div className="min-w-0">- <p className="truncate text-13 font-medium text-[var(--text-primary)]">{label}</p>- <p className="mt-1 text-11 leading-4 text-[var(--text-tertiary)]">{detail}</p>- </div>- <div className="flex shrink-0 items-center gap-3">- <div- className="h-1 w-40 overflow-hidden rounded-full bg-[var(--surface-chip)]"- role={percent === null ? undefined : 'progressbar'}- aria-label={t('billing.usage.progressLabel', { label })}- aria-valuemin={percent === null ? undefined : 0}- aria-valuemax={percent === null ? undefined : 100}- aria-valuenow={percent ?? undefined}- >- {percent !== null && (- <div- className="h-full rounded-full bg-[var(--text-primary)]"- style={{ width: `${percent}%` }}- />- )}- </div>- <p className="text-11 text-[var(--text-tertiary)]">- {t('billing.usage.remaining')}- <span className="ml-1.5 text-13 font-medium tabular-nums text-[var(--text-primary)]">- {formatMoney(pool.remaining, BILLING_CURRENCY, billingLocale)}- </span>- </p>+ <div className="grid grid-cols-[minmax(0,1fr)_minmax(160px,30%)] items-baseline gap-x-6 gap-y-1 px-5 py-3.5">+ <p className="min-w-0 text-13 font-medium text-[var(--text-primary)]">{label}</p>+ <p className="flex items-baseline justify-end gap-1.5 whitespace-nowrap text-11 text-[var(--text-tertiary)]">+ {t('billing.usage.remaining')}+ <span className="text-13 font-medium tabular-nums text-[var(--text-primary)]">+ {formatMoney(pool.remaining, BILLING_CURRENCY, billingLocale)}+ </span>+ </p>+ <p className="min-w-0 text-11 leading-4 text-[var(--text-tertiary)]">{detail}</p>+ <div+ className="h-1 w-full self-center overflow-hidden rounded-full bg-[var(--surface-chip)]"+ role={percent === null ? undefined : 'progressbar'}+ aria-label={t('billing.usage.progressLabel', { label })}+ aria-valuemin={percent === null ? undefined : 0}+ aria-valuemax={percent === null ? undefined : 100}+ aria-valuenow={percent ?? undefined}+ >+ {percent !== null && (+ <div+ className="ml-auto h-full rounded-full bg-[var(--text-primary)]"+ style={{ width: `${percent}%` }}+ />+ )}</div></div>);@@ -1858,11 +1910,10 @@ function OrderHistoryCard({: '—'}</p>)}- <div className="flex min-w-0 justify-end">+ <div className="flex flex-wrap items-center justify-end gap-x-3 gap-y-2"><spanclassName={cn(- 'shrink-0 whitespace-nowrap rounded-full bg-[var(--surface-chip)] px-2.5 py-1',- 'text-10 font-medium leading-[1.2]',+ 'shrink-0 whitespace-nowrap text-11',isAwaitingPaymentOrder(order)? 'text-[var(--text-primary)]': 'text-[var(--text-secondary)]',@@ -1871,13 +1922,13 @@ function OrderHistoryCard({{t(orderStatusLabelKey(order))}</span>{phaseForOrder(order) === 'COMPLETED' && (- <button- type="button"+ <Button+ variant="secondary"onClick={() => setInvoiceOrder(order)}- className="h-7 shrink-0 select-none rounded-full border border-[var(--border-default)] px-2.5 text-10 font-medium text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ className="whitespace-nowrap px-3">{t('billing.orders.invoice.action')}- </button>+ </Button>)}</div></div>@@ -2107,11 +2158,12 @@ function BillingOfferDialog({canCheckout,onClose,onRetry,- onSelectProduct,onSelectOffer,onSelectPurchaseOption,onCustomAmountChange,onSubmit,+ onTopup,+ subscriptionError = false,}: {open: boolean;kind: PurchaseKind;@@ -2131,11 +2183,12 @@ function BillingOfferDialog({canCheckout: boolean;onClose: () => void;onRetry: () => void;- onSelectProduct: (productCode: string) => void;onSelectOffer: (offerCode: string) => void;onSelectPurchaseOption: (optionId: string) => void;onCustomAmountChange: (amount: string) => void;onSubmit: () => void;+ onTopup?: () => void;+ subscriptionError?: boolean;}) {const { t, i18n } = useTranslation();const billingLocale = i18n.resolvedLanguage ?? i18n.language;@@ -2161,18 +2214,38 @@ function BillingOfferDialog({selected !== null &&isCatalogOfferPurchasable(selected) &&!(kind === 'SUBSCRIPTION' && selected.offer.code === currentSubscriptionOfferCode);+ const [choosingChannel, setChoosingChannel] = useState(false);+ useEffect(() => {+ if (!open) setChoosingChannel(false);+ }, [open]);+ const comparingPlans =+ kind === 'SUBSCRIPTION' && (!choosingChannel || !selected || subscriptionPurchaseBlocked);+ const selectedProductOffers =+ subscriptionProducts.find(({ product }) => product.code === selected?.product.code)?.offers ??+ [];const primaryFocusRef = useRef<HTMLButtonElement>(null);const closeButtonRef = useRef<HTMLButtonElement>(null);+ useEffect(() => {+ if (choosingChannel && (!selected || !isCatalogOfferPurchasable(selected)))+ setChoosingChannel(false);+ }, [choosingChannel, selected]);+ useEffect(() => {+ if (open && !loading && !catalogError && !subscriptionError) {+ (primaryFocusRef.current ?? closeButtonRef.current)?.focus();+ }+ }, [choosingChannel, open, loading, catalogError, subscriptionError]);return (<Dialog.Root open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}><Dialog.Portal><Dialog.Overlay className="fixed inset-0 z-[9990] bg-[var(--overlay-modal)]" /><Dialog.Content+ onPointerDownOutside={(event) => event.preventDefault()}aria-describedby={undefined}className={cn('fixed left-1/2 top-1/2 z-[9991] flex max-h-[min(720px,calc(100vh-48px))]',- 'w-[calc(100vw-48px)] max-w-[680px] -translate-x-1/2 -translate-y-1/2 flex-col',+ 'w-[calc(100vw-48px)] -translate-x-1/2 -translate-y-1/2 flex-col',+ comparingPlans ? 'max-w-[1120px]' : 'max-w-[600px]','overflow-hidden rounded-xl border border-[var(--border-default)]','bg-[var(--surface-elevated)] text-[var(--text-primary)] focus:outline-none',)}@@ -2181,10 +2254,29 @@ function BillingOfferDialog({(primaryFocusRef.current ?? closeButtonRef.current)?.focus();}}>- <div className="flex items-center justify-between gap-4 px-6 pb-4 pt-5">- <Dialog.Title className="truncate text-16 font-medium tracking-[-0.01em]">- {title}- </Dialog.Title>+ <div+ className={cn(+ 'flex items-center justify-between gap-4 py-4',+ comparingPlans ? 'px-6' : 'px-4',+ )}+ >+ <div className="flex min-w-0 items-center gap-2">+ {kind === 'SUBSCRIPTION' && !comparingPlans && (+ <button+ type="button"+ aria-label={t('billing.planChange.back')}+ onClick={() => setChoosingChannel(false)}+ className="grid size-8 shrink-0 place-items-center rounded-full text-[var(--text-secondary)] hover:bg-[var(--surface-hover-soft)] active:bg-[var(--surface-chip)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ >+ <ChevronLeft size={16} aria-hidden />+ </button>+ )}+ <Dialog.Title className="text-16 font-medium">+ {kind === 'SUBSCRIPTION' && !comparingPlans+ ? t('billing.dialogs.subscription.confirmTitle')+ : title}+ </Dialog.Title>+ </div><Dialog.Close asChild><buttonref={closeButtonRef}@@ -2197,14 +2289,23 @@ function BillingOfferDialog({</Dialog.Close></div>- <div className="min-h-0 flex-1 overflow-y-auto border-t border-[var(--border-default)] px-6 py-4 [scrollbar-gutter:stable]">+ <div+ className={cn(+ 'min-h-0 flex-1 overflow-y-auto border-t border-[var(--border-default)] py-4 [scrollbar-gutter:stable]',+ comparingPlans ? 'px-6' : 'px-4',+ )}+ >{loading ? (<CatalogSkeleton />- ) : catalogError ? (+ ) : catalogError || subscriptionError ? (<StateCardicon={<RefreshCcw size={22} />}- title={t('billing.catalog.errorTitle')}- description={t('billing.catalog.errorDescription')}+ title={t(+ subscriptionError+ ? 'billing.settings.subscriptionCard.unavailable'+ : 'billing.catalog.errorTitle',+ )}+ description={subscriptionError ? undefined : t('billing.catalog.errorDescription')}action={<buttonref={primaryFocusRef}@@ -2220,18 +2321,84 @@ function BillingOfferDialog({<StateCard icon={<PackageOpen size={22} />} title={t('billing.catalog.emptyTitle')} />) : (<>- {kind === 'SUBSCRIPTION' && (- <SubscriptionProductAccordion- products={subscriptionProducts}- selectedProductCode={selectedProductCode}- selectedOfferCode={selected?.offer.code ?? null}- currentSubscriptionOfferCode={currentSubscriptionOfferCode}- billingLocale={billingLocale}- initialFocusRef={primaryFocusRef}- onSelectProduct={onSelectProduct}- onSelectOffer={onSelectOffer}+ {comparingPlans && (+ <PlanComparison+ plans={subscriptionProducts.map(+ ({ product, offers: productOffers, defaultOffer }) => ({+ product,+ purchasableOffers: productOffers+ .filter(isCatalogOfferPurchasable)+ .map((entry) => entry.offer),+ defaultOfferCode: defaultOffer.offer.code,+ offers: productOffers.map((entry) => {+ const unavailable = catalogOfferUnavailableReason(entry);+ const current = entry.offer.code === currentSubscriptionOfferCode;+ return {+ offer: entry.offer,+ current,+ actionRef:+ product.code === selectedProductCode &&+ !current &&+ unavailable === null &&+ !subscriptionPurchaseBlocked+ ? primaryFocusRef+ : undefined,+ disabled: unavailable !== null || subscriptionPurchaseBlocked,+ action: current+ ? t('billing.catalog.currentPlan')+ : unavailable+ ? t(`billing.catalog.unavailableReasons.${unavailable}`)+ : t('billing.comparison.select', { name: product.name }),+ onSelect: () => {+ if (unavailable !== null || subscriptionPurchaseBlocked || current)+ return;+ onSelectOffer(entry.offer.code);+ setChoosingChannel(true);+ },+ };+ }),+ }),+ )}+ freeAction={t('billing.comparison.topup')}+ freeHint={t('billing.comparison.topupUnlock')}+ onFreeAction={() => onTopup?.()}/>)}+ {kind === 'SUBSCRIPTION' && !comparingPlans && selected && (+ <div className="space-y-1" aria-live="polite">+ <p className="break-words text-14 font-medium">{selected.product.name}</p>+ {selected.offer.creditAmount !== null && (+ <p className="text-13">+ {t(+ selected.offer.interval+ ? `billing.comparison.credits.${selected.offer.interval}`+ : 'billing.credits',+ {+ amount: formatMoney(+ selected.offer.creditAmount,+ selected.offer.currency,+ billingLocale,+ ),+ },+ )}+ </p>+ )}+ {selected.offer.rolloverCap !== null && (+ <p className="text-12 text-[var(--text-secondary)]">+ {t('billing.comparison.rollover', {+ amount: formatMoney(+ selected.offer.rolloverCap,+ selected.offer.currency,+ billingLocale,+ ),+ period: t(+ `billing.comparison.nextPeriod.${selected.offer.interval ?? 'OTHER'}`,+ ),+ })}+ </p>+ )}+ </div>+ )}<div className={kind === 'SUBSCRIPTION' ? 'mt-4' : undefined}>{kind !== 'SUBSCRIPTION' && (@@ -2262,7 +2429,7 @@ function BillingOfferDialog({? 'bg-[var(--surface-elevated)] opacity-55': active? 'bg-[var(--surface-hover-soft)]'- : 'bg-[var(--surface-elevated)] hover:bg-[var(--surface-hover-soft)]',+ : 'bg-[var(--surface-elevated)] enabled:hover:bg-[var(--surface-hover-soft)]',)}><div className="min-w-0 flex-1">@@ -2329,20 +2496,76 @@ function BillingOfferDialog({</div>)}- {selectedOfferCanChooseChannel && (+ {selectedOfferCanChooseChannel && !comparingPlans && (<div className="mt-5"><h3 className="text-13 font-medium text-[var(--text-primary)]">{t('billing.steps.channel.title')}</h3><div className="mt-3 divide-y divide-[var(--border-default)] overflow-hidden rounded-xl border border-[var(--border-default)]">- {selected!.purchaseOptions.map((option) => (- <PaymentOptionRow- key={option.id}- option={option}- active={selectedPurchaseOptionId === option.id}- onSelect={() => onSelectPurchaseOption(option.id)}- />- ))}+ {kind === 'SUBSCRIPTION'+ ? selectedProductOffers.map((entry) => {+ const unavailable = catalogOfferUnavailableReason(entry);+ const current = entry.offer.code === currentSubscriptionOfferCode;+ const disabled = unavailable !== null || current;+ const detail = current+ ? t('billing.catalog.currentPlan')+ : unavailable+ ? t(`billing.catalog.unavailableReasons.${unavailable}`)+ : entry.offer.name?.trim();+ const price =+ entry.offer.amount !== null+ ? formatMoney(+ entry.offer.amount,+ entry.offer.currency,+ billingLocale,+ )+ : '—';+ const period = entry.offer.interval+ ? ` / ${t(`billing.intervals.${entry.offer.interval}`)}`+ : '';+ if (entry.purchaseOptions.length === 0) {+ return (+ <div+ key={entry.offer.code}+ className="flex items-center justify-between gap-3 px-4 py-3 text-12 text-[var(--text-secondary)]"+ >+ <span>+ {entry.offer.name?.trim() || entry.product.name} · {detail}+ </span>+ <span className="shrink-0 tabular-nums">+ {price}+ {period}+ </span>+ </div>+ );+ }+ return entry.purchaseOptions.map((option) => (+ <PaymentOptionRow+ key={`${entry.offer.code}:${option.id}`}+ option={option}+ price={`${price}${period}`}+ detail={detail}+ disabled={disabled}+ active={+ selected?.offer.code === entry.offer.code &&+ selectedPurchaseOptionId === option.id+ }+ onSelect={() => {+ if (disabled) return;+ onSelectOffer(entry.offer.code);+ onSelectPurchaseOption(option.id);+ }}+ />+ ));+ })+ : selected!.purchaseOptions.map((option) => (+ <PaymentOptionRow+ key={option.id}+ option={option}+ active={selectedPurchaseOptionId === option.id}+ onSelect={() => onSelectPurchaseOption(option.id)}+ />+ ))}</div>{kind === 'CREDIT_TOPUP' && isCustomTopup(selected!.offer) && (@@ -2403,276 +2626,30 @@ function BillingOfferDialog({)}</div>- <div className="flex min-h-16 items-center justify-end gap-4 border-t border-[var(--border-default)] px-6 py-3">- <button- type="button"- onClick={onSubmit}- disabled={!canCheckout}- className="inline-flex h-9 shrink-0 items-center gap-2 rounded-full bg-[var(--accent-cta-bg)] px-5 text-13 font-medium text-[var(--accent-pure-cta-fg)] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface-elevated)] active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-35 disabled:active:scale-100"- >- {t('billing.actions.pay')}- <ArrowRight size={15} />- </button>- </div>- </Dialog.Content>- </Dialog.Portal>- </Dialog.Root>- );-}--function SubscriptionProductAccordion({- products,- selectedProductCode,- selectedOfferCode,- currentSubscriptionOfferCode,- billingLocale,- initialFocusRef,- onSelectProduct,- onSelectOffer,-}: {- products: SubscriptionProductEntry[];- selectedProductCode: string | null;- selectedOfferCode: string | null;- currentSubscriptionOfferCode: string | null;- billingLocale: string;- initialFocusRef: RefObject<HTMLButtonElement | null>;- onSelectProduct: (productCode: string) => void;- onSelectOffer: (offerCode: string) => void;-}) {- const { t } = useTranslation();-- return (- <div className="overflow-hidden rounded-xl border border-[var(--border-default)]">- {products.map((productEntry, productIndex) => {- const productActive = productEntry.product.code === selectedProductCode;- const offerRegionId = `billing-product-${productEntry.product.code}-offers`;- const singleOfferEntry = productEntry.offers.length === 1 ? productEntry.offers[0] : null;- const singleOfferCurrentPlan =- singleOfferEntry?.offer.code === currentSubscriptionOfferCode;- const singleOfferUnavailableReason = singleOfferEntry- ? catalogOfferUnavailableReason(singleOfferEntry)- : null;- const priceOffer = productEntry.defaultOffer.offer;- const price = priceOffer.amount- ? formatMoney(priceOffer.amount, priceOffer.currency, billingLocale)- : t('billing.amount.custom');- const interval = priceOffer.interval ? t(`billing.intervals.${priceOffer.interval}`) : null;- return (- <section- key={productEntry.product.code}- className={cn(productIndex > 0 && 'border-t border-[var(--border-default)]')}- >- {singleOfferEntry ? (- <button- ref={- productActive && !singleOfferCurrentPlan && singleOfferUnavailableReason === null- ? initialFocusRef- : undefined- }- type="button"- onClick={() => onSelectProduct(productEntry.product.code)}- disabled={singleOfferCurrentPlan || singleOfferUnavailableReason !== null}- aria-pressed={productActive}- aria-current={singleOfferCurrentPlan ? 'true' : undefined}- className={cn(- 'flex min-h-[72px] w-full items-center justify-between gap-5 px-4 py-3 text-left transition-colors',- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset',- 'focus-visible:ring-[var(--focus-ring)] disabled:cursor-not-allowed',- singleOfferCurrentPlan- ? 'bg-[var(--surface-chip)]'- : singleOfferUnavailableReason !== null- ? 'bg-[var(--surface-elevated)] opacity-55'- : productActive- ? 'bg-[var(--surface-hover-soft)]'- : 'bg-[var(--surface-elevated)] hover:bg-[var(--surface-hover-soft)]',- )}+ {!comparingPlans && (+ <div className="flex justify-end border-t border-[var(--border-default)] p-4">+ <Button+ variant="cta"+ size="lg"+ ref={primaryFocusRef}+ onClick={onSubmit}+ disabled={loading || catalogError || subscriptionError || !canCheckout}+ className="max-w-full gap-1.5">- <div className="flex min-w-0 items-center gap-2">- <span className="truncate text-13 font-medium text-[var(--text-primary)]">- {productEntry.product.name}- </span>- {(singleOfferCurrentPlan || singleOfferUnavailableReason !== null) && (- <span className="shrink-0 rounded-full bg-[var(--surface-elevated)] px-2 py-0.5 text-10 font-medium text-[var(--text-secondary)]">- {singleOfferCurrentPlan- ? t('billing.catalog.currentPlan')- : t(`billing.catalog.unavailableReasons.${singleOfferUnavailableReason}`)}+ <span>{t('billing.actions.pay')}</span>+ {kind === 'SUBSCRIPTION' &&+ selected?.offer.amount !== null &&+ selected?.offer.amount !== undefined && (+ <span className="tabular-nums">+ {formatMoney(selected.offer.amount, selected.offer.currency, billingLocale)}</span>)}- </div>- <div className="flex shrink-0 items-center gap-3">- <div className="flex flex-col items-end gap-0.5">- <p className="text-12 font-medium tabular-nums text-[var(--text-primary)]">- {price}- {interval && (- <span className="ml-1 text-11 font-normal text-[var(--text-tertiary)]">- / {interval}- </span>- )}- </p>- {priceOffer.creditAmount && (- <p className="text-12 text-[var(--text-secondary)]">- {t('billing.credits', {- amount: formatMoney(- priceOffer.creditAmount,- priceOffer.currency,- billingLocale,- ),- })}- </p>- )}- </div>- {!singleOfferCurrentPlan && singleOfferUnavailableReason === null ? (- <SelectionMark active={productActive} />- ) : (- <span className="size-5 shrink-0" aria-hidden />- )}- </div>- </button>- ) : (- <button- type="button"- onClick={() => onSelectProduct(productEntry.product.code)}- aria-pressed={productActive}- aria-expanded={productActive}- aria-controls={offerRegionId}- className={cn(- 'flex min-h-[52px] w-full items-center justify-between gap-3 px-4 text-left transition-colors',- 'bg-[var(--surface-elevated)] hover:bg-[var(--surface-hover-soft)]',- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset',- 'focus-visible:ring-[var(--focus-ring)]',- )}- >- <div className="flex min-w-0 items-center gap-2">- {productActive ? (- <ChevronUp size={16} className="shrink-0 text-[var(--text-secondary)]" />- ) : (- <ChevronRight size={16} className="shrink-0 text-[var(--text-tertiary)]" />- )}- <span className="min-w-0 truncate text-13 font-medium text-[var(--text-primary)]">- {productEntry.product.name}- </span>- </div>- {!productActive && (- <div className="flex flex-col items-end gap-0.5">- <p className="text-right text-12 font-medium tabular-nums text-[var(--text-primary)]">- {price}- {interval && (- <span className="ml-1 text-11 font-normal text-[var(--text-tertiary)]">- / {interval}- </span>- )}- </p>- {priceOffer.creditAmount && (- <p className="text-12 text-[var(--text-secondary)]">- {t('billing.credits', {- amount: formatMoney(- priceOffer.creditAmount,- priceOffer.currency,- billingLocale,- ),- })}- </p>- )}- </div>- )}- </button>- )}-- {!singleOfferEntry && productActive && (- <div- id={offerRegionId}- className="divide-y divide-[var(--border-default)] border-t border-[var(--border-default)]"- >- {productEntry.offers.map((entry) => {- const { offer } = entry;- const offerName = offer.name?.trim();- const unavailableReason = catalogOfferUnavailableReason(entry);- const currentPlan = offer.code === currentSubscriptionOfferCode;- const unavailable = unavailableReason !== null;- const offerActive = offer.code === selectedOfferCode;- return (- <button- key={offer.code}- ref={- offerActive && !currentPlan && !unavailable ? initialFocusRef : undefined- }- type="button"- onClick={() => onSelectOffer(offer.code)}- disabled={currentPlan || unavailable}- aria-pressed={offerActive}- aria-current={currentPlan ? 'true' : undefined}- className={cn(- 'flex min-h-[72px] w-full items-center justify-between gap-5 py-3 pl-10 pr-4 text-left transition-colors',- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset',- 'focus-visible:ring-[var(--focus-ring)]',- 'disabled:cursor-not-allowed disabled:hover:bg-transparent',- currentPlan- ? 'bg-[var(--surface-chip)]'- : unavailable- ? 'bg-[var(--surface-elevated)] opacity-55'- : offerActive- ? 'bg-[var(--surface-hover-soft)]'- : 'bg-[var(--surface-elevated)] hover:bg-[var(--surface-hover-soft)]',- )}- >- <div className="flex min-w-0 items-center">- <div className="min-w-0">- <div className="flex min-w-0 items-center gap-2">- {offerName && (- <p className="truncate text-13 font-medium text-[var(--text-primary)]">- {offerName}- </p>- )}- {(currentPlan || unavailable) && (- <span className="shrink-0 rounded-full bg-[var(--surface-elevated)] px-2 py-0.5 text-10 font-medium text-[var(--text-secondary)]">- {currentPlan- ? t('billing.catalog.currentPlan')- : t(`billing.catalog.unavailableReasons.${unavailableReason}`)}- </span>- )}- </div>- </div>- </div>-- <div className="flex shrink-0 items-center gap-3">- <div className="flex flex-col items-end gap-0.5">- <p className="text-12 font-medium tabular-nums text-[var(--text-primary)]">- {offer.amount- ? formatMoney(offer.amount, offer.currency, billingLocale)- : t('billing.amount.custom')}- {offer.interval && (- <span className="ml-1 text-11 font-normal text-[var(--text-tertiary)]">- / {t(`billing.intervals.${offer.interval}`)}- </span>- )}- </p>- <p className="text-12 text-[var(--text-secondary)]">- {offer.creditAmount- ? t('billing.credits', {- amount: formatMoney(- offer.creditAmount,- offer.currency,- billingLocale,- ),- })- : null}- </p>- </div>- {!currentPlan && !unavailable ? (- <SelectionMark active={offerActive} />- ) : (- <span className="size-5 shrink-0" aria-hidden />- )}- </div>- </button>- );- })}- </div>- )}- </section>- );- })}- </div>+ </Button>+ </div>+ )}+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog.Root>);}@@ -2719,10 +2696,16 @@ function PaymentOptionRow({option,active,onSelect,+ price,+ detail,+ disabled = false,}: {option: SupportedPurchaseOption;active: boolean;onSelect: () => void;+ price?: string;+ detail?: string;+ disabled?: boolean;}) {const { t } = useTranslation();const Icon = option.paymentAction === 'QR_CODE' ? CircleDollarSign : CreditCard;@@ -2730,14 +2713,15 @@ function PaymentOptionRow({<buttontype="button"onClick={onSelect}+ disabled={disabled}aria-pressed={active}className={cn(- 'flex w-full items-center gap-3 px-4 py-3 text-left transition-colors',+ 'flex w-full items-center gap-3 px-4 py-3 text-left transition-colors disabled:opacity-60 disabled:cursor-not-allowed enabled:active:bg-[var(--surface-chip)]','focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset','focus-visible:ring-[var(--focus-ring)]',active? 'bg-[var(--surface-hover-soft)]'- : 'bg-[var(--surface-elevated)] hover:bg-[var(--surface-hover-soft)]',+ : 'bg-[var(--surface-elevated)] enabled:hover:bg-[var(--surface-hover-soft)]',)}>{option.provider === 'alipay' ? (@@ -2745,16 +2729,22 @@ function PaymentOptionRow({) : (<Icon size={16} className="shrink-0 text-[var(--text-secondary)]" />)}- <div className="flex min-w-0 flex-1 items-baseline gap-2">- <p className="truncate text-13 font-medium text-[var(--text-primary)]">- {providerLabel(option.provider, t)}- </p>- <p className="truncate text-11 text-[var(--text-tertiary)]">- {option.paymentAction === 'QR_CODE'- ? t('billing.paymentActions.QR_CODE')- : t('billing.paymentActions.REDIRECT')}- </p>+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">+ <p className="break-words text-13 font-medium text-[var(--text-primary)]">+ {providerLabel(option.provider, t)}+ </p>+ <p className="text-12 text-[var(--text-secondary)]">+ {option.paymentAction === 'QR_CODE'+ ? t('billing.paymentActions.QR_CODE')+ : t('billing.paymentActions.REDIRECT')}+ </p>+ </div>+ {detail && (+ <p className="mt-1 break-words text-12 text-[var(--text-secondary)]">{detail}</p>+ )}</div>+ {price && <span className="shrink-0 text-13 font-medium tabular-nums">{price}</span>}<SelectionMark active={active} /></button>);diff --git a/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx b/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsxindex 2d00d54817..8948028651 100644--- a/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx+++ b/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx@@ -2,15 +2,12 @@ import { useEffect, useMemo, useRef, useState } from 'react';import * as Dialog from '@radix-ui/react-dialog';import * as QRCode from 'qrcode';import {- ArrowLeft,- ArrowDownRight,- ArrowRight,- ArrowUpRight,Check,+ ChevronLeft,+ ChevronRight,CircleAlert,ExternalLink,LoaderCircle,- PackageOpen,RotateCcw,X,} from 'lucide-react';@@ -22,11 +19,13 @@ import { cn } from '@/lib/utils';import type {BillingCatalogOffer,BillingCatalogProduct,+ BillingCatalogOfferUnavailableReason,BillingPaymentAction,} from '../../../shared/billing';+import { PlanComparison, type ComparisonPlan } from './PlanComparison';import { billingApi } from './api';import {- formatBillingAmount as formatMoney,+ formatBillingAmount,formatBillingMinorAmount as formatPlanChangeMinorAmount,} from './money';import type { PlanChangeState } from './usePlanChange';@@ -35,6 +34,8 @@ export type PlanChangeCandidate = {product: BillingCatalogProduct;offer: BillingCatalogOffer;providers: Array<'alipay' | 'stripe'>;+ available?: boolean;+ unavailableReason?: BillingCatalogOfferUnavailableReason | null;/*** UI hint only; the server quote is authoritative. Null means the product* level is missing, so the client hides the direction instead of guessing.@@ -42,35 +43,6 @@ export type PlanChangeCandidate = {direction: 'UPGRADE' | 'SAME_LEVEL' | 'DOWNGRADE' | null;};-type PlanChangeProductGroup = {- product: BillingCatalogProduct;- candidates: PlanChangeCandidate[];- defaultCandidate: PlanChangeCandidate;-};--function groupPlanChangeCandidates(candidates: PlanChangeCandidate[]): PlanChangeProductGroup[] {- const groups = new Map<- string,- { product: BillingCatalogProduct; candidates: PlanChangeCandidate[] }- >();- for (const candidate of candidates) {- const group = groups.get(candidate.product.code);- if (group) {- group.candidates.push(candidate);- } else {- groups.set(candidate.product.code, {- product: candidate.product,- candidates: [candidate],- });- }- }- return Array.from(groups.values()).map(({ product, candidates }) => ({- product,- candidates,- defaultCandidate: candidates[0],- }));-}-function formatEffectiveDate(iso: string, locale: string): string {const timestamp = Date.parse(iso);if (!Number.isFinite(timestamp)) return iso;@@ -90,288 +62,258 @@ export function PlanChangeTargetDialog({candidates,onClose,onSelect,+ onTopup,+ topupDisabled = false,+ disabled = false,}: {open: boolean;currentPlan: PlanChangeCandidate | null;candidates: PlanChangeCandidate[];onClose: () => void;onSelect: (candidate: PlanChangeCandidate) => void;+ onTopup?: () => void;+ topupDisabled?: boolean;+ disabled?: boolean;}) {const { t, i18n } = useTranslation();- const billingLocale = i18n.resolvedLanguage ?? i18n.language;- const groups = useMemo(() => groupPlanChangeCandidates(candidates), [candidates]);+ const locale = i18n.resolvedLanguage ?? i18n.language;const [selectedProductCode, setSelectedProductCode] = useState<string | null>(null);- const [selectedOfferCode, setSelectedOfferCode] = useState<string | null>(null);- const selectedGroup = groups.find((group) => group.product.code === selectedProductCode) ?? null;- const selectedCandidate =- selectedGroup?.candidates.find((candidate) => candidate.offer.code === selectedOfferCode) ??- selectedGroup?.defaultCandidate ??- null;-+ const selectedCandidates = candidates.filter(+ (candidate) => candidate.product.code === selectedProductCode,+ );useEffect(() => {- if (!open) {+ if (!open || (selectedProductCode && selectedCandidates.length === 0))setSelectedProductCode(null);- setSelectedOfferCode(null);- return;- }- if (!selectedProductCode) return;- if (!selectedGroup) {- setSelectedProductCode(null);- setSelectedOfferCode(null);- return;- }- if (!selectedGroup.candidates.some((candidate) => candidate.offer.code === selectedOfferCode)) {- setSelectedOfferCode(selectedGroup.defaultCandidate.offer.code);- }- }, [open, selectedGroup, selectedOfferCode, selectedProductCode]);-- const selectProduct = (productCode: string) => {- const group = groups.find((candidate) => candidate.product.code === productCode);- if (!group) return;- setSelectedProductCode(productCode);- setSelectedOfferCode(group.defaultCandidate.offer.code);- };-- const backToProducts = () => {- setSelectedProductCode(null);- setSelectedOfferCode(null);- };-- const renderAmount = (candidate: PlanChangeCandidate) => (- <div className="shrink-0 text-right">- <p className="text-12 font-medium tabular-nums text-[var(--text-primary)]">- {candidate.offer.amount- ? formatMoney(candidate.offer.amount, candidate.offer.currency, billingLocale)- : '—'}- {candidate.offer.interval && (- <span className="ml-1 text-11 font-normal text-[var(--text-tertiary)]">- / {t(`billing.intervals.${candidate.offer.interval}`)}- </span>- )}- </p>- {candidate.offer.creditAmount && (- <p className="mt-0.5 text-11 text-[var(--text-tertiary)]">- {t('billing.credits', {- amount: formatMoney(- candidate.offer.creditAmount,- candidate.offer.currency,- billingLocale,- ),- })}- </p>- )}- </div>- );-+ }, [open, selectedProductCode, selectedCandidates.length]);+ const choosingOffer = selectedProductCode !== null && selectedCandidates.length > 0;+ const offerListRef = useRef<HTMLDivElement>(null);+ useEffect(() => {+ if (open && choosingOffer)+ offerListRef.current?.querySelector<HTMLButtonElement>('button:not(:disabled)')?.focus();+ }, [open, choosingOffer]);+ const plans = new Map<string, ComparisonPlan>();+ for (const candidate of currentPlan ? [currentPlan, ...candidates] : candidates) {+ const current = candidate.offer.code === currentPlan?.offer.code;+ const action = current+ ? t('billing.catalog.currentPlan')+ : candidate.available === false+ ? candidate.unavailableReason+ ? t(`billing.catalog.unavailableReasons.${candidate.unavailableReason}`)+ : t('billing.comparison.changeUnavailable')+ : t(+ candidate.direction === 'UPGRADE'+ ? 'billing.comparison.upgrade'+ : candidate.direction === 'DOWNGRADE'+ ? 'billing.comparison.downgrade'+ : 'billing.comparison.select',+ { name: candidate.product.name },+ );+ const entry = {+ offer: candidate.offer,+ current,+ action,+ disabled: disabled || candidate.available === false,+ onSelect: () => {+ if (disabled || current || candidate.available === false) return;+ if (+ candidates.filter(+ (option) =>+ option.product.code === candidate.product.code && option.available !== false,+ ).length > 1+ ) {+ setSelectedProductCode(candidate.product.code);+ } else onSelect(candidate);+ },+ };+ const group = plans.get(candidate.product.code);+ if (group) {+ group.offers.push(entry);+ } else+ plans.set(candidate.product.code, {+ product: candidate.product,+ offers: [entry],+ defaultOfferCode: candidate.offer.code,+ });+ }+ const sortedPlans = [...plans.values()]+ .map((plan) => {+ // The current contract keeps its own price. Targets use only offers that+ // this subscription can switch to, regardless of transient refresh state.+ const available = candidates.filter(+ (candidate) =>+ candidate.product.code === plan.product.code && candidate.available !== false,+ );+ if (plan.offers.some((entry) => entry.current)) {+ return available.length === 0+ ? plan+ : {+ ...plan,+ action: {+ action: t('billing.settings.subscriptionCard.changeAction'),+ disabled,+ onSelect: () => {+ if (!disabled) setSelectedProductCode(plan.product.code);+ },+ },+ };+ }+ const defaultCandidate = available.reduce<PlanChangeCandidate | undefined>(+ (lowest, candidate) => {+ if (!lowest) return candidate;+ const offer = candidate.offer;+ return offer.currency === lowest.offer.currency &&+ offer.interval === lowest.offer.interval &&+ offer.amount !== null &&+ (lowest.offer.amount === null || Number(offer.amount) < Number(lowest.offer.amount))+ ? candidate+ : lowest;+ },+ undefined,+ );+ return {+ ...plan,+ defaultOfferCode: defaultCandidate?.offer.code ?? plan.defaultOfferCode,+ purchasableOffers: available.map((candidate) => candidate.offer),+ };+ })+ .sort((a, b) => a.product.sortOrder - b.product.sortOrder);return (<Dialog.Root open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}><Dialog.Portal><Dialog.Overlay className="fixed inset-0 z-[9990] bg-[var(--overlay-modal)]" /><Dialog.Content+ onPointerDownOutside={(event) => event.preventDefault()}aria-describedby={undefined}className={cn(- 'fixed left-1/2 top-1/2 z-[9991] flex max-h-[min(640px,calc(100vh-48px))]',- 'w-[calc(100vw-48px)] max-w-[640px] -translate-x-1/2 -translate-y-1/2 flex-col',- 'overflow-hidden rounded-xl border border-[var(--border-default)]',- 'bg-[var(--surface-elevated)] text-[var(--text-primary)] focus:outline-none',+ 'fixed left-1/2 top-1/2 z-[9991] flex max-h-[calc(100dvh-48px)] w-[calc(100vw-48px)] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] text-[var(--text-primary)] focus:outline-none',+ choosingOffer ? 'max-w-[600px]' : 'max-w-[1120px]',)}>- <div className="flex items-center justify-between gap-4 px-6 pb-4 pt-5">+ <div className="flex items-center justify-between gap-4 px-6 py-4"><div className="flex min-w-0 items-center gap-2">- <Dialog.Title className="truncate text-16 font-medium tracking-[-0.01em]">- {selectedGroup?.product.name ?? t('billing.planChange.targetTitle')}+ {choosingOffer && (+ <button+ type="button"+ aria-label={t('billing.planChange.back')}+ onClick={() => setSelectedProductCode(null)}+ className="grid size-8 shrink-0 place-items-center rounded-full text-[var(--text-secondary)] hover:bg-[var(--surface-hover-soft)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ >+ <ChevronLeft size={16} />+ </button>+ )}+ <Dialog.Title className="text-16 font-medium">+ {choosingOffer+ ? selectedCandidates[0].product.name+ : t('billing.planChange.targetTitle')}</Dialog.Title></div><Dialog.Close asChild><buttontype="button"- className="grid size-8 shrink-0 place-items-center rounded-full text-[var(--text-tertiary)] transition-colors hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)]"aria-label={t('billing.actions.close')}+ className="grid size-8 shrink-0 place-items-center rounded-full text-[var(--text-tertiary)] hover:bg-[var(--surface-hover-soft)]"><X size={16} /></button></Dialog.Close></div>-<div className="min-h-0 flex-1 overflow-y-auto border-t border-[var(--border-default)] px-6 py-4 [scrollbar-gutter:stable]">- {selectedGroup ? (- <div className="divide-y divide-[var(--border-default)] overflow-hidden rounded-xl border border-[var(--border-default)]">- {selectedGroup.candidates.map((candidate) => {- const active = selectedCandidate?.offer.code === candidate.offer.code;- const offerName = candidate.offer.name?.trim();+ {!candidates.some((candidate) => candidate.available !== false) && (+ <p role="status" className="mb-4 text-12 text-[var(--text-secondary)]">+ {t('billing.planChange.emptyTitle')}+ </p>+ )}+ {choosingOffer ? (+ <div+ ref={offerListRef}+ className="divide-y divide-[var(--border-default)] overflow-hidden rounded-xl border border-[var(--border-default)]"+ >+ {selectedCandidates.map((candidate) => {+ const offer = candidate.offer;+ const unavailable = candidate.available === false;return (<button- key={candidate.offer.code}+ key={offer.code}type="button"- aria-pressed={active}- onClick={() => setSelectedOfferCode(candidate.offer.code)}- className={cn(- 'flex min-h-[72px] w-full items-center justify-between gap-4 px-4 py-3 text-left transition-colors',- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset',- 'focus-visible:ring-[var(--focus-ring)]',- active- ? 'bg-[var(--surface-hover-soft)]'- : 'bg-[var(--surface-elevated)] hover:bg-[var(--surface-hover-soft)]',- )}+ disabled={disabled || unavailable}+ onClick={() => {+ if (!disabled && !unavailable) onSelect(candidate);+ }}+ className="flex w-full items-center gap-3 px-4 py-3 text-left text-13 transition-colors enabled:hover:bg-[var(--surface-hover-soft)] disabled:cursor-not-allowed disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus-ring)]">- <div className="min-w-0 flex-1">- {offerName && (- <p className="truncate text-13 font-medium text-[var(--text-primary)]">- {offerName}+ <div className="min-w-0 flex-1 space-y-1">+ <p className="font-medium">+ {candidate.providers+ .map((provider) => t(`billing.providers.${provider}`))+ .join(' / ')}+ </p>+ {offer.name?.trim() && <p>{offer.name}</p>}+ {offer.creditAmount !== null && (+ <p className="text-12 text-[var(--text-secondary)]">+ {t(+ offer.interval+ ? `billing.comparison.credits.${offer.interval}`+ : 'billing.credits',+ {+ amount: formatBillingAmount(+ offer.creditAmount,+ offer.currency,+ locale,+ ),+ },+ )}+ </p>+ )}+ {offer.rolloverCap !== null && (+ <p className="text-12 text-[var(--text-secondary)]">+ {t('billing.comparison.rollover', {+ amount: formatBillingAmount(+ offer.rolloverCap,+ offer.currency,+ locale,+ ),+ period: t(+ `billing.comparison.nextPeriod.${offer.interval ?? 'OTHER'}`,+ ),+ })}+ </p>+ )}+ {unavailable && (+ <p className="text-12 text-[var(--text-secondary)]">+ {t(+ candidate.unavailableReason+ ? `billing.catalog.unavailableReasons.${candidate.unavailableReason}`+ : 'billing.comparison.changeUnavailable',+ )}</p>)}</div>- <div className="flex shrink-0 items-center gap-3">- {renderAmount(candidate)}- <span- className={cn(- 'grid size-5 shrink-0 place-items-center rounded-full border',- active- ? 'border-[var(--text-primary)] bg-[var(--text-primary)] text-[var(--surface)]'- : 'border-[var(--border-default)]',- )}- >- {active && <Check size={12} strokeWidth={2.5} />}- </span>- </div>+ <p className="text-right tabular-nums">+ {offer.amount !== null+ ? formatBillingAmount(offer.amount, offer.currency, locale)+ : '—'}+ {offer.interval && (+ <span className="text-12 text-[var(--text-secondary)]">+ {' '}+ / {t(`billing.intervals.${offer.interval}`)}+ </span>+ )}+ </p>+ <ChevronRight size={16} className="shrink-0 text-[var(--text-secondary)]" /></button>);})}</div>) : (- <>- {currentPlan && (- <div className="overflow-hidden rounded-xl border border-[var(--border-default)]">- <div className="flex w-full items-center justify-between gap-4 bg-[var(--surface-chip)] px-4 py-3 text-left">- <div className="min-w-0 flex-1">- <div className="flex flex-wrap items-center gap-2">- <p className="truncate text-13 font-medium text-[var(--text-primary)]">- {currentPlan.product.name}- </p>- <span className="rounded-full bg-[var(--surface)] px-2 py-0.5 text-10 font-medium text-[var(--text-secondary)]">- {t('billing.catalog.currentPlan')}- </span>- </div>- </div>- {renderAmount(currentPlan)}- </div>- </div>- )}-- {groups.length > 0 && (- <div- className={cn(- 'divide-y divide-[var(--border-default)] overflow-hidden rounded-xl border border-[var(--border-default)]',- currentPlan && 'mt-4',- )}- >- {groups.map((group) => {- const candidate = group.defaultCandidate;- const hasMultipleOffers = group.candidates.length > 1;- const DirectionIcon =- candidate.direction === 'UPGRADE'- ? ArrowUpRight- : candidate.direction === 'DOWNGRADE'- ? ArrowDownRight- : null;- const directionLabel =- candidate.direction === 'UPGRADE'- ? t('billing.planChange.upgradeBadge')- : candidate.direction === 'DOWNGRADE'- ? t('billing.planChange.downgradeBadge')- : candidate.direction === 'SAME_LEVEL'- ? t('billing.planChange.sameLevelBadge')- : null;- const providerLabel = candidate.providers- .map((provider) => t(`billing.providers.${provider}`))- .join(', ');- return (- <button- key={group.product.code}- type="button"- onClick={() => {- if (hasMultipleOffers) {- selectProduct(group.product.code);- } else {- onSelect(candidate);- }- }}- className={cn(- 'flex w-full items-center justify-between gap-4 px-4 py-3 text-left transition-colors',- 'hover:bg-[var(--surface-hover-soft)] focus-visible:outline-none',- 'focus-visible:ring-2 focus-visible:ring-inset',- 'focus-visible:ring-[var(--focus-ring)]',- )}- >- <div className="min-w-0 flex-1">- <p className="truncate text-13 font-medium text-[var(--text-primary)]">- {group.product.name}- </p>- {(DirectionIcon || directionLabel || providerLabel) && (- <p className="mt-0.5 flex min-h-4 items-center gap-1 text-11 text-[var(--text-tertiary)]">- {DirectionIcon && <DirectionIcon size={12} />}- {directionLabel && <span>{directionLabel}</span>}- {directionLabel && providerLabel && <span aria-hidden>·</span>}- {providerLabel && <span>{providerLabel}</span>}- </p>- )}- </div>- <div className="flex shrink-0 items-center gap-3">- {renderAmount(candidate)}- {hasMultipleOffers && (- <ArrowRight size={16} className="text-[var(--text-tertiary)]" />- )}- </div>- </button>- );- })}- </div>- )}-- {groups.length === 0 && (- <div- className={cn(- 'flex min-h-[184px] flex-col items-center justify-center rounded-xl border',- 'border-[var(--border-default)] px-6 text-center',- currentPlan && 'mt-4',- )}- >- <div className="grid size-11 place-items-center rounded-full bg-[var(--surface-chip)]">- <PackageOpen size={22} />- </div>- <p className="mt-4 text-sm font-medium">{t('billing.planChange.emptyTitle')}</p>- <p className="mt-1 text-12 text-[var(--text-secondary)]">- {t('billing.planChange.emptyDescription')}- </p>- </div>- )}- </>+ <PlanComparison+ plans={sortedPlans}+ freeAction={t('billing.comparison.topup')}+ freeHint={t('billing.comparison.topupUnlock')}+ freeDisabled={topupDisabled || !onTopup}+ onFreeAction={() => onTopup?.()}+ />)}</div>-- {selectedGroup && (- <div className="flex min-h-16 items-center justify-between gap-4 border-t border-[var(--border-default)] px-6 py-3">- <button- type="button"- onClick={backToProducts}- className="inline-flex h-9 items-center gap-1.5 rounded-md px-1 text-13 font-medium text-[var(--text-secondary)] transition-colors hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"- >- <ArrowLeft size={15} />- {t('billing.planChange.back')}- </button>- <button- type="button"- disabled={selectedCandidate === null}- onClick={() => {- if (selectedCandidate) onSelect(selectedCandidate);- }}- className="inline-flex h-9 shrink-0 items-center gap-2 rounded-full bg-[var(--accent-cta-bg)] px-5 text-13 font-medium text-[var(--accent-pure-cta-fg)] transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface-elevated)] disabled:cursor-not-allowed disabled:opacity-35"- >- {t('billing.settings.subscriptionCard.changeAction')}- <ArrowUpRight size={15} />- </button>- </div>- )}</Dialog.Content></Dialog.Portal></Dialog.Root>@@ -504,15 +446,16 @@ export function PlanChangeStatusDialog({<Dialog.Portal><Dialog.Overlay className="fixed inset-0 z-[10000] bg-[var(--overlay-modal)]" /><Dialog.Content+ onPointerDownOutside={(event) => event.preventDefault()}className={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-[10001] flex max-h-[calc(100dvh-40px)] w-[calc(100vw-40px)] max-w-[600px] flex-col','-translate-x-1/2 -translate-y-1/2 overflow-hidden rounded-xl','border border-[var(--border-default)] bg-[var(--surface-elevated)]','text-[var(--text-primary)] focus:outline-none',)}aria-describedby={undefined}>- <div className="flex items-start justify-between gap-4 border-b border-[var(--border-default)] px-6 py-5">+ <div className="flex shrink-0 items-start justify-between gap-4 border-b border-[var(--border-default)] px-6 py-5"><div><Dialog.Title className="text-lg font-medium">{title}</Dialog.Title>{targetName && (@@ -534,170 +477,172 @@ export function PlanChangeStatusDialog({)}</div>- <div className="flex min-h-[260px] flex-col items-center justify-center px-6 py-7 text-center">- {busy && (- <>- <Spinner icon={LoaderCircle} size={28} className="text-[var(--text-secondary)]" />- <p className="mt-4 text-sm text-[var(--text-secondary)]">- {state.phase === 'QUOTING'- ? t('billing.planChange.quotingBody')- : t('billing.planChange.confirmingBody')}- </p>- </>- )}+ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-7 text-center">+ <div className="flex min-h-[204px] flex-col items-center justify-center">+ {busy && (+ <>+ <Spinner icon={LoaderCircle} size={28} className="text-[var(--text-secondary)]" />+ <p className="mt-4 text-sm text-[var(--text-secondary)]">+ {state.phase === 'QUOTING'+ ? t('billing.planChange.quotingBody')+ : t('billing.planChange.confirmingBody')}+ </p>+ </>+ )}- {state.phase === 'PENDING_PROVIDER' && (- <>- <Spinner icon={LoaderCircle} size={28} className="text-[var(--text-secondary)]" />- <p className="mt-4 max-w-[400px] text-sm text-[var(--text-secondary)]">- {t('billing.planChange.pendingProviderBody')}- </p>- </>- )}+ {state.phase === 'PENDING_PROVIDER' && (+ <>+ <Spinner icon={LoaderCircle} size={28} className="text-[var(--text-secondary)]" />+ <p className="mt-4 max-w-[400px] text-sm text-[var(--text-secondary)]">+ {t('billing.planChange.pendingProviderBody')}+ </p>+ </>+ )}- {state.phase === 'QUOTE_READY' && change && (- <>- <p className="text-sm font-medium">- {isUpgrade- ? quotedAmount- ? t('billing.planChange.upgradeDueNow', { amount: quotedAmount })- : t('billing.planChange.upgradeNoAmount')- : t('billing.planChange.downgradeAt', {- date: formatEffectiveDate(change.effectiveAt, billingLocale),- })}- </p>- <p className="mt-2 max-w-[400px] text-12 leading-5 text-[var(--text-secondary)]">- {isUpgrade- ? t('billing.planChange.upgradeHint')- : t('billing.planChange.downgradeHint')}- </p>- {quoteSeconds !== null && (- <p className="mt-3 text-11 text-[var(--text-tertiary)]">- {t('billing.planChange.quoteExpiresIn', {- minutes: Math.floor(quoteSeconds / 60),- seconds: String(quoteSeconds % 60).padStart(2, '0'),- })}+ {state.phase === 'QUOTE_READY' && change && (+ <>+ <p className="text-sm font-medium">+ {isUpgrade+ ? quotedAmount+ ? t('billing.planChange.upgradeDueNow', { amount: quotedAmount })+ : t('billing.planChange.upgradeNoAmount')+ : t('billing.planChange.downgradeAt', {+ date: formatEffectiveDate(change.effectiveAt, billingLocale),+ })}</p>- )}- {state.error && (- <p className="mt-3 text-12 text-[var(--text-primary)]">- {state.stale- ? t('billing.planChange.resyncHint')- : t('billing.planChange.requestFailed')}+ <p className="mt-2 max-w-[400px] text-12 leading-5 text-[var(--text-secondary)]">+ {isUpgrade+ ? t('billing.planChange.upgradeHint')+ : t('billing.planChange.downgradeHint')}</p>- )}- </>- )}-- {state.phase === 'AWAITING_PAYMENT' && action?.type === 'QR_CODE' && (- <>- <div- className="relative grid place-items-center rounded-xl border border-[var(--border-default)] bg-white p-2"- style={{- width: 'min(280px, calc(100vw - 96px), calc(100vh - 280px))',- height: 'min(280px, calc(100vw - 96px), calc(100vh - 280px))',- }}- >- {qrDataUrl ? (- <>- <img- src={qrDataUrl}- className="size-full"- alt={t('billing.checkout.qrAlt')}- />- <span- aria-hidden="true"- className="pointer-events-none absolute grid size-10 place-items-center rounded-lg bg-white p-1"- >- <img src={cindyIconUrl} className="size-8 rounded-md" alt="" />- </span>- </>- ) : (- <Spinner size={24} className="text-[var(--text-secondary)]" />- )}- </div>- <p className="mt-4 text-sm font-medium">- {quotedAmount- ? t('billing.planChange.scanToPay', { amount: quotedAmount })- : t('billing.checkout.scanHint')}- </p>- <p className="mt-1 text-12 text-[var(--text-tertiary)]">- {actionSeconds === null- ? t('billing.checkout.checkingExpiry')- : t('billing.checkout.expiresIn', {- minutes: Math.floor(actionSeconds / 60),- seconds: String(actionSeconds % 60).padStart(2, '0'),+ {quoteSeconds !== null && (+ <p className="mt-3 text-11 text-[var(--text-tertiary)]">+ {t('billing.planChange.quoteExpiresIn', {+ minutes: Math.floor(quoteSeconds / 60),+ seconds: String(quoteSeconds % 60).padStart(2, '0'),})}- </p>- </>- )}+ </p>+ )}+ {state.error && (+ <p className="mt-3 text-12 text-[var(--text-primary)]">+ {state.stale+ ? t('billing.planChange.resyncHint')+ : t('billing.planChange.requestFailed')}+ </p>+ )}+ </>+ )}- {state.phase === 'AWAITING_PAYMENT' && action?.type === 'REDIRECT' && (- <>- <div className="grid size-14 place-items-center rounded-full bg-[var(--surface-chip)]">- <ExternalLink size={22} />- </div>- <p className="mt-4 text-sm font-medium">{t('billing.checkout.redirectHint')}</p>- <button- type="button"- onClick={() => void billingApi.openPaymentRedirect(action.url)}- className="mt-5 inline-flex h-9 items-center gap-2 rounded-full bg-[var(--text-primary)] px-5 text-sm font-medium text-[var(--surface)]"- >- <ExternalLink size={14} />- {t('billing.checkout.openPayment')}- </button>- </>- )}+ {state.phase === 'AWAITING_PAYMENT' && action?.type === 'QR_CODE' && (+ <>+ <div+ className="relative grid place-items-center rounded-xl border border-[var(--border-default)] bg-white p-2"+ style={{+ width: 'min(280px, calc(100vw - 96px))',+ height: 'min(280px, calc(100vw - 96px))',+ }}+ >+ {qrDataUrl ? (+ <>+ <img+ src={qrDataUrl}+ className="size-full"+ alt={t('billing.checkout.qrAlt')}+ />+ <span+ aria-hidden="true"+ className="pointer-events-none absolute grid size-10 place-items-center rounded-lg bg-white p-1"+ >+ <img src={cindyIconUrl} className="size-8 rounded-md" alt="" />+ </span>+ </>+ ) : (+ <Spinner size={24} className="text-[var(--text-secondary)]" />+ )}+ </div>+ <p className="mt-4 text-sm font-medium">+ {quotedAmount+ ? t('billing.planChange.scanToPay', { amount: quotedAmount })+ : t('billing.checkout.scanHint')}+ </p>+ <p className="mt-1 text-12 text-[var(--text-tertiary)]">+ {actionSeconds === null+ ? t('billing.checkout.checkingExpiry')+ : t('billing.checkout.expiresIn', {+ minutes: Math.floor(actionSeconds / 60),+ seconds: String(actionSeconds % 60).padStart(2, '0'),+ })}+ </p>+ </>+ )}- {state.phase === 'AWAITING_PAYMENT' && !action && (- <>- <Spinner size={26} className="text-[var(--text-secondary)]" />- <p className="mt-4 text-sm text-[var(--text-secondary)]">- {t('billing.checkout.refreshingAction')}- </p>- </>- )}+ {state.phase === 'AWAITING_PAYMENT' && action?.type === 'REDIRECT' && (+ <>+ <div className="grid size-14 place-items-center rounded-full bg-[var(--surface-chip)]">+ <ExternalLink size={22} />+ </div>+ <p className="mt-4 text-sm font-medium">{t('billing.checkout.redirectHint')}</p>+ <button+ type="button"+ onClick={() => void billingApi.openPaymentRedirect(action.url)}+ className="mt-5 inline-flex h-9 items-center gap-2 rounded-full bg-[var(--text-primary)] px-5 text-sm font-medium text-[var(--surface)]"+ >+ <ExternalLink size={14} />+ {t('billing.checkout.openPayment')}+ </button>+ </>+ )}- {(state.phase === 'SCHEDULED' || state.phase === 'APPLIED') && (- <>- <div className="grid size-14 place-items-center rounded-full bg-[var(--text-primary)] text-[var(--surface)]">- <Check size={24} />- </div>- <p className="mt-4 text-sm font-medium">- {state.phase === 'APPLIED'- ? t('billing.planChange.appliedBody')- : change- ? t('billing.planChange.scheduledBody', {- date: formatEffectiveDate(change.effectiveAt, billingLocale),- })- : t('billing.planChange.scheduledTitle')}- </p>- </>- )}+ {state.phase === 'AWAITING_PAYMENT' && !action && (+ <>+ <Spinner size={26} className="text-[var(--text-secondary)]" />+ <p className="mt-4 text-sm text-[var(--text-secondary)]">+ {t('billing.checkout.refreshingAction')}+ </p>+ </>+ )}- {(state.phase === 'FAILED' ||- state.phase === 'CANCELED' ||- state.phase === 'EXPIRED') && (- <>- <div className="grid size-14 place-items-center rounded-full bg-[var(--surface-chip)]">- <CircleAlert size={23} />- </div>- <p className="mt-4 max-w-[340px] text-sm text-[var(--text-secondary)]">- {state.error- ? state.quoteFailureReason === 'TARGET_NOT_ALLOWED'- ? t('billing.planChange.quoteRejected')- : t('billing.planChange.requestFailed')- : state.phase === 'CANCELED'- ? t('billing.planChange.canceledBody')- : state.phase === 'EXPIRED'- ? t('billing.planChange.expiredBody')- : t('billing.planChange.failedBody')}- </p>- </>- )}+ {(state.phase === 'SCHEDULED' || state.phase === 'APPLIED') && (+ <>+ <div className="grid size-14 place-items-center rounded-full bg-[var(--text-primary)] text-[var(--surface)]">+ <Check size={24} />+ </div>+ <p className="mt-4 text-sm font-medium">+ {state.phase === 'APPLIED'+ ? t('billing.planChange.appliedBody')+ : change+ ? t('billing.planChange.scheduledBody', {+ date: formatEffectiveDate(change.effectiveAt, billingLocale),+ })+ : t('billing.planChange.scheduledTitle')}+ </p>+ </>+ )}++ {(state.phase === 'FAILED' ||+ state.phase === 'CANCELED' ||+ state.phase === 'EXPIRED') && (+ <>+ <div className="grid size-14 place-items-center rounded-full bg-[var(--surface-chip)]">+ <CircleAlert size={23} />+ </div>+ <p className="mt-4 max-w-[340px] text-sm text-[var(--text-secondary)]">+ {state.error+ ? state.quoteFailureReason === 'TARGET_NOT_ALLOWED'+ ? t('billing.planChange.quoteRejected')+ : t('billing.planChange.requestFailed')+ : state.phase === 'CANCELED'+ ? t('billing.planChange.canceledBody')+ : state.phase === 'EXPIRED'+ ? t('billing.planChange.expiredBody')+ : t('billing.planChange.failedBody')}+ </p>+ </>+ )}+ </div></div>- <div className="flex min-h-16 items-center justify-between gap-3 border-t border-[var(--border-default)] px-6 py-3">+ <div className="flex min-h-16 shrink-0 flex-wrap items-center justify-between gap-3 border-t border-[var(--border-default)] px-6 py-3"><div>{state.phase === 'QUOTE_READY' && change?.status === 'QUOTED' && !state.stale && (<button@@ -709,7 +654,7 @@ export function PlanChangeStatusDialog({</button>)}</div>- <div className="flex items-center gap-2">+ <div className="flex flex-wrap items-center justify-end gap-2">{state.phase === 'FAILED' && state.quoteFailureReason === 'TARGET_NOT_ALLOWED' && (<buttontype="button"diff --git a/apps/desktop/src/renderer/features/billing/PlanComparison.tsx b/apps/desktop/src/renderer/features/billing/PlanComparison.tsxnew file mode 100644index 0000000000..fdabd86e4c--- /dev/null+++ b/apps/desktop/src/renderer/features/billing/PlanComparison.tsx@@ -0,0 +1,234 @@+import type { RefObject } from 'react';+import { Check } from 'lucide-react';+import { useTranslation } from 'react-i18next';+import type { BillingCatalogOffer, BillingCatalogProduct } from '../../../shared/billing';+import { formatBillingAmount } from './money';++export type ComparisonOffer = {+ offer: BillingCatalogOffer;+ current?: boolean;+ actionRef?: RefObject<HTMLButtonElement | null>;+ disabled?: boolean;+ action: string;+ onSelect: () => void;+};++export type ComparisonPlan = {+ product: BillingCatalogProduct;+ offers: ComparisonOffer[];+ defaultOfferCode: string;+ purchasableOffers?: BillingCatalogOffer[];+ action?: Pick<ComparisonOffer, 'action' | 'disabled' | 'onSelect'>;+};++/** Catalog amounts and availability come from the server; this component only presents them. */+export function PlanComparison({+ plans,+ freeAction,+ freeHint,+ onFreeAction,+ freeDisabled = false,+}: {+ plans: ComparisonPlan[];+ freeAction: string;+ freeHint: string;+ onFreeAction: () => void;+ freeDisabled?: boolean;+}) {+ const { t, i18n } = useTranslation();+ const locale = i18n.resolvedLanguage ?? i18n.language;+ const selected = plans.map((plan) => {+ const entry =+ plan.offers.find((entry) => entry.offer.code === plan.defaultOfferCode) ?? plan.offers[0];+ // Each displayed price and its terms must describe the same available offer.+ // Keep currencies and billing periods separate; current contracts use their snapshot.+ const groups = new Map<string, BillingCatalogOffer[]>();+ for (const offer of plan.purchasableOffers?.length+ ? plan.purchasableOffers+ : entry+ ? [entry.offer]+ : []) {+ const key = `${offer.currency}:${offer.interval}`;+ const group = groups.get(key);+ if (group) group.push(offer);+ else groups.set(key, [offer]);+ }+ const prices = [...groups].map(([key, offers]) => {+ const pricedOffers = offers.filter((offer) => offer.amount !== null);+ const lowest = pricedOffers.reduce<BillingCatalogOffer | undefined>(+ (min, offer) => (!min || Number(offer.amount) < Number(min.amount) ? offer : min),+ undefined,+ );+ return {+ key,+ offer: lowest ?? offers[0],+ hasDifferentPrices: pricedOffers.some(+ (offer) => Number(offer.amount) !== Number(lowest?.amount),+ ),+ };+ });+ return {+ ...plan,+ entry,+ prices,+ actionEntry: plan.offers.find((entry) => entry.current) ?? entry,+ };+ });+ const currency = selected[0]?.entry?.offer.currency;+ const buttonClass =+ 'flex min-h-9 w-full items-center justify-center rounded-full border border-[var(--border-default)] px-3 py-2 text-13 font-medium transition-colors enabled:hover:bg-[var(--surface-hover-soft)] enabled:active:bg-[var(--surface-chip)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-not-allowed disabled:opacity-50';+ const feature = (key: string) => (+ <li key={key} className="flex items-start gap-2 text-13 leading-relaxed">+ <Check size={15} className="mt-0.5 shrink-0 text-[var(--text-secondary)]" aria-hidden />+ <span>{t(`billing.comparison.${key}`)}</span>+ </li>+ );+ return (+ <div className="overflow-x-auto pb-2">+ <div className="grid min-h-[460px] auto-cols-[minmax(220px,1fr)] grid-flow-col divide-x divide-[var(--border-default)]">+ <section className="flex min-w-0 flex-col px-6 first:pl-0 last:pr-0">+ <h3 className="min-h-7 text-14 font-medium">{t('billing.comparison.free')}</h3>+ <p className="mt-5 text-28 font-medium tabular-nums">+ {currency ? formatBillingAmount('0', currency, locale) : '0'}+ </p>+ <p className="mt-1 min-h-5 text-12 text-[var(--text-secondary)]">+ {t('billing.comparison.freeUsage')}+ </p>+ <div className="mt-6 min-h-16">+ <p className="text-13 font-medium">{t('billing.comparison.topup')}</p>+ <p className="mt-1 text-12 text-[var(--text-secondary)]">+ {t('billing.comparison.topupExpiry')}+ </p>+ </div>+ <ul className="mb-10 space-y-3 border-t border-[var(--border-default)] pt-5">+ {['agent', 'apiKey', 'existingSubscription', 'localModels', 'basicModels'].map(feature)}+ </ul>+ <div className="mt-auto">+ <p className="mb-3 text-11 leading-relaxed text-[var(--text-secondary)]">{freeHint}</p>+ <button+ type="button"+ className={buttonClass}+ disabled={freeDisabled}+ onClick={onFreeAction}+ >+ {freeAction}+ </button>+ </div>+ </section>+ {selected.map(({ product, offers, entry, prices, action, actionEntry }) => {+ if (!entry || !actionEntry) return null;+ const offer = prices[0].offer;+ const baseline = selected[0];+ const baseOffer = baseline?.prices[0]?.offer;+ const multiple =+ prices.length === 1 &&+ baseline.prices.length === 1 &&+ baseOffer &&+ product.code !== baseline.product.code &&+ baseOffer.currency === offer.currency &&+ baseOffer.interval === offer.interval &&+ Number(baseOffer.creditAmount) > 0 &&+ offer.creditAmount !== null+ ? Number(offer.creditAmount) / Number(baseOffer.creditAmount)+ : null;+ return (+ <section key={product.code} className="flex min-w-0 flex-col px-6 last:pr-0">+ <div className="flex min-h-7 flex-wrap items-center gap-2">+ <h3 className="break-words text-14 font-medium">{product.name}</h3>+ {offers.some((option) => option.current) && (+ <span className="rounded-full bg-[var(--surface-chip)] px-2 py-1 text-10 text-[var(--text-secondary)]">+ {t('billing.catalog.currentPlan')}+ </span>+ )}+ </div>+ <div className="mt-5 text-28 font-medium tabular-nums">+ {prices.map(({ key, offer: price, hasDifferentPrices }) => {+ return (+ <p key={key}>+ {price.amount !== null+ ? formatBillingAmount(price.amount, price.currency, locale)+ : '—'}+ {hasDifferentPrices && (+ <span className="ml-1 text-12 font-normal text-[var(--text-secondary)]">+ {t('billing.comparison.priceFromSuffix')}+ </span>+ )}+ {price.interval && (+ <span className="ml-1 text-12 font-normal text-[var(--text-secondary)]">+ / {t(`billing.intervals.${price.interval}`)}+ </span>+ )}+ </p>+ );+ })}+ </div>+ <div className="mt-1 min-h-5 text-12 text-[var(--text-secondary)]">+ {t('billing.comparison.subscription')}+ </div>+ <div className="mt-6 min-h-16 space-y-3">+ {prices.map(({ key, offer }) => (+ <div key={key}>+ {offer.creditAmount !== null && (+ <p className="text-13 font-medium">+ {t(+ offer.interval+ ? `billing.comparison.credits.${offer.interval}`+ : 'billing.credits',+ {+ amount: formatBillingAmount(offer.creditAmount, offer.currency, locale),+ },+ )}+ </p>+ )}+ {offer.rolloverCap !== null && (+ <p className="mt-1 text-12 text-[var(--text-secondary)]">+ {t('billing.comparison.rollover', {+ amount: formatBillingAmount(offer.rolloverCap, offer.currency, locale),+ period: t(`billing.comparison.nextPeriod.${offer.interval ?? 'OTHER'}`),+ })}+ </p>+ )}+ </div>+ ))}+ </div>+ <div className="mb-10 border-t border-[var(--border-default)] pt-5">+ <p className="mb-4 text-12 text-[var(--text-secondary)]">+ {t('billing.comparison.includesFree')}+ </p>+ <ul className="space-y-3">+ {['advancedModels', 'managedService'].map(feature)}+ {multiple !== null && Number.isInteger(multiple) && multiple > 1 && (+ <li className="flex items-start gap-2 text-13 leading-relaxed">+ <Check+ size={15}+ className="mt-0.5 shrink-0 text-[var(--text-secondary)]"+ aria-hidden+ />+ <span>+ {t('billing.comparison.creditMultiple', {+ name: baseline.product.name,+ multiple,+ })}+ </span>+ </li>+ )}+ </ul>+ </div>+ <div className="mt-auto">+ <button+ type="button"+ ref={actionEntry.actionRef}+ disabled={action ? action.disabled : actionEntry.disabled || actionEntry.current}+ onClick={action?.onSelect ?? actionEntry.onSelect}+ className={buttonClass}+ >+ {action?.action ?? actionEntry.action}+ </button>+ </div>+ </section>+ );+ })}+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsxindex 0d3784aaf7..03cb4580b9 100644--- a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx@@ -140,6 +140,8 @@ beforeEach(() => {modelCatalogMocks.refreshBuiltinProviderModels.mockClear();authState.dataOwnerId = 'account-fixture';routerState.search = '';+ checkout.startSubscription.mockClear();+ checkout.startTopup.mockClear();});async function openSubscriptionManagementMenu() {@@ -1026,7 +1028,11 @@ describe('BillingPage remote catalog rendering', () => {await waitFor(() => expect(screen.queryByText('Configured top-up')).toBeNull());fireEvent.click(screen.getByText('billing.settings.subscriptionCard.action'));- fireEvent.click((await screen.findByText('Configured subscription')).closest('button')!);+ fireEvent.click(+ (await screen.findByText('Configured subscription'))+ .closest('section')!+ .querySelector('button')!,+ );expect(screen.getByText('stripe')).toBeTruthy();expect(screen.queryByText('alipay')).toBeNull();fireEvent.click(screen.getByText('stripe').closest('button')!);@@ -1037,6 +1043,151 @@ describe('BillingPage remote catalog rendering', () => {});});+ it('keeps the subscription empty state instead of showing a misleading FREE-only catalog', async () => {+ window.electronAPI.billing.getCatalog = vi.fn(async () => ({ products: [] }));+ render(<BillingPage />);+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));+ const dialog = await screen.findByRole('dialog');+ expect(await within(dialog).findByText('billing.catalog.emptyTitle')).toBeTruthy();+ expect(within(dialog).queryByText('billing.comparison.free')).toBeNull();+ expect(within(dialog).queryByText('billing.actions.pay')).toBeNull();+ });++ it.each(['OFFER_COMING_SOON', 'NO_AVAILABLE_PAYMENT_CHANNEL'] as const)(+ 'keeps subscription reason %s visible and prevents purchase',+ async (reason) => {+ const catalog = await window.electronAPI.billing.getCatalog();+ const product = catalog.products.find((entry) => entry.kind === 'SUBSCRIPTION')!;+ window.electronAPI.billing.getCatalog = vi.fn(async () => ({+ products: [+ {+ ...product,+ offers: product.offers.map((offer) => ({+ ...offer,+ salesState:+ reason === 'OFFER_COMING_SOON' ? ('COMING_SOON' as const) : ('AVAILABLE' as const),+ purchasable: false,+ unavailableReason: reason,+ purchaseOptions: [],+ })),+ },+ ],+ }));+ render(<BillingPage />);+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));+ const dialog = await screen.findByRole('dialog');+ expect(+ await within(dialog).findByText(`billing.catalog.unavailableReasons.${reason}`),+ ).toBeTruthy();+ const button = within(dialog).getByRole('button', {+ name: `billing.catalog.unavailableReasons.${reason}`,+ });+ expect(button).toHaveProperty('disabled', true);+ fireEvent.click(button);+ expect(within(dialog).queryByText('billing.steps.channel.title')).toBeNull();+ expect(checkout.startSubscription).not.toHaveBeenCalled();+ },+ );++ it('uses identical action buttons, restores keyboard focus on back, and opens top-up from FREE', async () => {+ render(<BillingPage />);+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));+ const dialog = await screen.findByRole('dialog');+ const purchase = await within(dialog).findByRole('button', { name: /Configured subscription/ });+ const free = within(dialog).getByRole('button', { name: 'billing.comparison.topup' });+ expect(purchase.className).toBe(free.className);+ expect(purchase.hasAttribute('aria-pressed')).toBe(false);+ expect(purchase.className).not.toContain('accent-cta');+ expect(document.activeElement).toBe(purchase);+ fireEvent.click(purchase);+ fireEvent.click(within(dialog).getByRole('button', { name: 'billing.planChange.back' }));+ expect(document.activeElement).toBe(+ within(dialog).getByRole('button', { name: /Configured subscription/ }),+ );+ fireEvent.click(within(dialog).getByRole('button', { name: 'billing.comparison.topup' }));+ expect(await screen.findByRole('dialog', { name: 'billing.dialogs.topup.title' })).toBeTruthy();+ expect(checkout.startTopup).not.toHaveBeenCalled();+ expect(checkout.startSubscription).not.toHaveBeenCalled();+ });++ it('disables stale checkout while catalog refresh is pending or failed and allows retry', async () => {+ const catalog = await window.electronAPI.billing.getCatalog();+ let rejectRefresh!: (error: Error) => void;+ window.electronAPI.billing.getCatalog = vi+ .fn()+ .mockResolvedValueOnce(catalog)+ .mockImplementationOnce(+ () =>+ new Promise((_, reject) => {+ rejectRefresh = reject;+ }),+ )+ .mockResolvedValueOnce(catalog);+ render(<BillingPage />);+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));+ const dialog = await screen.findByRole('dialog');+ fireEvent.click(await within(dialog).findByRole('button', { name: /Configured subscription/ }));+ expect(within(dialog).getByRole('button', { name: /^billing\.actions\.pay/ })).toHaveProperty(+ 'disabled',+ false,+ );+ fireEvent.click(screen.getByText('billing.actions.refreshCatalog'));+ expect(within(dialog).getByRole('button', { name: /^billing\.actions\.pay/ })).toHaveProperty(+ 'disabled',+ true,+ );+ await act(async () => rejectRefresh(new Error('offline')));+ expect(within(dialog).getByText('billing.catalog.errorTitle')).toBeTruthy();+ expect(within(dialog).queryByRole('button', { name: /^billing\.actions\.pay/ })).toBeNull();+ expect(checkout.startSubscription).not.toHaveBeenCalled();+ fireEvent.click(within(dialog).getByRole('button', { name: 'billing.actions.retry' }));+ fireEvent.click(await within(dialog).findByRole('button', { name: /Configured subscription/ }));+ await waitFor(() =>+ expect(within(dialog).getByRole('button', { name: /^billing\.actions\.pay/ })).toHaveProperty(+ 'disabled',+ false,+ ),+ );+ });++ it('returns to comparison if the selected offer becomes unavailable after refresh', async () => {+ const catalog = await window.electronAPI.billing.getCatalog();+ const unavailableCatalog = {+ products: catalog.products.map((product) =>+ product.kind === 'SUBSCRIPTION'+ ? {+ ...product,+ offers: product.offers.map((offer) => ({+ ...offer,+ salesState: 'COMING_SOON' as const,+ purchasable: false,+ unavailableReason: 'OFFER_COMING_SOON' as const,+ purchaseOptions: [],+ })),+ }+ : product,+ ),+ };+ window.electronAPI.billing.getCatalog = vi+ .fn()+ .mockResolvedValueOnce(catalog)+ .mockResolvedValueOnce(unavailableCatalog);+ render(<BillingPage />);+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));+ const dialog = await screen.findByRole('dialog');+ fireEvent.click(await within(dialog).findByRole('button', { name: /Configured subscription/ }));+ fireEvent.click(screen.getByText('billing.actions.refreshCatalog'));+ const action = await within(dialog).findByRole('button', {+ name: 'billing.catalog.unavailableReasons.OFFER_COMING_SOON',+ });+ expect(action).toHaveProperty('disabled', true);+ expect(+ within(dialog).getByText('billing.catalog.unavailableReasons.OFFER_COMING_SOON'),+ ).toBeTruthy();+ expect(within(dialog).queryByRole('button', { name: /^billing\.actions\.pay/ })).toBeNull();+ expect(checkout.startSubscription).not.toHaveBeenCalled();+ });+it('does not expose plan change when an active subscription has no effective plan', async () => {window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => ({subscription: {@@ -1064,7 +1215,7 @@ describe('BillingPage remote catalog rendering', () => {expect(checkout.startSubscription).not.toHaveBeenCalled();});- it('keeps a Product enterable when its current Offer has another Offer', async () => {+ it('keeps the current product labeled and blocks duplicate purchase even with another Offer', async () => {window.electronAPI.billing.getCatalog = vi.fn(async () => ({products: [{@@ -1096,7 +1247,7 @@ describe('BillingPage remote catalog rendering', () => {code: 'plus_month_more',interval: 'MONTH' as const,currency: 'usd',- amount: '20',+ amount: '1',minAmount: null,maxAmount: null,creditAmount: '250',@@ -1143,27 +1294,13 @@ describe('BillingPage remote catalog rendering', () => {await selectSubscriptionManagementAction('billing.settings.subscriptionCard.action');const dialog = await screen.findByRole('dialog');- const product = within(dialog).getByRole('button', { name: /Configured subscription/ });- expect(product).toHaveProperty('disabled', false);- const currentPlan = within(dialog).getByText('billing.catalog.currentPlan').closest('button')!;- const alternativeOffer = within(dialog).getByText('$20.00').closest('button')!;- const alternativeCredits = new Intl.NumberFormat('en', {- style: 'currency',- currency: 'USD',- }).format(250);+ expect(within(dialog).queryByRole('combobox')).toBeNull();expect(- within(alternativeOffer).getByText(`billing.credits:{"amount":"${alternativeCredits}"}`)- .className,- ).toContain('text-12');- expect(within(dialog).queryByText('plus_month_more')).toBeNull();- expect(currentPlan).toHaveProperty('disabled', true);- expect(currentPlan.getAttribute('aria-current')).toBe('true');- expect(alternativeOffer).toHaveProperty('disabled', false);- expect(alternativeOffer.getAttribute('aria-pressed')).toBe('true');- expect(alternativeOffer.className).not.toContain('shadow-[inset');- expect(within(dialog).getByText('billing.steps.channel.title')).toBeTruthy();- expect(within(dialog).getByText('stripe')).toBeTruthy();-+ within(dialog).getByRole('button', { name: 'billing.catalog.currentPlan' }),+ ).toHaveProperty('disabled', true);+ expect(+ within(dialog).getByText('billing.comparison.credits.MONTH:{"amount":"$250.00"}'),+ ).toBeTruthy();expect(checkout.startSubscription).not.toHaveBeenCalled();});@@ -1246,94 +1383,216 @@ describe('BillingPage remote catalog rendering', () => {fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));const dialog = await screen.findByRole('dialog');- const defaultOffer = within(dialog).getByText('$9.00').closest('button')!;- await waitFor(() => expect(document.activeElement).toBe(defaultOffer));- const proProduct = within(dialog).getByRole('button', { name: /Pro/ });- const futureProduct = within(dialog).getByRole('button', { name: /Coming Soon/ });- expect(proProduct).toHaveProperty('disabled', false);- expect(proProduct.closest('section')?.parentElement?.className).toContain('rounded-xl');- expect(proProduct.closest('section')?.className).not.toContain('border-[var(--text-primary)]');+ expect(within(dialog).queryByRole('combobox')).toBeNull();+ const futureProduct = within(dialog).getByRole('button', {+ name: 'billing.catalog.unavailableReasons.OFFER_COMING_SOON',+ });expect(futureProduct).toHaveProperty('disabled', true);expect(- within(futureProduct).getByText('billing.catalog.unavailableReasons.OFFER_COMING_SOON'),+ within(dialog).getByText('billing.catalog.unavailableReasons.OFFER_COMING_SOON'),).toBeTruthy();-- const secondOffer = within(dialog).getByText('$20.00').closest('button')!;- const defaultCredits = new Intl.NumberFormat('en', {- style: 'currency',- currency: 'USD',- }).format(100);- expect(- within(defaultOffer).getByText(`billing.credits:{"amount":"${defaultCredits}"}`),- ).toBeTruthy();- expect(within(dialog).queryByText('pro_month_current')).toBeNull();+ expect(within(dialog).getByText('billing.comparison.free')).toBeTruthy();+ fireEvent.click(within(dialog).getByRole('button', { name: /Pro/ }));+ expect(within(dialog).queryByRole('combobox')).toBeNull();+ const more = within(dialog).getByRole('button', { name: /stripe.*\$20\.00/ });+ fireEvent.click(more);+ expect(more.getAttribute('aria-pressed')).toBe('true');expect(within(dialog).queryByText('pro_month_more')).toBeNull();- expect(defaultOffer).toHaveProperty('disabled', false);- expect(defaultOffer.getAttribute('aria-pressed')).toBe('true');- expect(defaultOffer.firstElementChild?.querySelector('svg')).toBeNull();- expect(defaultOffer.lastElementChild?.querySelector('svg')).toBeTruthy();- expect(secondOffer.getAttribute('aria-pressed')).toBe('false');-- fireEvent.click(secondOffer);- expect(secondOffer.getAttribute('aria-pressed')).toBe('true');- expect(secondOffer.className).not.toContain('shadow-[inset');+ expect(within(dialog).getAllByText('stripe')).toHaveLength(2);+ fireEvent.click(within(dialog).getByText('billing.actions.pay'));+ expect(checkout.startSubscription).toHaveBeenCalledWith({+ offerCode: 'pro_month_more',+ purchaseOptionId: 'pro_more_stripe',+ });});- it('shows the server-default Offer price when a Product is collapsed', async () => {- const offer = (code: string, amount: string) => ({- code,- interval: 'MONTH' as const,- currency: 'usd',- amount,- minAmount: null,- maxAmount: null,- creditAmount: amount,- rolloverCap: '0',- purchaseOptions: [- {- id: `${code}_stripe`,- provider: 'stripe',- capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,- paymentAction: 'REDIRECT' as const,- },- ],- });+ it('shows every channel price and submits the selected offer and channel together', async () => {+ const catalog = await window.electronAPI.billing.getCatalog();+ const product = catalog.products.find((entry) => entry.kind === 'SUBSCRIPTION')!;+ const base = product.offers[0];window.electronAPI.billing.getCatalog = vi.fn(async () => ({products: [{- code: 'pro',- name: 'Pro',- kind: 'SUBSCRIPTION' as const,- level: 1,- sortOrder: 1,- offers: [offer('pro_default', '20'), offer('pro_cheaper', '9')],- },- {- code: 'basic',- name: 'Basic',- kind: 'SUBSCRIPTION' as const,- level: 0,- sortOrder: 2,- offers: [offer('basic_default', '5')],+ ...product,+ offers: [+ {+ ...base,+ code: 'monthly_alipay',+ currency: 'cny',+ amount: '80',+ creditAmount: '100',+ purchaseOptions: [+ {+ id: 'ali',+ provider: 'alipay',+ capability: 'MERCHANT_INITIATED_MANDATE' as const,+ paymentAction: 'QR_CODE' as const,+ },+ ],+ },+ {+ ...base,+ code: 'monthly_stripe',+ currency: 'usd',+ amount: '12',+ creditAmount: '15',+ purchaseOptions: [+ {+ id: 'card',+ provider: 'stripe',+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,+ paymentAction: 'REDIRECT' as const,+ },+ ],+ },+ {+ ...base,+ code: 'future',+ name: 'Future price',+ amount: '20',+ salesState: 'COMING_SOON' as const,+ purchasable: false,+ unavailableReason: 'OFFER_COMING_SOON' as const,+ purchaseOptions: [+ {+ id: 'future_card',+ provider: 'stripe',+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,+ paymentAction: 'REDIRECT' as const,+ },+ ],+ },+ ],},],}));- window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => ({ subscription: null }));-render(<BillingPage />);fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));-const dialog = await screen.findByRole('dialog');- const defaultOffer = within(dialog).getByText('$20.00').closest('button')!;- expect(defaultOffer.getAttribute('aria-pressed')).toBe('true');-- fireEvent.click(within(dialog).getByRole('button', { name: /Basic/ }));- const collapsedProduct = within(dialog).getByRole('button', { name: /Pro/ });- expect(within(collapsedProduct).getByText('$20.00')).toBeTruthy();- expect(within(collapsedProduct).queryByText('$9.00')).toBeNull();- expect(within(collapsedProduct).queryByText(/billing\.amount\.startingAt/)).toBeNull();+ const column = within(dialog)+ .getByRole('button', { name: /Configured subscription/ })+ .closest('section')!;+ expect(within(column).getByText(/billing\.comparison\.credits\.MONTH.*100/)).toBeTruthy();+ expect(+ within(column).getByText('billing.comparison.credits.MONTH:{"amount":"$15.00"}'),+ ).toBeTruthy();+ expect(within(column).queryByText('billing.comparison.priceFromSuffix')).toBeNull();+ fireEvent.click(await within(dialog).findByRole('button', { name: /Configured subscription/ }));+ expect(within(dialog).getByText('billing.dialogs.subscription.confirmTitle')).toBeTruthy();+ expect(within(dialog).queryByRole('combobox')).toBeNull();+ expect(within(dialog).queryByText('billing.comparison.renewal')).toBeNull();+ const alipay = within(dialog).getByRole('button', { name: /alipay.*80/ });+ const stripe = within(dialog).getByRole('button', { name: /stripe.*\$12\.00/ });+ const unavailable = within(dialog).getByRole('button', { name: /stripe.*OFFER_COMING_SOON/ });+ expect(unavailable).toHaveProperty('disabled', true);+ fireEvent.click(stripe);+ expect(stripe.getAttribute('aria-pressed')).toBe('true');+ expect(alipay.getAttribute('aria-pressed')).toBe('false');+ expect(+ within(dialog).getByText('billing.comparison.credits.MONTH:{"amount":"$15.00"}'),+ ).toBeTruthy();+ const pay = within(dialog).getByRole('button', { name: /^billing\.actions\.pay/ });+ expect(pay.textContent).toContain('$12.00');+ fireEvent.click(unavailable);+ expect(pay.textContent).toContain('$12.00');+ fireEvent.click(pay);+ expect(checkout.startSubscription).toHaveBeenCalledWith({+ offerCode: 'monthly_stripe',+ purchaseOptionId: 'card',+ });});+ it.each([+ { otherAmount: '9', expectedAmount: '9', expectedCode: 'pro_cheaper', from: true },+ { otherAmount: '20', expectedAmount: '20', expectedCode: 'pro_default', from: false },+ ])(+ 'keeps comparison price, terms and checkout aligned ($otherAmount)',+ async ({ otherAmount, expectedAmount, expectedCode, from }) => {+ const offer = (code: string, amount: string) => ({+ code,+ interval: 'MONTH' as const,+ currency: 'usd',+ amount,+ minAmount: null,+ maxAmount: null,+ creditAmount: String(Number(amount) * 10),+ rolloverCap: String(Number(amount) * 5),+ purchaseOptions: [+ {+ id: `${code}_stripe`,+ provider: 'stripe',+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,+ paymentAction: 'REDIRECT' as const,+ },+ ],+ });+ window.electronAPI.billing.getCatalog = vi.fn(async () => ({+ products: [+ {+ code: 'pro',+ name: 'Pro',+ kind: 'SUBSCRIPTION' as const,+ level: 1,+ sortOrder: 1,+ offers: [offer('pro_default', '20'), offer('pro_cheaper', otherAmount)],+ },+ {+ code: 'basic',+ name: 'Basic',+ kind: 'SUBSCRIPTION' as const,+ level: 0,+ sortOrder: 2,+ offers: [offer('basic_default', '5')],+ },+ ],+ }));+ window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => ({+ subscription: null,+ }));++ render(<BillingPage />);+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));++ const dialog = await screen.findByRole('dialog');+ expect(within(dialog).queryByRole('combobox')).toBeNull();+ const column = within(dialog).getByRole('button', { name: /Pro/ }).closest('section')!;+ const assertComparison = () => {+ const currentColumn = within(dialog)+ .getByRole('button', { name: /Pro/ })+ .closest('section')!;+ expect(currentColumn.textContent).toContain(`$${Number(expectedAmount).toFixed(2)}`);+ expect(+ Boolean(within(currentColumn).queryByText('billing.comparison.priceFromSuffix')),+ ).toBe(from);+ expect(+ within(currentColumn).getByText(+ `billing.comparison.credits.MONTH:{"amount":"$${(Number(expectedAmount) * 10).toFixed(2)}"}`,+ ),+ ).toBeTruthy();+ expect(+ within(currentColumn).getByText(+ `billing.comparison.rollover:{"amount":"$${(Number(expectedAmount) * 5).toFixed(2)}","period":"billing.comparison.nextPeriod.MONTH"}`,+ ),+ ).toBeTruthy();+ };+ assertComparison();+ fireEvent.click(within(column).getByRole('button', { name: /Pro/ }));+ const channels = within(dialog).getAllByRole('button', { name: /stripe.*\$20\.00/ });+ fireEvent.click(channels[0]);+ fireEvent.click(within(dialog).getByRole('button', { name: 'billing.planChange.back' }));+ assertComparison();+ fireEvent.click(within(dialog).getByRole('button', { name: /Pro/ }));+ expect(+ within(dialog).getByRole('button', { name: /^billing\.actions\.pay/ }).textContent,+ ).toContain(`$${Number(expectedAmount).toFixed(2)}`);+ fireEvent.click(within(dialog).getByRole('button', { name: /^billing\.actions\.pay/ }));+ expect(checkout.startSubscription).toHaveBeenCalledWith({+ offerCode: expectedCode,+ purchaseOptionId: `${expectedCode}_stripe`,+ });+ },+ );+it('reselects the first valid Offer in the same Product after a catalog refresh', async () => {const firstOffer = {code: 'pro_month',@@ -1405,24 +1664,19 @@ describe('BillingPage remote catalog rendering', () => {fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));const dialog = await screen.findByRole('dialog');+ expect(within(dialog).queryByRole('combobox')).toBeNull();fireEvent.click(within(dialog).getByRole('button', { name: /Pro/ }));- const secondOfferButton = within(dialog).getByText('$20.00').closest('button')!;- fireEvent.click(secondOfferButton);- expect(secondOfferButton.getAttribute('aria-pressed')).toBe('true');-+ const more = within(dialog).getByRole('button', { name: /stripe.*\$20\.00/ });+ fireEvent.click(more);+ expect(more.getAttribute('aria-pressed')).toBe('true');fireEvent.click(screen.getByText('billing.actions.refreshCatalog'));- await waitFor(() =>- expect(- within(dialog).getByText('$9.00').closest('button')?.getAttribute('aria-pressed'),- ).toBe('true'),- );- expect(within(dialog).queryByText('pro_month')).toBeNull();+ await within(dialog).findByRole('button', { name: /Pro/ });+ expect(within(dialog).getByText('$9.00')).toBeTruthy();+ expect(within(dialog).queryByRole('combobox')).toBeNull();expect(within(dialog).queryByText('$20.00')).toBeNull();-fireEvent.click(screen.getByText('billing.actions.refreshCatalog'));- await waitFor(() => expect(within(dialog).getByRole('button', { name: /Basic/ })).toBeTruthy());- expect(within(dialog).queryByLabelText('settings.back')).toBeNull();- expect(within(dialog).queryByText('$9.00')).toBeNull();+ await within(dialog).findByRole('button', { name: /Basic/ });+ expect(within(dialog).queryByRole('button', { name: /Pro/ })).toBeNull();});it.each(['INCOMPLETE', 'CANCELED', 'INCOMPLETE_EXPIRED'] as const)(@@ -1447,7 +1701,11 @@ describe('BillingPage remote catalog rendering', () => {expect(screen.queryByText(`billing.subscriptionStatus.${status}`)).toBeNull();fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));- fireEvent.click((await screen.findByText('Configured subscription')).closest('button')!);+ fireEvent.click(+ (await screen.findByText('Configured subscription'))+ .closest('section')!+ .querySelector('button')!,+ );fireEvent.click(screen.getByText('stripe').closest('button')!);fireEvent.click(screen.getByText('billing.actions.pay'));@@ -1524,7 +1782,7 @@ describe('BillingPage remote catalog rendering', () => {).toHaveProperty('disabled', true);});- it('renders single-Offer subscription Products as direct rows', async () => {+ it('renders subscription Products side by side and chooses their payment channels', async () => {window.electronAPI.billing.getCatalog = vi.fn(async () => ({products: (['alipay', 'stripe', 'alipay'] as const).map((provider, index) => ({code: `plan_${index + 1}`,@@ -1564,44 +1822,16 @@ describe('BillingPage remote catalog rendering', () => {const planButtons = await screen.findAllByRole('button', { name: /Remote plan/ });expect(planButtons).toHaveLength(3);- expect(planButtons.map((button) => button.getAttribute('aria-pressed'))).toEqual([- 'true',- 'false',- 'false',- ]);- expect(planButtons.map((button) => button.getAttribute('aria-expanded'))).toEqual([- null,- null,- null,- ]);- expect(within(planButtons[0]).getByText(/1\.00/)).toBeTruthy();- expect(within(planButtons[0]).queryByText(/billing\.amount\.startingAt/)).toBeNull();- const firstPlanCredits = new Intl.NumberFormat('en', {- style: 'currency',- currency: 'CNY',- }).format(100);- expect(- within(planButtons[0]).getByText(`billing.credits:{"amount":"${firstPlanCredits}"}`),- ).toBeTruthy();- expect(screen.queryByText('plan_1_month')).toBeNull();- expect(screen.getByText('alipay')).toBeTruthy();+ expect(screen.getByText('billing.comparison.free')).toBeTruthy();expect(screen.queryByText('stripe')).toBeNull();-+ expect(screen.queryByText('alipay')).toBeNull();fireEvent.click(planButtons[1]);- expect(screen.queryByText('plan_1_month')).toBeNull();- expect(- (await screen.findAllByRole('button', { name: /Remote plan/ })).map((button) =>- button.getAttribute('aria-pressed'),- ),- ).toEqual(['false', 'true', 'false']);- expect(- screen- .getAllByRole('button', { name: /Remote plan/ })- .map((button) => button.getAttribute('aria-expanded')),- ).toEqual([null, null, null]);- expect(screen.queryByText('plan_2_month')).toBeNull();expect(await screen.findByText('stripe')).toBeTruthy();expect(screen.queryByText('alipay')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'billing.planChange.back' }));+ fireEvent.click(screen.getAllByRole('button', { name: /Remote plan/ })[0]);+ expect(screen.getByText('alipay')).toBeTruthy();+ expect(screen.queryByText('stripe')).toBeNull();});it('allows an uncertain failed checkout to be dismissed for later recovery', async () => {@@ -2081,8 +2311,13 @@ describe('BillingPage plan change', () => {await waitFor(() => expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(2));await selectSubscriptionManagementAction('billing.settings.subscriptionCard.changeAction');- expect(await screen.findByText('Alipay-only Max')).toBeTruthy();+ const alipayTarget = await screen.findByText('Alipay-only Max');+ expect(alipayTarget.closest('section')!.querySelector('button')).toHaveProperty(+ 'disabled',+ false,+ );expect(screen.queryByText('Max plan')).toBeNull();+ expect(billing.quotePlanChange).not.toHaveBeenCalled();});it('keeps the completed checkout subscription when the canonical reload temporarily fails', async () => {@@ -2232,7 +2467,7 @@ describe('BillingPage plan change', () => {).toBeTruthy();});- it('offers same-provider monthly Products in Catalog order', async () => {+ it('orders comparison Products by server sortOrder and hides unavailable offers and other providers', async () => {const billing = install(billingMocks());billing.quotePlanChange.mockResolvedValue({planChangeId: 'plan_change_1',@@ -2250,20 +2485,31 @@ describe('BillingPage plan change', () => {await screen.findByText('billing.planChange.targetTitle');const dialog = screen.getByRole('dialog');- const maxButton = screen.getByText('Max plan').closest('button')!;- const sameLevelButton = screen.getByText('Same-level plan').closest('button')!;- const starterButton = screen.getByText('Starter plan').closest('button')!;+ const maxButton = screen.getByText('Max plan').closest('section')!.querySelector('button')!;+ const sameLevelButton = screen+ .getByText('Same-level plan')+ .closest('section')!+ .querySelector('button')!;+ const starterButton = screen+ .getByText('Starter plan')+ .closest('section')!+ .querySelector('button')!;expect(- maxButton.compareDocumentPosition(sameLevelButton) & Node.DOCUMENT_POSITION_FOLLOWING,+ starterButton.compareDocumentPosition(maxButton) & Node.DOCUMENT_POSITION_FOLLOWING,).toBe(Node.DOCUMENT_POSITION_FOLLOWING);expect(sameLevelButton.compareDocumentPosition(starterButton) & Node.DOCUMENT_POSITION_FOLLOWING,).toBe(Node.DOCUMENT_POSITION_FOLLOWING);- expect(within(maxButton).getByText('billing.planChange.upgradeBadge')).toBeTruthy();- expect(within(dialog).getByText('billing.catalog.currentPlan')).toBeTruthy();- expect(within(maxButton).getByText('stripe')).toBeTruthy();- expect(within(sameLevelButton).getByText('billing.planChange.sameLevelBadge')).toBeTruthy();- expect(within(starterButton).getByText('billing.planChange.downgradeBadge')).toBeTruthy();+ expect(maxButton.textContent).toContain('billing.comparison.upgrade');+ expect(+ within(dialog).getByRole('button', { name: 'billing.catalog.currentPlan' }),+ ).toBeTruthy();+ expect(+ within(maxButton.closest('section')!).queryByText('billing.comparison.upgradeHint'),+ ).toBeNull();+ expect(sameLevelButton.textContent).toBe('billing.comparison.changeUnavailable');+ expect(sameLevelButton).toHaveProperty('disabled', true);+ expect(starterButton.textContent).toContain('billing.comparison.downgrade');expect(screen.queryByText('Alipay-only Max')).toBeNull();expect(screen.queryByText('Coming soon Max')).toBeNull();@@ -2296,6 +2542,36 @@ describe('BillingPage plan change', () => {expect(modelCatalogMocks.refreshBuiltinProviderModels).toHaveBeenCalledWith('xd');});+ it('opens change plans for a canceled Alipay subscription still in its paid period', async () => {+ routerState.search = 'tab=billing&intent=subscribe';+ const billing = billingMocks();+ const base = activeSubscription(null, 'MONTH', 'ACTIVE', true);+ billing.getCurrentSubscription = vi.fn(async () => ({+ subscription: {+ ...base,+ provider: 'alipay',+ currentPeriodEndAt: '2099-08-01T00:00:00Z',+ effectivePlan: {+ ...base.effectivePlan!,+ terms: { ...base.effectivePlan!.terms, currency: 'cny' },+ },+ },+ }));+ install(billing);+ render(<BillingPage />);+ await screen.findByText('billing.planChange.targetTitle');+ expect(screen.getByRole('button', { name: 'billing.catalog.currentPlan' })).toHaveProperty(+ 'disabled',+ true,+ );+ expect(+ screen.getByText('Alipay-only Max').closest('section')!.querySelector('button'),+ ).toHaveProperty('disabled', false);+ expect(screen.queryByText('billing.comparison.resignUpgradeHint')).toBeNull();+ expect(screen.queryByText('billing.comparison.cancelHint')).toBeNull();+ expect(checkout.startSubscription).not.toHaveBeenCalled();+ });+it('深链 ?intent=plan-change 在有更改入口时打开目标弹窗并摘掉参数', async () => {routerState.search = 'tab=billing&intent=plan-change';install(billingMocks());@@ -2350,7 +2626,7 @@ describe('BillingPage plan change', () => {expect(new URLSearchParams(routerState.search).get('intent')).toBeNull();});- it('quotes the selected same-Product monthly Offer', async () => {+ it('keeps the current plan disabled when another Offer belongs to the same Product', async () => {const billing = billingMocks();billing.getCatalog = vi.fn(async () => ({products: [@@ -2416,19 +2692,20 @@ describe('BillingPage plan change', () => {render(<BillingPage />);await selectSubscriptionManagementAction('billing.settings.subscriptionCard.changeAction');- const productButton = screen- .getAllByText('Plus plan')- .map((element) => element.closest('button'))- .find((button): button is HTMLButtonElement => button !== null)!;- expect(productButton).toHaveProperty('disabled', false);- fireEvent.click(productButton);-- await waitFor(() =>- expect(billing.quotePlanChange).toHaveBeenCalledWith({- targetOfferCode: 'plus_month_more',- idempotencyKey: 'desktop:plan-change:00000000-0000-4000-8000-000000000042',+ const dialog = await screen.findByRole('dialog');+ expect(within(dialog).queryByRole('combobox')).toBeNull();+ const currentButton = within(dialog).getByRole('button', {+ name: 'billing.catalog.currentPlan',+ });+ expect(currentButton).toHaveProperty('disabled', true);+ fireEvent.click(currentButton);+ expect(billing.quotePlanChange).not.toHaveBeenCalled();+ expect(+ within(dialog).queryByRole('button', {+ name: 'billing.settings.subscriptionCard.changeAction',}),- );+ ).toBeNull();+ expect(within(dialog).queryByRole('button', { name: /\$20\.00/ })).toBeNull();});it('opens a Stripe plan-change redirect automatically once and keeps the manual fallback', async () => {@@ -2461,7 +2738,9 @@ describe('BillingPage plan change', () => {render(<BillingPage />);await selectSubscriptionManagementAction('billing.settings.subscriptionCard.changeAction');- fireEvent.click((await screen.findByText('Max plan')).closest('button')!);+ fireEvent.click(+ (await screen.findByText('Max plan')).closest('section')!.querySelector('button')!,+ );fireEvent.click(await screen.findByText('billing.planChange.confirm'));await waitFor(() => expect(billing.openPaymentRedirect).toHaveBeenCalledWith({ url }));@@ -2491,9 +2770,13 @@ describe('BillingPage plan change', () => {await selectSubscriptionManagementAction('billing.settings.subscriptionCard.changeAction');const dialog = await screen.findByRole('dialog');- expect(within(dialog).getByText('billing.catalog.currentPlan')).toBeTruthy();+ expect(+ within(dialog).getByRole('button', { name: 'billing.catalog.currentPlan' }),+ ).toHaveProperty('disabled', true);expect(within(dialog).getByText('$7.00')).toBeTruthy();- expect(within(dialog).getByText('billing.credits:{"amount":"$80.00"}')).toBeTruthy();+ expect(+ within(dialog).getByText('billing.comparison.credits.MONTH:{"amount":"$80.00"}'),+ ).toBeTruthy();});it('does not expose plan change for yearly subscriptions while server v1 is monthly-only', async () => {@@ -2526,7 +2809,9 @@ describe('BillingPage plan change', () => {render(<BillingPage />);await selectSubscriptionManagementAction('billing.settings.subscriptionCard.changeAction');- expect(await screen.findByText('billing.planChange.emptyTitle')).toBeTruthy();+ expect(+ await screen.findByRole('button', { name: 'billing.catalog.currentPlan' }),+ ).toHaveProperty('disabled', true);expect(screen.queryByText('Max plan')).toBeNull();expect(billing.quotePlanChange).not.toHaveBeenCalled();});@@ -2583,8 +2868,10 @@ describe('BillingPage plan change', () => {render(<BillingPage />);fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));- fireEvent.click((await screen.findAllByText('Plus plan'))[0].closest('button')!);- fireEvent.click(screen.getByText('stripe').closest('button')!);+ fireEvent.click(+ within(await screen.findByRole('dialog')).getByRole('button', { name: /Plus plan/ }),+ );+ fireEvent.click(screen.getAllByText('stripe')[0].closest('button')!);const pay = screen.getByText('billing.actions.pay').closest('button')!;expect(pay).toHaveProperty('disabled', false);fireEvent.click(pay);@@ -2629,8 +2916,10 @@ describe('BillingPage plan change', () => {expect(billing.getCurrentSubscription.mock.calls.length).toBeGreaterThan(1),);fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));- fireEvent.click((await screen.findAllByText('Plus plan'))[0].closest('button')!);- fireEvent.click(screen.getByText('stripe').closest('button')!);+ fireEvent.click(+ within(await screen.findByRole('dialog')).getByRole('button', { name: /Plus plan/ }),+ );+ fireEvent.click(screen.getAllByText('stripe')[0].closest('button')!);expect(screen.getByText('billing.actions.pay').closest('button')).toHaveProperty('disabled',false,@@ -2647,12 +2936,11 @@ describe('BillingPage plan change', () => {render(<BillingPage />);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(- 'disabled',- true,+ fireEvent.click(+ within(await screen.findByRole('dialog')).getByRole('button', { name: /Plus plan/ }),);+ expect(screen.queryByText('billing.actions.pay')).toBeNull();+ expect(checkout.startSubscription).not.toHaveBeenCalled();expect(screen.getByText('billing.currentSubscription.purchaseBlocked')).toBeTruthy();});@@ -2666,12 +2954,11 @@ describe('BillingPage plan change', () => {render(<BillingPage />);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(- 'disabled',- true,+ fireEvent.click(+ within(await screen.findByRole('dialog')).getByRole('button', { name: /Plus plan/ }),);+ expect(screen.queryByText('billing.actions.pay')).toBeNull();+ expect(checkout.startSubscription).not.toHaveBeenCalled();expect(screen.getByText(/billing\.currentSubscription\.purchaseBlockedUntilPeriodEnd/),).toBeTruthy();@@ -2692,8 +2979,9 @@ describe('BillingPage plan change', () => {render(<BillingPage />);await selectSubscriptionManagementAction('billing.settings.subscriptionCard.action');- fireEvent.click((await screen.findAllByText('Plus plan'))[0].closest('button')!);- fireEvent.click(screen.getByText('stripe').closest('button')!);+ fireEvent.click(+ within(await screen.findByRole('dialog')).getByRole('button', { name: /Plus plan/ }),+ );expect(screen.getByText('billing.currentSubscription.purchaseBlocked')).toBeTruthy();expect(screen.queryByText(/purchaseBlockedUntilPeriodEnd/)).toBeNull();});@@ -2793,7 +3081,9 @@ describe('BillingPage plan change', () => {render(<BillingPage />);await selectSubscriptionManagementAction('billing.settings.subscriptionCard.changeAction');- fireEvent.click(await screen.findByText('Max plan'));+ fireEvent.click(+ (await screen.findByText('Max plan')).closest('section')!.querySelector('button')!,+ );expect(await screen.findByText('billing.planChange.quoteRejected')).toBeTruthy();fireEvent.click(screen.getByText('billing.planChange.chooseAnotherPlan'));@@ -3007,7 +3297,9 @@ describe('BillingPage order history', () => {expect(screen.getByText('billing.orders.invoice.fields.email')).toBeTruthy();fireEvent.click(supportEmailButton);- await waitFor(() => expect(uiMocks.clipboardWriteText).toHaveBeenCalledWith('[email protected]'));+ await waitFor(() =>+ expect(uiMocks.clipboardWriteText).toHaveBeenCalledWith('[email protected]'),+ );expect(uiMocks.toastSuccess).toHaveBeenCalledWith('billing.orders.invoice.emailCopied');fireEvent.click(screen.getByRole('button', { name: 'billing.orders.invoice.sendAction' }));@@ -3131,9 +3423,7 @@ describe('BillingPage order history', () => {name: 'billing.orders.invoice.action',});expect(invoiceButtons).toHaveLength(1);- expect(invoiceButtons[0].closest('[role="listitem"]')?.textContent).toContain(- 'o-com****leted',- );+ expect(invoiceButtons[0].closest('[role="listitem"]')?.textContent).toContain('o-com****leted');});it('copies the complete order id from both the id text and copy icon', async () => {diff --git a/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsxindex f6aad2a2a7..a5c9939cdc 100644--- a/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx+++ b/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx@@ -21,6 +21,7 @@ import {type PlanChangeCandidate,} from '../PlanChangeDialog';import type { PlanChangeState } from '../usePlanChange';+import { PlanComparison } from '../PlanComparison';function quoteReadyState(overrides: Partial<PlanChangeState> = {}): PlanChangeState {return {@@ -253,28 +254,27 @@ describe('PlanChangeTargetDialog product-first selection', () => {},];- it('submits a Product with one alternative Offer directly', () => {+ it('keeps the current plan disabled without a price selector', () => {const onSelect = vi.fn();render(<PlanChangeTargetDialogopencurrentPlan={currentPlan}- candidates={candidates}+ candidates={candidates.slice(1)}onClose={vi.fn()}onSelect={onSelect}/>,);-- const proProduct = screen- .getAllByText('Pro')- .map((element) => element.closest('button'))- .find((button): button is HTMLButtonElement => button !== null)!;- expect(proProduct).toHaveProperty('disabled', false);- fireEvent.click(proProduct);- expect(onSelect).toHaveBeenCalledWith(candidates[0]);+ expect(screen.getByRole('button', { name: 'billing.catalog.currentPlan' })).toHaveProperty(+ 'disabled',+ true,+ );+ expect(screen.queryByRole('combobox')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'billing.catalog.currentPlan' }));+ expect(onSelect).not.toHaveBeenCalled();});- it('defaults to the first Offer in server order and lets the user switch before submitting', () => {+ it('keeps alternative server offers selectable after the plan action without a dropdown', () => {const onSelect = vi.fn();render(<PlanChangeTargetDialog@@ -285,58 +285,252 @@ describe('PlanChangeTargetDialog product-first selection', () => {onSelect={onSelect}/>,);-- fireEvent.click(screen.getByText('Max').closest('button')!);-- const firstOffer = screen.getByText('$20.00').closest('button')!;- const secondOffer = screen.getByText('$200.00').closest('button')!;- expect(screen.queryByText('max_month')).toBeNull();+ expect(screen.queryByRole('combobox')).toBeNull();+ expect(screen.queryByText('max_month_more')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: /billing.comparison.upgrade.*Max/ }));+ expect(onSelect).not.toHaveBeenCalled();+ expect(screen.queryByRole('combobox')).toBeNull();expect(screen.queryByText('max_month_more')).toBeNull();- expect(firstOffer.getAttribute('aria-pressed')).toBe('true');- expect(secondOffer.getAttribute('aria-pressed')).toBe('false');- expect(screen.getByText('billing.planChange.back').closest('button')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: /\$200\.00/ }));+ expect(onSelect).toHaveBeenCalledWith(candidates[2]);+ });- const submitButton = screen- .getByText('billing.settings.subscriptionCard.changeAction')- .closest('button')!;- expect(submitButton.className).toContain('bg-[var(--accent-cta-bg)]');- expect(submitButton.className).toContain('text-[var(--accent-pure-cta-fg)]');+ it('keeps the current contract as the action instead of offering unsupported same-level changes', () => {+ const onSelect = vi.fn();+ render(+ <PlanChangeTargetDialog+ open+ currentPlan={currentPlan}+ candidates={candidates.map((candidate) =>+ candidate.direction === 'SAME_LEVEL' ? { ...candidate, available: false } : candidate,+ )}+ onClose={vi.fn()}+ onSelect={onSelect}+ />,+ );+ expect(screen.getByText('$9.00')).toBeTruthy();+ const button = screen.getByRole('button', { name: 'billing.catalog.currentPlan' });+ expect(button).toHaveProperty('disabled', true);+ fireEvent.click(button);+ expect(onSelect).not.toHaveBeenCalled();+ expect(+ screen.queryByRole('button', { name: 'billing.settings.subscriptionCard.changeAction' }),+ ).toBeNull();+ });- fireEvent.click(secondOffer);- fireEvent.click(submitButton);- expect(onSelect).toHaveBeenCalledWith(candidates[2]);+ it('uses the current offer action even when a cheaper offer is displayed', () => {+ const onSelect = vi.fn();+ render(+ <PlanComparison+ plans={[+ {+ product: currentPlan.product,+ defaultOfferCode: 'cheaper',+ offers: [+ {+ offer: { ...currentPlan.offer, code: 'cheaper', amount: '1' },+ action: 'Select',+ onSelect,+ },+ { offer: currentPlan.offer, current: true, action: 'Current', onSelect },+ ],+ },+ ]}+ freeAction="Top up"+ freeHint=""+ onFreeAction={vi.fn()}+ />,+ );+ expect(screen.getByText('$1.00')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Current' })).toHaveProperty('disabled', true);+ expect(screen.queryByRole('button', { name: 'Select' })).toBeNull();});- it('returns to the Product list when the selected Product disappears', async () => {+ it('uses the remaining server Offer when the default Offer disappears', () => {+ const onSelect = vi.fn();const view = render(<PlanChangeTargetDialogopencurrentPlan={currentPlan}candidates={candidates}onClose={vi.fn()}- onSelect={vi.fn()}+ onSelect={onSelect}/>,);+ expect(screen.queryByRole('combobox')).toBeNull();+ view.rerender(+ <PlanChangeTargetDialog+ open+ currentPlan={currentPlan}+ candidates={[candidates[0], candidates[2]]}+ onClose={vi.fn()}+ onSelect={onSelect}+ />,+ );+ fireEvent.click(screen.getByRole('button', { name: /billing.comparison.upgrade.*Max/ }));+ expect(onSelect).toHaveBeenCalledWith(candidates[2]);+ });- fireEvent.click(screen.getByText('Max').closest('button')!);+ it.each(['OFFER_COMING_SOON', 'NO_AVAILABLE_PAYMENT_CHANNEL'] as const)(+ 'preserves the server unavailable reason %s in plan comparison',+ (unavailableReason) => {+ const onSelect = vi.fn();+ render(+ <PlanChangeTargetDialog+ open+ currentPlan={currentPlan}+ candidates={[{ ...candidates[1], available: false, unavailableReason }]}+ onClose={vi.fn()}+ onSelect={onSelect}+ />,+ );+ expect(+ screen.getByText(`billing.catalog.unavailableReasons.${unavailableReason}`),+ ).toBeTruthy();+ expect(screen.getByText('billing.planChange.emptyTitle')).toBeTruthy();+ const button = screen.getByRole('button', {+ name: `billing.catalog.unavailableReasons.${unavailableReason}`,+ });+ expect(button).toHaveProperty('disabled', true);+ fireEvent.click(button);+ expect(onSelect).not.toHaveBeenCalled();+ },+ );++ it.each([+ { amounts: ['90', '100'], from: true },+ { amounts: ['100', '100'], from: false },+ ])('summarizes available target prices $amounts', ({ amounts, from }) => {+ const onSelect = vi.fn();+ const offers = [candidates[1], candidates[2]].map((candidate, index) => ({+ ...candidate,+ offer: { ...candidate.offer, amount: amounts[index] },+ }));+ render(+ <PlanChangeTargetDialog+ open+ currentPlan={currentPlan}+ candidates={[...offers].reverse()}+ onClose={vi.fn()}+ onSelect={onSelect}+ />,+ );+ expect(Boolean(screen.queryByText('billing.comparison.priceFromSuffix'))).toBe(from);+ fireEvent.click(screen.getByRole('button', { name: /billing.comparison.upgrade.*Max/ }));+ expect(onSelect).not.toHaveBeenCalled();+ expect(screen.getAllByRole('button', { name: /billing.providers.stripe/ })).toHaveLength(2);+ });++ it('excludes unavailable lower prices and keeps the target stable while refreshing', () => {+ const onSelect = vi.fn();+ const offers = [{ ...candidates[1], available: false }, candidates[2]];+ const view = render(+ <PlanChangeTargetDialog+ open+ currentPlan={currentPlan}+ candidates={offers}+ onClose={vi.fn()}+ onSelect={onSelect}+ disabled+ />,+ );expect(screen.getByText('$200.00')).toBeTruthy();+ expect(screen.queryByText('billing.comparison.priceFromSuffix')).toBeNull();+ expect(screen.getByRole('button', { name: /billing.comparison.upgrade.*Max/ })).toHaveProperty(+ 'disabled',+ true,+ );+ view.rerender(+ <PlanChangeTargetDialog+ open+ currentPlan={currentPlan}+ candidates={offers}+ onClose={vi.fn()}+ onSelect={onSelect}+ />,+ );+ fireEvent.click(screen.getByRole('button', { name: /billing.comparison.upgrade.*Max/ }));+ expect(onSelect).toHaveBeenCalledWith(candidates[2]);+ });+ it('defaults to an available offer when the first offer in a target product is unavailable', () => {+ const onSelect = vi.fn();+ render(+ <PlanChangeTargetDialog+ open+ currentPlan={currentPlan}+ candidates={[{ ...candidates[1], available: false }, candidates[2]]}+ onClose={vi.fn()}+ onSelect={onSelect}+ />,+ );+ const button = screen.getByRole('button', { name: /billing.comparison.upgrade.*Max/ });+ expect(button).toHaveProperty('disabled', false);+ fireEvent.click(button);+ expect(onSelect).toHaveBeenCalledWith(candidates[2]);+ });++ it('disables topup during catalog refresh and re-enables it when ready', () => {+ const onSelect = vi.fn();+ const onTopup = vi.fn();+ const view = render(+ <PlanChangeTargetDialog+ open+ currentPlan={currentPlan}+ candidates={[candidates[1]]}+ onClose={vi.fn()}+ onSelect={onSelect}+ onTopup={onTopup}+ topupDisabled+ disabled+ />,+ );+ const button = screen.getByRole('button', { name: /billing.comparison.upgrade.*Max/ });+ expect(button).toHaveProperty('disabled', true);+ expect(button.hasAttribute('aria-pressed')).toBe(false);+ expect(button.className).not.toContain('accent-cta');+ const free = screen.getByRole('button', { name: 'billing.comparison.topup' });+ expect(free).toHaveProperty('disabled', true);+ fireEvent.click(button);+ fireEvent.click(free);+ expect(onSelect).not.toHaveBeenCalled();+ expect(onTopup).not.toHaveBeenCalled();view.rerender(<PlanChangeTargetDialogopencurrentPlan={currentPlan}- candidates={[candidates[0]]}+ candidates={[]}onClose={vi.fn()}- onSelect={vi.fn()}+ onSelect={onSelect}+ onTopup={onTopup}/>,);+ expect(screen.getByRole('button', { name: 'billing.comparison.topup' })).toHaveProperty(+ 'disabled',+ false,+ );+ fireEvent.click(screen.getByRole('button', { name: 'billing.comparison.topup' }));+ expect(onTopup).toHaveBeenCalledOnce();+ });- expect(await screen.findByText('billing.planChange.targetTitle')).toBeTruthy();- const proProduct = screen- .getAllByText('Pro')- .map((element) => element.closest('button'))- .find((button): button is HTMLButtonElement => button !== null)!;- expect(proProduct).toHaveProperty('disabled', false);- expect(screen.queryByLabelText('settings.back')).toBeNull();+ it('keeps unavailable plans visible without quoting and routes FREE to topup', () => {+ const onSelect = vi.fn();+ const onTopup = vi.fn();+ render(+ <PlanChangeTargetDialog+ open+ currentPlan={currentPlan}+ candidates={[{ ...candidates[1], available: false }]}+ onClose={vi.fn()}+ onSelect={onSelect}+ onTopup={onTopup}+ />,+ );+ const upgrade = screen.getByRole('button', { name: 'billing.comparison.changeUnavailable' });+ expect(upgrade).toHaveProperty('disabled', true);+ fireEvent.click(upgrade);+ expect(onSelect).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'billing.comparison.topup' }));+ expect(onTopup).toHaveBeenCalledOnce();});});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 213d55c63d..6f9974c875 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -12170,6 +12170,38 @@}},"billing": {+ "comparison": {+ "free": "FREE",+ "freeUsage": "Free to use",+ "priceFromSuffix": "and up",+ "topup": "Top up as needed",+ "topupExpiry": "Top-up credits never expire",+ "agent": "Full Agent features",+ "apiKey": "Bring your own API key",+ "existingSubscription": "Connect existing subscriptions",+ "localModels": "Use local models",+ "basicModels": "Access basic models",+ "subscription": "Subscription plan",+ "rollover": "Keep up to {{amount}} in unused credits for {{period}}",+ "nextPeriod": {+ "MONTH": "next month",+ "YEAR": "next year",+ "OTHER": "the next period"+ },+ "includesFree": "Everything in FREE",+ "advancedModels": "Unlock advanced models",+ "managedService": "Managed service, no setup",+ "topupUnlock": "Pay as you go to unlock advanced models",+ "select": "Choose {{name}}",+ "upgrade": "Upgrade to {{name}}",+ "downgrade": "Downgrade to {{name}}",+ "changeUnavailable": "Unavailable",+ "creditMultiple": "{{multiple}}× the period credits of {{name}}",+ "credits": {+ "MONTH": "{{amount}} credits each month",+ "YEAR": "{{amount}} credits each year"+ }+ },"sidebar": "Balance & Plans","settings": {"title": "Usage and billing",@@ -12223,7 +12255,7 @@"observedAt": "Balance updated {{date}}","poolDetail": "Used {{used}} · Total {{total}}","remaining": "Remaining",- "progressLabel": "{{label}} usage",+ "progressLabel": "{{label}} remaining percentage","noPlanCredits": "No plan balance because there is no active subscription.","historyUnavailable": "Usage history is incomplete. Only the remaining balance is available.","detailsUnavailable": "Usage details are temporarily unavailable. Current balances are shown instead.",@@ -12292,6 +12324,7 @@},"dialogs": {"subscription": {+ "confirmTitle": "Confirm subscription","title": "Choose a subscription plan"},"topup": {@@ -12384,13 +12417,9 @@"failedBody": "Payment failed. Try again later or contact support."},"planChange": {+ "emptyTitle": "No plans available to switch to","targetTitle": "Change subscription plan","back": "Back",- "upgradeBadge": "Upgrade",- "sameLevelBadge": "Same tier",- "downgradeBadge": "Downgrade",- "emptyTitle": "No plans available to switch to",- "emptyDescription": "There are no other plans available to switch to.","quotingTitle": "Preparing plan change","quotingBody": "Confirming the price and effective time…","quoteTitle": "Confirm plan change",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex ae9e0c4107..6310d96fb0 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -12153,6 +12153,38 @@}},"billing": {+ "comparison": {+ "free": "FREE",+ "freeUsage": "無料で利用",+ "priceFromSuffix": "〜",+ "topup": "必要な分だけチャージ",+ "topupExpiry": "チャージしたクレジットは無期限",+ "agent": "Agent の全機能",+ "apiKey": "自分の API key を使用",+ "existingSubscription": "既存のサブスクリプションを接続",+ "localModels": "ローカルモデルに対応",+ "basicModels": "基本モデルを利用",+ "subscription": "サブスクリプション",+ "rollover": "未使用クレジットは{{period}}も利用可能(最大 {{amount}})",+ "nextPeriod": {+ "MONTH": "翌月",+ "YEAR": "翌年",+ "OTHER": "次の期間"+ },+ "includesFree": "FREE の全機能を含む",+ "advancedModels": "上位モデルを利用可能に",+ "managedService": "公式サービス、設定不要",+ "topupUnlock": "必要な分だけ支払い、上位モデルを利用",+ "select": "{{name}} を選択",+ "upgrade": "{{name}} にアップグレード",+ "downgrade": "{{name}} にダウングレード",+ "changeUnavailable": "変更不可",+ "creditMultiple": "{{name}} の {{multiple}} 倍の期間クレジット",+ "credits": {+ "MONTH": "毎月 {{amount}} のクレジット",+ "YEAR": "毎年 {{amount}} のクレジット"+ }+ },"sidebar": "残高とプラン","settings": {"title": "使用量と請求",@@ -12206,7 +12238,7 @@"observedAt": "残高更新: {{date}}","poolDetail": "使用済み {{used}} · 合計 {{total}}","remaining": "残り",- "progressLabel": "{{label}}の使用量",+ "progressLabel": "{{label}}の残りの割合","noPlanCredits": "有効なサブスクリプションがないため、プラン残高はありません。","historyUnavailable": "使用履歴が完全ではないため、残りの残高のみ表示しています。","detailsUnavailable": "使用量の詳細を取得できないため、現在の残高のみ表示しています。",@@ -12275,6 +12307,7 @@},"dialogs": {"subscription": {+ "confirmTitle": "サブスクリプションの確認","title": "サブスクリプションプランを選択"},"topup": {@@ -12367,13 +12400,9 @@"failedBody": "支払いに失敗しました。しばらくしてからもう一度お試しください。"},"planChange": {+ "emptyTitle": "切り替え可能なプランがありません","targetTitle": "サブスクリプションプランの変更","back": "戻る",- "upgradeBadge": "アップグレード",- "sameLevelBadge": "同じレベル",- "downgradeBadge": "ダウングレード",- "emptyTitle": "切り替え可能なプランがありません",- "emptyDescription": "現在、切り替え可能な他のプランはありません。","quotingTitle": "プラン変更を準備中","quotingBody": "金額と適用時期を確認しています…","quoteTitle": "プラン変更の確認",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 55f1716d11..684bb83aca 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -12153,6 +12153,38 @@}},"billing": {+ "comparison": {+ "free": "FREE",+ "freeUsage": "무료 사용",+ "priceFromSuffix": "부터",+ "topup": "필요할 때 충전",+ "topupExpiry": "충전 크레딧은 만료되지 않음",+ "agent": "모든 Agent 기능",+ "apiKey": "내 API key 사용",+ "existingSubscription": "기존 구독 연결",+ "localModels": "로컬 모델 지원",+ "basicModels": "기본 모델 사용",+ "subscription": "구독 요금제",+ "rollover": "남은 크레딧은 {{period}}에 최대 {{amount}}까지 사용 가능",+ "nextPeriod": {+ "MONTH": "다음 달",+ "YEAR": "다음 해",+ "OTHER": "다음 기간"+ },+ "includesFree": "FREE의 모든 기능 포함",+ "advancedModels": "고급 모델 잠금 해제",+ "managedService": "공식 서비스, 설정 불필요",+ "topupUnlock": "필요한 만큼 결제하고 고급 모델 사용",+ "select": "{{name}} 선택",+ "upgrade": "{{name}}(으)로 업그레이드",+ "downgrade": "{{name}}(으)로 다운그레이드",+ "changeUnavailable": "변경 불가",+ "creditMultiple": "{{name}} 대비 {{multiple}}배의 기간 크레딧",+ "credits": {+ "MONTH": "매월 {{amount}} 크레딧",+ "YEAR": "매년 {{amount}} 크레딧"+ }+ },"sidebar": "잔액 및 요금제","settings": {"title": "사용량 및 결제",@@ -12206,7 +12238,7 @@"observedAt": "잔액 업데이트: {{date}}","poolDetail": "사용 {{used}} · 전체 {{total}}","remaining": "잔여",- "progressLabel": "{{label}} 사용량",+ "progressLabel": "{{label}} 잔여 비율","noPlanCredits": "활성 구독이 없어 요금제 잔액이 없습니다.","historyUnavailable": "사용 기록이 완전하지 않아 잔여 잔액만 표시합니다.","detailsUnavailable": "사용량 상세를 불러올 수 없어 현재 잔액만 표시합니다.",@@ -12275,6 +12307,7 @@},"dialogs": {"subscription": {+ "confirmTitle": "구독 확인","title": "구독 요금제 선택"},"topup": {@@ -12367,13 +12400,9 @@"failedBody": "결제에 실패했습니다. 나중에 다시 시도하세요."},"planChange": {+ "emptyTitle": "전환 가능한 플랜이 없습니다","targetTitle": "구독 플랜 변경","back": "이전",- "upgradeBadge": "업그레이드",- "sameLevelBadge": "동일 등급",- "downgradeBadge": "다운그레이드",- "emptyTitle": "전환 가능한 플랜이 없습니다",- "emptyDescription": "현재 전환할 수 있는 다른 요금제가 없습니다.","quotingTitle": "플랜 변경 준비 중","quotingBody": "금액과 적용 시점을 확인하는 중…","quoteTitle": "플랜 변경 확인",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 3b5c46055d..49224c5ebc 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -12153,6 +12153,38 @@}},"billing": {+ "comparison": {+ "free": "FREE",+ "freeUsage": "免费使用",+ "priceFromSuffix": "起",+ "topup": "按需充值",+ "topupExpiry": "充值点数不过期",+ "agent": "完整 Agent 功能",+ "apiKey": "自带 API key",+ "existingSubscription": "接入已有订阅",+ "localModels": "支持本地模型",+ "basicModels": "可用基础模型",+ "subscription": "订阅套餐",+ "rollover": "剩余点数可留到{{period}},最多 {{amount}}",+ "nextPeriod": {+ "MONTH": "下月",+ "YEAR": "下一年",+ "OTHER": "下期"+ },+ "includesFree": "包含 FREE 全部能力",+ "advancedModels": "解锁高级模型",+ "managedService": "官方服务,免配置",+ "topupUnlock": "按需付费,解锁高级模型",+ "select": "选择 {{name}}",+ "upgrade": "升级至 {{name}}",+ "downgrade": "降级至 {{name}}",+ "changeUnavailable": "暂不可切换",+ "creditMultiple": "{{name}} 的 {{multiple}} 倍周期点数",+ "credits": {+ "MONTH": "每月 {{amount}} 点数",+ "YEAR": "每年 {{amount}} 点数"+ }+ },"sidebar": "余额与订阅","settings": {"title": "用量和计费",@@ -12206,7 +12238,7 @@"observedAt": "余额更新于 {{date}}","poolDetail": "已用 {{used}} · 总额 {{total}}","remaining": "剩余",- "progressLabel": "{{label}}使用进度",+ "progressLabel": "{{label}}剩余比例","noPlanCredits": "当前无生效订阅,因此没有订阅余额。","historyUnavailable": "历史记录不完整,暂时仅显示剩余余额。","detailsUnavailable": "用量明细暂时不可用,当前仅显示各类余额。",@@ -12275,6 +12307,7 @@},"dialogs": {"subscription": {+ "confirmTitle": "确认订阅","title": "选择订阅套餐"},"topup": {@@ -12367,13 +12400,9 @@"failedBody": "支付失败,请稍后重试或联系支持。"},"planChange": {+ "emptyTitle": "暂无可切换的套餐","targetTitle": "更改订阅套餐","back": "上一步",- "upgradeBadge": "升级",- "sameLevelBadge": "同等级",- "downgradeBadge": "降级",- "emptyTitle": "暂无可切换的套餐",- "emptyDescription": "当前没有其他可切换的套餐。","quotingTitle": "正在准备套餐变更","quotingBody": "正在确认价格与生效时间…","quoteTitle": "确认套餐变更",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex b419c04969..09833050d3 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -12153,6 +12153,38 @@}},"billing": {+ "comparison": {+ "free": "FREE",+ "freeUsage": "免費使用",+ "priceFromSuffix": "起",+ "topup": "按需儲值",+ "topupExpiry": "儲值點數不過期",+ "agent": "完整 Agent 功能",+ "apiKey": "自備 API key",+ "existingSubscription": "接入現有訂閱",+ "localModels": "支援本機模型",+ "basicModels": "可用基礎模型",+ "subscription": "訂閱方案",+ "rollover": "剩餘點數可留到{{period}},最多 {{amount}}",+ "nextPeriod": {+ "MONTH": "下個月",+ "YEAR": "下一年",+ "OTHER": "下期"+ },+ "includesFree": "包含 FREE 全部功能",+ "advancedModels": "解鎖進階模型",+ "managedService": "官方服務,免設定",+ "topupUnlock": "按需付費,解鎖進階模型",+ "select": "選擇 {{name}}",+ "upgrade": "升級至 {{name}}",+ "downgrade": "降級至 {{name}}",+ "changeUnavailable": "暫不可切換",+ "creditMultiple": "{{name}} 的 {{multiple}} 倍週期點數",+ "credits": {+ "MONTH": "每月 {{amount}} 點數",+ "YEAR": "每年 {{amount}} 點數"+ }+ },"sidebar": "餘額與訂閱","settings": {"title": "用量和計費",@@ -12206,7 +12238,7 @@"observedAt": "餘額更新於 {{date}}","poolDetail": "已用 {{used}} · 總額 {{total}}","remaining": "剩餘",- "progressLabel": "{{label}}使用進度",+ "progressLabel": "{{label}}剩餘比例","noPlanCredits": "當前無生效訂閱,因此沒有訂閱餘額。","historyUnavailable": "歷史記錄不完整,暫時僅顯示剩餘餘額。","detailsUnavailable": "用量明細暫時不可用,當前僅顯示各類餘額。",@@ -12275,6 +12307,7 @@},"dialogs": {"subscription": {+ "confirmTitle": "確認訂閱","title": "選擇訂閱套餐"},"topup": {@@ -12367,13 +12400,9 @@"failedBody": "支付失敗,請稍後重試或聯絡支援。"},"planChange": {+ "emptyTitle": "暫無可切換的套餐","targetTitle": "更改訂閱套餐","back": "上一步",- "upgradeBadge": "升級",- "sameLevelBadge": "同等級",- "downgradeBadge": "降級",- "emptyTitle": "暫無可切換的套餐",- "emptyDescription": "當前沒有其他可切換的套餐。","quotingTitle": "正在準備套餐變更","quotingBody": "正在確認價格與生效時間…","quoteTitle": "確認套餐變更",diff --git a/design-qa.md b/design-qa.mdnew file mode 100644index 0000000000..b33fcf3601--- /dev/null+++ b/design-qa.md@@ -0,0 +1,69 @@+# 套餐对比改动与验收++当前状态:相关单测、类型检查与 ESLint 通过;已复核 macOS 浅色界面截图。截图拍摄后统一了套餐购买与变更弹窗标题区,并补齐 FREE 说明行高度;这两处微调尚未重新截图。真实支付联调和最新深色、窄窗实机验证待完成。++## 交付范围++| 分组 | 文件范围 | 目的 |+| --- | --- | --- |+| 客户端套餐页面(12 个文件) | `apps/desktop/src/renderer/features/billing/` 下 4 个组件、2 个测试文件,五种语言 `common.json`,本文档 | 套餐比较、渠道价格展示及状态适配 |+| 服务端支付宝修复(独立服务端仓,7 个文件) | `planChangeService.ts`、`planChangeRepository.ts`、`alipaySubscriptionRepository.ts`、3 个测试文件及订阅文档 | 取消续费后仍可升级并重新签约 |+| 本地运行包缓存(2 个文件) | `scripts/ensure-agent-binaries.mjs` 及其测试 | 校验并复用同版本的完整运行包,减少下载 |++客户端界面与启动缓存分别组织提交。服务端支付宝修复已通过独立 PR #701 合并,不包含在客户端 PR 中;此前已合并的 Stripe 取消状态与退款账单关联修复也不包含在客户端 PR 中。启动缓存改动不属于套餐页面逻辑。++## 最终界面与交互++- 首次订阅与更改套餐共用 `PlanComparison`:横向列出 FREE 和服务端套餐。无推荐标签、价格下拉框或套餐按钮选中态。+- FREE 展示完整 Agent 功能、自带 API key、接入已有订阅、本地模型和基础模型;付费套餐包含共有能力并展示高级模型权限。不列具体模型型号。+- 付费价格、币种、周期、点数和剩余点数上限均来自服务端,FREE 固定为 0。同币种、同周期的可用报价同价直接显示,异价显示最低价加“起”;权益跟随对应报价。不同币种或周期分开展示。+- 升降级目标只汇总当前可切换的报价;当前套餐使用合同快照。当前套餐标签与按钮一致,同级切换沿用服务端不支持的约定。+- 点击套餐后复用已有购买或变更流程。购买步骤同时列出渠道与对应价格,提交实际选择的 `offerCode` 和 `purchaseOptionId`。+- FREE 按钮打开原充值流程;取消续费仍位于订阅管理菜单。购买套餐页保留敬请期待和无渠道报价,状态直接放到禁用按钮;升降级页按旧规则隐藏不可购买、不同周期或不同支付渠道的报价。保留加载失败、报价过期和支付结果状态。+- 弹窗外部点击不关闭。矮窗口正文可滚动,二维码保持可扫尺寸;窄窗口仅套餐区域横向滚动。+- 颜色使用既有主题 token;沿用应用字体、标准支付按钮和图标。容器为 12px 圆角,套餐操作为胶囊按钮。+- 余额用量采用两行布局,剩余金额右对齐;深色表示剩余余额并靠右,浅色表示已用,不显示百分比。+- 订单状态使用纯文字,申请开票使用标准描边按钮,两者居中对齐并保留间距。++## 支付宝行为边界++- 取消续费但本期仍有效时,允许新发起升级,通过现有补差价和签约流程重新开通自动续费。+- 升级付款和新协议签约均成功后才恢复续费;未付款、未签约或失败保持原取消状态。报价创建后再次取消,旧报价不能恢复续费。+- 客户端复用已有弹窗;套餐按钮上方不再展示升级、降级及续费说明。服务端修复需先可用,再验收客户端取消后的升级流程。+- 原未付款升级单阻止直接更换目标套餐的限制保留;取消状态下的降级、Stripe 变更和期末限制不变。+- 未新增 API、数据库字段、自动退款、待付款状态投影或“继续支付”流程。++## 验证记录++| 项目 | 状态 |+| --- | --- |+| 最新行为代码静态检查 | Desktop 与服务端 typecheck、相关 TSX ESLint 通过 |+| 本次整理 | 仅删除未使用文案并整理本文档;JSON 结构、多语言和术语检查通过,仅有既有非阻断提醒 |+| diff 检查 | 两仓在整体 review 时通过;整理后客户端复查通过 |+| 历史组件测试 | 曾完成 139 项及后续支付页 109 项回归;之后代码已有变化,不作为最新通过证据 |+| 最新回归测试 | `pnpm test:unit:related` 通过;套餐组件定向测试 116 项通过。文件监听与跨进程锁测试在沙箱内超时,系统权限下完整相关门禁通过 |+| 最新视觉复核 | 已复核以下五张 macOS 浅色截图;最后两处对齐微调未重新截图,真实支付联调未执行 |++已更新的用例覆盖价格汇总、渠道提交一致性、不可用套餐、当前套餐身份、取消后升级,以及支付宝旧报价、新取消、未付款和未签约边界。发布前需执行相关测试,并验证支付宝重新签约链路。++## 本次视觉证据++平台:macOS Desktop,浅色主题。金额为开发环境报价,不代表正式售价。截图未验证支付结果、深色主题或窄窗口。++| 页面 | 截图 |+| --- | --- |+| 套餐购买 | [plans-light.png](docs/assets/billing-subscription/plans-light.png) |+| 支付渠道与价格 | [payment-channels-light.png](docs/assets/billing-subscription/payment-channels-light.png) |+| 套餐升降级 | [change-plan-light.png](docs/assets/billing-subscription/change-plan-light.png) |+| 余额用量 | [balance-usage-light.png](docs/assets/billing-subscription/balance-usage-light.png) |+| 订单状态与开票 | [order-history-light.png](docs/assets/billing-subscription/order-history-light.png) |++套餐购买与升降级截图拍摄后,标题区域统一为左右 24px、上下 16px,正文顶部分隔线保持一致;FREE 说明行补齐与付费套餐相同的最小高度。++## 历史视觉证据++- 设计依据:已确认的 subscription-v10 套餐对比及后续支付确认页设计。+- 本地证据目录:`/Users/liugaowei/.codex/visualizations/2026/09/14/01a09efc-7345-7480-bf7d-aa5ed5926d0e/implementation/`。+- 套餐:`change-light.png`、`change-dark-current.png`、`subscription-narrow-current.png`。窄窗 640px,套餐滚动容器 542px、内容 880px,无页面级横向溢出。+- 支付:`checkout-cindy-light.png`、`checkout-cindy-dark.png`、`checkout-github-dark.png`、`checkout-solarized-light.png`、`checkout-cindy-dark-large.png`;`checkout-light-comparison.png` 为设计与实现对照。+- 上述截图使用实际 React 组件、Tailwind 和主题 token 静态渲染;示例数据未进入产品代码。没有操作用户窗口或执行支付写接口,不等同于 Electron 端到端、任意自定义主题或最新版本验收。diff --git a/docs/assets/billing-subscription/balance-usage-light.png b/docs/assets/billing-subscription/balance-usage-light.pngnew file mode 100644index 0000000000..9ff723a997Binary files /dev/null and b/docs/assets/billing-subscription/balance-usage-light.png differdiff --git a/docs/assets/billing-subscription/change-plan-light.png b/docs/assets/billing-subscription/change-plan-light.pngnew file mode 100644index 0000000000..cdd1d1c086Binary files /dev/null and b/docs/assets/billing-subscription/change-plan-light.png differdiff --git a/docs/assets/billing-subscription/order-history-light.png b/docs/assets/billing-subscription/order-history-light.pngnew file mode 100644index 0000000000..7c5e6969faBinary files /dev/null and b/docs/assets/billing-subscription/order-history-light.png differdiff --git a/docs/assets/billing-subscription/payment-channels-light.png b/docs/assets/billing-subscription/payment-channels-light.pngnew file mode 100644index 0000000000..1b304ae4faBinary files /dev/null and b/docs/assets/billing-subscription/payment-channels-light.png differdiff --git a/docs/assets/billing-subscription/plans-light.png b/docs/assets/billing-subscription/plans-light.pngnew file mode 100644index 0000000000..0803349a51Binary files /dev/null and b/docs/assets/billing-subscription/plans-light.png differdiff --git a/scripts/__tests__/ensure-agent-binaries.test.mjs b/scripts/__tests__/ensure-agent-binaries.test.mjsindex 9b46626a26..4ee25e523a 100644--- a/scripts/__tests__/ensure-agent-binaries.test.mjs+++ b/scripts/__tests__/ensure-agent-binaries.test.mjs@@ -20,6 +20,7 @@ import {SUPPORTED_BINARY_KINDS,supportsCdnFallback,tryReuseFromSiblingWorktree,+ tryReuseDirDistFromSiblingWorktree,updateScriptForKind,} from '../ensure-agent-binaries.mjs';import { verifyDirDistManifest, writeDirDistManifest } from '../../tools/shared/dir-dist-manifest.mjs';@@ -46,6 +47,43 @@ const LFS_POINTER = ['',].join('\n');+test('directory reuse validates all assets, skips mismatches and replaces stale files', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'reuse-dir-dist-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const makeSource = (name, version) => {+ const dir = path.join(root, name);+ fs.mkdirSync(path.join(dir, 'bin'), { recursive: true });+ fs.writeFileSync(path.join(dir, 'bin', 'codex'), Buffer.alloc(2048, 1), { mode: 0o755 });+ fs.writeFileSync(path.join(dir, 'asset.json'), 'good');+ fs.writeFileSync(path.join(dir, '.version'), version);+ writeDirDistManifest(dir);+ return dir;+ };+ const old = makeSource('old', '1');+ const damaged = makeSource('damaged', '2');+ fs.writeFileSync(path.join(damaged, 'asset.json'), 'evil');+ const good = makeSource('good', '2');+ const destDir = makeSource('dest', '1');+ fs.writeFileSync(path.join(destDir, 'stale'), 'old asset');+ const options = {+ binaryRelativePath: path.join('bin', 'codex'),+ requiredFiles: ['asset.json'], version: '2', destDir,+ };+ assert.equal(tryReuseDirDistFromSiblingWorktree({+ ...options, candidates: [old, damaged, path.join(root, 'missing')],+ }), null);+ assert.equal(fs.readFileSync(path.join(destDir, '.version'), 'utf8'), '1');+ assert.equal(tryReuseDirDistFromSiblingWorktree({+ ...options, candidates: [damaged, good],+ }), good);+ assert.equal(verifyDirDistManifest(destDir), true);+ assert.equal(fs.existsSync(path.join(destDir, 'stale')), false);+ assert.equal(fs.readFileSync(path.join(destDir, 'asset.json'), 'utf8'), 'good');+ fs.writeFileSync(path.join(destDir, 'asset.json'), 'edit');+ assert.equal(fs.readFileSync(path.join(good, 'asset.json'), 'utf8'), 'good');+ assert.equal(fs.readdirSync(root).some((name) => name.startsWith('dest.reuse-')), false);+});+function tmpFile(name, contents) {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ensure-bin-test-'));const p = path.join(dir, name);diff --git a/scripts/ensure-agent-binaries.mjs b/scripts/ensure-agent-binaries.mjsindex f95e8bc198..3abd30356a 100644--- a/scripts/ensure-agent-binaries.mjs+++ b/scripts/ensure-agent-binaries.mjs@@ -28,7 +28,7 @@ const LFS_POINTER_HEADER = 'version https://git-lfs.github.com/spec/v1';const MIN_EXPECTED_BYTES = 1024;// kind → 本地落点 + 提供 ensurePlatform/readPinnedVersion 的下载模块-// dirDist: 产物是"目录 + 主执行文件"(非单文件),sibling-worktree 单文件复用不适用+// dirDist: 产物是"目录 + 主执行文件",复用时必须复制并校验完整目录。const KINDS = {claude: { binDir: 'claude-code-bin', base: 'claude', module: '../tools/claude/update.mjs' },codex: {@@ -217,9 +217,61 @@ export function tryReuseFromSiblingWorktree({ candidates, binFile, version, dest}/**- * 确保 <kind> 在 <platformKey> 平台的二进制就位。已存在合法文件且非 force 时跳过。- * 返回最终二进制的绝对路径。+ * 复用同版本的完整目录分发;源与副本均须通过清单和必需资产校验。*/+export function tryReuseDirDistFromSiblingWorktree({+ candidates, binaryRelativePath, requiredFiles, version, destDir,+}) {+ for (const candidateDir of candidates) {+ let staging;+ let previous;+ try {+ if (readInstalledVersion(path.join(candidateDir, '.version')) !== version) continue;+ if (!isValidDirDist(candidateDir, path.join(candidateDir, binaryRelativePath), requiredFiles)) {+ warn(`local directory cache invalid, skipping: ${candidateDir}`);+ continue;+ }+ // 同一文件系统内落临时目录,完整校验后再替换;不合并旧安装残留。+ fs.mkdirSync(path.dirname(destDir), { recursive: true });+ staging = fs.mkdtempSync(`${destDir}.reuse-`);+ const next = path.join(staging, 'next');+ fs.cpSync(candidateDir, next, { recursive: true, mode: fs.constants.COPYFILE_FICLONE });+ if (readInstalledVersion(path.join(next, '.version')) !== version+ || !isValidDirDist(next, path.join(next, binaryRelativePath), requiredFiles)) {+ throw new Error('copied directory failed validation');+ }+ if (fs.existsSync(destDir)) {+ const backup = path.join(staging, 'previous');+ fs.renameSync(destDir, backup);+ previous = backup;+ }+ try {+ fs.renameSync(next, destDir);+ } catch (err) {+ if (previous) {+ fs.renameSync(previous, destDir);+ previous = undefined;+ }+ throw err;+ }+ previous = undefined;+ return candidateDir;+ } catch (err) {+ // 回滚失败时保留旧安装,停止,不能继续下载覆盖证据。+ if (previous && fs.existsSync(previous)) {+ throw new Error(`Cannot restore previous runtime at ${previous}: ${err.message}`);+ }+ warn(`local directory reuse failed from ${candidateDir}: ${err.message}`);+ } finally {+ if (staging && !previous) {+ try { fs.rmSync(staging, { recursive: true, force: true }); } catch { /* best effort */ }+ }+ }+ }+ return null;+}++/** 确保固定版本的运行包就位,返回主执行文件路径。 */export async function ensureBinary(kind, platformKey = currentPlatformKey(), { force = false } = {}) {const cfg = KINDS[kind];if (!cfg) throw new Error(`Unknown kind: ${kind} (known: ${Object.keys(KINDS).join(', ')})`);@@ -256,16 +308,22 @@ export async function ensureBinary(kind, platformKey = currentPlatformKey(), { f// 磁盘),弱网/断网时这是唯一不用等超时的路径。force 语义是"强制重新获取",// 保持走正宗下载不复用。let reusedFrom = null;- // dirDist kind 的产物含主执行文件之外的运行时资产,单文件复用会产出缺资产的坏安装。- if (!force && !cfg.dirDist) {- reusedFrom = tryReuseFromSiblingWorktree({+ if (!force) {+ const reuseOptions = {candidates: listSiblingWorktreeRoots(ROOT).map((root) =>path.join(root, 'apps', cfg.binDir, platformKey),),binFile,version,destDir: binDirPath,- });+ };+ reusedFrom = cfg.dirDist+ ? tryReuseDirDistFromSiblingWorktree({+ ...reuseOptions,+ binaryRelativePath,+ requiredFiles: requiredDirDistFilesFor(cfg, platformKey),+ })+ : tryReuseFromSiblingWorktree(reuseOptions);if (reusedFrom) {log(`${kind} ${platformKey}: reused local copy @ ${version} from ${reusedFrom}`);}