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。

fix(desktop): 收敛订阅取消交互

liugaowei7c48f264f5e4
diff --git a/apps/desktop/src/renderer/features/billing/BillingPage.tsx b/apps/desktop/src/renderer/features/billing/BillingPage.tsx
index 40beeb0452..87e1f9619c 100644
--- a/apps/desktop/src/renderer/features/billing/BillingPage.tsx
+++ b/apps/desktop/src/renderer/features/billing/BillingPage.tsx
@@ -87,6 +87,14 @@ const SUBSCRIPTION_PURCHASE_BLOCKING_STATUSES: BillingSubscription['status'][] =
'UNPAID',
'PAUSED',
];
+const SUBSCRIPTION_CANCELLABLE_STATUSES: BillingSubscription['status'][] = [
+ 'INCOMPLETE',
+ 'TRIALING',
+ 'ACTIVE',
+ 'PAST_DUE',
+ 'UNPAID',
+ 'PAUSED',
+];
function decimalParts(value: string): { value: bigint; scale: number } | null {
const match = /^(0|[1-9]\d{0,14})(?:\.(\d{1,9}))?$/.exec(value.trim());
@@ -244,6 +252,7 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
const [customAmount, setCustomAmount] = useState('');
const checkout = useBillingCheckout(accountId);
const previousCheckoutPhaseRef = useRef(checkout.state.phase);
+ const cancelSubscriptionLockRef = useRef(false);
const resetSelection = useCallback(() => {
setSelectedOfferCode(null);
@@ -461,51 +470,54 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
}, [billingLocale, currentSubscription, planNameOf, t]);
const cancelCurrentSubscription = useCallback(async () => {
- if (!currentSubscription || currentSubscription.cancelAtPeriodEnd || cancelingSubscription) {
+ if (
+ cancelSubscriptionLockRef.current ||
+ !currentSubscription ||
+ currentSubscription.cancelAtPeriodEnd ||
+ !SUBSCRIPTION_CANCELLABLE_STATUSES.includes(currentSubscription.status)
+ ) {
return;
}
- const periodEndAt = currentPlanFacts?.periodEndAt ?? null;
- const confirmed = await confirm({
- title: t('billing.settings.subscriptionCard.cancelConfirmTitle'),
- description: periodEndAt
- ? t('billing.settings.subscriptionCard.cancelConfirmDescription', {
- date: periodEndAt,
- })
- : t('billing.settings.subscriptionCard.cancelConfirmDescriptionWithoutDate'),
- confirmText: t('billing.settings.subscriptionCard.cancelConfirmAction'),
- cancelText: t('commonUi.confirmDialog.cancel'),
- });
- if (!confirmed) return;
-
- setCancelingSubscription(true);
+ cancelSubscriptionLockRef.current = true;
try {
- const canceled = await billingApi.cancelCurrentSubscription();
- setCurrentSubscription(canceled);
- setSubscriptionError(false);
- const canceledPeriodEndAt = formatBillingDate(canceled.currentPeriodEndAt, billingLocale);
- toast.success(
- canceledPeriodEndAt
- ? t('billing.settings.subscriptionCard.cancelSuccess', { date: canceledPeriodEndAt })
- : t('billing.settings.subscriptionCard.cancelSuccessWithoutDate'),
- );
- } catch (error) {
- const ipcError = extractIpcError(error);
- toast.error(
- ipcError?.code === 'PRECONDITION_FAILED'
- ? t('billing.settings.subscriptionCard.cancelNotSupported')
- : t('billing.settings.subscriptionCard.cancelFailed'),
- );
+ const periodEndAt = currentPlanFacts?.periodEndAt ?? null;
+ const confirmed = await confirm({
+ title: t('billing.settings.subscriptionCard.cancelConfirmTitle'),
+ description: periodEndAt
+ ? t('billing.settings.subscriptionCard.cancelConfirmDescription', {
+ date: periodEndAt,
+ })
+ : t('billing.settings.subscriptionCard.cancelConfirmDescriptionWithoutDate'),
+ confirmText: t('billing.settings.subscriptionCard.cancelConfirmAction'),
+ cancelText: t('commonUi.confirmDialog.cancel'),
+ });
+ if (!confirmed) return;
+
+ setCancelingSubscription(true);
+ try {
+ const canceled = await billingApi.cancelCurrentSubscription();
+ setCurrentSubscription(canceled);
+ setSubscriptionError(false);
+ const canceledPeriodEndAt = formatBillingDate(canceled.currentPeriodEndAt, billingLocale);
+ toast.success(
+ canceledPeriodEndAt
+ ? t('billing.settings.subscriptionCard.cancelSuccess', { date: canceledPeriodEndAt })
+ : t('billing.settings.subscriptionCard.cancelSuccessWithoutDate'),
+ );
+ } catch (error) {
+ const ipcError = extractIpcError(error);
+ toast.error(
+ ipcError?.code === 'PRECONDITION_FAILED'
+ ? t('billing.settings.subscriptionCard.cancelNotSupported')
+ : t('billing.settings.subscriptionCard.cancelFailed'),
+ );
+ } finally {
+ setCancelingSubscription(false);
+ }
} finally {
- setCancelingSubscription(false);
+ cancelSubscriptionLockRef.current = false;
}
- }, [
- billingLocale,
- cancelingSubscription,
- confirm,
- currentPlanFacts?.periodEndAt,
- currentSubscription,
- t,
- ]);
+ }, [billingLocale, confirm, currentPlanFacts?.periodEndAt, currentSubscription, t]);
// UI candidates only. The quote is the authority on whether a target is
// actually reachable; this filter just avoids offering obviously invalid
@@ -624,7 +636,9 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
<button
type="button"
onClick={() => void loadBillingState()}
- disabled={loadingCatalog || loadingSubscription || loadingBalance}
+ disabled={
+ loadingCatalog || loadingSubscription || loadingBalance || cancelingSubscription
+ }
className="inline-flex h-8 shrink-0 items-center gap-2 rounded-full border border-[var(--border-default)] px-3.5 text-12 font-medium text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-hover-soft)] disabled:opacity-45"
>
{loadingCatalog || loadingSubscription || loadingBalance ? (
@@ -947,20 +961,23 @@ function SubscriptionOverviewCard({
)}
</div>
<div className="flex shrink-0 items-center gap-2.5">
- {facts && !facts.cancelAtPeriodEnd && (
- <button
- type="button"
- onClick={onCancelSubscription}
- disabled={actionDisabled}
- className="inline-flex h-8 select-none items-center justify-center rounded-full border border-[var(--border-default)] px-3.5 text-12 font-medium text-[var(--error-fg)] transition-colors hover:bg-[var(--error-bg)] disabled:cursor-not-allowed disabled:opacity-40"
- >
- {canceling ? (
- <Spinner size={13} />
- ) : (
- t('billing.settings.subscriptionCard.cancelAction')
- )}
- </button>
- )}
+ {facts &&
+ !facts.cancelAtPeriodEnd &&
+ SUBSCRIPTION_CANCELLABLE_STATUSES.includes(facts.status) && (
+ <button
+ type="button"
+ onClick={onCancelSubscription}
+ disabled={actionDisabled}
+ aria-label={t('billing.settings.subscriptionCard.cancelAction')}
+ className="inline-flex h-8 select-none items-center justify-center rounded-full border border-[var(--border-default)] px-3.5 text-12 font-medium text-[var(--error-fg)] transition-colors hover:bg-[var(--error-bg)] disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ {canceling ? (
+ <Spinner size={13} />
+ ) : (
+ t('billing.settings.subscriptionCard.cancelAction')
+ )}
+ </button>
+ )}
<button
type="button"
onClick={planChangeable ? onChangePlan : onPurchase}
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 a2fafd1247..b91c60a13a 100644
--- a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
-import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { BillingPaymentOrder, BillingSubscription } from '../../../../shared/billing';
@@ -1110,9 +1110,9 @@ describe('BillingPage plan change', () => {
};
const activeSubscription = (
- pendingPlanChange: unknown = null,
+ pendingPlanChange: BillingSubscription['pendingPlanChange'] = null,
interval: 'MONTH' | 'YEAR' = 'MONTH',
- ) => ({
+ ): BillingSubscription => ({
subscriptionId: 'subscription_active',
status: 'ACTIVE' as const,
provider: 'stripe',
@@ -1206,6 +1206,71 @@ describe('BillingPage plan change', () => {
expect(screen.queryByText('billing.settings.subscriptionCard.cancelAction')).toBeNull();
});
+ it.each(['CANCELED', 'INCOMPLETE_EXPIRED'] as const)(
+ 'does not offer cancellation for a terminal %s subscription',
+ async (status) => {
+ const billing = billingMocks();
+ billing.getCurrentSubscription = vi.fn(async () => ({
+ subscription: { ...activeSubscription(), status },
+ }));
+ install(billing);
+
+ render(<BillingPage />);
+
+ await screen.findByText(`billing.subscriptionStatus.${status}`);
+ expect(screen.queryByText('billing.settings.subscriptionCard.cancelAction')).toBeNull();
+ expect(billing.cancelCurrentSubscription).not.toHaveBeenCalled();
+ },
+ );
+
+ it('locks cancellation before confirmation resolves', async () => {
+ const billing = install(billingMocks());
+ let resolveConfirm!: (confirmed: boolean) => void;
+ uiMocks.confirm.mockReturnValueOnce(
+ new Promise<boolean>((resolve) => {
+ resolveConfirm = resolve;
+ }),
+ );
+
+ render(<BillingPage />);
+ const cancelButton = await screen.findByText('billing.settings.subscriptionCard.cancelAction');
+ fireEvent.click(cancelButton);
+ fireEvent.click(cancelButton);
+
+ expect(uiMocks.confirm).toHaveBeenCalledTimes(1);
+ expect(billing.cancelCurrentSubscription).not.toHaveBeenCalled();
+
+ await act(async () => resolveConfirm(false));
+ });
+
+ it('keeps the loading cancellation accessible and disables refresh during the request', async () => {
+ const billing = install(billingMocks());
+ const canceled = { ...activeSubscription(), cancelAtPeriodEnd: true };
+ let resolveCancellation!: (subscription: BillingSubscription) => void;
+ billing.cancelCurrentSubscription.mockReturnValueOnce(
+ new Promise<BillingSubscription>((resolve) => {
+ resolveCancellation = resolve;
+ }),
+ );
+ uiMocks.confirm.mockResolvedValueOnce(true);
+
+ render(<BillingPage />);
+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.cancelAction'));
+
+ await waitFor(() => expect(billing.cancelCurrentSubscription).toHaveBeenCalledTimes(1));
+ expect(
+ screen
+ .getByRole('button', { name: 'billing.settings.subscriptionCard.cancelAction' })
+ .hasAttribute('disabled'),
+ ).toBe(true);
+ const refreshButton = screen.getByRole('button', { name: 'billing.actions.refreshCatalog' });
+ expect(refreshButton.hasAttribute('disabled')).toBe(true);
+ fireEvent.click(refreshButton);
+ expect(billing.getCurrentSubscription).toHaveBeenCalledTimes(1);
+
+ await act(async () => resolveCancellation(canceled));
+ });
+
it('shows the server-state rejection without inferring a payment provider', async () => {
const billing = install(billingMocks());
billing.cancelCurrentSubscription.mockRejectedValue(
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index dad77c3135..6090dde0a8 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -7148,11 +7148,11 @@
"includedCredits": "Includes {{amount}} credits per {{interval}}",
"renewsAt": "Renews {{date}}",
"endsAt": "Plan ends {{date}}",
- "cancelAction": "Cancel subscription",
- "cancelConfirmTitle": "Cancel your current subscription?",
+ "cancelAction": "Cancel Subscription",
+ "cancelConfirmTitle": "Cancel Your Current Subscription?",
"cancelConfirmDescription": "This action does not issue a refund or immediately change your credits. Your current plan stays available through {{date}}, then it will not renew.",
"cancelConfirmDescriptionWithoutDate": "This action does not issue a refund or immediately change your credits. Your current plan stays available through the end of this billing period, then it will not renew.",
- "cancelConfirmAction": "Confirm cancellation",
+ "cancelConfirmAction": "Confirm Cancellation",
"cancelSuccess": "Auto-renewal is canceled. Your current plan remains available through {{date}}.",
"cancelSuccessWithoutDate": "Auto-renewal is canceled. Your current plan will end after this billing period.",
"cancelNotSupported": "This subscription cannot be canceled yet.",