Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(billing): make checkout sessions ephemeral with server-side replacement (#462)

GaoWei Liu96b3fb331039
diff --git a/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsx b/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsx
index dd4448da48..135ee2ed5d 100644
--- a/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsx
+++ b/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useState } from 'react';
+import { useEffect, useMemo, useRef, useState } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import * as QRCode from 'qrcode';
import { Check, CircleAlert, ExternalLink, LoaderCircle, RotateCcw, X } from 'lucide-react';
@@ -79,6 +79,17 @@ export function BillingCheckoutDialog({
if (action?.type === 'REDIRECT') void billingApi.openPaymentRedirect(action.url);
};
+ // 过期判定以服务端为权威:服务端只下发仍有效的动作,动作过期后轮询响应里
+ // 会把它置空。因此“曾经有动作、现在没有了”才代表过期,本地时钟偏移不会
+ // 误藏仍可支付的二维码,也不会闪现已过期动作。倒计时仅作展示。
+ const hadActionRef = useRef(false);
+ useEffect(() => {
+ if (action) hadActionRef.current = true;
+ if (!state.open || state.phase !== 'AWAITING_PAYMENT') hadActionRef.current = false;
+ }, [action, state.open, state.phase]);
+ const actionExpired =
+ state.phase === 'AWAITING_PAYMENT' && action === null && hadActionRef.current;
+
const canRetry =
(state.error && state.intent !== null && state.order === null && state.subscription === null) ||
(state.kind === 'TOPUP' &&
@@ -132,7 +143,18 @@ export function BillingCheckoutDialog({
</>
)}
- {state.phase === 'AWAITING_PAYMENT' && action?.type === 'QR_CODE' && (
+ {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="grid place-items-center rounded-xl border border-[var(--border-default)] bg-white p-2"
@@ -159,7 +181,7 @@ export function BillingCheckoutDialog({
</>
)}
- {state.phase === 'AWAITING_PAYMENT' && action?.type === 'REDIRECT' && (
+ {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} />
@@ -176,7 +198,7 @@ export function BillingCheckoutDialog({
</>
)}
- {state.phase === 'AWAITING_PAYMENT' && !action && (
+ {state.phase === 'AWAITING_PAYMENT' && !action && !actionExpired && (
<>
<Spinner size={26} className="text-[var(--text-secondary)]" />
<p className="mt-4 text-sm text-[var(--text-secondary)]">
diff --git a/apps/desktop/src/renderer/features/billing/BillingPage.tsx b/apps/desktop/src/renderer/features/billing/BillingPage.tsx
index 901cc52617..ce10b1d6c9 100644
--- a/apps/desktop/src/renderer/features/billing/BillingPage.tsx
+++ b/apps/desktop/src/renderer/features/billing/BillingPage.tsx
@@ -23,7 +23,6 @@ import type {
BillingCatalogOfferUnavailableReason,
BillingCatalogProduct,
BillingPendingPlanChange,
- BillingPaymentOrder,
BillingPurchaseOption,
BillingSubscription,
} from '../../../shared/billing';
@@ -79,6 +78,8 @@ const SUPPORTED_SUBSCRIPTION_CAPABILITIES = new Set<BillingPurchaseOption['capab
'PROVIDER_MANAGED_SUBSCRIPTION',
]);
+// 新服务端的“当前订阅”只包含真实生命周期状态,未完成首购不再下发也不阻断重选;
+// INCOMPLETE 仅作为旧服务端兼容防御保留(旧服务端仍会拒绝重复首购)。
const SUBSCRIPTION_PURCHASE_BLOCKING_STATUSES: BillingSubscription['status'][] = [
'INCOMPLETE',
'TRIALING',
@@ -90,10 +91,6 @@ const SUBSCRIPTION_PURCHASE_BLOCKING_STATUSES: BillingSubscription['status'][] =
const SUBSCRIPTION_CANCELLABLE_STATUSES: BillingSubscription['status'][] =
SUBSCRIPTION_PURCHASE_BLOCKING_STATUSES.filter((status) => status !== 'INCOMPLETE');
-// This list only controls which card action opens the plan-change flow. It is
-// intentionally separate from the new-purchase guard above: INCOMPLETE still
-// blocks a duplicate purchase, but without an effective plan there is nothing
-// meaningful to change.
const PLAN_CHANGE_ENTRY_STATUSES: BillingSubscription['status'][] = ['ACTIVE'];
function decimalParts(value: string): { value: bigint; scale: number } | null {
@@ -338,6 +335,15 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
}
}, [checkout.state.subscription]);
+ const closeCheckout = useCallback(() => {
+ const abandonedIncomplete = checkout.state.subscription?.status === 'INCOMPLETE';
+ checkout.close();
+ if (abandonedIncomplete) {
+ setCurrentSubscription(null);
+ void loadSubscription();
+ }
+ }, [checkout, loadSubscription]);
+
useEffect(() => {
const previousPhase = previousCheckoutPhaseRef.current;
previousCheckoutPhaseRef.current = checkout.state.phase;
@@ -356,13 +362,6 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
[loadBillingState, loadSubscription],
);
const planChange = usePlanChange(accountId, handlePlanChangeSettled);
- const hasRecoverableFailedIntent =
- !checkout.state.open &&
- checkout.state.phase === 'FAILED' &&
- checkout.state.error &&
- checkout.state.intent !== null &&
- checkout.state.order === null &&
- checkout.state.subscription === null;
const offers = useMemo<CatalogOfferEntry[]>(() => {
if (!catalog) return [];
@@ -462,7 +461,6 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
}, [billingLocale, customAmount, selected, t]);
const canCheckout =
- !checkout.recovering &&
selected !== null &&
selectedOption !== null &&
!(
@@ -492,11 +490,6 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
PLAN_CHANGE_ENTRY_STATUSES.includes(currentSubscription.status) &&
!currentSubscription.cancelAtPeriodEnd &&
currentPlan.offer.interval === 'MONTH';
- const recoverableSubscription =
- currentSubscription?.status === 'INCOMPLETE' &&
- checkout.recoverables.subscription?.subscriptionId === currentSubscription.subscriptionId
- ? checkout.recoverables.subscription
- : null;
const currentPlanFacts = useMemo(() => {
if (!currentSubscription) return null;
const plan = currentSubscription.effectivePlan;
@@ -661,12 +654,8 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
};
const openPlanChange = () => {
- // An open change is the server's fact; re-enter it instead of quoting anew.
- if (pendingPlanChange) {
- planChange.resumePending(pendingPlanChange);
- } else {
- setPlanChangeTargetOpen(true);
- }
+ // 服务端在新报价时自动撤销旧未完成变更;这里总是重新选择目标。
+ setPlanChangeTargetOpen(true);
};
const selectPlanChangeTarget = (candidate: PlanChangeCandidate) => {
@@ -721,20 +710,6 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
</button>
</div>
- {!checkout.recovering &&
- (checkout.recoverables.topups.length > 0 ||
- checkout.recoverables.subscription !== null ||
- hasRecoverableFailedIntent) && (
- <BillingRecoveryNotice
- topups={checkout.recoverables.topups}
- subscription={checkout.recoverables.subscription}
- failedIntent={hasRecoverableFailedIntent}
- onResumeTopup={checkout.resumeTopup}
- onResumeSubscription={checkout.resumeSubscription}
- onResumeFailed={checkout.resumeFailed}
- />
- )}
-
<div className="mt-6 flex flex-col gap-8">
<BillingGroup title={t('billing.settings.subscriptionCard.title')}>
<SubscriptionOverviewCard
@@ -742,25 +717,13 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
loading={loadingSubscription}
error={subscriptionError}
showPlanChangeEntry={showPlanChangeEntry}
- recoveryAvailable={recoverableSubscription !== null}
canceling={cancelingSubscription}
- actionDisabled={
- loadingSubscription ||
- subscriptionError ||
- cancelingSubscription ||
- (recoverableSubscription !== null && checkout.recovering)
- }
+ actionDisabled={loadingSubscription || subscriptionError || cancelingSubscription}
pendingPlanChange={pendingPlanChange}
pendingTargetName={planNameOf(pendingPlanChange?.targetPlan?.product.code)}
onCancelSubscription={() => void cancelCurrentSubscription()}
onChangePlan={openPlanChange}
- onRecover={() => {
- if (recoverableSubscription) checkout.resumeSubscription(recoverableSubscription);
- }}
onPurchase={() => openPurchaseDialog('SUBSCRIPTION')}
- onResumePending={() => {
- if (pendingPlanChange) planChange.resumePending(pendingPlanChange);
- }}
onCancelPending={() => {
if (pendingPlanChange) void planChange.cancelChange(pendingPlanChange.planChangeId);
}}
@@ -857,7 +820,7 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
<BillingCheckoutDialog
state={checkout.state}
- onClose={checkout.close}
+ onClose={closeCheckout}
onRefresh={() => void checkout.refreshActive()}
onRetry={() => void checkout.retry()}
/>
@@ -885,98 +848,31 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
);
}
-function BillingRecoveryNotice({
- topups,
- subscription,
- failedIntent,
- onResumeTopup,
- onResumeSubscription,
- onResumeFailed,
-}: {
- topups: BillingPaymentOrder[];
- subscription: BillingSubscription | null;
- failedIntent: boolean;
- onResumeTopup: (order: BillingPaymentOrder) => void;
- onResumeSubscription: (subscription: BillingSubscription) => void;
- onResumeFailed: () => void;
-}) {
- const { t, i18n } = useTranslation();
- const billingLocale = i18n.resolvedLanguage ?? i18n.language;
- return (
- <section className="mt-5 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-5 py-4">
- <p className="text-sm font-medium text-[var(--text-primary)]">
- {t('billing.recovery.title')}
- </p>
- <p className="mt-1 text-12 text-[var(--text-secondary)]">
- {t('billing.recovery.description')}
- </p>
- <div className="mt-3 flex flex-wrap gap-2">
- {topups.map((order) => (
- <button
- key={order.orderId}
- type="button"
- onClick={() => onResumeTopup(order)}
- className="select-none rounded-full border border-[var(--border-default)] px-3 py-1.5 text-12 font-medium transition-colors hover:bg-[var(--surface-hover-soft)]"
- >
- {t('billing.recovery.continueTopup', {
- amount: formatMoney(order.amount, order.currency, billingLocale),
- })}
- </button>
- ))}
- {subscription && (
- <button
- type="button"
- onClick={() => onResumeSubscription(subscription)}
- className="select-none rounded-full border border-[var(--border-default)] px-3 py-1.5 text-12 font-medium transition-colors hover:bg-[var(--surface-hover-soft)]"
- >
- {t('billing.recovery.continueSubscription')}
- </button>
- )}
- {failedIntent && (
- <button
- type="button"
- onClick={onResumeFailed}
- className="select-none rounded-full border border-[var(--border-default)] px-3 py-1.5 text-12 font-medium transition-colors hover:bg-[var(--surface-hover-soft)]"
- >
- {t('billing.recovery.continueFailed')}
- </button>
- )}
- </div>
- </section>
- );
-}
-
function SubscriptionOverviewCard({
facts,
loading,
error,
showPlanChangeEntry,
- recoveryAvailable,
canceling,
actionDisabled,
pendingPlanChange,
pendingTargetName,
onCancelSubscription,
onChangePlan,
- onRecover,
onPurchase,
- onResumePending,
onCancelPending,
}: {
facts: CurrentPlanFacts | null;
loading: boolean;
error: boolean;
showPlanChangeEntry: boolean;
- recoveryAvailable: boolean;
canceling: boolean;
actionDisabled: boolean;
pendingPlanChange: BillingPendingPlanChange | null;
pendingTargetName: string | null;
onCancelSubscription: () => void;
onChangePlan: () => void;
- onRecover: () => void;
onPurchase: () => void;
- onResumePending: () => void;
onCancelPending: () => void;
}) {
const { t } = useTranslation();
@@ -1066,26 +962,21 @@ function SubscriptionOverviewCard({
)}
<button
type="button"
- onClick={
- showPlanChangeEntry ? onChangePlan : recoveryAvailable ? onRecover : onPurchase
- }
+ onClick={showPlanChangeEntry ? onChangePlan : onPurchase}
disabled={actionDisabled}
className="h-8 select-none rounded-full border border-[var(--border-default)] px-3.5 text-12 font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover-soft)] disabled:cursor-not-allowed disabled:opacity-40"
>
{showPlanChangeEntry
? t('billing.settings.subscriptionCard.changeAction')
- : recoveryAvailable
- ? t('billing.recovery.continueSubscription')
- : t('billing.settings.subscriptionCard.action')}
+ : t('billing.settings.subscriptionCard.action')}
</button>
</div>
</div>
- {pendingPlanChange && (
+ {pendingPlanChange?.status === 'SCHEDULED' && (
<PendingPlanChangeBanner
pending={pendingPlanChange}
targetName={pendingTargetName}
disabled={actionDisabled}
- onResume={onResumePending}
onUndo={onCancelPending}
/>
)}
@@ -1093,17 +984,16 @@ function SubscriptionOverviewCard({
);
}
+// 服务端普通订阅投影只下发 SCHEDULED 变更:它是已确定的期末事实,展示并允许撤销。
function PendingPlanChangeBanner({
pending,
targetName,
disabled,
- onResume,
onUndo,
}: {
pending: BillingPendingPlanChange;
targetName: string | null;
disabled: boolean;
- onResume: () => void;
onUndo: () => void;
}) {
const { t, i18n } = useTranslation();
@@ -1112,41 +1002,22 @@ function PendingPlanChangeBanner({
() => formatBillingDate(pending.effectiveAt, billingLocale) ?? pending.effectiveAt,
[billingLocale, pending.effectiveAt],
);
- const label =
- pending.status === 'SCHEDULED'
- ? t('billing.planChange.pendingDowngrade', {
- name: targetName ?? t('billing.settings.subscriptionCard.unnamedPlan'),
- date: effectiveDate,
- })
- : pending.status === 'AWAITING_PAYMENT'
- ? t('billing.planChange.pendingPayment', {
- name: targetName ?? t('billing.settings.subscriptionCard.unnamedPlan'),
- })
- : t('billing.planChange.pendingQuote', {
- name: targetName ?? t('billing.settings.subscriptionCard.unnamedPlan'),
- });
return (
<div className="flex flex-wrap items-center gap-3 border-t border-[var(--border-default)] px-5 py-3">
- <p className="min-w-0 flex-1 text-12 leading-5 text-[var(--text-secondary)]">{label}</p>
- {pending.status === 'SCHEDULED' ? (
- <button
- type="button"
- onClick={onUndo}
- disabled={disabled}
- className="h-8 shrink-0 select-none rounded-full border border-[var(--border-default)] px-3.5 text-12 font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover-soft)] disabled:cursor-not-allowed disabled:opacity-40"
- >
- {t('billing.planChange.undo')}
- </button>
- ) : (
- <button
- type="button"
- onClick={onResume}
- disabled={disabled}
- className="h-8 shrink-0 select-none rounded-full border border-[var(--border-default)] px-3.5 text-12 font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover-soft)] disabled:cursor-not-allowed disabled:opacity-40"
- >
- {t('billing.planChange.resume')}
- </button>
- )}
+ <p className="min-w-0 flex-1 text-12 leading-5 text-[var(--text-secondary)]">
+ {t('billing.planChange.pendingDowngrade', {
+ name: targetName ?? t('billing.settings.subscriptionCard.unnamedPlan'),
+ date: effectiveDate,
+ })}
+ </p>
+ <button
+ type="button"
+ onClick={onUndo}
+ disabled={disabled}
+ className="h-8 shrink-0 select-none rounded-full border border-[var(--border-default)] px-3.5 text-12 font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover-soft)] disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ {t('billing.planChange.undo')}
+ </button>
</div>
);
}
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
index 1efc08ec3f..e4511df124 100644
--- a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
@@ -27,20 +27,12 @@ const checkout = {
subscription: null,
error: false,
},
- recoverables: {
- topups: [] as BillingPaymentOrder[],
- subscription: null as BillingSubscription | null,
- },
- recovering: false,
startTopup: vi.fn(),
startSubscription: vi.fn(),
refreshActive: vi.fn(),
retry: vi.fn(),
cancel: vi.fn(),
close: vi.fn(),
- resumeTopup: vi.fn(),
- resumeSubscription: vi.fn(),
- resumeFailed: vi.fn(),
};
vi.mock('react-i18next', () => ({
@@ -104,12 +96,6 @@ describe('BillingPage remote catalog rendering', () => {
checkout.startTopup.mockClear();
checkout.startSubscription.mockClear();
checkout.close.mockClear();
- checkout.resumeTopup.mockClear();
- checkout.resumeSubscription.mockClear();
- checkout.resumeFailed.mockClear();
- checkout.recoverables.topups = [];
- checkout.recoverables.subscription = null;
- checkout.recovering = false;
Object.defineProperty(window, 'electronAPI', {
configurable: true,
value: {
@@ -520,64 +506,11 @@ describe('BillingPage remote catalog rendering', () => {
).toBeNull();
});
- it('places recoverable checkout actions before the balance overview', async () => {
- const order = {
- orderId: 'order_pending',
- productCode: 'credit_topup',
- offerCode: 'credit_topup_custom',
- amount: '10',
- currency: 'cny',
- status: 'PENDING' as const,
- fulfillmentStatus: 'NOT_STARTED' as const,
- paymentAction: null,
- createdAt: '2026-07-24T00:00:00.000Z',
- updatedAt: '2026-07-24T00:00:00.000Z',
- };
- checkout.recoverables.topups = [order];
-
+ it('never renders a payment recovery banner on the settings page', async () => {
render(<BillingPage />);
- const recovery = screen.getByText('billing.recovery.title');
- const balanceTitle = await screen.findByText('billing.balance.title');
- expect(recovery.compareDocumentPosition(balanceTitle) & Node.DOCUMENT_POSITION_FOLLOWING).toBe(
- Node.DOCUMENT_POSITION_FOLLOWING,
- );
- fireEvent.click(screen.getByText((text) => text.startsWith('billing.recovery.continueTopup')));
- expect(checkout.resumeTopup).toHaveBeenCalledWith(order);
- });
-
- it('offers a user-initiated retry entry after background recovery fails', async () => {
- Object.assign(checkout.state, {
- open: false,
- kind: 'TOPUP',
- phase: 'FAILED',
- intent: {
- version: 1,
- kind: 'TOPUP',
- idempotencyKey: 'desktop:topup:uncertain',
- request: {
- offerCode: 'credit_topup_custom',
- amount: '10',
- purchaseOptionId: 'listing_alipay',
- },
- orderId: null,
- createdAt: '2026-07-24T00:00:00.000Z',
- },
- order: null,
- subscription: null,
- error: true,
- });
-
- render(<BillingPage />);
-
- const resume = screen.getByText('billing.recovery.continueFailed');
- const balanceTitle = await screen.findByText('billing.balance.title');
- expect(resume.compareDocumentPosition(balanceTitle) & Node.DOCUMENT_POSITION_FOLLOWING).toBe(
- Node.DOCUMENT_POSITION_FOLLOWING,
- );
- fireEvent.click(resume);
- expect(checkout.resumeFailed).toHaveBeenCalledTimes(1);
- expect(checkout.retry).not.toHaveBeenCalled();
+ await screen.findByText('billing.balance.title');
+ expect(screen.queryByText((text) => text.startsWith('billing.recovery'))).toBeNull();
});
it('shows usage progress and each promotional grant with its own state and expiry', async () => {
@@ -703,6 +636,41 @@ describe('BillingPage remote catalog rendering', () => {
expect(getBalance).toHaveBeenCalledTimes(2);
});
+ it('switches to the expired hint once the server stops issuing the payment action', async () => {
+ const order = {
+ orderId: 'order_expiring_action',
+ productCode: 'credit_topup',
+ offerCode: 'credit_topup_custom',
+ amount: '10',
+ currency: 'cny',
+ status: 'PENDING' as const,
+ paymentAction: {
+ type: 'QR_CODE' as const,
+ value: 'https://qr.alipay.example/live',
+ expiresAt: new Date(Date.now() + 60_000).toISOString(),
+ },
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:01:00.000Z',
+ };
+ Object.assign(checkout.state, {
+ open: true,
+ kind: 'TOPUP',
+ phase: 'AWAITING_PAYMENT',
+ order,
+ });
+
+ const view = render(<BillingPage />);
+ // 服务端仍下发的动作以服务端为准展示,不用本地时钟提前藏码。
+ expect(await screen.findByAltText('billing.checkout.qrAlt')).toBeTruthy();
+ expect(screen.queryByText('billing.checkout.actionExpiredBody')).toBeNull();
+
+ // 服务端判定过期后轮询响应把动作置空:切换为过期提示,不再显示二维码。
+ Object.assign(checkout.state, { order: { ...order, paymentAction: null } });
+ view.rerender(<BillingPage />);
+ expect(await screen.findByText('billing.checkout.actionExpiredBody')).toBeTruthy();
+ expect(screen.queryByAltText('billing.checkout.qrAlt')).toBeNull();
+ });
+
it('does not show zero or block purchases when balance is not provisioned', async () => {
window.electronAPI.billing.getBalance = vi.fn(async () => {
throw Object.assign(new Error('[NOT_FOUND] balance account is not provisioned'), {
@@ -807,27 +775,6 @@ describe('BillingPage remote catalog rendering', () => {
});
});
- it('keeps checkout disabled until startup recovery finishes', async () => {
- checkout.recovering = true;
- const view = render(<BillingPage />);
-
- fireEvent.click(screen.getByText('billing.settings.topupCard.action'));
- fireEvent.click((await screen.findByText('Configured top-up')).closest('button')!);
- fireEvent.click((await screen.findByText('alipay')).closest('button')!);
- fireEvent.change(screen.getByPlaceholderText('billing.amount.placeholder'), {
- target: { value: '10' },
- });
-
- const pay = screen.getByText('billing.actions.pay').closest('button')!;
- expect(pay).toHaveProperty('disabled', true);
- fireEvent.click(pay);
- expect(checkout.startTopup).not.toHaveBeenCalled();
-
- checkout.recovering = false;
- view.rerender(<BillingPage />);
- expect(pay).toHaveProperty('disabled', false);
- });
-
it('does not expose plan change when an active subscription has no effective plan', async () => {
window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => ({
subscription: {
@@ -1323,9 +1270,6 @@ describe('BillingPage plan change', () => {
beforeEach(() => {
localStorage.clear();
- checkout.recoverables.topups = [];
- checkout.recoverables.subscription = null;
- checkout.recovering = false;
Object.assign(checkout.state, {
open: false,
kind: null,
@@ -1618,37 +1562,69 @@ describe('BillingPage plan change', () => {
expect(screen.getByText('billing.settings.subscriptionCard.action')).toBeTruthy();
});
- it('routes INCOMPLETE without an effective plan to recovery and keeps duplicate purchase blocked', async () => {
- const incompleteSubscription: BillingSubscription = {
- ...activeSubscription(null, 'MONTH', 'INCOMPLETE'),
- effectivePlan: null,
- };
+ it('keeps new selection enabled when no current subscription exists (no INCOMPLETE task)', async () => {
+ // 服务端不再把未支付的首购作为“当前订阅”下发;页面必须允许正常重新选择。
const billing = billingMocks();
- billing.getCurrentSubscription = vi.fn(async () => ({
- subscription: incompleteSubscription,
- }));
+ billing.getCurrentSubscription = vi.fn(
+ async () => ({ subscription: null }),
+ ) as unknown as typeof billing.getCurrentSubscription;
install(billing);
- checkout.recoverables.subscription = incompleteSubscription;
render(<BillingPage />);
- await waitFor(() =>
- expect(screen.getAllByText('billing.recovery.continueSubscription')).toHaveLength(2),
+ 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')!);
+ const pay = screen.getByText('billing.actions.pay').closest('button')!;
+ expect(pay).toHaveProperty('disabled', false);
+ fireEvent.click(pay);
+ expect(checkout.startSubscription).toHaveBeenCalledWith({
+ offerCode: 'plus_month',
+ purchaseOptionId: 'listing_plus_stripe',
+ });
+ });
+
+ it('stops treating the abandoned checkout subscription as current when the dialog closes', async () => {
+ const billing = billingMocks();
+ billing.getCurrentSubscription = vi.fn(
+ async () => ({ subscription: null }),
+ ) as unknown as typeof billing.getCurrentSubscription;
+ install(billing);
+ Object.assign(checkout.state, {
+ open: true,
+ kind: 'SUBSCRIPTION',
+ phase: 'AWAITING_PAYMENT',
+ subscription: {
+ subscriptionId: 'subscription_incomplete',
+ status: 'INCOMPLETE',
+ currentPeriodStartAt: null,
+ currentPeriodEndAt: null,
+ entitlementValidUntil: null,
+ cancelAtPeriodEnd: false,
+ effectivePlan: null,
+ purchaseAttemptId: 'attempt_incomplete',
+ paymentAction: null,
+ },
+ });
+
+ render(<BillingPage />);
+ fireEvent.click(await screen.findByLabelText('billing.actions.close'));
+
+ expect(checkout.close).toHaveBeenCalled();
+ await waitFor(() => 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')!);
+ expect(screen.getByText('billing.actions.pay').closest('button')).toHaveProperty(
+ 'disabled',
+ false,
);
- const recoveryActions = screen.getAllByText('billing.recovery.continueSubscription');
- expect(screen.queryByText('billing.settings.subscriptionCard.changeAction')).toBeNull();
- fireEvent.click(recoveryActions[1]);
- expect(checkout.resumeSubscription).toHaveBeenCalledWith(incompleteSubscription);
});
- it('keeps the duplicate-purchase guard reachable when INCOMPLETE recovery is unavailable', async () => {
- const incompleteSubscription: BillingSubscription = {
- ...activeSubscription(null, 'MONTH', 'INCOMPLETE'),
- effectivePlan: null,
- };
+ it('still blocks a duplicate purchase while a real subscription is live', async () => {
const billing = billingMocks();
billing.getCurrentSubscription = vi.fn(async () => ({
- subscription: incompleteSubscription,
+ subscription: { ...activeSubscription(), effectivePlan: null },
}));
install(billing);
@@ -1722,7 +1698,9 @@ describe('BillingPage plan change', () => {
await waitFor(() => expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(2));
});
- it('resumes a pending alipay upgrade payment with the server-issued QR action', async () => {
+ it('ignores non-SCHEDULED pending changes and reopens target selection instead', async () => {
+ // 兼容旧服务端:即使投影里出现 AWAITING_PAYMENT,也不再提供“继续支付”入口;
+ // 变更套餐总是回到目标选择,由服务端在新报价时自动替换旧动作。
const qr = {
type: 'QR_CODE' as const,
value: 'https://qr.alipay.example/plan-change',
@@ -1750,27 +1728,16 @@ describe('BillingPage plan change', () => {
},
}));
install(billing);
- billing.refreshPlanChange.mockResolvedValue({
- planChangeId: 'plan_change_up',
- changeType: 'UPGRADE',
- status: 'AWAITING_PAYMENT',
- quotedAmountMinor: 1500,
- quotedCurrency: 'cny',
- quoteExpiresAt: null,
- effectiveAt: '2026-07-24T00:00:00.000Z',
- paymentAction: qr,
- });
render(<BillingPage />);
- await screen.findByText((text) => text.startsWith('billing.planChange.pendingPayment'));
-
- fireEvent.click(screen.getByText('billing.planChange.resume'));
- await screen.findByText('billing.planChange.awaitingTitle');
+ await screen.findByText('Plus plan');
expect(
- await screen.findByText((text) => text.startsWith('billing.planChange.scanToPay')),
- ).toBeTruthy();
- await screen.findByAltText('billing.checkout.qrAlt');
- // Resuming re-displays the stored server action without quoting again.
- expect(billing.quotePlanChange).not.toHaveBeenCalled();
+ screen.queryByText((text) => text.startsWith('billing.planChange.pendingDowngrade')),
+ ).toBeNull();
+ expect(screen.queryByText('billing.planChange.undo')).toBeNull();
+
+ fireEvent.click(screen.getByText('billing.settings.subscriptionCard.changeAction'));
+ expect(await screen.findByText('billing.planChange.targetTitle')).toBeTruthy();
+ expect(billing.refreshPlanChange).not.toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/checkoutIntent.test.ts b/apps/desktop/src/renderer/features/billing/__tests__/checkoutIntent.test.ts
index 0782b78e3d..b20dce37b8 100644
--- a/apps/desktop/src/renderer/features/billing/__tests__/checkoutIntent.test.ts
+++ b/apps/desktop/src/renderer/features/billing/__tests__/checkoutIntent.test.ts
@@ -2,70 +2,16 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import {
- billingCheckoutIntentKey,
- billingPlanChangeIntentKey,
- clearBillingCheckoutIntent,
- clearBillingPlanChangeIntent,
- newBillingIdempotencyKey,
- readBillingCheckoutIntent,
- readBillingPlanChangeIntent,
- writeBillingCheckoutIntent,
- writeBillingPlanChangeIntent,
-} from '../checkoutIntent';
+import { clearLegacyBillingIntentStorage, newBillingIdempotencyKey } from '../checkoutIntent';
const ACCOUNT_A = 'account-a';
const ACCOUNT_B = 'account-b';
-describe('billing checkout intent', () => {
+describe('billing checkout intent hygiene', () => {
beforeEach(() => {
localStorage.clear();
});
- it('round-trips a valid top-up intent', () => {
- const intent = {
- version: 1 as const,
- kind: 'TOPUP' as const,
- idempotencyKey: 'desktop:topup:fixture-0001',
- request: {
- offerCode: 'credit_topup_custom',
- amount: '20.00',
- purchaseOptionId: 'listing_alipay',
- },
- orderId: null,
- createdAt: '2026-01-01T00:00:00.000Z',
- };
- writeBillingCheckoutIntent(ACCOUNT_A, intent);
- expect(readBillingCheckoutIntent(ACCOUNT_A)).toEqual(intent);
- clearBillingCheckoutIntent(ACCOUNT_A);
- expect(readBillingCheckoutIntent(ACCOUNT_A)).toBeNull();
- });
-
- it('removes malformed or future-version storage', () => {
- localStorage.setItem(
- billingCheckoutIntentKey(ACCOUNT_A),
- JSON.stringify({ version: 2, kind: 'TOPUP' }),
- );
- expect(readBillingCheckoutIntent(ACCOUNT_A)).toBeNull();
- expect(localStorage.getItem(billingCheckoutIntentKey(ACCOUNT_A))).toBeNull();
- });
-
- it('removes intents containing undeclared response or payment fields', () => {
- localStorage.setItem(
- billingCheckoutIntentKey(ACCOUNT_A),
- JSON.stringify({
- version: 1,
- kind: 'TOPUP_RETRY',
- idempotencyKey: 'desktop:retry:fixture-0001',
- orderId: 'order_fixture',
- createdAt: '2026-01-01T00:00:00.000Z',
- paymentUrl: 'https://pay.example.test/should-not-persist',
- }),
- );
- expect(readBillingCheckoutIntent(ACCOUNT_A)).toBeNull();
- expect(localStorage.getItem(billingCheckoutIntentKey(ACCOUNT_A))).toBeNull();
- });
-
it('creates a fresh namespaced idempotency key per user action', () => {
vi.stubGlobal('crypto', { randomUUID: () => '00000000-0000-4000-8000-000000000001' });
expect(newBillingIdempotencyKey('subscription')).toBe(
@@ -74,91 +20,35 @@ describe('billing checkout intent', () => {
vi.unstubAllGlobals();
});
- it('round-trips a retry intent without storing catalog or provider data', () => {
- const intent = {
- version: 1 as const,
- kind: 'TOPUP_RETRY' as const,
- idempotencyKey: 'desktop:retry:fixture-0001',
- orderId: 'order_fixture',
- createdAt: '2026-01-01T00:00:00.000Z',
- };
- writeBillingCheckoutIntent(ACCOUNT_A, intent);
- expect(readBillingCheckoutIntent(ACCOUNT_A)).toEqual(intent);
- });
-
- it('keeps checkout recovery isolated between accounts', () => {
- const intent = {
- version: 1 as const,
- kind: 'TOPUP_RETRY' as const,
- idempotencyKey: 'desktop:retry:fixture-0001',
- orderId: 'order_fixture',
- createdAt: '2026-01-01T00:00:00.000Z',
- };
- writeBillingCheckoutIntent(ACCOUNT_A, intent);
-
- expect(readBillingCheckoutIntent(ACCOUNT_B)).toBeNull();
- expect(readBillingCheckoutIntent(ACCOUNT_A)).toEqual(intent);
- });
-
- it('drops legacy unscoped recovery instead of assigning it to the active account', () => {
+ it('removes every legacy persisted intent for the active account', () => {
+ localStorage.setItem('cindy.billing.checkout-intent.v1', JSON.stringify({ version: 1 }));
localStorage.setItem(
- 'cindy.billing.checkout-intent.v1',
- JSON.stringify({
- version: 1,
- kind: 'TOPUP_RETRY',
- idempotencyKey: 'desktop:retry:fixture-0001',
- orderId: 'order_fixture',
- createdAt: '2026-01-01T00:00:00.000Z',
- }),
+ `cindy.billing.checkout-intent.v2:${encodeURIComponent(ACCOUNT_A)}`,
+ JSON.stringify({ version: 1, kind: 'TOPUP' }),
);
-
- expect(readBillingCheckoutIntent(ACCOUNT_A)).toBeNull();
- expect(localStorage.getItem('cindy.billing.checkout-intent.v1')).toBeNull();
- });
-});
-
-describe('billing plan change intent persistence', () => {
- beforeEach(() => {
- localStorage.clear();
- });
-
- const intent = {
- version: 1 as const,
- targetOfferCode: 'max_month',
- idempotencyKey: 'desktop:plan-change:fixture-0001',
- planChangeId: 'plan_change_1',
- createdAt: '2026-07-24T00:00:00.000Z',
- };
-
- it('round-trips a valid intent per account', () => {
- writeBillingPlanChangeIntent(ACCOUNT_A, intent);
-
- expect(readBillingPlanChangeIntent(ACCOUNT_A)).toEqual(intent);
- expect(readBillingPlanChangeIntent(ACCOUNT_B)).toBeNull();
- });
-
- it('drops a tampered or extended intent instead of replaying it', () => {
- localStorage.setItem(
- billingPlanChangeIntentKey(ACCOUNT_A),
- JSON.stringify({ ...intent, provider: 'alipay' }),
- );
- expect(readBillingPlanChangeIntent(ACCOUNT_A)).toBeNull();
-
localStorage.setItem(
- billingPlanChangeIntentKey(ACCOUNT_A),
- JSON.stringify({ ...intent, targetOfferCode: 'Bad Code!' }),
+ `cindy.billing.plan-change-intent.v1:${encodeURIComponent(ACCOUNT_A)}`,
+ JSON.stringify({ version: 1 }),
);
- expect(readBillingPlanChangeIntent(ACCOUNT_A)).toBeNull();
- expect(localStorage.getItem(billingPlanChangeIntentKey(ACCOUNT_A))).toBeNull();
- });
-
- it('clears only the requested account intent', () => {
- writeBillingPlanChangeIntent(ACCOUNT_A, intent);
- writeBillingPlanChangeIntent(ACCOUNT_B, { ...intent, planChangeId: null });
+ const otherKey = `cindy.billing.checkout-intent.v2:${encodeURIComponent(ACCOUNT_B)}`;
+ localStorage.setItem(otherKey, JSON.stringify({ version: 1, kind: 'TOPUP' }));
- clearBillingPlanChangeIntent(ACCOUNT_A);
+ clearLegacyBillingIntentStorage(ACCOUNT_A);
- expect(readBillingPlanChangeIntent(ACCOUNT_A)).toBeNull();
- expect(readBillingPlanChangeIntent(ACCOUNT_B)).toEqual({ ...intent, planChangeId: null });
+ expect(localStorage.getItem('cindy.billing.checkout-intent.v1')).toBeNull();
+ expect(
+ localStorage.getItem(`cindy.billing.checkout-intent.v2:${encodeURIComponent(ACCOUNT_A)}`),
+ ).toBeNull();
+ expect(
+ localStorage.getItem(`cindy.billing.plan-change-intent.v1:${encodeURIComponent(ACCOUNT_A)}`),
+ ).toBeNull();
+ // 其他账号的残留由其自身会话启动时清理。
+ expect(localStorage.getItem(otherKey)).not.toBeNull();
+ });
+
+ it('still removes the unscoped legacy key when no account is active', () => {
+ localStorage.setItem('cindy.billing.checkout-intent.v1', JSON.stringify({ version: 1 }));
+ clearLegacyBillingIntentStorage(null);
+ expect(localStorage.getItem('cindy.billing.checkout-intent.v1')).toBeNull();
});
});
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.ts b/apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.ts
index 2929ba6053..ae555ecb08 100644
--- a/apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.ts
+++ b/apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.ts
@@ -16,40 +16,29 @@ const api = vi.hoisted(() => ({
vi.mock('../api', () => ({ billingApi: api }));
-import {
- isRecoverableTopup,
- phaseForOrder,
- phaseForSubscription,
- useBillingCheckout,
-} from '../useBillingCheckout';
-import { readBillingCheckoutIntent, writeBillingCheckoutIntent } from '../checkoutIntent';
+import { phaseForOrder, phaseForSubscription, useBillingCheckout } from '../useBillingCheckout';
const ACCOUNT_ID = 'account-fixture';
-describe('billing checkout phase projection', () => {
- beforeEach(() => {
- localStorage.clear();
- api.listOrders.mockReset().mockResolvedValue({ orders: [], nextCursor: null });
- api.getCurrentSubscription.mockReset().mockResolvedValue({ subscription: null });
- api.createTopup.mockReset();
- api.createSubscription.mockReset();
- api.retryTopup.mockReset();
- api.refreshTopup.mockReset();
- api.refreshSubscriptionPurchase.mockReset();
- api.getOrder.mockReset();
- Object.defineProperty(document, 'visibilityState', {
- configurable: true,
- value: 'visible',
- });
- vi.stubGlobal('crypto', {
- randomUUID: () => '00000000-0000-4000-8000-000000000001',
- });
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
- });
+function pendingOrder(orderId = 'order_pending') {
+ return {
+ orderId,
+ productCode: 'credit_topup',
+ offerCode: 'credit_topup_20',
+ amount: '20',
+ currency: 'cny',
+ status: 'PENDING' as const,
+ paymentAction: {
+ type: 'QR_CODE' as const,
+ value: 'https://qr.example/1',
+ expiresAt: new Date(Date.now() + 300_000).toISOString(),
+ },
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:01:00.000Z',
+ };
+}
+describe('billing checkout phase projection', () => {
it('treats successful top-ups as completed regardless of fulfillment projection', () => {
const base = {
orderId: 'order_fixture',
@@ -64,7 +53,6 @@ describe('billing checkout phase projection', () => {
};
expect(phaseForOrder(base)).toBe('COMPLETED');
expect(phaseForOrder({ ...base, fulfillmentStatus: 'PENDING' })).toBe('COMPLETED');
- expect(phaseForOrder({ ...base, fulfillmentStatus: 'SUCCEEDED' })).toBe('COMPLETED');
expect(phaseForOrder({ ...base, fulfillmentStatus: 'FAILED' })).toBe('COMPLETED');
});
@@ -81,601 +69,257 @@ describe('billing checkout phase projection', () => {
paymentAction: null,
};
expect(phaseForSubscription(base)).toBe('COMPLETED');
- expect(phaseForSubscription({ ...base, entitlementStatus: 'SUCCEEDED' })).toBe('COMPLETED');
expect(phaseForSubscription({ ...base, entitlementStatus: 'FAILED' })).toBe('COMPLETED');
});
+});
- it('lets the server confirm expiry instead of trusting the client clock', () => {
- const pendingOrder = {
- status: 'PENDING' as const,
- paymentAction: {
- expiresAt: '2000-01-01T00:00:00.000Z',
- },
- };
- expect(isRecoverableTopup(pendingOrder)).toBe(true);
- });
-
- it('keeps created top-ups with a payment action recoverable', () => {
- const createdOrder = {
- status: 'CREATED' as const,
- paymentAction: {
- expiresAt: '2099-01-01T00:00:00.000Z',
- },
- };
- expect(isRecoverableTopup(createdOrder)).toBe(true);
- });
+describe('useBillingCheckout ephemeral sessions', () => {
+ let uuidCounter = 0;
- it('keeps pending top-ups recoverable before a payment action is projected', () => {
- const createdOrder = { status: 'CREATED' as const, paymentAction: null };
- const pendingOrder = { status: 'PENDING' as const, paymentAction: null };
- expect(isRecoverableTopup(createdOrder)).toBe(true);
- expect(isRecoverableTopup(pendingOrder)).toBe(true);
+ beforeEach(() => {
+ localStorage.clear();
+ for (const mock of Object.values(api)) mock.mockReset();
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ value: 'visible',
+ });
+ uuidCounter = 0;
+ vi.stubGlobal('crypto', {
+ randomUUID: () => `00000000-0000-4000-8000-${String(++uuidCounter).padStart(12, '0')}`,
+ });
});
- it('never treats successful top-ups as recoverable', () => {
- const base = {
- orderId: 'order_paid',
- productCode: 'credit_topup',
- offerCode: 'credit_topup_20',
- amount: '20',
- currency: 'cny',
- status: 'SUCCEEDED' as const,
- paymentAction: null,
- createdAt: '2026-01-01T00:00:00.000Z',
- updatedAt: '2026-01-01T00:01:00.000Z',
- };
- for (const fulfillmentStatus of [undefined, 'PENDING', 'FAILED', 'SUCCEEDED'] as const) {
- const order = fulfillmentStatus ? { ...base, fulfillmentStatus } : base;
- expect(isRecoverableTopup(order)).toBe(false);
- }
+ afterEach(() => {
+ vi.restoreAllMocks();
});
- it('completes a successful top-up immediately and clears its checkout intent', async () => {
- const paidOrder = {
- orderId: 'order_paid',
- productCode: 'credit_topup',
- offerCode: 'credit_topup_20',
- amount: '20',
- currency: 'cny',
- status: 'SUCCEEDED' as const,
- paymentAction: null,
- createdAt: '2026-01-01T00:00:00.000Z',
- updatedAt: '2026-01-01T00:01:00.000Z',
- };
- api.createTopup.mockResolvedValue(paidOrder);
- const setIntervalSpy = vi.spyOn(window, 'setInterval');
+ it('does not call any billing API on startup and never restores past checkouts', async () => {
const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
- await waitFor(() => expect(result.current.recovering).toBe(false));
+ await waitFor(() => expect(result.current.state.phase).toBe('IDLE'));
+ expect(api.listOrders).not.toHaveBeenCalled();
+ expect(api.getCurrentSubscription).not.toHaveBeenCalled();
+ expect(api.getOrder).not.toHaveBeenCalled();
+ expect(result.current.state.open).toBe(false);
+ });
- await act(() =>
- result.current.startTopup({
- offerCode: 'credit_topup_20',
- purchaseOptionId: 'listing_alipay',
+ it('clears legacy persisted intents without replaying them', async () => {
+ const legacyKey = `cindy.billing.checkout-intent.v2:${encodeURIComponent(ACCOUNT_ID)}`;
+ localStorage.setItem(
+ legacyKey,
+ JSON.stringify({
+ version: 1,
+ kind: 'TOPUP',
+ idempotencyKey: 'desktop:topup:legacy',
+ request: { offerCode: 'credit_topup_20', purchaseOptionId: 'option_1' },
+ orderId: 'order_legacy',
+ createdAt: '2026-01-01T00:00:00.000Z',
}),
);
-
- expect(result.current.state.phase).toBe('COMPLETED');
- expect(result.current.recoverables.topups).toEqual([]);
- expect(readBillingCheckoutIntent(ACCOUNT_ID)).toBeNull();
+ localStorage.setItem(
+ `cindy.billing.plan-change-intent.v1:${encodeURIComponent(ACCOUNT_ID)}`,
+ JSON.stringify({ version: 1 }),
+ );
+ renderHook(() => useBillingCheckout(ACCOUNT_ID));
+ await waitFor(() => expect(localStorage.getItem(legacyKey)).toBeNull());
+ expect(
+ localStorage.getItem(`cindy.billing.plan-change-intent.v1:${encodeURIComponent(ACCOUNT_ID)}`),
+ ).toBeNull();
+ expect(api.createTopup).not.toHaveBeenCalled();
+ expect(api.retryTopup).not.toHaveBeenCalled();
expect(api.getOrder).not.toHaveBeenCalled();
- expect(setIntervalSpy).not.toHaveBeenCalledWith(expect.any(Function), 3_000);
});
- it('replays an unresolved persisted purchase in the background without opening it', async () => {
- const pending = {
- subscriptionId: 'subscription_pending',
- status: 'INCOMPLETE' as const,
- currentPeriodStartAt: null,
- currentPeriodEndAt: null,
- entitlementValidUntil: null,
- cancelAtPeriodEnd: false,
- effectivePlan: null,
- purchaseAttemptId: 'purchase_pending',
- paymentAction: {
- type: 'QR_CODE' as const,
- value: 'alipays://pending',
- expiresAt: '2099-01-01T00:00:00.000Z',
- },
- };
- api.createSubscription.mockResolvedValue(pending);
- writeBillingCheckoutIntent(ACCOUNT_ID, {
- version: 1,
- kind: 'SUBSCRIPTION',
- idempotencyKey: 'desktop:subscription:stale-intent',
- request: {
- offerCode: 'retired_plus_month',
- purchaseOptionId: 'listing_alipay',
- },
- subscriptionId: null,
- purchaseAttemptId: null,
- createdAt: '2026-01-01T00:00:00.000Z',
- });
+ it('sends a fresh idempotency key after the dialog is closed and reopened', async () => {
+ api.createTopup.mockResolvedValue(pendingOrder());
+ const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
+ const request = { offerCode: 'credit_topup_20', purchaseOptionId: 'option_1' };
+
+ await act(() => result.current.startTopup(request));
+ const firstKey = api.createTopup.mock.calls[0][1] as string;
+ act(() => result.current.close());
+ expect(result.current.state.phase).toBe('IDLE');
+ expect(result.current.state.order).toBeNull();
+
+ await act(() => result.current.startTopup(request));
+ const secondKey = api.createTopup.mock.calls[1][1] as string;
+ expect(secondKey).not.toBe(firstKey);
+ });
+
+ it('keeps polling the open session and completes when the server reports success', async () => {
+ const order = pendingOrder();
+ api.createTopup.mockResolvedValue(order);
+ api.refreshTopup.mockResolvedValue({ ...order, status: 'SUCCEEDED', paymentAction: null });
const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
- await waitFor(() => expect(result.current.recovering).toBe(false));
- expect(api.listOrders).toHaveBeenCalledTimes(1);
- expect(api.getCurrentSubscription).toHaveBeenCalledTimes(1);
- expect(api.createTopup).not.toHaveBeenCalled();
- expect(api.createSubscription).toHaveBeenCalledWith(
- {
- offerCode: 'retired_plus_month',
- purchaseOptionId: 'listing_alipay',
- },
- 'desktop:subscription:stale-intent',
+ await act(() =>
+ result.current.startTopup({ offerCode: 'credit_topup_20', purchaseOptionId: 'option_1' }),
);
- expect(result.current.state.open).toBe(false);
expect(result.current.state.phase).toBe('AWAITING_PAYMENT');
- expect(result.current.recoverables.subscription).toEqual(pending);
- expect(readBillingCheckoutIntent(ACCOUNT_ID)).toEqual({
- version: 1,
- kind: 'SUBSCRIPTION',
- idempotencyKey: 'desktop:subscription:stale-intent',
- request: {
- offerCode: 'retired_plus_month',
- purchaseOptionId: 'listing_alipay',
- },
- subscriptionId: 'subscription_pending',
- purchaseAttemptId: 'purchase_pending',
- createdAt: '2026-01-01T00:00:00.000Z',
- });
- act(() => result.current.resumeSubscription(result.current.recoverables.subscription!));
- expect(result.current.state.open).toBe(true);
- expect(result.current.state.subscription).toEqual(pending);
+ await act(() => result.current.refreshActive());
+ expect(api.refreshTopup).toHaveBeenCalledWith(order.orderId);
+ expect(result.current.state.phase).toBe('COMPLETED');
});
- it('completes a restored successful top-up in the background without polling', async () => {
- const paidOrder = {
- orderId: 'order_paid',
- productCode: 'credit_topup',
- offerCode: 'credit_topup_20',
- amount: '20',
- currency: 'cny',
- status: 'SUCCEEDED' as const,
- fulfillmentStatus: 'PENDING' as const,
- paymentAction: null,
- createdAt: '2026-01-01T00:00:00.000Z',
- updatedAt: '2026-01-01T00:01:00.000Z',
- };
- writeBillingCheckoutIntent(ACCOUNT_ID, {
- version: 1,
- kind: 'TOPUP',
- idempotencyKey: 'desktop:topup:paid-intent',
- request: {
- offerCode: 'credit_topup_20',
- purchaseOptionId: 'listing_alipay',
- },
- orderId: paidOrder.orderId,
- createdAt: '2026-01-01T00:00:00.000Z',
- });
- api.listOrders.mockResolvedValue({ orders: [paidOrder], nextCursor: null });
- const setIntervalSpy = vi.spyOn(window, 'setInterval');
-
+ it('lets an expired session end and a new selection start over with a new key', async () => {
+ const order = pendingOrder();
+ api.createTopup.mockResolvedValueOnce(order);
+ api.refreshTopup.mockResolvedValue({ ...order, status: 'EXPIRED', paymentAction: null });
const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
- await waitFor(() => expect(result.current.recovering).toBe(false));
- expect(result.current.state).toMatchObject({
- open: false,
- phase: 'COMPLETED',
- order: paidOrder,
- });
- act(() => window.dispatchEvent(new Event('focus')));
+ await act(() =>
+ result.current.startTopup({ offerCode: 'credit_topup_20', purchaseOptionId: 'option_1' }),
+ );
+ await act(() => result.current.refreshActive());
+ expect(result.current.state.phase).toBe('EXPIRED');
- expect(api.getOrder).not.toHaveBeenCalled();
- expect(setIntervalSpy).not.toHaveBeenCalledWith(expect.any(Function), 3_000);
- expect(result.current.state.open).toBe(false);
- expect(result.current.recoverables.topups).toEqual([]);
- expect(readBillingCheckoutIntent(ACCOUNT_ID)).toBeNull();
+ api.createTopup.mockResolvedValueOnce(pendingOrder('order_next'));
+ act(() => result.current.close());
+ await act(() =>
+ result.current.startTopup({ offerCode: 'credit_topup_20', purchaseOptionId: 'option_1' }),
+ );
+ expect(result.current.state.order?.orderId).toBe('order_next');
+ const keys = api.createTopup.mock.calls.map((call) => call[1]);
+ expect(new Set(keys).size).toBe(keys.length);
});
- it('does not replace a persisted subscription intent with another current subscription', async () => {
- const intent = {
- version: 1 as const,
- kind: 'SUBSCRIPTION' as const,
- idempotencyKey: 'desktop:subscription:pending-intent',
- request: {
- offerCode: 'plus_month',
- purchaseOptionId: 'listing_alipay',
- },
- subscriptionId: 'subscription_expected',
- purchaseAttemptId: 'purchase_expected',
- createdAt: '2026-01-01T00:00:00.000Z',
- };
- const unrelated = {
- subscriptionId: 'subscription_other',
- status: 'ACTIVE' as const,
+ it('creates a subscription session and polls it through the purchase attempt only', async () => {
+ const incomplete = {
+ subscriptionId: 'subscription_1',
+ status: 'INCOMPLETE' as const,
currentPeriodStartAt: null,
currentPeriodEndAt: null,
entitlementValidUntil: null,
cancelAtPeriodEnd: false,
effectivePlan: null,
- purchaseAttemptId: 'purchase_other',
- paymentAction: null,
- };
- writeBillingCheckoutIntent(ACCOUNT_ID, intent);
- api.getCurrentSubscription.mockResolvedValue({ subscription: unrelated });
- api.refreshSubscriptionPurchase.mockResolvedValue(unrelated);
-
- const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
- await waitFor(() => expect(result.current.recovering).toBe(false));
-
- expect(api.refreshSubscriptionPurchase).toHaveBeenCalledWith('purchase_expected');
- expect(result.current.state).toMatchObject({
- open: false,
- phase: 'FAILED',
- intent,
- subscription: null,
- error: true,
- });
- expect(readBillingCheckoutIntent(ACCOUNT_ID)).toEqual(intent);
- });
-
- it('accepts a terminal same-subscription result after its purchase attempt is cleared', async () => {
- const intent = {
- version: 1 as const,
- kind: 'SUBSCRIPTION' as const,
- idempotencyKey: 'desktop:subscription:completed-intent',
- request: {
- offerCode: 'plus_month',
- purchaseOptionId: 'listing_alipay',
+ purchaseAttemptId: 'attempt_1',
+ paymentAction: {
+ type: 'QR_CODE' as const,
+ value: 'https://qr.example/sub',
+ expiresAt: new Date(Date.now() + 300_000).toISOString(),
},
- subscriptionId: 'subscription_expected',
- purchaseAttemptId: 'purchase_expected',
- createdAt: '2026-01-01T00:00:00.000Z',
};
- const completed = {
- subscriptionId: 'subscription_expected',
+ api.createSubscription.mockResolvedValue(incomplete);
+ api.refreshSubscriptionPurchase.mockResolvedValue({
+ ...incomplete,
status: 'ACTIVE' as const,
- currentPeriodStartAt: '2026-01-01T00:00:00.000Z',
- currentPeriodEndAt: '2026-02-01T00:00:00.000Z',
- entitlementValidUntil: '2026-02-01T00:00:00.000Z',
- cancelAtPeriodEnd: false,
- effectivePlan: null,
- purchaseAttemptId: null,
paymentAction: null,
- };
- writeBillingCheckoutIntent(ACCOUNT_ID, intent);
- api.getCurrentSubscription.mockResolvedValue({ subscription: completed });
- api.refreshSubscriptionPurchase.mockResolvedValue(completed);
-
- const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
- await waitFor(() => expect(result.current.recovering).toBe(false));
-
- expect(api.refreshSubscriptionPurchase).toHaveBeenCalledWith('purchase_expected');
- expect(result.current.state).toMatchObject({
- open: false,
- phase: 'COMPLETED',
- subscription: completed,
- error: false,
});
- expect(readBillingCheckoutIntent(ACCOUNT_ID)).toBeNull();
- });
-
- it('clears an expired persisted top-up without opening a dialog', async () => {
- const intent = {
- version: 1 as const,
- kind: 'TOPUP' as const,
- idempotencyKey: 'desktop:topup:expired-intent',
- request: {
- offerCode: 'credit_topup_20',
- purchaseOptionId: 'listing_alipay',
- },
- orderId: 'order_expired',
- createdAt: '2026-01-01T00:00:00.000Z',
- };
- const expiredOrder = {
- orderId: 'order_expired',
- productCode: 'credit_topup',
- offerCode: 'credit_topup_20',
- amount: '20',
- currency: 'cny',
- status: 'EXPIRED' as const,
- paymentAction: null,
- createdAt: '2026-01-01T00:00:00.000Z',
- updatedAt: '2026-01-01T00:01:00.000Z',
- };
- writeBillingCheckoutIntent(ACCOUNT_ID, intent);
- api.listOrders.mockResolvedValue({ orders: [expiredOrder], nextCursor: null });
-
const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
- await waitFor(() => expect(result.current.recovering).toBe(false));
- expect(result.current.state).toMatchObject({
- open: false,
- phase: 'EXPIRED',
- order: expiredOrder,
- });
- expect(result.current.recoverables.topups).toEqual([]);
- expect(readBillingCheckoutIntent(ACCOUNT_ID)).toBeNull();
- });
-
- it('clears an expired persisted subscription purchase without opening a dialog', async () => {
- const intent = {
- version: 1 as const,
- kind: 'SUBSCRIPTION' as const,
- idempotencyKey: 'desktop:subscription:expired-intent',
- request: {
- offerCode: 'plus_month',
- purchaseOptionId: 'listing_alipay',
- },
- subscriptionId: 'subscription_expired',
- purchaseAttemptId: 'purchase_expired',
- createdAt: '2026-01-01T00:00:00.000Z',
- };
- const expiredSubscription = {
- subscriptionId: 'subscription_expired',
- status: 'INCOMPLETE_EXPIRED' as const,
- currentPeriodStartAt: null,
- currentPeriodEndAt: null,
- entitlementValidUntil: null,
- cancelAtPeriodEnd: false,
- effectivePlan: null,
- purchaseAttemptId: 'purchase_expired',
- paymentAction: null,
- };
- writeBillingCheckoutIntent(ACCOUNT_ID, intent);
- api.getCurrentSubscription.mockResolvedValue({ subscription: expiredSubscription });
- api.refreshSubscriptionPurchase.mockResolvedValue(expiredSubscription);
-
- const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
- await waitFor(() => expect(result.current.recovering).toBe(false));
+ await act(() =>
+ result.current.startSubscription({ offerCode: 'pro_monthly', purchaseOptionId: 'option_1' }),
+ );
+ expect(result.current.state.phase).toBe('AWAITING_PAYMENT');
- expect(result.current.state).toMatchObject({
- open: false,
- phase: 'EXPIRED',
- subscription: expiredSubscription,
- });
- expect(result.current.recoverables.subscription).toBeNull();
- expect(readBillingCheckoutIntent(ACCOUNT_ID)).toBeNull();
+ await act(() => result.current.refreshActive());
+ expect(api.refreshSubscriptionPurchase).toHaveBeenCalledWith('attempt_1');
+ expect(api.getCurrentSubscription).not.toHaveBeenCalled();
+ expect(result.current.state.phase).toBe('COMPLETED');
});
- it('lists a pending top-up as recoverable without opening it, then opens on resume', async () => {
- const pendingOrder = {
- orderId: 'order_pending',
- productCode: 'credit_topup',
- offerCode: 'credit_topup_20',
- amount: '20',
- currency: 'cny',
- status: 'PENDING' as const,
- paymentAction: null,
- createdAt: '2026-01-01T00:00:00.000Z',
- updatedAt: '2026-01-01T00:01:00.000Z',
- };
- const succeededOrder = {
- ...pendingOrder,
- orderId: 'order_succeeded',
- status: 'SUCCEEDED' as const,
- };
- api.listOrders.mockResolvedValue({
- orders: [
- succeededOrder,
- { ...succeededOrder, orderId: 'order_succeeded_legacy', fulfillmentStatus: 'FAILED' },
- pendingOrder,
- ],
- nextCursor: null,
- });
-
+ it('marks the session failed when create errors and replays the same key on retry', async () => {
+ api.createTopup.mockRejectedValueOnce(new Error('offline'));
const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
- await waitFor(() => expect(result.current.recovering).toBe(false));
-
- expect(result.current.state.open).toBe(false);
- expect(result.current.recoverables.topups).toEqual([pendingOrder]);
- act(() => result.current.resumeTopup(result.current.recoverables.topups[0]));
- expect(result.current.state).toMatchObject({
- open: true,
- phase: 'AWAITING_PAYMENT',
- order: pendingOrder,
- });
- });
-
- it('keeps an unresolved persisted purchase retryable when recovery fails', async () => {
- const intent = {
- version: 1 as const,
- kind: 'TOPUP' as const,
- idempotencyKey: 'desktop:topup:unresolved-intent',
- request: {
- offerCode: 'credit_topup_custom',
- amount: '20',
- purchaseOptionId: 'listing_alipay',
- },
- orderId: null,
- createdAt: '2026-01-01T00:00:00.000Z',
- };
- writeBillingCheckoutIntent(ACCOUNT_ID, intent);
- api.createTopup.mockRejectedValue(new Error('network result unknown'));
+ await act(() =>
+ result.current.startTopup({ offerCode: 'credit_topup_20', purchaseOptionId: 'option_1' }),
+ );
+ expect(result.current.state.phase).toBe('FAILED');
+ expect(result.current.state.error).toBe(true);
- const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
- await waitFor(() => expect(result.current.recovering).toBe(false));
-
- expect(result.current.state).toMatchObject({
- open: false,
- kind: 'TOPUP',
- phase: 'FAILED',
- intent,
- error: true,
- });
- expect(readBillingCheckoutIntent(ACCOUNT_ID)).toEqual(intent);
-
- act(() => result.current.resumeFailed());
- expect(result.current.state).toMatchObject({
- open: true,
- phase: 'FAILED',
- intent,
- error: true,
- });
- expect(readBillingCheckoutIntent(ACCOUNT_ID)).toEqual(intent);
+ api.createTopup.mockResolvedValueOnce(pendingOrder());
+ await act(() => result.current.retry());
+ expect(api.createTopup.mock.calls[1][1]).toBe(api.createTopup.mock.calls[0][1]);
+ expect(result.current.state.phase).toBe('AWAITING_PAYMENT');
});
- it('does not bind an unidentified intent to another pending subscription', async () => {
- const unrelated = {
- subscriptionId: 'subscription_other',
- status: 'INCOMPLETE' as const,
- currentPeriodStartAt: null,
- currentPeriodEndAt: null,
- entitlementValidUntil: null,
- cancelAtPeriodEnd: false,
- effectivePlan: null,
- purchaseAttemptId: 'purchase_other',
- paymentAction: {
- type: 'QR_CODE' as const,
- value: 'alipays://pending',
- expiresAt: '2099-01-01T00:00:00.000Z',
- },
- };
- api.createSubscription.mockRejectedValue(new Error('SUBSCRIPTION_NOT_MANAGEABLE'));
- api.getCurrentSubscription
- .mockResolvedValueOnce({ subscription: null })
- .mockResolvedValueOnce({ subscription: unrelated });
-
+ it('ignores in-flight responses after the dialog is closed instead of reopening it', async () => {
+ let release!: (value: unknown) => void;
+ api.createTopup.mockImplementation(() => new Promise((resolve) => (release = resolve)));
const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
- await waitFor(() => expect(result.current.recovering).toBe(false));
- await act(async () =>
- result.current.startSubscription({
- offerCode: 'plus_month',
- purchaseOptionId: 'listing_alipay',
- }),
- );
-
- expect(api.getCurrentSubscription).toHaveBeenCalledTimes(1);
- expect(result.current.state).toMatchObject({
- phase: 'FAILED',
- subscription: null,
- error: true,
- });
- expect(result.current.state.intent).toMatchObject({
- subscriptionId: null,
- purchaseAttemptId: null,
+ let started!: Promise<void>;
+ act(() => {
+ started = result.current.startTopup({
+ offerCode: 'credit_topup_20',
+ purchaseOptionId: 'option_1',
+ });
});
- });
+ act(() => result.current.close());
+ expect(result.current.state.open).toBe(false);
- it('reuses the same retry key while the retry result is unknown', async () => {
- const failedOrder = {
- orderId: 'order_fixture',
- productCode: 'credit_topup',
- offerCode: 'credit_topup_20',
- amount: '20',
- currency: 'cny',
- status: 'FAILED' as const,
- paymentAction: null,
- createdAt: '2026-01-01T00:00:00.000Z',
- updatedAt: '2026-01-01T00:01:00.000Z',
- };
- api.retryTopup.mockRejectedValue(new Error('network result unknown'));
+ await act(async () => {
+ release(pendingOrder());
+ await started;
+ });
- const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
- await waitFor(() => expect(result.current.recovering).toBe(false));
-
- act(() => result.current.resumeTopup(failedOrder));
- await act(async () => result.current.retry());
- await act(async () => result.current.retry());
-
- expect(api.retryTopup).toHaveBeenCalledTimes(2);
- expect(api.retryTopup.mock.calls[0]).toEqual(api.retryTopup.mock.calls[1]);
- expect(api.retryTopup.mock.calls[0]).toEqual([
- 'order_fixture',
- 'desktop:retry:00000000-0000-4000-8000-000000000001',
- ]);
+ // 关闭已结束该结算会话:迟到的创建响应不得重开弹窗或恢复旧支付动作。
+ expect(result.current.state).toMatchObject({ open: false, phase: 'IDLE', order: null });
});
- it('refreshes on focus without allowing concurrent status requests', async () => {
- const pendingOrder = {
- orderId: 'order_fixture',
- productCode: 'credit_topup',
- offerCode: 'credit_topup_20',
- amount: '20',
- currency: 'cny',
- status: 'PENDING' as const,
- paymentAction: {
- type: 'QR_CODE' as const,
- value: 'https://pay.example.test/checkout/fixture',
- expiresAt: '2099-01-01T00:00:00.000Z',
- },
- createdAt: '2026-01-01T00:00:00.000Z',
- updatedAt: '2026-01-01T00:01:00.000Z',
- };
- let resolveRefresh: ((value: typeof pendingOrder) => void) | null = null;
- api.refreshTopup.mockImplementation(
- () =>
- new Promise<typeof pendingOrder>((resolve) => {
- resolveRefresh = resolve;
- }),
- );
-
+ it('ignores a late refresh error after the dialog is closed', async () => {
+ const order = pendingOrder();
+ api.createTopup.mockResolvedValue(order);
+ let reject!: (error: unknown) => void;
+ api.refreshTopup.mockImplementation(() => new Promise((_, rej) => (reject = rej)));
const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
- await waitFor(() => expect(result.current.recovering).toBe(false));
- act(() => result.current.resumeTopup(pendingOrder));
- await waitFor(() => expect(result.current.state.phase).toBe('AWAITING_PAYMENT'));
+ await act(() =>
+ result.current.startTopup({ offerCode: 'credit_topup_20', purchaseOptionId: 'option_1' }),
+ );
+ let refreshing!: Promise<void>;
act(() => {
- window.dispatchEvent(new Event('focus'));
- window.dispatchEvent(new Event('focus'));
+ refreshing = result.current.refreshActive();
+ });
+ act(() => result.current.close());
+ await act(async () => {
+ reject(new Error('offline'));
+ await refreshing;
});
- await waitFor(() => expect(api.refreshTopup).toHaveBeenCalledTimes(1));
- await act(async () => resolveRefresh?.(pendingOrder));
- expect(api.refreshTopup).toHaveBeenCalledWith('order_fixture');
+ expect(result.current.state).toMatchObject({ open: false, phase: 'IDLE', error: false });
});
- it('keeps a visible checkout open when refresh reports it expired', async () => {
- const pendingOrder = {
- orderId: 'order_fixture',
- productCode: 'credit_topup',
- offerCode: 'credit_topup_20',
- amount: '20',
- currency: 'cny',
- status: 'PENDING' as const,
- paymentAction: null,
- createdAt: '2026-01-01T00:00:00.000Z',
- updatedAt: '2026-01-01T00:01:00.000Z',
- };
- api.refreshTopup.mockResolvedValue({
- ...pendingOrder,
- status: 'EXPIRED',
+ it('does not let a queued poll callback refresh the abandoned order after close', async () => {
+ const order = pendingOrder();
+ api.createTopup.mockResolvedValue(order);
+ let queuedFocus: EventListener | null = null;
+ const addEventListener = vi.spyOn(window, 'addEventListener');
+ addEventListener.mockImplementation((type, listener) => {
+ if (type === 'focus') queuedFocus = listener as EventListener;
});
-
const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
- await waitFor(() => expect(result.current.recovering).toBe(false));
- act(() => result.current.resumeTopup(pendingOrder));
- await act(() => result.current.refreshActive());
+ await act(() =>
+ result.current.startTopup({ offerCode: 'credit_topup_20', purchaseOptionId: 'option_1' }),
+ );
+ expect(queuedFocus).not.toBeNull();
- expect(result.current.state).toMatchObject({
- open: true,
- phase: 'EXPIRED',
+ await act(async () => {
+ result.current.close();
+ queuedFocus!(new Event('focus'));
+ await Promise.resolve();
});
- });
- it('keeps a pending checkout recoverable after its dialog is closed', async () => {
- const pendingOrder = {
- orderId: 'order_pending',
- productCode: 'credit_topup',
- offerCode: 'credit_topup_20',
- amount: '20',
- currency: 'cny',
- status: 'PENDING' as const,
- paymentAction: {
- type: 'QR_CODE' as const,
- value: 'https://pay.example.test/checkout/pending',
- expiresAt: '2099-01-01T00:00:00.000Z',
- },
- createdAt: '2026-01-01T00:00:00.000Z',
- updatedAt: '2026-01-01T00:01:00.000Z',
- };
+ expect(api.refreshTopup).not.toHaveBeenCalled();
+ expect(result.current.state).toMatchObject({ open: false, phase: 'IDLE', order: null });
+ });
+ it('retries a failed order through the retry endpoint with a new key', async () => {
+ const failed = { ...pendingOrder(), status: 'FAILED' as const, paymentAction: null };
+ api.createTopup.mockResolvedValueOnce(failed);
+ api.retryTopup.mockResolvedValueOnce(pendingOrder());
const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
- await waitFor(() => expect(result.current.recovering).toBe(false));
-
- act(() => result.current.resumeTopup(pendingOrder));
- act(() => result.current.close());
- expect(result.current.state.open).toBe(false);
- expect(result.current.recoverables.topups).toEqual([pendingOrder]);
+ await act(() =>
+ result.current.startTopup({ offerCode: 'credit_topup_20', purchaseOptionId: 'option_1' }),
+ );
+ expect(result.current.state.phase).toBe('FAILED');
- act(() => result.current.resumeTopup(result.current.recoverables.topups[0]));
- expect(result.current.state.open).toBe(true);
- expect(result.current.state.order).toEqual(pendingOrder);
+ await act(() => result.current.retry());
+ expect(api.retryTopup).toHaveBeenCalledWith(failed.orderId, expect.stringMatching(/^desktop:retry:/));
+ expect(result.current.state.phase).toBe('AWAITING_PAYMENT');
});
});
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/usePlanChange.test.ts b/apps/desktop/src/renderer/features/billing/__tests__/usePlanChange.test.ts
index 68f74a97ed..8d44d56bca 100644
--- a/apps/desktop/src/renderer/features/billing/__tests__/usePlanChange.test.ts
+++ b/apps/desktop/src/renderer/features/billing/__tests__/usePlanChange.test.ts
@@ -14,11 +14,6 @@ const api = vi.hoisted(() => ({
vi.mock('../api', () => ({ billingApi: api }));
import { usePlanChange } from '../usePlanChange';
-import {
- billingPlanChangeIntentKey,
- readBillingPlanChangeIntent,
- writeBillingPlanChangeIntent,
-} from '../checkoutIntent';
import type { BillingPlanChange } from '../../../../shared/billing';
const ACCOUNT_ID = 'account-fixture';
@@ -71,10 +66,6 @@ describe('usePlanChange', () => {
phase: 'QUOTE_READY',
targetPlan: TARGET_PLAN,
});
- expect(readBillingPlanChangeIntent(ACCOUNT_ID)).toMatchObject({
- targetOfferCode: 'max_month',
- planChangeId: 'plan_change_1',
- });
await act(() => result.current.confirm());
expect(result.current.state.phase).toBe('AWAITING_PAYMENT');
@@ -84,7 +75,6 @@ describe('usePlanChange', () => {
expect(result.current.state.phase).toBe('APPLIED');
expect(onSettled).toHaveBeenCalledTimes(1);
expect(onSettled).toHaveBeenCalledWith('APPLIED');
- expect(readBillingPlanChangeIntent(ACCOUNT_ID)).toBeNull();
});
it.each(['FAILED', 'EXPIRED'] as const)(
@@ -164,7 +154,6 @@ describe('usePlanChange', () => {
expect(result.current.state.phase).toBe('SCHEDULED');
expect(onSettled).toHaveBeenCalledWith('SCHEDULED');
- expect(readBillingPlanChangeIntent(ACCOUNT_ID)).toBeNull();
});
it('cancels a scheduled downgrade (undo)', async () => {
@@ -259,36 +248,6 @@ describe('usePlanChange', () => {
});
});
- it('adopts the server pending projection when the quote request fails', async () => {
- api.quotePlanChange.mockRejectedValue(new Error('conflict'));
- api.getCurrentSubscription.mockResolvedValue({
- subscription: {
- subscriptionId: 'subscription_1',
- status: 'ACTIVE',
- currentPeriodStartAt: null,
- currentPeriodEndAt: null,
- entitlementValidUntil: null,
- cancelAtPeriodEnd: false,
- effectivePlan: null,
- purchaseAttemptId: null,
- paymentAction: null,
- pendingPlanChange: {
- ...change({ status: 'SCHEDULED', changeType: 'DOWNGRADE' }),
- targetPlan: TARGET_PLAN,
- },
- },
- });
- const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, vi.fn()));
-
- await act(() => result.current.startQuote('plus_month', null));
-
- expect(result.current.state).toMatchObject({
- open: true,
- phase: 'SCHEDULED',
- targetPlan: TARGET_PLAN,
- });
- });
-
it.each([
['[PLAN_CHANGE_NOT_AVAILABLE] target offer is not allowed', 'TARGET_NOT_ALLOWED'],
[
@@ -310,7 +269,8 @@ describe('usePlanChange', () => {
});
});
- it('reuses the same idempotency key when retrying the same target after a failure', async () => {
+ it('generates a fresh idempotency key for every new quote attempt', async () => {
+ // 服务端在新报价时自动撤销旧未完成变更;客户端不再复用失败请求的键。
api.quotePlanChange.mockRejectedValueOnce(new Error('network'));
api.quotePlanChange.mockResolvedValueOnce(change());
const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, vi.fn()));
@@ -319,63 +279,56 @@ describe('usePlanChange', () => {
await act(() => result.current.startQuote('max_month', TARGET_PLAN));
expect(api.quotePlanChange).toHaveBeenCalledTimes(2);
- expect(api.quotePlanChange.mock.calls[0]![1]).toBe(api.quotePlanChange.mock.calls[1]![1]);
+ expect(api.quotePlanChange.mock.calls[0]![1]).not.toBe(api.quotePlanChange.mock.calls[1]![1]);
});
- it('recovers a persisted in-flight change on restart and reopens the payment step', async () => {
- writeBillingPlanChangeIntent(ACCOUNT_ID, {
- version: 1,
- targetOfferCode: 'max_month',
- idempotencyKey: 'desktop:plan-change:12345678',
- planChangeId: 'plan_change_1',
- createdAt: '2026-07-24T00:00:00.000Z',
- });
- api.refreshPlanChange.mockResolvedValue(
- change({
- status: 'AWAITING_PAYMENT',
- paymentAction: {
- type: 'QR_CODE',
- value: 'https://qr.alipay.example/pay',
- expiresAt: '2099-01-01T00:00:00.000Z',
- },
- }),
+ it('lets a new target start immediately after closing during an in-flight refresh', async () => {
+ api.quotePlanChange
+ .mockResolvedValueOnce(change())
+ .mockResolvedValueOnce(change({ planChangeId: 'plan_change_2' }));
+ let releaseRefresh!: (value: BillingPlanChange) => void;
+ api.refreshPlanChange.mockImplementation(
+ () => new Promise<BillingPlanChange>((resolve) => (releaseRefresh = resolve)),
);
const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, vi.fn()));
- await waitFor(() => expect(result.current.state.phase).toBe('AWAITING_PAYMENT'));
- expect(result.current.state.open).toBe(true);
- expect(api.refreshPlanChange).toHaveBeenCalledWith('plan_change_1');
- expect(api.quotePlanChange).not.toHaveBeenCalled();
- });
+ await act(() => result.current.startQuote('max_month', TARGET_PLAN));
+ let refreshing!: Promise<void>;
+ act(() => {
+ refreshing = result.current.refresh();
+ });
- it('clears a keyed intent that never produced a plan change instead of re-quoting', async () => {
- writeBillingPlanChangeIntent(ACCOUNT_ID, {
- version: 1,
- targetOfferCode: 'max_month',
- idempotencyKey: 'desktop:plan-change:12345678',
- planChangeId: null,
- createdAt: '2026-07-24T00:00:00.000Z',
+ await act(async () => {
+ result.current.close();
+ await result.current.startQuote('plus_month', null);
});
- renderHook(() => usePlanChange(ACCOUNT_ID, vi.fn()));
+ expect(api.quotePlanChange).toHaveBeenCalledTimes(2);
+ expect(result.current.state.planChange?.planChangeId).toBe('plan_change_2');
- await waitFor(() => expect(readBillingPlanChangeIntent(ACCOUNT_ID)).toBeNull());
- expect(api.quotePlanChange).not.toHaveBeenCalled();
- expect(api.refreshPlanChange).not.toHaveBeenCalled();
+ await act(async () => {
+ releaseRefresh(change({ status: 'APPLIED' }));
+ await refreshing;
+ });
+ expect(result.current.state.planChange?.planChangeId).toBe('plan_change_2');
});
- it("never reads another account's intent", async () => {
- writeBillingPlanChangeIntent('other-account', {
- version: 1,
- targetOfferCode: 'max_month',
- idempotencyKey: 'desktop:plan-change:12345678',
- planChangeId: 'plan_change_other',
- createdAt: '2026-07-24T00:00:00.000Z',
- });
+ it('starts from a clean state on mount and never replays persisted intents', async () => {
+ localStorage.setItem(
+ `cindy.billing.plan-change-intent.v1:${encodeURIComponent(ACCOUNT_ID)}`,
+ JSON.stringify({
+ version: 1,
+ targetOfferCode: 'max_month',
+ idempotencyKey: 'desktop:plan-change:12345678',
+ planChangeId: 'plan_change_1',
+ createdAt: '2026-07-24T00:00:00.000Z',
+ }),
+ );
const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, vi.fn()));
await Promise.resolve();
- expect(api.refreshPlanChange).not.toHaveBeenCalled();
expect(result.current.state.phase).toBe('IDLE');
- expect(localStorage.getItem(billingPlanChangeIntentKey('other-account'))).not.toBeNull();
+ expect(result.current.state.open).toBe(false);
+ expect(api.refreshPlanChange).not.toHaveBeenCalled();
+ expect(api.quotePlanChange).not.toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/renderer/features/billing/checkoutIntent.ts b/apps/desktop/src/renderer/features/billing/checkoutIntent.ts
index 30560f556f..6efa6e4c15 100644
--- a/apps/desktop/src/renderer/features/billing/checkoutIntent.ts
+++ b/apps/desktop/src/renderer/features/billing/checkoutIntent.ts
@@ -1,160 +1,35 @@
-import type {
- CreateBillingSubscriptionRequest,
- CreateBillingTopupRequest,
-} from '../../../shared/billing';
-
-const LEGACY_BILLING_CHECKOUT_INTENT_KEY = 'cindy.billing.checkout-intent.v1';
-const BILLING_CHECKOUT_INTENT_KEY_PREFIX = 'cindy.billing.checkout-intent.v2';
-
-export type BillingCheckoutIntentV1 =
- | {
- version: 1;
- kind: 'TOPUP';
- idempotencyKey: string;
- request: CreateBillingTopupRequest;
- orderId: string | null;
- createdAt: string;
- }
- | {
- version: 1;
- kind: 'SUBSCRIPTION';
- idempotencyKey: string;
- request: CreateBillingSubscriptionRequest;
- subscriptionId: string | null;
- purchaseAttemptId: string | null;
- createdAt: string;
- }
- | {
- version: 1;
- kind: 'TOPUP_RETRY';
- idempotencyKey: string;
- orderId: string;
- createdAt: string;
- };
-
-const KEY_PATTERN = /^[A-Za-z0-9._:-]{8,128}$/;
-const CODE_PATTERN = /^[a-z][a-z0-9_]{1,63}$/;
-const AMOUNT_PATTERN = /^(0|[1-9]\d{0,14})(?:\.\d{1,9})?$/;
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
-}
-
-function isRequiredString(value: unknown): value is string {
- return typeof value === 'string' && value.length > 0 && value.length <= 128;
-}
-
-function hasOnlyKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {
- return Object.keys(value).every((key) => keys.includes(key));
-}
-
-function isTopupRequest(value: unknown): value is CreateBillingTopupRequest {
- if (!isRecord(value)) return false;
- return (
- hasOnlyKeys(value, ['offerCode', 'amount', 'purchaseOptionId']) &&
- typeof value.offerCode === 'string' &&
- CODE_PATTERN.test(value.offerCode) &&
- isRequiredString(value.purchaseOptionId) &&
- (value.amount === undefined ||
- (typeof value.amount === 'string' && AMOUNT_PATTERN.test(value.amount)))
- );
-}
-
-function isSubscriptionRequest(value: unknown): value is CreateBillingSubscriptionRequest {
- if (!isRecord(value)) return false;
- return (
- hasOnlyKeys(value, ['offerCode', 'purchaseOptionId']) &&
- typeof value.offerCode === 'string' &&
- CODE_PATTERN.test(value.offerCode) &&
- isRequiredString(value.purchaseOptionId)
- );
-}
+/**
+ * Checkout state is ephemeral: the idempotency key and the current server
+ * response live only in hook memory for the open dialog. Nothing is persisted
+ * across restarts anymore — closing the dialog abandons the session and the
+ * server replaces any stale payment action on the next create call.
+ */
-export function isBillingCheckoutIntent(value: unknown): value is BillingCheckoutIntentV1 {
- if (
- !isRecord(value) ||
- value.version !== 1 ||
- typeof value.idempotencyKey !== 'string' ||
- !KEY_PATTERN.test(value.idempotencyKey) ||
- typeof value.createdAt !== 'string' ||
- !Number.isFinite(Date.parse(value.createdAt))
- )
- return false;
- if (value.kind === 'TOPUP') {
- return (
- hasOnlyKeys(value, [
- 'version',
- 'kind',
- 'idempotencyKey',
- 'request',
- 'orderId',
- 'createdAt',
- ]) &&
- isTopupRequest(value.request) &&
- (value.orderId === null || isRequiredString(value.orderId))
- );
- }
- if (value.kind === 'SUBSCRIPTION') {
- return (
- hasOnlyKeys(value, [
- 'version',
- 'kind',
- 'idempotencyKey',
- 'request',
- 'subscriptionId',
- 'purchaseAttemptId',
- 'createdAt',
- ]) &&
- isSubscriptionRequest(value.request) &&
- (value.subscriptionId === null || isRequiredString(value.subscriptionId)) &&
- (value.purchaseAttemptId === null || isRequiredString(value.purchaseAttemptId))
- );
- }
- if (value.kind === 'TOPUP_RETRY') {
- return (
- hasOnlyKeys(value, ['version', 'kind', 'idempotencyKey', 'orderId', 'createdAt']) &&
- isRequiredString(value.orderId)
- );
- }
- return false;
-}
+const LEGACY_STORAGE_KEYS = [
+ 'cindy.billing.checkout-intent.v1',
+] as const;
-export function billingCheckoutIntentKey(accountId: string): string {
- return `${BILLING_CHECKOUT_INTENT_KEY_PREFIX}:${encodeURIComponent(accountId)}`;
-}
+const LEGACY_STORAGE_KEY_PREFIXES = [
+ 'cindy.billing.checkout-intent.v2',
+ 'cindy.billing.plan-change-intent.v1',
+] as const;
-export function readBillingCheckoutIntent(accountId: string): BillingCheckoutIntentV1 | null {
- const storageKey = billingCheckoutIntentKey(accountId);
+/**
+ * Old app versions persisted checkout / plan-change intents in localStorage
+ * and replayed them on startup. Remove them without replaying: the server no
+ * longer exposes recoverable payment tasks.
+ */
+export function clearLegacyBillingIntentStorage(accountId: string | null): void {
try {
- // A v1 intent has no account identity and must never be replayed after an
- // account switch. Drop it instead of guessing who created it.
- localStorage.removeItem(LEGACY_BILLING_CHECKOUT_INTENT_KEY);
- const raw = localStorage.getItem(storageKey);
- if (!raw) return null;
- const parsed: unknown = JSON.parse(raw);
- if (isBillingCheckoutIntent(parsed)) return parsed;
- localStorage.removeItem(storageKey);
- } catch {
- try {
- localStorage.removeItem(storageKey);
- } catch {
- // Storage is unavailable; checkout remains server-recoverable.
+ for (const key of LEGACY_STORAGE_KEYS) localStorage.removeItem(key);
+ if (accountId) {
+ for (const prefix of LEGACY_STORAGE_KEY_PREFIXES) {
+ localStorage.removeItem(`${prefix}:${encodeURIComponent(accountId)}`);
+ }
}
+ } catch {
+ // Storage unavailable; nothing to clean.
}
- return null;
-}
-
-export function writeBillingCheckoutIntent(
- accountId: string,
- intent: BillingCheckoutIntentV1,
-): void {
- localStorage.removeItem(LEGACY_BILLING_CHECKOUT_INTENT_KEY);
- localStorage.setItem(billingCheckoutIntentKey(accountId), JSON.stringify(intent));
-}
-
-export function clearBillingCheckoutIntent(accountId: string): void {
- localStorage.removeItem(LEGACY_BILLING_CHECKOUT_INTENT_KEY);
- localStorage.removeItem(billingCheckoutIntentKey(accountId));
}
export function newBillingIdempotencyKey(
@@ -162,72 +37,3 @@ export function newBillingIdempotencyKey(
): string {
return `desktop:${kind}:${crypto.randomUUID()}`;
}
-
-const BILLING_PLAN_CHANGE_INTENT_KEY_PREFIX = 'cindy.billing.plan-change-intent.v1';
-
-/**
- * Request-level recovery only. The server's `pendingPlanChange` projection is
- * the source of truth for what is actually open; a stored intent must never
- * override it.
- */
-export type BillingPlanChangeIntentV1 = {
- version: 1;
- targetOfferCode: string;
- idempotencyKey: string;
- planChangeId: string | null;
- createdAt: string;
-};
-
-export function isBillingPlanChangeIntent(value: unknown): value is BillingPlanChangeIntentV1 {
- return (
- isRecord(value) &&
- value.version === 1 &&
- hasOnlyKeys(value, [
- 'version',
- 'targetOfferCode',
- 'idempotencyKey',
- 'planChangeId',
- 'createdAt',
- ]) &&
- typeof value.targetOfferCode === 'string' &&
- CODE_PATTERN.test(value.targetOfferCode) &&
- typeof value.idempotencyKey === 'string' &&
- KEY_PATTERN.test(value.idempotencyKey) &&
- (value.planChangeId === null || isRequiredString(value.planChangeId)) &&
- typeof value.createdAt === 'string' &&
- Number.isFinite(Date.parse(value.createdAt))
- );
-}
-
-export function billingPlanChangeIntentKey(accountId: string): string {
- return `${BILLING_PLAN_CHANGE_INTENT_KEY_PREFIX}:${encodeURIComponent(accountId)}`;
-}
-
-export function readBillingPlanChangeIntent(accountId: string): BillingPlanChangeIntentV1 | null {
- const storageKey = billingPlanChangeIntentKey(accountId);
- try {
- const raw = localStorage.getItem(storageKey);
- if (!raw) return null;
- const parsed: unknown = JSON.parse(raw);
- if (isBillingPlanChangeIntent(parsed)) return parsed;
- localStorage.removeItem(storageKey);
- } catch {
- try {
- localStorage.removeItem(storageKey);
- } catch {
- // Storage is unavailable; the server projection still recovers state.
- }
- }
- return null;
-}
-
-export function writeBillingPlanChangeIntent(
- accountId: string,
- intent: BillingPlanChangeIntentV1,
-): void {
- localStorage.setItem(billingPlanChangeIntentKey(accountId), JSON.stringify(intent));
-}
-
-export function clearBillingPlanChangeIntent(accountId: string): void {
- localStorage.removeItem(billingPlanChangeIntentKey(accountId));
-}
diff --git a/apps/desktop/src/renderer/features/billing/useBillingCheckout.ts b/apps/desktop/src/renderer/features/billing/useBillingCheckout.ts
index c15e255be0..b7bc0d5d44 100644
--- a/apps/desktop/src/renderer/features/billing/useBillingCheckout.ts
+++ b/apps/desktop/src/renderer/features/billing/useBillingCheckout.ts
@@ -7,34 +7,31 @@ import type {
CreateBillingTopupRequest,
} from '../../../shared/billing';
import { billingApi } from './api';
-import {
- clearBillingCheckoutIntent,
- newBillingIdempotencyKey,
- readBillingCheckoutIntent,
- writeBillingCheckoutIntent,
- type BillingCheckoutIntentV1,
-} from './checkoutIntent';
+import { clearLegacyBillingIntentStorage, newBillingIdempotencyKey } from './checkoutIntent';
export type BillingCheckoutPhase =
'IDLE' | 'CREATING' | 'AWAITING_PAYMENT' | 'COMPLETED' | 'FAILED' | 'EXPIRED' | 'CANCELED';
+/**
+ * In-memory only. A checkout session belongs to the open dialog: closing it
+ * discards the intent, and the next selection generates a fresh idempotency
+ * key. The server verifies and replaces any stale payment action on create.
+ */
+export type BillingCheckoutIntent =
+ | { kind: 'TOPUP'; idempotencyKey: string; request: CreateBillingTopupRequest }
+ | { kind: 'SUBSCRIPTION'; idempotencyKey: string; request: CreateBillingSubscriptionRequest }
+ | { kind: 'TOPUP_RETRY'; idempotencyKey: string; orderId: string };
+
export type BillingCheckoutState = {
open: boolean;
kind: 'TOPUP' | 'SUBSCRIPTION' | null;
phase: BillingCheckoutPhase;
- intent: BillingCheckoutIntentV1 | null;
+ intent: BillingCheckoutIntent | null;
order: BillingPaymentOrder | null;
subscription: BillingSubscription | null;
error: boolean;
};
-export type BillingRecoverables = {
- topups: BillingPaymentOrder[];
- subscription: BillingSubscription | null;
-};
-
-type CheckoutPresentation = 'VISIBLE' | 'BACKGROUND';
-
const INITIAL_STATE: BillingCheckoutState = {
open: false,
kind: null,
@@ -61,155 +58,78 @@ function phaseForSubscription(subscription: BillingSubscription): BillingCheckou
return 'FAILED';
}
-function isTerminal(phase: BillingCheckoutPhase): boolean {
- return ['COMPLETED', 'FAILED', 'EXPIRED', 'CANCELED'].includes(phase);
-}
-
-function isRecoverableTopup(value: Pick<BillingPaymentOrder, 'status'>): boolean {
- return value.status === 'CREATED' || value.status === 'PENDING';
-}
-
-function persistIntent(accountId: string | null, intent: BillingCheckoutIntentV1 | null): void {
- if (!accountId) return;
- try {
- if (intent) writeBillingCheckoutIntent(accountId, intent);
- else clearBillingCheckoutIntent(accountId);
- } catch {
- // Server recovery remains available when browser storage is unavailable.
- }
-}
-
-function matchesSubscriptionIntent(
- subscription: BillingSubscription,
- intent: Extract<BillingCheckoutIntentV1, { kind: 'SUBSCRIPTION' }>,
-): boolean {
- if (intent.subscriptionId && subscription.subscriptionId !== intent.subscriptionId) return false;
- if (intent.purchaseAttemptId && subscription.purchaseAttemptId !== intent.purchaseAttemptId) {
- const terminalSameSubscription =
- intent.subscriptionId !== null &&
- subscription.subscriptionId === intent.subscriptionId &&
- subscription.status !== 'INCOMPLETE' &&
- subscription.purchaseAttemptId === null;
- if (!terminalSameSubscription) return false;
- }
- return true;
-}
-
export function useBillingCheckout(accountId: string | null) {
const [state, setState] = useState<BillingCheckoutState>(INITIAL_STATE);
- const [recoverables, setRecoverables] = useState<BillingRecoverables>({
- topups: [],
- subscription: null,
- });
- const [recovering, setRecovering] = useState(true);
const stateRef = useRef(state);
const mountedRef = useRef(true);
- const inFlightRef = useRef(false);
+ // 会话代次:close/切换账号使当前会话失效,迟到的异步响应不得重开已结束的会话。
+ const sessionRef = useRef(0);
+ // 请求锁按会话持有:记录在途请求所属代次。旧会话的在途请求不阻断新会话发起,
+ // 且其结束时不会误释放新会话已持有的锁。
+ const inFlightRef = useRef<number | null>(null);
stateRef.current = state;
const applyOrder = useCallback(
- (
- order: BillingPaymentOrder,
- intent: BillingCheckoutIntentV1 | null,
- presentation: CheckoutPresentation = 'VISIBLE',
- ) => {
- const nextIntent =
- intent?.kind === 'TOPUP' && intent.orderId !== order.orderId
- ? { ...intent, orderId: order.orderId }
- : intent;
- const phase = phaseForOrder(order);
- if (nextIntent && !isTerminal(phase)) persistIntent(accountId, nextIntent);
- if (isTerminal(phase)) persistIntent(accountId, null);
- if (!mountedRef.current) return;
- setRecoverables((current) => ({
- ...current,
- topups: isRecoverableTopup(order)
- ? [order, ...current.topups.filter((item) => item.orderId !== order.orderId)]
- : current.topups.filter((item) => item.orderId !== order.orderId),
- }));
+ (order: BillingPaymentOrder, intent: BillingCheckoutIntent | null, session: number) => {
+ if (!mountedRef.current || session !== sessionRef.current) return;
setState({
- open: presentation === 'VISIBLE',
+ open: true,
kind: 'TOPUP',
- phase,
- intent: nextIntent,
+ phase: phaseForOrder(order),
+ intent,
order,
subscription: null,
error: false,
});
},
- [accountId],
+ [],
);
const applySubscription = useCallback(
- (
- subscription: BillingSubscription,
- intent: BillingCheckoutIntentV1 | null,
- presentation: CheckoutPresentation = 'VISIBLE',
- ) => {
- if (intent?.kind === 'SUBSCRIPTION' && !matchesSubscriptionIntent(subscription, intent))
- return false;
- const nextIntent =
- intent?.kind === 'SUBSCRIPTION'
- ? {
- ...intent,
- subscriptionId: subscription.subscriptionId,
- purchaseAttemptId: subscription.purchaseAttemptId,
- }
- : intent;
- const phase = phaseForSubscription(subscription);
- if (nextIntent && !isTerminal(phase)) persistIntent(accountId, nextIntent);
- if (isTerminal(phase)) persistIntent(accountId, null);
- if (!mountedRef.current) return true;
- setRecoverables((current) => ({
- ...current,
- subscription: subscription.status === 'INCOMPLETE' ? subscription : null,
- }));
+ (subscription: BillingSubscription, intent: BillingCheckoutIntent | null, session: number) => {
+ if (!mountedRef.current || session !== sessionRef.current) return;
setState({
- open: presentation === 'VISIBLE',
+ open: true,
kind: 'SUBSCRIPTION',
- phase,
- intent: nextIntent,
+ phase: phaseForSubscription(subscription),
+ intent,
order: null,
subscription,
error: false,
});
- return true;
},
- [accountId],
+ [],
);
- const failCurrentOperation = useCallback((presentation: CheckoutPresentation = 'VISIBLE') => {
- if (!mountedRef.current) return;
- setState((current) => ({
- ...current,
- open: presentation === 'VISIBLE',
- phase: 'FAILED',
- error: true,
- }));
+ const failCurrentOperation = useCallback((session: number) => {
+ if (!mountedRef.current || session !== sessionRef.current) return;
+ setState((current) => ({ ...current, phase: 'FAILED', error: true }));
}, []);
- const withRequestLock = useCallback(async (request: () => Promise<void>) => {
- if (inFlightRef.current) return;
- inFlightRef.current = true;
+ const flagError = useCallback((session: number) => {
+ if (!mountedRef.current || session !== sessionRef.current) return;
+ setState((value) => ({ ...value, error: true }));
+ }, []);
+
+ const withRequestLock = useCallback(async (session: number, request: () => Promise<void>) => {
+ if (inFlightRef.current === session) return;
+ inFlightRef.current = session;
try {
await request();
} finally {
- inFlightRef.current = false;
+ if (inFlightRef.current === session) inFlightRef.current = null;
}
}, []);
const startTopup = useCallback(
async (request: CreateBillingTopupRequest) => {
- if (!accountId || inFlightRef.current) return;
- const intent: BillingCheckoutIntentV1 = {
- version: 1,
+ if (!accountId || inFlightRef.current === sessionRef.current) return;
+ const session = ++sessionRef.current;
+ const intent: BillingCheckoutIntent = {
kind: 'TOPUP',
idempotencyKey: newBillingIdempotencyKey('topup'),
request,
- orderId: null,
- createdAt: new Date().toISOString(),
};
- persistIntent(accountId, intent);
setState({
open: true,
kind: 'TOPUP',
@@ -219,44 +139,26 @@ export function useBillingCheckout(accountId: string | null) {
subscription: null,
error: false,
});
- await withRequestLock(async () => {
+ await withRequestLock(session, async () => {
try {
- applyOrder(await billingApi.createTopup(request, intent.idempotencyKey), intent);
+ applyOrder(await billingApi.createTopup(request, intent.idempotencyKey), intent, session);
} catch {
- failCurrentOperation();
+ failCurrentOperation(session);
}
});
},
[accountId, applyOrder, failCurrentOperation, withRequestLock],
);
- const recoverPendingSubscription = useCallback(
- async (intent: Extract<BillingCheckoutIntentV1, { kind: 'SUBSCRIPTION' }>) => {
- if (!intent.subscriptionId && !intent.purchaseAttemptId) return false;
- try {
- const current = (await billingApi.getCurrentSubscription()).subscription;
- if (current?.status !== 'INCOMPLETE') return false;
- return applySubscription(current, intent);
- } catch {
- return false;
- }
- },
- [applySubscription],
- );
-
const startSubscription = useCallback(
async (request: CreateBillingSubscriptionRequest) => {
- if (!accountId || inFlightRef.current) return;
- const intent: BillingCheckoutIntentV1 = {
- version: 1,
+ if (!accountId || inFlightRef.current === sessionRef.current) return;
+ const session = ++sessionRef.current;
+ const intent: BillingCheckoutIntent = {
kind: 'SUBSCRIPTION',
idempotencyKey: newBillingIdempotencyKey('subscription'),
request,
- subscriptionId: null,
- purchaseAttemptId: null,
- createdAt: new Date().toISOString(),
};
- persistIntent(accountId, intent);
setState({
open: true,
kind: 'SUBSCRIPTION',
@@ -266,137 +168,107 @@ export function useBillingCheckout(accountId: string | null) {
subscription: null,
error: false,
});
- await withRequestLock(async () => {
+ await withRequestLock(session, async () => {
try {
applySubscription(
await billingApi.createSubscription(request, intent.idempotencyKey),
intent,
+ session,
);
} catch {
- if (!(await recoverPendingSubscription(intent))) failCurrentOperation();
+ failCurrentOperation(session);
}
});
},
- [
- accountId,
- applySubscription,
- failCurrentOperation,
- recoverPendingSubscription,
- withRequestLock,
- ],
+ [accountId, applySubscription, failCurrentOperation, withRequestLock],
);
- const refreshActive = useCallback(async () => {
- await withRequestLock(async () => {
+ const refreshActive = useCallback(async (expectedSession = sessionRef.current) => {
+ if (expectedSession !== sessionRef.current) return;
+ const session = expectedSession;
+ await withRequestLock(session, async () => {
+ if (session !== sessionRef.current) return;
const current = stateRef.current;
- const presentation: CheckoutPresentation = current.open ? 'VISIBLE' : 'BACKGROUND';
try {
if (current.kind === 'TOPUP' && current.order) {
const order =
current.phase === 'AWAITING_PAYMENT'
? await billingApi.refreshTopup(current.order.orderId)
: await billingApi.getOrder(current.order.orderId);
- applyOrder(order, current.intent, presentation);
+ applyOrder(order, current.intent, session);
return;
}
- if (current.kind === 'SUBSCRIPTION' && current.subscription) {
- const subscription =
- current.phase === 'AWAITING_PAYMENT' && current.subscription.purchaseAttemptId
- ? await billingApi.refreshSubscriptionPurchase(current.subscription.purchaseAttemptId)
- : (await billingApi.getCurrentSubscription()).subscription;
- if (subscription && !applySubscription(subscription, current.intent, presentation)) {
- failCurrentOperation(presentation);
- }
+ if (current.kind === 'SUBSCRIPTION' && current.subscription?.purchaseAttemptId) {
+ applySubscription(
+ await billingApi.refreshSubscriptionPurchase(current.subscription.purchaseAttemptId),
+ current.intent,
+ session,
+ );
}
} catch {
- if (mountedRef.current) setState((value) => ({ ...value, error: true }));
+ flagError(session);
}
});
- }, [applyOrder, applySubscription, failCurrentOperation, withRequestLock]);
+ }, [applyOrder, applySubscription, flagError, withRequestLock]);
const retry = useCallback(async () => {
- if (inFlightRef.current) return;
+ if (inFlightRef.current === sessionRef.current) return;
const current = stateRef.current;
if (current.error && current.intent?.kind === 'TOPUP_RETRY') {
await startTopupRetryWithIntent(current.intent);
return;
}
if (current.kind === 'TOPUP' && current.order) {
- const intent: Extract<BillingCheckoutIntentV1, { kind: 'TOPUP_RETRY' }> = {
- version: 1,
+ await startTopupRetryWithIntent({
kind: 'TOPUP_RETRY',
idempotencyKey: newBillingIdempotencyKey('retry'),
orderId: current.order.orderId,
- createdAt: new Date().toISOString(),
- };
- persistIntent(accountId, intent);
- await startTopupRetryWithIntent(intent);
+ });
return;
}
- if (current.intent && !current.order && !current.subscription) {
- if (current.intent.kind === 'TOPUP') {
- await startTopupWithIntent(current.intent);
- } else if (current.intent.kind === 'SUBSCRIPTION') {
- await startSubscriptionWithIntent(current.intent);
- } else {
- await startTopupRetryWithIntent(current.intent);
- }
+ // Create request failed before any business object existed: replay the
+ // same in-memory intent (same idempotency key) once more.
+ if (current.intent?.kind === 'TOPUP' && !current.order) {
+ const intent = current.intent;
+ const session = sessionRef.current;
+ setState((value) => ({ ...value, phase: 'CREATING', error: false }));
+ await withRequestLock(session, async () => {
+ try {
+ applyOrder(
+ await billingApi.createTopup(intent.request, intent.idempotencyKey),
+ intent,
+ session,
+ );
+ } catch {
+ failCurrentOperation(session);
+ }
+ });
+ return;
}
- }, [accountId, applyOrder, failCurrentOperation, withRequestLock]);
-
- async function startTopupWithIntent(intent: Extract<BillingCheckoutIntentV1, { kind: 'TOPUP' }>) {
- setState({
- open: true,
- kind: 'TOPUP',
- phase: 'CREATING',
- intent,
- order: null,
- subscription: null,
- error: false,
- });
- await withRequestLock(async () => {
- try {
- const order = intent.orderId
- ? await billingApi.getOrder(intent.orderId)
- : await billingApi.createTopup(intent.request, intent.idempotencyKey);
- applyOrder(order, intent);
- } catch {
- failCurrentOperation();
- }
- });
- }
-
- async function startSubscriptionWithIntent(
- intent: Extract<BillingCheckoutIntentV1, { kind: 'SUBSCRIPTION' }>,
- ) {
- setState({
- open: true,
- kind: 'SUBSCRIPTION',
- phase: 'CREATING',
- intent,
- order: null,
- subscription: null,
- error: false,
- });
- await withRequestLock(async () => {
- try {
- const subscription = intent.purchaseAttemptId
- ? await billingApi.refreshSubscriptionPurchase(intent.purchaseAttemptId)
- : intent.subscriptionId
- ? (await billingApi.getCurrentSubscription()).subscription
- : await billingApi.createSubscription(intent.request, intent.idempotencyKey);
- if (!subscription || !applySubscription(subscription, intent)) failCurrentOperation();
- } catch {
- if (!(await recoverPendingSubscription(intent))) failCurrentOperation();
- }
- });
- }
+ if (current.intent?.kind === 'SUBSCRIPTION' && !current.subscription) {
+ const intent = current.intent;
+ const session = sessionRef.current;
+ setState((value) => ({ ...value, phase: 'CREATING', error: false }));
+ await withRequestLock(session, async () => {
+ try {
+ applySubscription(
+ await billingApi.createSubscription(intent.request, intent.idempotencyKey),
+ intent,
+ session,
+ );
+ } catch {
+ failCurrentOperation(session);
+ }
+ });
+ }
+ }, [applyOrder, applySubscription, failCurrentOperation, withRequestLock]);
async function startTopupRetryWithIntent(
- intent: Extract<BillingCheckoutIntentV1, { kind: 'TOPUP_RETRY' }>,
+ intent: Extract<BillingCheckoutIntent, { kind: 'TOPUP_RETRY' }>,
) {
const previousOrder =
stateRef.current.order?.orderId === intent.orderId ? stateRef.current.order : null;
+ const session = sessionRef.current;
setState({
open: true,
kind: 'TOPUP',
@@ -406,11 +278,15 @@ export function useBillingCheckout(accountId: string | null) {
subscription: null,
error: false,
});
- await withRequestLock(async () => {
+ await withRequestLock(session, async () => {
try {
- applyOrder(await billingApi.retryTopup(intent.orderId, intent.idempotencyKey), intent);
+ applyOrder(
+ await billingApi.retryTopup(intent.orderId, intent.idempotencyKey),
+ intent,
+ session,
+ );
} catch {
- failCurrentOperation();
+ failCurrentOperation(session);
}
});
}
@@ -418,156 +294,47 @@ export function useBillingCheckout(accountId: string | null) {
const cancel = useCallback(async () => {
const current = stateRef.current;
if (current.kind !== 'TOPUP' || !current.order) return;
- await withRequestLock(async () => {
+ const session = sessionRef.current;
+ await withRequestLock(session, async () => {
try {
- applyOrder(await billingApi.cancelTopup(current.order!.orderId), current.intent);
+ applyOrder(await billingApi.cancelTopup(current.order!.orderId), current.intent, session);
} catch {
- if (mountedRef.current) setState((value) => ({ ...value, error: true }));
+ flagError(session);
}
});
- }, [applyOrder, withRequestLock]);
+ }, [applyOrder, flagError, withRequestLock]);
+ // Closing the dialog ends the checkout session entirely: the generation bump
+ // invalidates in-flight responses so they cannot reopen the dialog, and the
+ // next selection starts over with a new idempotency key.
const close = useCallback(() => {
- setState((current) => ({ ...current, open: false }));
- }, []);
-
- const resumeTopup = useCallback(
- (order: BillingPaymentOrder) => {
- applyOrder(order, null);
- },
- [applyOrder],
- );
-
- const resumeSubscription = useCallback(
- (subscription: BillingSubscription) => {
- applySubscription(subscription, null);
- },
- [applySubscription],
- );
-
- const resumeFailed = useCallback(() => {
- setState((current) => {
- if (
- current.open ||
- current.phase !== 'FAILED' ||
- !current.error ||
- !current.intent ||
- current.order ||
- current.subscription
- ) {
- return current;
- }
- return { ...current, open: true };
- });
+ sessionRef.current += 1;
+ inFlightRef.current = null;
+ stateRef.current = INITIAL_STATE;
+ setState(INITIAL_STATE);
}, []);
useEffect(() => {
mountedRef.current = true;
- if (!accountId) {
- setState(INITIAL_STATE);
- setRecoverables({ topups: [], subscription: null });
- setRecovering(false);
- return () => {
- mountedRef.current = false;
- };
- }
- const restore = async () => {
- const intent = readBillingCheckoutIntent(accountId);
- inFlightRef.current = true;
- try {
- const [ordersResult, subscriptionResult] = await Promise.allSettled([
- billingApi.listOrders(),
- billingApi.getCurrentSubscription(),
- ]);
- if (!mountedRef.current) return;
- setRecoverables({
- topups:
- ordersResult.status === 'fulfilled'
- ? ordersResult.value.orders.filter(isRecoverableTopup)
- : [],
- subscription:
- subscriptionResult.status === 'fulfilled' &&
- subscriptionResult.value.subscription?.status === 'INCOMPLETE'
- ? subscriptionResult.value.subscription
- : null,
- });
-
- if (!intent) return;
- setState({
- open: false,
- kind: intent.kind === 'SUBSCRIPTION' ? 'SUBSCRIPTION' : 'TOPUP',
- phase: 'CREATING',
- intent,
- order: null,
- subscription: null,
- error: false,
- });
- try {
- if (intent.kind === 'TOPUP') {
- const listedOrder =
- intent.orderId && ordersResult.status === 'fulfilled'
- ? ordersResult.value.orders.find((order) => order.orderId === intent.orderId)
- : null;
- const order =
- listedOrder ??
- (intent.orderId
- ? await billingApi.getOrder(intent.orderId)
- : await billingApi.createTopup(intent.request, intent.idempotencyKey));
- applyOrder(order, intent, 'BACKGROUND');
- return;
- }
-
- if (intent.kind === 'TOPUP_RETRY') {
- applyOrder(
- await billingApi.retryTopup(intent.orderId, intent.idempotencyKey),
- intent,
- 'BACKGROUND',
- );
- return;
- }
-
- if (
- intent.subscriptionId &&
- !intent.purchaseAttemptId &&
- subscriptionResult.status === 'rejected'
- ) {
- failCurrentOperation('BACKGROUND');
- return;
- }
- const currentSubscription =
- subscriptionResult.status === 'fulfilled'
- ? subscriptionResult.value.subscription
- : null;
- const subscription = intent.purchaseAttemptId
- ? await billingApi.refreshSubscriptionPurchase(intent.purchaseAttemptId)
- : intent.subscriptionId
- ? currentSubscription
- : await billingApi.createSubscription(intent.request, intent.idempotencyKey);
- if (!subscription || !applySubscription(subscription, intent, 'BACKGROUND')) {
- failCurrentOperation('BACKGROUND');
- }
- } catch {
- failCurrentOperation('BACKGROUND');
- }
- } finally {
- inFlightRef.current = false;
- if (mountedRef.current) setRecovering(false);
- }
- };
- void restore();
+ sessionRef.current += 1;
+ inFlightRef.current = null;
+ stateRef.current = INITIAL_STATE;
+ setState(INITIAL_STATE);
+ clearLegacyBillingIntentStorage(accountId);
return () => {
mountedRef.current = false;
};
- }, [accountId, applyOrder, applySubscription, failCurrentOperation]);
+ }, [accountId]);
useEffect(() => {
const shouldPoll = state.open && state.phase === 'AWAITING_PAYMENT';
if (!shouldPoll) return;
+ const session = sessionRef.current;
const timer = window.setInterval(() => {
- if (document.visibilityState === 'visible') void refreshActive();
+ if (document.visibilityState === 'visible') void refreshActive(session);
}, 3_000);
const onVisible = () => {
- if (document.visibilityState === 'visible') void refreshActive();
+ if (document.visibilityState === 'visible') void refreshActive(session);
};
window.addEventListener('focus', onVisible);
document.addEventListener('visibilitychange', onVisible);
@@ -580,18 +347,13 @@ export function useBillingCheckout(accountId: string | null) {
return {
state,
- recoverables,
- recovering,
startTopup,
startSubscription,
refreshActive,
retry,
cancel,
close,
- resumeTopup,
- resumeSubscription,
- resumeFailed,
};
}
-export { isRecoverableTopup, phaseForOrder, phaseForSubscription };
+export { phaseForOrder, phaseForSubscription };
diff --git a/apps/desktop/src/renderer/features/billing/usePlanChange.ts b/apps/desktop/src/renderer/features/billing/usePlanChange.ts
index a6dfce8703..b8ccc8943a 100644
--- a/apps/desktop/src/renderer/features/billing/usePlanChange.ts
+++ b/apps/desktop/src/renderer/features/billing/usePlanChange.ts
@@ -2,18 +2,11 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { extractIpcError } from '@/utils/ipcError';
import type {
- BillingPendingPlanChange,
BillingPlanChange,
BillingPlanChangeTargetPlan,
} from '../../../shared/billing';
import { billingApi } from './api';
-import {
- clearBillingPlanChangeIntent,
- newBillingIdempotencyKey,
- readBillingPlanChangeIntent,
- writeBillingPlanChangeIntent,
- type BillingPlanChangeIntentV1,
-} from './checkoutIntent';
+import { newBillingIdempotencyKey } from './checkoutIntent';
export type PlanChangePhase =
| 'IDLE'
@@ -87,16 +80,6 @@ function phaseForPlanChange(change: BillingPlanChange): PlanChangePhase {
}
}
-function isSettledPhase(phase: PlanChangePhase): boolean {
- return (
- phase === 'APPLIED' ||
- phase === 'CANCELED' ||
- phase === 'FAILED' ||
- phase === 'EXPIRED' ||
- phase === 'SCHEDULED'
- );
-}
-
function quoteFailureReason(error: unknown): PlanChangeQuoteFailureReason {
return extractIpcError(error)?.code === 'PLAN_CHANGE_NOT_AVAILABLE'
? 'TARGET_NOT_ALLOWED'
@@ -110,25 +93,16 @@ export function usePlanChange(
const [state, setState] = useState<PlanChangeState>(INITIAL_STATE);
const stateRef = useRef(state);
const mountedRef = useRef(true);
- const inFlightRef = useRef(false);
+ // 会话代次:切换账号或重新挂载后,旧账号/旧会话的迟到响应不得覆盖新状态。
+ const sessionRef = useRef(0);
+ // 请求锁按会话持有:旧会话的在途刷新不阻断新目标的重新报价,
+ // 且旧请求结束时不会误释放新会话已持有的锁。
+ const inFlightRef = useRef<number | null>(null);
const settledNotifiedRef = useRef(new Set<string>());
const onSettledRef = useRef(onSettled);
stateRef.current = state;
onSettledRef.current = onSettled;
- const persistIntent = useCallback(
- (intent: BillingPlanChangeIntentV1 | null) => {
- if (!accountId) return;
- try {
- if (intent) writeBillingPlanChangeIntent(accountId, intent);
- else clearBillingPlanChangeIntent(accountId);
- } catch {
- // Server projection still recovers state without local storage.
- }
- },
- [accountId],
- );
-
const notifySettled = useCallback((change: BillingPlanChange) => {
if (
change.status !== 'APPLIED' &&
@@ -147,17 +121,14 @@ export function usePlanChange(
const applyChange = useCallback(
(
change: BillingPlanChange,
+ session: number,
options?: { targetPlan?: PlanChangeTargetSnapshot | null; open?: boolean },
) => {
- const phase = phaseForPlanChange(change);
- if (phase !== 'QUOTE_READY' && phase !== 'AWAITING_PAYMENT') {
- persistIntent(null);
- }
+ if (!mountedRef.current || session !== sessionRef.current) return;
notifySettled(change);
- if (!mountedRef.current) return;
setState((current) => ({
open: options?.open ?? current.open,
- phase,
+ phase: phaseForPlanChange(change),
planChange: change,
targetPlan: options?.targetPlan !== undefined ? options.targetPlan : current.targetPlan,
error: false,
@@ -165,46 +136,26 @@ export function usePlanChange(
stale: false,
}));
},
- [notifySettled, persistIntent],
+ [notifySettled],
);
- const withRequestLock = useCallback(async (request: () => Promise<void>) => {
- if (inFlightRef.current) return;
- inFlightRef.current = true;
+ const withRequestLock = useCallback(async (session: number, request: () => Promise<void>) => {
+ if (inFlightRef.current === session) return;
+ inFlightRef.current = session;
try {
await request();
} finally {
- inFlightRef.current = false;
+ if (inFlightRef.current === session) inFlightRef.current = null;
}
}, []);
- /** Adopt whatever the server says is open; never trust local state over it. */
- const adoptServerPending = useCallback(async (): Promise<boolean> => {
- try {
- const pending = (await billingApi.getCurrentSubscription()).subscription?.pendingPlanChange;
- if (!pending) return false;
- applyChange(pending, { targetPlan: pending.targetPlan, open: true });
- return true;
- } catch {
- return false;
- }
- }, [applyChange]);
-
const startQuote = useCallback(
async (targetOfferCode: string, targetPlan: PlanChangeTargetSnapshot | null) => {
- if (!accountId || inFlightRef.current) return;
- const previous = readBillingPlanChangeIntent(accountId);
- const intent: BillingPlanChangeIntentV1 =
- previous && previous.targetOfferCode === targetOfferCode && !previous.planChangeId
- ? previous
- : {
- version: 1,
- targetOfferCode,
- idempotencyKey: newBillingIdempotencyKey('plan-change'),
- planChangeId: null,
- createdAt: new Date().toISOString(),
- };
- persistIntent(intent);
+ if (!accountId || inFlightRef.current === sessionRef.current) return;
+ // 每次重新选择目标都是新的结算会话:新代次 + 新幂等键,旧会话在途响应作废,
+ // 服务端自动撤销旧未完成变更。
+ const session = ++sessionRef.current;
+ const idempotencyKey = newBillingIdempotencyKey('plan-change');
setState({
open: true,
phase: 'QUOTING',
@@ -214,14 +165,13 @@ export function usePlanChange(
quoteFailureReason: null,
stale: false,
});
- await withRequestLock(async () => {
+ await withRequestLock(session, async () => {
try {
- const change = await billingApi.quotePlanChange(targetOfferCode, intent.idempotencyKey);
- persistIntent({ ...intent, planChangeId: change.planChangeId });
- applyChange(change, { targetPlan });
+ applyChange(await billingApi.quotePlanChange(targetOfferCode, idempotencyKey), session, {
+ targetPlan,
+ });
} catch (error) {
- if (await adoptServerPending()) return;
- if (mountedRef.current) {
+ if (mountedRef.current && session === sessionRef.current) {
setState((current) => ({
...current,
phase: 'FAILED',
@@ -232,23 +182,28 @@ export function usePlanChange(
}
});
},
- [accountId, adoptServerPending, applyChange, persistIntent, withRequestLock],
+ [accountId, applyChange, withRequestLock],
);
const confirm = useCallback(async () => {
const current = stateRef.current;
- if (!current.planChange || current.planChange.status !== 'QUOTED' || inFlightRef.current)
+ if (
+ !current.planChange ||
+ current.planChange.status !== 'QUOTED' ||
+ inFlightRef.current === sessionRef.current
+ )
return;
const change = current.planChange;
+ const session = sessionRef.current;
setState((value) => ({
...value,
phase: 'CONFIRMING',
error: false,
quoteFailureReason: null,
}));
- await withRequestLock(async () => {
+ await withRequestLock(session, async () => {
try {
- applyChange(await billingApi.confirmPlanChange(change.planChangeId));
+ applyChange(await billingApi.confirmPlanChange(change.planChangeId), session);
} catch {
// The confirm may have landed server-side even though the response was
// lost. Re-read the change before restoring anything local, so a
@@ -259,9 +214,9 @@ export function usePlanChange(
} catch {
// Fall back to the pre-request snapshot below.
}
- if (!mountedRef.current) return;
+ if (!mountedRef.current || session !== sessionRef.current) return;
if (latest) {
- applyChange(latest);
+ applyChange(latest, session);
if (latest.status === change.status) {
setState((value) => ({ ...value, error: true }));
}
@@ -280,15 +235,20 @@ export function usePlanChange(
});
}, [applyChange, withRequestLock]);
- const refresh = useCallback(async () => {
+ const refresh = useCallback(async (expectedSession = sessionRef.current) => {
+ if (expectedSession !== sessionRef.current) return;
const current = stateRef.current;
if (!current.planChange) return;
const planChangeId = current.planChange.planChangeId;
- await withRequestLock(async () => {
+ const session = expectedSession;
+ await withRequestLock(session, async () => {
+ if (session !== sessionRef.current) return;
try {
- applyChange(await billingApi.refreshPlanChange(planChangeId));
+ applyChange(await billingApi.refreshPlanChange(planChangeId), session);
} catch {
- if (mountedRef.current) setState((value) => ({ ...value, error: true }));
+ if (mountedRef.current && session === sessionRef.current) {
+ setState((value) => ({ ...value, error: true }));
+ }
}
});
}, [applyChange, withRequestLock]);
@@ -296,75 +256,44 @@ export function usePlanChange(
/** Cancels a quoted change or a scheduled downgrade (撤销). */
const cancelChange = useCallback(
async (planChangeId: string) => {
- if (inFlightRef.current) return;
- await withRequestLock(async () => {
+ if (inFlightRef.current === sessionRef.current) return;
+ const session = sessionRef.current;
+ await withRequestLock(session, async () => {
try {
- applyChange(await billingApi.cancelPlanChange(planChangeId));
+ applyChange(await billingApi.cancelPlanChange(planChangeId), session);
} catch {
- if (mountedRef.current) setState((value) => ({ ...value, error: true }));
+ if (mountedRef.current && session === sessionRef.current) {
+ setState((value) => ({ ...value, error: true }));
+ }
}
});
},
[applyChange, withRequestLock],
);
- /** Re-enter a server-reported open change (e.g. resume an alipay QR). */
- const resumePending = useCallback(
- (pending: BillingPendingPlanChange) => {
- applyChange(pending, { targetPlan: pending.targetPlan, open: true });
- },
- [applyChange],
- );
-
const close = useCallback(() => {
- setState((current) =>
- current.phase === 'QUOTING' || current.phase === 'CONFIRMING'
- ? current
- : { ...current, open: false },
- );
+ const current = stateRef.current;
+ if (current.phase === 'QUOTING' || current.phase === 'CONFIRMING') return;
+ sessionRef.current += 1;
+ inFlightRef.current = null;
+ const next = { ...current, open: false };
+ stateRef.current = next;
+ setState(next);
}, []);
useEffect(() => {
+ // 套餐变更会话只属于当前打开的 Dialog:切换账号或重新挂载都从空状态开始,
+ // 不从本地存储或服务端恢复历史二维码。
mountedRef.current = true;
+ sessionRef.current += 1;
+ inFlightRef.current = null;
settledNotifiedRef.current = new Set();
+ stateRef.current = INITIAL_STATE;
setState(INITIAL_STATE);
- if (!accountId) {
- return () => {
- mountedRef.current = false;
- };
- }
- const intent = readBillingPlanChangeIntent(accountId);
- if (intent?.planChangeId) {
- const planChangeId = intent.planChangeId;
- void withRequestLock(async () => {
- try {
- const change = await billingApi.refreshPlanChange(planChangeId);
- if (!mountedRef.current) return;
- const phase = phaseForPlanChange(change);
- applyChange(change, {
- // The catalog-side target label is rebuilt from the server pending
- // projection when present; a bare refresh keeps it unknown.
- targetPlan: null,
- open:
- phase === 'AWAITING_PAYMENT' ||
- phase === 'PENDING_PROVIDER' ||
- phase === 'QUOTE_READY',
- });
- if (isSettledPhase(phase)) persistIntent(null);
- } catch {
- // The pendingPlanChange banner remains the recovery entry point.
- }
- });
- } else if (intent) {
- // The quote request never resolved locally. If it landed server-side the
- // pendingPlanChange projection will surface it; the stored key alone must
- // not trigger a new quote on startup.
- persistIntent(null);
- }
return () => {
mountedRef.current = false;
};
- }, [accountId, applyChange, persistIntent, withRequestLock]);
+ }, [accountId]);
useEffect(() => {
// Poll while waiting for a payment, and also while showing a stale
@@ -375,11 +304,12 @@ export function usePlanChange(
(state.phase !== 'AWAITING_PAYMENT' && state.phase !== 'PENDING_PROVIDER' && !state.stale)
)
return;
+ const session = sessionRef.current;
const timer = window.setInterval(() => {
- if (document.visibilityState === 'visible') void refresh();
+ if (document.visibilityState === 'visible') void refresh(session);
}, 3_000);
const onVisible = () => {
- if (document.visibilityState === 'visible') void refresh();
+ if (document.visibilityState === 'visible') void refresh(session);
};
window.addEventListener('focus', onVisible);
document.addEventListener('visibilitychange', onVisible);
@@ -396,7 +326,6 @@ export function usePlanChange(
confirm,
refresh,
cancelChange,
- resumePending,
close,
};
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 03c2ba4c98..3b27349315 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -7298,13 +7298,6 @@
"CANCELED": "Canceled",
"PAUSED": "Paused"
},
- "recovery": {
- "title": "Unfinished payment found",
- "description": "Continue the previous payment and confirm its latest state with the server.",
- "continueTopup": "Continue {{amount}} payment",
- "continueSubscription": "Continue subscription payment",
- "continueFailed": "Continue interrupted payment"
- },
"checkout": {
"creatingTitle": "Creating payment",
"awaitingTitle": "Awaiting payment",
@@ -7325,6 +7318,7 @@
"paymentCompleted": "Your payment was completed.",
"requestFailed": "The request failed. Retry safely; an uncertain create result keeps the original idempotency key.",
"expiredBody": "This payment link expired. Create a new payment to continue.",
+ "actionExpiredBody": "This code expired. Close this window and choose again to generate a new one.",
"canceledBody": "This payment was canceled.",
"failedBody": "Payment failed. Try again later or contact support."
},
@@ -7368,9 +7362,6 @@
"abandon": "Discard",
"targetLabel": "Target plan: {{name}}",
"pendingDowngrade": "Downgrade to {{name}} is scheduled for {{date}}.",
- "pendingPayment": "The upgrade to {{name}} is waiting for payment.",
- "pendingQuote": "A plan change to {{name}} is in progress.",
- "resume": "Continue",
"undo": "Undo downgrade"
}
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 5def3fb85e..53745553e4 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -7287,13 +7287,6 @@
"CANCELED": "キャンセル済み",
"PAUSED": "一時停止"
},
- "recovery": {
- "title": "未完了の支払いがあります",
- "description": "前回の支払いを続け、最新状態をサーバーで確認できます。",
- "continueTopup": "{{amount}}の支払いを続ける",
- "continueSubscription": "サブスクリプションの支払いを続ける",
- "continueFailed": "中断した支払いを続ける"
- },
"checkout": {
"creatingTitle": "支払いを作成中",
"awaitingTitle": "支払い待ち",
@@ -7314,6 +7307,7 @@
"paymentCompleted": "支払いが完了しました。",
"requestFailed": "リクエストに失敗しました。不明な作成結果では同じ冪等キーで安全に再試行します。",
"expiredBody": "支払いリンクの期限が切れました。新しい支払いを作成してください。",
+ "actionExpiredBody": "コードの有効期限が切れました。閉じてから再度選択し、新しい支払いを作成してください。",
"canceledBody": "この支払いはキャンセルされました。",
"failedBody": "支払いに失敗しました。しばらくしてからもう一度お試しください。"
},
@@ -7357,9 +7351,6 @@
"abandon": "破棄",
"targetLabel": "変更先プラン:{{name}}",
"pendingDowngrade": "{{name}} へのダウングレードが {{date}} に予約されています。",
- "pendingPayment": "{{name}} へのアップグレードは差額のお支払い待ちです。",
- "pendingQuote": "{{name}} へのプラン変更が進行中です。",
- "resume": "続行",
"undo": "ダウングレードを取り消す"
}
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 8a214b56fb..1dd29929cf 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -7287,13 +7287,6 @@
"CANCELED": "취소됨",
"PAUSED": "일시 중지"
},
- "recovery": {
- "title": "완료되지 않은 결제가 있습니다",
- "description": "이전 결제를 계속하고 서버에서 최신 상태를 확인할 수 있습니다.",
- "continueTopup": "{{amount}} 결제 계속",
- "continueSubscription": "구독 결제 계속",
- "continueFailed": "중단된 결제 계속"
- },
"checkout": {
"creatingTitle": "결제 생성 중",
"awaitingTitle": "결제 대기",
@@ -7314,6 +7307,7 @@
"paymentCompleted": "결제가 완료되었습니다.",
"requestFailed": "요청에 실패했습니다. 결과가 불확실한 생성 요청은 같은 멱등성 키로 안전하게 재시도합니다.",
"expiredBody": "결제 링크가 만료되었습니다. 새 결제를 생성하세요.",
+ "actionExpiredBody": "코드가 만료되었습니다. 창을 닫고 다시 선택하여 새 결제를 생성하세요.",
"canceledBody": "이 결제가 취소되었습니다.",
"failedBody": "결제에 실패했습니다. 나중에 다시 시도하세요."
},
@@ -7357,9 +7351,6 @@
"abandon": "취소",
"targetLabel": "대상 플랜: {{name}}",
"pendingDowngrade": "{{name}}(으)로의 다운그레이드가 {{date}}에 예약되어 있습니다.",
- "pendingPayment": "{{name}}(으)로의 업그레이드가 차액 결제를 기다리고 있습니다.",
- "pendingQuote": "{{name}}(으)로의 플랜 변경이 진행 중입니다.",
- "resume": "계속",
"undo": "다운그레이드 취소"
}
},
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index ba95ce8a57..1cbf07353a 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -7287,13 +7287,6 @@
"CANCELED": "已取消",
"PAUSED": "已暂停"
},
- "recovery": {
- "title": "发现未完成的支付",
- "description": "你可以继续上次的支付,状态将从服务端重新确认。",
- "continueTopup": "继续支付 {{amount}}",
- "continueSubscription": "继续订阅支付",
- "continueFailed": "继续未完成的支付"
- },
"checkout": {
"creatingTitle": "正在创建支付",
"awaitingTitle": "等待支付",
@@ -7314,6 +7307,7 @@
"paymentCompleted": "支付已完成。",
"requestFailed": "请求失败。可以重试;结果不确定时会继续复用原幂等请求。",
"expiredBody": "支付链接已过期,请重新创建支付。",
+ "actionExpiredBody": "二维码已过期,请关闭后重新选择以生成新的支付。",
"canceledBody": "本次支付已取消。",
"failedBody": "支付失败,请稍后重试或联系支持。"
},
@@ -7357,9 +7351,6 @@
"abandon": "放弃",
"targetLabel": "目标套餐:{{name}}",
"pendingDowngrade": "已排期降级至 {{name}},{{date}} 生效。",
- "pendingPayment": "升级到 {{name}} 的差价待支付。",
- "pendingQuote": "有一笔切换到 {{name}} 的套餐变更进行中。",
- "resume": "继续",
"undo": "撤销降级"
}
},