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。

merge: 同步 main 并解决订阅页面冲突

liugaoweic76e5a46d7f0
diff --cc apps/desktop/src/renderer/features/billing/BillingPage.tsx
index 64488a0384,b7d7b37a38..ef6f7854f2
--- a/apps/desktop/src/renderer/features/billing/BillingPage.tsx
+++ b/apps/desktop/src/renderer/features/billing/BillingPage.tsx
@@@ -87,8 -85,13 +87,14 @@@ const SUBSCRIPTION_PURCHASE_BLOCKING_ST
'UNPAID',
'PAUSED',
];
+const SUBSCRIPTION_CANCELLABLE_STATUSES = SUBSCRIPTION_PURCHASE_BLOCKING_STATUSES;
+ // 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 {
const match = /^(0|[1-9]\d{0,14})(?:\.(\d{1,9}))?$/.exec(value.trim());
if (!match) return null;
@@@ -476,62 -474,17 +494,67 @@@ export function BillingSettingsSection(
};
}, [billingLocale, currentSubscription, planNameOf, t]);
+ const cancelCurrentSubscription = useCallback(async () => {
+ if (
+ cancelSubscriptionLockRef.current ||
+ !currentSubscription ||
+ currentSubscription.cancelAtPeriodEnd ||
+ !SUBSCRIPTION_CANCELLABLE_STATUSES.includes(currentSubscription.status)
+ ) {
+ return;
+ }
+ cancelSubscriptionLockRef.current = true;
+ try {
+ 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 {
+ cancelSubscriptionLockRef.current = false;
+ }
+ }, [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
- // targets (other interval, same level, or another provider's offers).
+ // The server quote remains authoritative for business reachability. Until
+ // that contract supports cross-interval/provider changes, keep those two
+ // client-side compatibility gates so the dialog cannot offer known-invalid
+ // targets.
const planChangeCandidates = useMemo<PlanChangeCandidate[]>(() => {
- if (!planChangeable || !currentPlan) return [];
- const currentProvider = currentSubscription?.provider ?? null;
+ if (!showPlanChangeEntry || !currentPlan || !currentProvider) return [];
+ const directionRank: Record<Exclude<PlanChangeCandidate['direction'], null>, number> = {
+ UPGRADE: 0,
+ SAME_LEVEL: 1,
+ DOWNGRADE: 2,
+ };
return subscriptionOffers
.filter(
(entry) =>
@@@ -683,13 -642,19 +720,22 @@@
facts={currentPlanFacts}
loading={loadingSubscription}
error={subscriptionError}
- planChangeable={planChangeable}
+ showPlanChangeEntry={showPlanChangeEntry}
+ recoveryAvailable={recoverableSubscription !== null}
+ canceling={cancelingSubscription}
- actionDisabled={loadingSubscription || subscriptionError || cancelingSubscription}
+ actionDisabled={
+ loadingSubscription ||
+ subscriptionError ||
++ cancelingSubscription ||
+ (recoverableSubscription !== null && checkout.recovering)
+ }
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);
@@@ -883,13 -847,13 +930,15 @@@ function SubscriptionOverviewCard(
facts,
loading,
error,
- planChangeable,
+ showPlanChangeEntry,
+ recoveryAvailable,
+ canceling,
actionDisabled,
pendingPlanChange,
pendingTargetName,
+ onCancelSubscription,
onChangePlan,
+ onRecover,
onPurchase,
onResumePending,
onCancelPending,
@@@ -897,13 -861,13 +946,15 @@@
facts: CurrentPlanFacts | null;
loading: boolean;
error: boolean;
- planChangeable: 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;
@@@ -975,35 -939,18 +1026,39 @@@
</>
)}
</div>
- <button
- type="button"
- onClick={showPlanChangeEntry ? onChangePlan : recoveryAvailable ? onRecover : onPurchase}
- disabled={actionDisabled}
- 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"
- >
- {showPlanChangeEntry
- ? t('billing.settings.subscriptionCard.changeAction')
- : recoveryAvailable
- ? t('billing.recovery.continueSubscription')
- : t('billing.settings.subscriptionCard.action')}
- </button>
+ <div className="flex shrink-0 items-center gap-2.5">
+ {facts &&
+ !facts.cancelAtPeriodEnd &&
+ SUBSCRIPTION_CANCELLABLE_STATUSES.includes(facts.status) && (
+ <button
+ type="button"
+ onClick={onCancelSubscription}
+ disabled={actionDisabled}
+ aria-label={t('billing.settings.subscriptionCard.cancelAction')}
+ className="inline-flex h-8 select-none items-center justify-center rounded-full border border-[var(--border-default)] px-3.5 text-12 font-medium text-[var(--error-fg)] transition-colors hover:bg-[var(--error-bg)] disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ {canceling ? (
+ <Spinner size={13} />
+ ) : (
+ t('billing.settings.subscriptionCard.cancelAction')
+ )}
+ </button>
+ )}
+ <button
+ type="button"
- onClick={planChangeable ? onChangePlan : onPurchase}
++ onClick={
++ showPlanChangeEntry ? onChangePlan : recoveryAvailable ? onRecover : 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"
+ >
- {planChangeable
++ {showPlanChangeEntry
+ ? t('billing.settings.subscriptionCard.changeAction')
- : t('billing.settings.subscriptionCard.action')}
++ : recoveryAvailable
++ ? t('billing.recovery.continueSubscription')
++ : t('billing.settings.subscriptionCard.action')}
+ </button>
+ </div>
</div>
{pendingPlanChange && (
<PendingPlanChangeBanner
diff --cc apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
index a9f76ce8cd,b614170729..621a9192c5
--- a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
@@@ -852,47 -826,38 +847,79 @@@ describe('BillingPage remote catalog re
expect(checkout.startSubscription).not.toHaveBeenCalled();
});
+ it('marks the current subscription offer and prevents selecting it again', async () => {
+ window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => ({
+ subscription: {
+ subscriptionId: 'subscription_fixture',
+ status: 'ACTIVE' as const,
+ currentPeriodStartAt: '2026-07-01T00:00:00.000Z',
+ currentPeriodEndAt: '2026-08-01T00:00:00.000Z',
+ entitlementValidUntil: '2026-08-02T00:00:00.000Z',
+ cancelAtPeriodEnd: true,
+ effectivePlan: {
+ version: 1 as const,
+ product: { code: 'plus', kind: 'SUBSCRIPTION' as const, level: 1 },
+ offer: { code: 'plus_month', interval: 'MONTH' as const },
+ terms: {
+ amount: '9',
+ currency: 'usd',
+ creditAmount: '100',
+ rolloverCap: '0',
+ },
+ capturedAt: '2026-07-01T00:00:00.000Z',
+ },
+ purchaseAttemptId: null,
+ paymentAction: null,
+ },
+ }));
+
+ render(<BillingPage />);
+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));
+
+ const dialog = await screen.findByRole('dialog');
+ const currentPlan = within(dialog).getByRole('button', { name: /Configured subscription/ });
+ expect(currentPlan).toHaveProperty('disabled', true);
+ expect(currentPlan.getAttribute('aria-current')).toBe('true');
+ expect(within(dialog).getByText('billing.catalog.currentPlan')).toBeTruthy();
+ expect(within(dialog).queryByText('billing.steps.channel.title')).toBeNull();
+ expect(within(dialog).queryByText('stripe')).toBeNull();
+
+ fireEvent.click(currentPlan);
+ expect(checkout.startSubscription).not.toHaveBeenCalled();
+ });
+
+ it.each(['CANCELED', 'INCOMPLETE_EXPIRED'] as const)(
+ 'routes a %s terminal subscription to repurchase',
+ async (status) => {
+ window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => ({
+ subscription: {
+ subscriptionId: 'subscription_terminal',
+ status,
+ currentPeriodStartAt: null,
+ currentPeriodEndAt: null,
+ entitlementValidUntil: null,
+ cancelAtPeriodEnd: false,
+ effectivePlan: null,
+ purchaseAttemptId: null,
+ paymentAction: null,
+ },
+ }));
+
+ render(<BillingPage />);
+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));
+
+ fireEvent.click((await screen.findByText('Configured subscription')).closest('button')!);
+ fireEvent.click(screen.getByText('stripe').closest('button')!);
+ fireEvent.click(screen.getByText('billing.actions.pay'));
+
+ expect(screen.queryByText('billing.settings.subscriptionCard.changeAction')).toBeNull();
+ expect(checkout.startSubscription).toHaveBeenCalledWith({
+ offerCode: 'plus_month',
+ purchaseOptionId: 'listing_stripe',
+ });
+ },
+ );
+
it('keeps subscription purchases disabled when subscription status is unavailable', async () => {
window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => {
throw new Error('subscription status unavailable');
@@@ -1218,121 -1274,7 +1337,121 @@@ describe('BillingPage plan change', ()
});
});
+ it('confirms provider-neutral cancellation and keeps credits unchanged until period end', async () => {
+ const billing = install(billingMocks());
+ billing.cancelCurrentSubscription.mockResolvedValue({
+ ...activeSubscription(),
+ currentPeriodEndAt: '2026-09-01T00:00:00.000Z',
+ cancelAtPeriodEnd: true,
+ });
+ uiMocks.confirm.mockResolvedValueOnce(true);
+
+ render(<BillingPage />);
+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.cancelAction'));
+
+ await waitFor(() => expect(billing.cancelCurrentSubscription).toHaveBeenCalledWith());
+ expect(uiMocks.confirm).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: 'billing.settings.subscriptionCard.cancelConfirmTitle',
+ confirmText: 'billing.settings.subscriptionCard.cancelConfirmAction',
+ }),
+ );
+ expect(billing.getBalance).toHaveBeenCalledTimes(1);
+ expect(uiMocks.toastSuccess).toHaveBeenCalledWith(
+ expect.stringContaining('"date":"Sep 1, 2026"'),
+ );
+ expect(
+ screen.getByText((text) => text.startsWith('billing.settings.subscriptionCard.endsAt')),
+ ).toBeTruthy();
+ 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(
+ new Error('[PRECONDITION_FAILED] billing request conflicts with the current state'),
+ );
+ uiMocks.confirm.mockResolvedValueOnce(true);
+
+ render(<BillingPage />);
+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.cancelAction'));
+
+ await waitFor(() =>
+ expect(uiMocks.toastError).toHaveBeenCalledWith(
+ 'billing.settings.subscriptionCard.cancelNotSupported',
+ ),
+ );
+ expect(billing.cancelCurrentSubscription).toHaveBeenCalledWith();
+ expect(billing.getBalance).toHaveBeenCalledTimes(1);
+ expect(screen.getByText('billing.settings.subscriptionCard.cancelAction')).toBeTruthy();
+ });
+
- it('offers plan change for an active subscription with same-provider candidates only', async () => {
+ it('offers same-provider monthly plans in upgrade, same-tier, downgrade order', async () => {
const billing = install(billingMocks());
billing.quotePlanChange.mockResolvedValue({
planChangeId: 'plan_change_1',