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): 恢复订阅套餐变更入口 (#440)

GaoWei Liu43e3e2047d9d
diff --git a/apps/desktop/src/main/__tests__/serverApiClient.test.ts b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
index 236a47b33f..eb3ad20de2 100644
--- a/apps/desktop/src/main/__tests__/serverApiClient.test.ts
+++ b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
@@ -220,4 +220,56 @@ describe('serverApiFetch', () => {
'method=GET',
);
});
+
+ it('surfaces only explicitly allowed business codes on redacted requests', async () => {
+ mocks.getAccessToken.mockReturnValue('token-a');
+ mocks.netFetch
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 409,
+ json: async () => ({
+ error: {
+ code: 'PLAN_CHANGE_NOT_AVAILABLE',
+ message: 'private subscription detail',
+ },
+ }),
+ })
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 409,
+ json: async () => ({
+ error: {
+ code: 'PRIVATE_SUBSCRIPTION_STATE',
+ message: 'another private subscription detail',
+ },
+ }),
+ });
+
+ await expect(
+ serverApiFetch('/api/billing/subscription/plan-change-quotes', {
+ baseUrl: 'https://model-access.example.com',
+ redactErrorDetails: true,
+ allowedRedactedErrorCodes: ['PLAN_CHANGE_NOT_AVAILABLE'],
+ }),
+ ).rejects.toMatchObject({
+ code: 'PLAN_CHANGE_NOT_AVAILABLE',
+ statusCode: 409,
+ message: '请求失败 (409)',
+ });
+ await expect(
+ serverApiFetch('/api/billing/subscription/plan-change-quotes', {
+ baseUrl: 'https://model-access.example.com',
+ redactErrorDetails: true,
+ allowedRedactedErrorCodes: ['PLAN_CHANGE_NOT_AVAILABLE'],
+ }),
+ ).rejects.toMatchObject({
+ code: 'HTTP_409',
+ statusCode: 409,
+ message: '请求失败 (409)',
+ });
+
+ const logged = JSON.stringify(mocks.logger.warn.mock.calls);
+ expect(logged).not.toContain('private subscription detail');
+ expect(logged).not.toContain('PRIVATE_SUBSCRIPTION_STATE');
+ });
});
diff --git a/apps/desktop/src/main/billing/__tests__/index.test.ts b/apps/desktop/src/main/billing/__tests__/index.test.ts
index c903ab5df3..f8628e6e40 100644
--- a/apps/desktop/src/main/billing/__tests__/index.test.ts
+++ b/apps/desktop/src/main/billing/__tests__/index.test.ts
@@ -370,6 +370,28 @@ describe('billing IPC', () => {
method: 'POST',
body: { targetOfferCode: 'plus_month' },
headers: { 'Idempotency-Key': 'desktop:plan-change:12345678' },
+ allowedRedactedErrorCodes: ['PLAN_CHANGE_NOT_AVAILABLE'],
+ });
+ });
+
+ it('preserves the safe plan-change rejection code across IPC', async () => {
+ const { call, fetch } = harness();
+ fetch.mockRejectedValueOnce(
+ new ServerApiError(
+ 'PLAN_CHANGE_NOT_AVAILABLE',
+ 409,
+ 'upstream detail must not reach the renderer',
+ ),
+ );
+
+ await expect(
+ call(BILLING_INVOKE.QUOTE_PLAN_CHANGE, {
+ targetOfferCode: 'max_month',
+ idempotencyKey: 'desktop:plan-change:12345678',
+ }),
+ ).rejects.toMatchObject({
+ code: 'PLAN_CHANGE_NOT_AVAILABLE',
+ message: '[PLAN_CHANGE_NOT_AVAILABLE] target plan is not available',
});
});
diff --git a/apps/desktop/src/main/billing/index.ts b/apps/desktop/src/main/billing/index.ts
index 36634d4efe..643827afca 100644
--- a/apps/desktop/src/main/billing/index.ts
+++ b/apps/desktop/src/main/billing/index.ts
@@ -56,6 +56,9 @@ function assertMainWindowSender(
function throwBillingFetchError(error: unknown): never {
if (error instanceof ServerApiError) {
+ if (error.code === 'PLAN_CHANGE_NOT_AVAILABLE') {
+ throwIpcError('PLAN_CHANGE_NOT_AVAILABLE', 'target plan is not available');
+ }
if (error.statusCode === 400) {
throwIpcError('INVALID_PARAMS', 'billing request was rejected');
}
@@ -341,6 +344,7 @@ export function createBillingHandlers(
method: 'POST',
body: { targetOfferCode },
headers: { 'Idempotency-Key': idempotencyKey },
+ allowedRedactedErrorCodes: ['PLAN_CHANGE_NOT_AVAILABLE'],
}),
projectBillingPlanChange,
);
diff --git a/apps/desktop/src/main/serverApiClient.ts b/apps/desktop/src/main/serverApiClient.ts
index 6f09c9305d..7849916b5e 100644
--- a/apps/desktop/src/main/serverApiClient.ts
+++ b/apps/desktop/src/main/serverApiClient.ts
@@ -50,6 +50,12 @@ export interface ApiFetchOptions {
timeoutMs?: number;
/** Keep upstream response/network details out of local logs for sensitive flows. */
redactErrorDetails?: boolean;
+ /**
+ * Upstream business codes that may cross a redacted boundary. Messages and
+ * response bodies remain hidden; every code must be explicitly allowlisted
+ * by the caller.
+ */
+ allowedRedactedErrorCodes?: readonly string[];
}
interface RawResponse<T> {
@@ -161,7 +167,9 @@ export async function serverApiFetch<T>(apiPath: string, opts: ApiFetchOptions):
);
}
throw new ServerApiError(
- opts.redactErrorDetails ? statusToCode(result.status) : errCode,
+ opts.redactErrorDetails && !opts.allowedRedactedErrorCodes?.includes(errCode)
+ ? statusToCode(result.status)
+ : errCode,
result.status,
opts.redactErrorDetails ? `请求失败 (${result.status})` : errMsg,
);
diff --git a/apps/desktop/src/renderer/features/billing/BillingPage.tsx b/apps/desktop/src/renderer/features/billing/BillingPage.tsx
index 4a1b6af92c..b7d7b37a38 100644
--- a/apps/desktop/src/renderer/features/billing/BillingPage.tsx
+++ b/apps/desktop/src/renderer/features/billing/BillingPage.tsx
@@ -77,7 +77,7 @@ const SUPPORTED_SUBSCRIPTION_CAPABILITIES = new Set<BillingPurchaseOption['capab
'PROVIDER_MANAGED_SUBSCRIPTION',
]);
-const SUBSCRIPTION_PURCHASE_BLOCKING_STATUSES: BillingSubscription['status'][] = [
+const NON_TERMINAL_SUBSCRIPTION_STATUSES: BillingSubscription['status'][] = [
'INCOMPLETE',
'TRIALING',
'ACTIVE',
@@ -86,6 +86,12 @@ const SUBSCRIPTION_PURCHASE_BLOCKING_STATUSES: BillingSubscription['status'][] =
'PAUSED',
];
+// 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;
@@ -417,7 +423,7 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
const subscriptionPurchaseBlocked =
currentSubscription !== null &&
- SUBSCRIPTION_PURCHASE_BLOCKING_STATUSES.includes(currentSubscription.status);
+ NON_TERMINAL_SUBSCRIPTION_STATUSES.includes(currentSubscription.status);
const canCheckout =
!checkout.recovering &&
selected !== null &&
@@ -438,10 +444,22 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
const currentPlan = currentSubscription?.effectivePlan ?? null;
const pendingPlanChange = currentSubscription?.pendingPlanChange ?? null;
- const planChangeable =
- currentSubscription?.status === 'ACTIVE' &&
+ const currentProvider =
+ currentSubscription?.provider &&
+ SUPPORTED_BILLING_PROVIDERS.has(currentSubscription.provider as SupportedBillingProvider)
+ ? (currentSubscription.provider as SupportedBillingProvider)
+ : null;
+ const showPlanChangeEntry =
+ currentPlan !== null &&
+ currentSubscription !== null &&
+ PLAN_CHANGE_ENTRY_STATUSES.includes(currentSubscription.status) &&
!currentSubscription.cancelAtPeriodEnd &&
- currentPlan?.offer.interval === 'MONTH';
+ 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;
@@ -456,32 +474,46 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
};
}, [billingLocale, currentSubscription, planNameOf, 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) =>
isCatalogOfferPurchasable(entry) &&
entry.offer.interval === currentPlan.offer.interval &&
entry.offer.code !== currentPlan.offer.code &&
- entry.product.level !== null &&
- entry.product.level !== currentPlan.product.level &&
- (currentProvider === null ||
- entry.purchaseOptions.some((option) => option.provider === currentProvider)),
+ entry.purchaseOptions.some((option) => option.provider === currentProvider),
)
.map(({ product, offer }) => ({
product,
offer,
+ providers: [currentProvider],
direction:
- (product.level ?? 0) > currentPlan.product.level
- ? ('UPGRADE' as const)
- : ('DOWNGRADE' as const),
- }));
- }, [subscriptionOffers, planChangeable, currentPlan, currentSubscription?.provider]);
+ product.level === null
+ ? null
+ : product.level > currentPlan.product.level
+ ? ('UPGRADE' as const)
+ : product.level < currentPlan.product.level
+ ? ('DOWNGRADE' as const)
+ : ('SAME_LEVEL' as const),
+ }))
+ .sort(
+ (left, right) =>
+ (left.direction === null ? 3 : directionRank[left.direction]) -
+ (right.direction === null ? 3 : directionRank[right.direction]) ||
+ left.product.sortOrder - right.product.sortOrder ||
+ left.offer.code.localeCompare(right.offer.code),
+ );
+ }, [subscriptionOffers, showPlanChangeEntry, currentPlan, currentProvider]);
const openPurchaseDialog = (kind: PurchaseKind) => {
resetSelection();
@@ -544,7 +576,7 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
if (candidate.offer.interval === null) return;
setPlanChangeTargetOpen(false);
void planChange.startQuote(candidate.offer.code, {
- product: { code: candidate.product.code, level: candidate.product.level ?? 0 },
+ product: { code: candidate.product.code, level: candidate.product.level },
offer: { code: candidate.offer.code, interval: candidate.offer.interval },
terms: {
amount: candidate.offer.amount ?? '0',
@@ -563,6 +595,11 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
void loadSubscription();
};
+ const reselectPlanChangeTarget = () => {
+ planChange.close();
+ setPlanChangeTargetOpen(true);
+ };
+
return (
<>
<div>
@@ -605,18 +642,25 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
facts={currentPlanFacts}
loading={loadingSubscription}
error={subscriptionError}
- planChangeable={planChangeable}
- actionDisabled={loadingSubscription || subscriptionError}
+ showPlanChangeEntry={showPlanChangeEntry}
+ recoveryAvailable={recoverableSubscription !== null}
+ actionDisabled={
+ loadingSubscription ||
+ subscriptionError ||
+ (recoverableSubscription !== null && checkout.recovering)
+ }
pendingPlanChange={pendingPlanChange}
pendingTargetName={planNameOf(pendingPlanChange?.targetPlan?.product.code)}
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);
+ if (pendingPlanChange) void planChange.cancelChange(pendingPlanChange.planChangeId);
}}
/>
</BillingGroup>
@@ -728,6 +772,7 @@ export function BillingSettingsSection({ accountId }: { accountId: string | null
onClose={closePlanChangeStatus}
onConfirm={() => void planChange.confirm()}
onRefresh={() => void planChange.refresh()}
+ onReselect={reselectPlanChangeTarget}
onAbandon={() => {
const change = planChange.state.planChange;
if (change) void planChange.cancelChange(change.planChangeId);
@@ -802,11 +847,13 @@ function SubscriptionOverviewCard({
facts,
loading,
error,
- planChangeable,
+ showPlanChangeEntry,
+ recoveryAvailable,
actionDisabled,
pendingPlanChange,
pendingTargetName,
onChangePlan,
+ onRecover,
onPurchase,
onResumePending,
onCancelPending,
@@ -814,11 +861,13 @@ function SubscriptionOverviewCard({
facts: CurrentPlanFacts | null;
loading: boolean;
error: boolean;
- planChangeable: boolean;
+ showPlanChangeEntry: boolean;
+ recoveryAvailable: boolean;
actionDisabled: boolean;
pendingPlanChange: BillingPendingPlanChange | null;
pendingTargetName: string | null;
onChangePlan: () => void;
+ onRecover: () => void;
onPurchase: () => void;
onResumePending: () => void;
onCancelPending: () => void;
@@ -892,13 +941,15 @@ function SubscriptionOverviewCard({
</div>
<button
type="button"
- onClick={planChangeable ? onChangePlan : onPurchase}
+ 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"
>
- {planChangeable
+ {showPlanChangeEntry
? t('billing.settings.subscriptionCard.changeAction')
- : t('billing.settings.subscriptionCard.action')}
+ : recoveryAvailable
+ ? t('billing.recovery.continueSubscription')
+ : t('billing.settings.subscriptionCard.action')}
</button>
</div>
{pendingPlanChange && (
diff --git a/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx b/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx
index ed122c4212..689469739a 100644
--- a/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx
+++ b/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx
@@ -31,8 +31,12 @@ import type { PlanChangeState } from './usePlanChange';
export type PlanChangeCandidate = {
product: BillingCatalogProduct;
offer: BillingCatalogOffer;
- /** UI hint only; the server quote is the authority on the change type. */
- direction: 'UPGRADE' | 'DOWNGRADE';
+ providers: Array<'alipay' | 'stripe'>;
+ /**
+ * UI hint only; the server quote is authoritative. Null means the product
+ * level is missing, so the client hides the direction instead of guessing.
+ */
+ direction: 'UPGRADE' | 'SAME_LEVEL' | 'DOWNGRADE' | null;
};
function formatEffectiveDate(iso: string, locale: string): string {
@@ -104,7 +108,22 @@ export function PlanChangeTargetDialog({
<div className="divide-y divide-[var(--border-default)] overflow-hidden rounded-xl border border-[var(--border-default)]">
{candidates.map((candidate) => {
const DirectionIcon =
- candidate.direction === 'UPGRADE' ? ArrowUpRight : ArrowDownRight;
+ candidate.direction === 'UPGRADE'
+ ? ArrowUpRight
+ : candidate.direction === 'DOWNGRADE'
+ ? ArrowDownRight
+ : null;
+ const directionLabel =
+ candidate.direction === 'UPGRADE'
+ ? t('billing.planChange.upgradeBadge')
+ : candidate.direction === 'DOWNGRADE'
+ ? t('billing.planChange.downgradeBadge')
+ : candidate.direction === 'SAME_LEVEL'
+ ? t('billing.planChange.sameLevelBadge')
+ : null;
+ const providerLabel = candidate.providers
+ .map((provider) => t(`billing.providers.${provider}`))
+ .join(', ');
return (
<button
key={candidate.offer.code}
@@ -121,12 +140,14 @@ export function PlanChangeTargetDialog({
<p className="truncate text-13 font-medium text-[var(--text-primary)]">
{candidate.product.name}
</p>
- <p className="mt-0.5 inline-flex items-center gap-1 text-11 text-[var(--text-tertiary)]">
- <DirectionIcon size={12} />
- {candidate.direction === 'UPGRADE'
- ? t('billing.planChange.upgradeBadge')
- : t('billing.planChange.downgradeBadge')}
- </p>
+ {(directionLabel || providerLabel) && (
+ <p className="mt-0.5 flex min-h-4 items-center gap-1 text-11 text-[var(--text-tertiary)]">
+ {DirectionIcon && <DirectionIcon size={12} />}
+ {directionLabel && <span>{directionLabel}</span>}
+ {directionLabel && providerLabel && <span aria-hidden>·</span>}
+ {providerLabel && <span>{providerLabel}</span>}
+ </p>
+ )}
</div>
<div className="shrink-0 text-right">
<p className="text-13 font-medium tabular-nums text-[var(--text-primary)]">
@@ -184,6 +205,7 @@ export function PlanChangeStatusDialog({
onClose,
onConfirm,
onRefresh,
+ onReselect,
onAbandon,
}: {
state: PlanChangeState;
@@ -191,6 +213,7 @@ export function PlanChangeStatusDialog({
onClose: () => void;
onConfirm: () => void;
onRefresh: () => void;
+ onReselect: () => void;
onAbandon: () => void;
}) {
const { t, i18n } = useTranslation();
@@ -433,7 +456,9 @@ export function PlanChangeStatusDialog({
</div>
<p className="mt-4 max-w-[340px] text-sm text-[var(--text-secondary)]">
{state.error
- ? t('billing.planChange.requestFailed')
+ ? state.quoteFailureReason === 'TARGET_NOT_ALLOWED'
+ ? t('billing.planChange.quoteRejected')
+ : t('billing.planChange.requestFailed')
: state.phase === 'CANCELED'
? t('billing.planChange.canceledBody')
: state.phase === 'EXPIRED'
@@ -457,6 +482,15 @@ export function PlanChangeStatusDialog({
)}
</div>
<div className="flex items-center gap-2">
+ {state.phase === 'FAILED' && state.quoteFailureReason === 'TARGET_NOT_ALLOWED' && (
+ <button
+ type="button"
+ onClick={onReselect}
+ className="h-9 rounded-full bg-[var(--text-primary)] px-5 text-13 font-medium text-[var(--surface)]"
+ >
+ {t('billing.planChange.chooseAnotherPlan')}
+ </button>
+ )}
{(state.phase === 'AWAITING_PAYMENT' ||
state.phase === 'PENDING_PROVIDER' ||
(state.phase === 'QUOTE_READY' && state.stale)) && (
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 b57fb58323..b614170729 100644
--- a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
@@ -804,7 +804,7 @@ describe('BillingPage remote catalog rendering', () => {
expect(pay).toHaveProperty('disabled', false);
});
- it('does not create a second subscription while one is still live', async () => {
+ it('does not expose plan change when an active subscription has no effective plan', async () => {
window.electronAPI.billing.getCurrentSubscription = vi.fn(async () => ({
subscription: {
subscriptionId: 'subscription_fixture',
@@ -820,17 +820,44 @@ describe('BillingPage remote catalog rendering', () => {
}));
render(<BillingPage />);
- fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));
- fireEvent.click((await screen.findByText('Configured subscription')).closest('button')!);
- fireEvent.click((await screen.findByText('stripe')).closest('button')!);
- const pay = screen.getByText('billing.actions.pay').closest('button')!;
- expect(pay).toHaveProperty('disabled', true);
- expect(screen.getByText('billing.currentSubscription.purchaseBlocked')).toBeTruthy();
- fireEvent.click(pay);
+ expect(await screen.findByText('billing.settings.subscriptionCard.action')).toBeTruthy();
+ expect(screen.queryByText('billing.settings.subscriptionCard.changeAction')).toBeNull();
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');
@@ -1006,6 +1033,24 @@ describe('BillingPage plan change', () => {
},
],
},
+ {
+ code: 'plus_year',
+ interval: 'YEAR' as const,
+ currency: 'usd',
+ amount: '90',
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: '1200',
+ rolloverCap: '0',
+ purchaseOptions: [
+ {
+ id: 'listing_plus_year_stripe',
+ provider: 'stripe',
+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,
+ paymentAction: 'REDIRECT' as const,
+ },
+ ],
+ },
],
},
{
@@ -1033,6 +1078,78 @@ describe('BillingPage plan change', () => {
},
],
},
+ {
+ code: 'max_year',
+ interval: 'YEAR' as const,
+ currency: 'usd',
+ amount: '200',
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: '3000',
+ rolloverCap: '0',
+ purchaseOptions: [
+ {
+ id: 'listing_max_year_stripe',
+ provider: 'stripe',
+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,
+ paymentAction: 'REDIRECT' as const,
+ },
+ ],
+ },
+ ],
+ },
+ {
+ code: 'same_level',
+ name: 'Same-level plan',
+ kind: 'SUBSCRIPTION' as const,
+ level: 1,
+ sortOrder: 0,
+ offers: [
+ {
+ code: 'same_level_month',
+ interval: 'MONTH' as const,
+ currency: 'usd',
+ amount: '12',
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: '120',
+ rolloverCap: '0',
+ purchaseOptions: [
+ {
+ id: 'listing_same_level_stripe',
+ provider: 'stripe',
+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,
+ paymentAction: 'REDIRECT' as const,
+ },
+ ],
+ },
+ ],
+ },
+ {
+ code: 'starter',
+ name: 'Starter plan',
+ kind: 'SUBSCRIPTION' as const,
+ level: 0,
+ sortOrder: 0,
+ offers: [
+ {
+ code: 'starter_month',
+ interval: 'MONTH' as const,
+ currency: 'usd',
+ amount: '5',
+ minAmount: null,
+ maxAmount: null,
+ creditAmount: '50',
+ rolloverCap: '0',
+ purchaseOptions: [
+ {
+ id: 'listing_starter_stripe',
+ provider: 'stripe',
+ capability: 'PROVIDER_MANAGED_SUBSCRIPTION' as const,
+ paymentAction: 'REDIRECT' as const,
+ },
+ ],
+ },
],
},
{
@@ -1089,20 +1206,22 @@ describe('BillingPage plan change', () => {
};
const activeSubscription = (
- pendingPlanChange: unknown = null,
+ pendingPlanChange: BillingSubscription['pendingPlanChange'] = null,
interval: 'MONTH' | 'YEAR' = 'MONTH',
- ) => ({
+ status: BillingSubscription['status'] = 'ACTIVE',
+ cancelAtPeriodEnd = false,
+ ): BillingSubscription => ({
subscriptionId: 'subscription_active',
- status: 'ACTIVE' as const,
+ status,
provider: 'stripe',
currentPeriodStartAt: '2026-07-01T00:00:00.000Z',
currentPeriodEndAt: '2026-08-01T00:00:00.000Z',
entitlementValidUntil: '2026-08-02T00:00:00.000Z',
- cancelAtPeriodEnd: false,
+ cancelAtPeriodEnd,
effectivePlan: {
version: 1 as const,
product: { code: 'plus', kind: 'SUBSCRIPTION' as const, level: 1 },
- offer: { code: 'plus_month', interval },
+ offer: { code: interval === 'YEAR' ? 'plus_year' : 'plus_month', interval },
terms: { amount: '9', currency: 'usd', creditAmount: '100', rolloverCap: '0' },
capturedAt: '2026-07-01T00:00:00.000Z',
},
@@ -1155,7 +1274,7 @@ describe('BillingPage plan change', () => {
});
});
- 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',
@@ -1172,13 +1291,23 @@ describe('BillingPage plan change', () => {
fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.changeAction'));
await screen.findByText('billing.planChange.targetTitle');
- expect(screen.getByText('Max plan')).toBeTruthy();
+ const maxButton = screen.getByText('Max plan').closest('button')!;
+ const sameLevelButton = screen.getByText('Same-level plan').closest('button')!;
+ const starterButton = screen.getByText('Starter plan').closest('button')!;
+ expect(
+ maxButton.compareDocumentPosition(sameLevelButton) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBe(Node.DOCUMENT_POSITION_FOLLOWING);
+ expect(
+ sameLevelButton.compareDocumentPosition(starterButton) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBe(Node.DOCUMENT_POSITION_FOLLOWING);
+ expect(within(maxButton).getByText('billing.planChange.upgradeBadge')).toBeTruthy();
+ expect(within(maxButton).getByText('stripe')).toBeTruthy();
+ expect(within(sameLevelButton).getByText('billing.planChange.sameLevelBadge')).toBeTruthy();
+ expect(within(starterButton).getByText('billing.planChange.downgradeBadge')).toBeTruthy();
expect(screen.queryByText('Alipay-only Max')).toBeNull();
expect(screen.queryByText('Coming soon Max')).toBeNull();
- // The current plan renders in the summary card but must not be a candidate.
- expect(screen.getByText('billing.planChange.upgradeBadge')).toBeTruthy();
- fireEvent.click(screen.getByText('Max plan'));
+ fireEvent.click(maxButton);
await screen.findByText('billing.planChange.quoteTitle');
expect(billing.quotePlanChange).toHaveBeenCalledTimes(1);
expect(billing.quotePlanChange).toHaveBeenCalledWith({
@@ -1221,6 +1350,114 @@ describe('BillingPage plan change', () => {
expect(billing.quotePlanChange).not.toHaveBeenCalled();
});
+ it('does not offer cross-provider targets when the current provider is unavailable', async () => {
+ const subscription = activeSubscription();
+ delete subscription.provider;
+ const billing = billingMocks();
+ billing.getCurrentSubscription = vi.fn(async () => ({ subscription }));
+ install(billing);
+
+ render(<BillingPage />);
+
+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.changeAction'));
+ expect(await screen.findByText('billing.planChange.emptyTitle')).toBeTruthy();
+ expect(screen.queryByText('Max plan')).toBeNull();
+ expect(billing.quotePlanChange).not.toHaveBeenCalled();
+ });
+
+ it.each(['TRIALING', 'PAST_DUE', 'UNPAID', 'PAUSED'] as const)(
+ 'does not expose plan change for server-ineligible %s subscriptions',
+ async (status) => {
+ const billing = billingMocks();
+ billing.getCurrentSubscription = vi.fn(async () => ({
+ subscription: activeSubscription(null, 'MONTH', status),
+ }));
+ install(billing);
+
+ render(<BillingPage />);
+
+ await screen.findByText('Plus plan');
+ expect(screen.queryByText('billing.settings.subscriptionCard.changeAction')).toBeNull();
+ expect(screen.getByText('billing.settings.subscriptionCard.action')).toBeTruthy();
+ },
+ );
+
+ it('does not expose plan change when cancellation is scheduled for period end', async () => {
+ const billing = billingMocks();
+ billing.getCurrentSubscription = vi.fn(async () => ({
+ subscription: activeSubscription(null, 'MONTH', 'ACTIVE', true),
+ }));
+ install(billing);
+
+ render(<BillingPage />);
+
+ await screen.findByText('Plus plan');
+ expect(screen.queryByText('billing.settings.subscriptionCard.changeAction')).toBeNull();
+ 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,
+ };
+ const billing = billingMocks();
+ billing.getCurrentSubscription = vi.fn(async () => ({
+ subscription: incompleteSubscription,
+ }));
+ install(billing);
+ checkout.recoverables.subscription = incompleteSubscription;
+
+ render(<BillingPage />);
+
+ await waitFor(() =>
+ expect(screen.getAllByText('billing.recovery.continueSubscription')).toHaveLength(2),
+ );
+ 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,
+ };
+ const billing = billingMocks();
+ billing.getCurrentSubscription = vi.fn(async () => ({
+ subscription: incompleteSubscription,
+ }));
+ install(billing);
+
+ render(<BillingPage />);
+
+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.action'));
+ fireEvent.click((await screen.findAllByText('Plus plan'))[0].closest('button')!);
+ fireEvent.click(screen.getByText('stripe').closest('button')!);
+ expect(screen.getByText('billing.actions.pay').closest('button')).toHaveProperty(
+ 'disabled',
+ true,
+ );
+ expect(screen.getByText('billing.currentSubscription.purchaseBlocked')).toBeTruthy();
+ });
+
+ it('explains a rejected quote and returns to the candidate list', async () => {
+ const billing = install(billingMocks());
+ billing.quotePlanChange.mockRejectedValue(
+ new Error('[PLAN_CHANGE_NOT_AVAILABLE] target offer is not allowed'),
+ );
+
+ render(<BillingPage />);
+ fireEvent.click(await screen.findByText('billing.settings.subscriptionCard.changeAction'));
+ fireEvent.click(await screen.findByText('Max plan'));
+
+ expect(await screen.findByText('billing.planChange.quoteRejected')).toBeTruthy();
+ fireEvent.click(screen.getByText('billing.planChange.chooseAnotherPlan'));
+ expect(await screen.findByText('billing.planChange.targetTitle')).toBeTruthy();
+ expect(screen.getByText('Max plan')).toBeTruthy();
+ });
+
it('shows a scheduled downgrade banner and undoes it through DELETE', async () => {
const billing = billingMocks();
billing.getCurrentSubscription = vi.fn(async () => ({
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx
index eed78a68d7..6135fc3124 100644
--- a/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx
+++ b/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx
@@ -33,6 +33,7 @@ function quoteReadyState(overrides: Partial<PlanChangeState> = {}): PlanChangeSt
},
targetPlan: null,
error: false,
+ quoteFailureReason: null,
stale: false,
...overrides,
};
@@ -47,6 +48,7 @@ describe('PlanChangeStatusDialog stale snapshot handling', () => {
onClose={vi.fn()}
onConfirm={vi.fn()}
onRefresh={vi.fn()}
+ onReselect={vi.fn()}
onAbandon={vi.fn()}
/>,
);
@@ -65,6 +67,7 @@ describe('PlanChangeStatusDialog stale snapshot handling', () => {
onClose={vi.fn()}
onConfirm={vi.fn()}
onRefresh={onRefresh}
+ onReselect={vi.fn()}
onAbandon={vi.fn()}
/>,
);
@@ -92,6 +95,7 @@ describe('PlanChangeStatusDialog stale snapshot handling', () => {
onClose={vi.fn()}
onConfirm={vi.fn()}
onRefresh={onRefresh}
+ onReselect={vi.fn()}
onAbandon={vi.fn()}
/>,
);
@@ -104,4 +108,28 @@ describe('PlanChangeStatusDialog stale snapshot handling', () => {
fireEvent.click(screen.getByText('billing.actions.refresh'));
expect(onRefresh).toHaveBeenCalledTimes(1);
});
+
+ it('explains a rejected target and returns to plan selection', () => {
+ const onReselect = vi.fn();
+ render(
+ <PlanChangeStatusDialog
+ state={quoteReadyState({
+ phase: 'FAILED',
+ planChange: null,
+ error: true,
+ quoteFailureReason: 'TARGET_NOT_ALLOWED',
+ })}
+ targetName="Max"
+ onClose={vi.fn()}
+ onConfirm={vi.fn()}
+ onRefresh={vi.fn()}
+ onReselect={onReselect}
+ onAbandon={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByText('billing.planChange.quoteRejected')).toBeTruthy();
+ fireEvent.click(screen.getByText('billing.planChange.chooseAnotherPlan'));
+ expect(onReselect).toHaveBeenCalledTimes(1);
+ });
});
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 ae75bcd52e..68f74a97ed 100644
--- a/apps/desktop/src/renderer/features/billing/__tests__/usePlanChange.test.ts
+++ b/apps/desktop/src/renderer/features/billing/__tests__/usePlanChange.test.ts
@@ -289,6 +289,27 @@ describe('usePlanChange', () => {
});
});
+ it.each([
+ ['[PLAN_CHANGE_NOT_AVAILABLE] target offer is not allowed', 'TARGET_NOT_ALLOWED'],
+ [
+ 'Error invoking remote method: Error: [PRECONDITION_FAILED] subscription changed',
+ 'REQUEST_FAILED',
+ ],
+ ['[INVALID_PARAMS] targetOfferCode is invalid', 'REQUEST_FAILED'],
+ ['[INTERNAL] billing service request failed', 'REQUEST_FAILED'],
+ ] as const)('classifies a quote failure from the IPC error protocol', async (message, reason) => {
+ api.quotePlanChange.mockRejectedValue(new Error(message));
+ const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, vi.fn()));
+
+ await act(() => result.current.startQuote('max_month', TARGET_PLAN));
+
+ expect(result.current.state).toMatchObject({
+ phase: 'FAILED',
+ error: true,
+ quoteFailureReason: reason,
+ });
+ });
+
it('reuses the same idempotency key when retrying the same target after a failure', async () => {
api.quotePlanChange.mockRejectedValueOnce(new Error('network'));
api.quotePlanChange.mockResolvedValueOnce(change());
diff --git a/apps/desktop/src/renderer/features/billing/usePlanChange.ts b/apps/desktop/src/renderer/features/billing/usePlanChange.ts
index 75d537c487..a6dfce8703 100644
--- a/apps/desktop/src/renderer/features/billing/usePlanChange.ts
+++ b/apps/desktop/src/renderer/features/billing/usePlanChange.ts
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react';
+import { extractIpcError } from '@/utils/ipcError';
import type {
BillingPendingPlanChange,
BillingPlanChange,
@@ -27,12 +28,19 @@ export type PlanChangePhase =
| 'FAILED'
| 'EXPIRED';
+export type PlanChangeTargetSnapshot = Omit<BillingPlanChangeTargetPlan, 'product'> & {
+ product: Omit<BillingPlanChangeTargetPlan['product'], 'level'> & { level: number | null };
+};
+
+export type PlanChangeQuoteFailureReason = 'TARGET_NOT_ALLOWED' | 'REQUEST_FAILED';
+
export type PlanChangeState = {
open: boolean;
phase: PlanChangePhase;
planChange: BillingPlanChange | null;
- targetPlan: BillingPlanChangeTargetPlan | null;
+ targetPlan: PlanChangeTargetSnapshot | null;
error: boolean;
+ quoteFailureReason: PlanChangeQuoteFailureReason | null;
/**
* True when the rendered change is a pre-request snapshot that could not be
* re-read from the server (confirm and the recovery read both failed). A
@@ -49,6 +57,7 @@ const INITIAL_STATE: PlanChangeState = {
planChange: null,
targetPlan: null,
error: false,
+ quoteFailureReason: null,
stale: false,
};
@@ -88,6 +97,12 @@ function isSettledPhase(phase: PlanChangePhase): boolean {
);
}
+function quoteFailureReason(error: unknown): PlanChangeQuoteFailureReason {
+ return extractIpcError(error)?.code === 'PLAN_CHANGE_NOT_AVAILABLE'
+ ? 'TARGET_NOT_ALLOWED'
+ : 'REQUEST_FAILED';
+}
+
export function usePlanChange(
accountId: string | null,
onSettled: (kind: PlanChangeSettledKind) => void,
@@ -132,7 +147,7 @@ export function usePlanChange(
const applyChange = useCallback(
(
change: BillingPlanChange,
- options?: { targetPlan?: BillingPlanChangeTargetPlan | null; open?: boolean },
+ options?: { targetPlan?: PlanChangeTargetSnapshot | null; open?: boolean },
) => {
const phase = phaseForPlanChange(change);
if (phase !== 'QUOTE_READY' && phase !== 'AWAITING_PAYMENT') {
@@ -146,6 +161,7 @@ export function usePlanChange(
planChange: change,
targetPlan: options?.targetPlan !== undefined ? options.targetPlan : current.targetPlan,
error: false,
+ quoteFailureReason: null,
stale: false,
}));
},
@@ -175,7 +191,7 @@ export function usePlanChange(
}, [applyChange]);
const startQuote = useCallback(
- async (targetOfferCode: string, targetPlan: BillingPlanChangeTargetPlan | null) => {
+ async (targetOfferCode: string, targetPlan: PlanChangeTargetSnapshot | null) => {
if (!accountId || inFlightRef.current) return;
const previous = readBillingPlanChangeIntent(accountId);
const intent: BillingPlanChangeIntentV1 =
@@ -195,6 +211,7 @@ export function usePlanChange(
planChange: null,
targetPlan,
error: false,
+ quoteFailureReason: null,
stale: false,
});
await withRequestLock(async () => {
@@ -202,10 +219,15 @@ export function usePlanChange(
const change = await billingApi.quotePlanChange(targetOfferCode, intent.idempotencyKey);
persistIntent({ ...intent, planChangeId: change.planChangeId });
applyChange(change, { targetPlan });
- } catch {
+ } catch (error) {
if (await adoptServerPending()) return;
if (mountedRef.current) {
- setState((current) => ({ ...current, phase: 'FAILED', error: true }));
+ setState((current) => ({
+ ...current,
+ phase: 'FAILED',
+ error: true,
+ quoteFailureReason: quoteFailureReason(error),
+ }));
}
}
});
@@ -218,7 +240,12 @@ export function usePlanChange(
if (!current.planChange || current.planChange.status !== 'QUOTED' || inFlightRef.current)
return;
const change = current.planChange;
- setState((value) => ({ ...value, phase: 'CONFIRMING', error: false }));
+ setState((value) => ({
+ ...value,
+ phase: 'CONFIRMING',
+ error: false,
+ quoteFailureReason: null,
+ }));
await withRequestLock(async () => {
try {
applyChange(await billingApi.confirmPlanChange(change.planChangeId));
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index e7ffbcf26a..49d8b88ac6 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -7320,6 +7320,7 @@
"planChange": {
"targetTitle": "Change subscription plan",
"upgradeBadge": "Upgrade",
+ "sameLevelBadge": "Same tier",
"downgradeBadge": "Downgrade",
"emptyTitle": "No plans available to switch to",
"emptyDescription": "The server has not configured another plan for your current payment method.",
@@ -7341,7 +7342,9 @@
"expiredBody": "The quote expired. Start the plan change again to get a new quote.",
"failedTitle": "Plan change failed",
"failedBody": "The plan change did not complete. Your current plan is unchanged.",
- "requestFailed": "The request failed. Please try again.",
+ "requestFailed": "The plan change request couldn’t be completed. Refresh your subscription status and try again.",
+ "quoteRejected": "This plan isn’t available for your current subscription. Choose another plan.",
+ "chooseAnotherPlan": "Choose Another Plan",
"resyncHint": "The confirmation result could not be verified. Syncing the latest status from the server…",
"upgradeDueNow": "Pay {{amount}} now for the remainder of this period",
"upgradeNoAmount": "The upgrade takes effect immediately after confirmation.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index c4341dc3c0..e7345358e0 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -7309,6 +7309,7 @@
"planChange": {
"targetTitle": "サブスクリプションプランの変更",
"upgradeBadge": "アップグレード",
+ "sameLevelBadge": "同じレベル",
"downgradeBadge": "ダウングレード",
"emptyTitle": "切り替え可能なプランがありません",
"emptyDescription": "現在の支払い方法で切り替え可能なプランがまだ設定されていません。",
@@ -7330,7 +7331,9 @@
"expiredBody": "見積もりの有効期限が切れました。もう一度プラン変更を開始してください。",
"failedTitle": "プラン変更に失敗しました",
"failedBody": "プラン変更は完了しませんでした。現在のプランは変わりません。",
- "requestFailed": "リクエストに失敗しました。もう一度お試しください。",
+ "requestFailed": "プラン変更リクエストを完了できませんでした。サブスクリプションの状態を更新して、もう一度お試しください。",
+ "quoteRejected": "現在のサブスクリプションではこのプランに変更できません。別のプランを選択してください。",
+ "chooseAnotherPlan": "別のプランを選択",
"resyncHint": "確認結果を検証できませんでした。サーバーから最新の状態を同期しています…",
"upgradeDueNow": "今期の差額 {{amount}} をお支払いください",
"upgradeNoAmount": "確認後、アップグレードは即時適用されます。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 5ac5bfc9fa..c4b3bd7797 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -7309,6 +7309,7 @@
"planChange": {
"targetTitle": "구독 플랜 변경",
"upgradeBadge": "업그레이드",
+ "sameLevelBadge": "동일 등급",
"downgradeBadge": "다운그레이드",
"emptyTitle": "전환 가능한 플랜이 없습니다",
"emptyDescription": "현재 결제 수단으로 전환할 수 있는 다른 플랜이 아직 설정되지 않았습니다.",
@@ -7330,7 +7331,9 @@
"expiredBody": "견적이 만료되었습니다. 플랜 변경을 다시 시작해 주세요.",
"failedTitle": "플랜 변경 실패",
"failedBody": "플랜 변경이 완료되지 않았습니다. 현재 플랜은 그대로 유지됩니다.",
- "requestFailed": "요청에 실패했습니다. 다시 시도해 주세요.",
+ "requestFailed": "플랜 변경 요청을 완료하지 못했습니다. 구독 상태를 새로고침한 후 다시 시도하세요.",
+ "quoteRejected": "현재 구독에서는 이 플랜으로 변경할 수 없습니다. 다른 플랜을 선택하세요.",
+ "chooseAnotherPlan": "다른 플랜 선택",
"resyncHint": "확인 결과를 검증할 수 없습니다. 서버에서 최신 상태를 동기화하는 중…",
"upgradeDueNow": "이번 기간 차액 {{amount}}을(를) 결제하세요",
"upgradeNoAmount": "확인 후 업그레이드가 즉시 적용됩니다.",
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 aad02ecf76..3dd2c3f909 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -7309,6 +7309,7 @@
"planChange": {
"targetTitle": "更改订阅套餐",
"upgradeBadge": "升级",
+ "sameLevelBadge": "同等级",
"downgradeBadge": "降级",
"emptyTitle": "暂无可切换的套餐",
"emptyDescription": "服务端尚未为当前支付方式配置其他可切换套餐。",
@@ -7330,7 +7331,9 @@
"expiredBody": "报价已过期,请重新发起套餐变更获取新报价。",
"failedTitle": "套餐变更失败",
"failedBody": "套餐变更未完成,当前套餐保持不变。",
- "requestFailed": "请求失败,请重试。",
+ "requestFailed": "套餐变更请求未完成,请刷新订阅状态后重试。",
+ "quoteRejected": "当前订阅无法切换到这个套餐,请选择其他套餐。",
+ "chooseAnotherPlan": "选择其他套餐",
"resyncHint": "确认结果暂时无法核实,正在从服务端同步最新状态…",
"upgradeDueNow": "本期需支付差价 {{amount}}",
"upgradeNoAmount": "确认后升级立即生效。",
diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.ts
index 1f969c5a5e..f1e11b09fa 100644
--- a/apps/desktop/src/shared/ipc-errors.ts
+++ b/apps/desktop/src/shared/ipc-errors.ts
@@ -110,6 +110,7 @@ export type IpcErrorCode =
| 'MODEL_ACCESS_FAILED' // 拉取/轮换失败(网络或服务端错误),可重试
| 'MODEL_ACCESS_DISABLED' // 服务端灰度未启用(503)——走手填兜底
| 'MODEL_ACCESS_UNSUPPORTED' // 企业未接入(403)——XD 网关不可用,不重试
+ | 'PLAN_CHANGE_NOT_AVAILABLE' // 当前订阅不能切换到目标套餐,可返回候选列表重选
// 个人资料自助修改(settings → 用户卡片;服务端直写)
| 'PROFILE_AVATAR_UPLOAD_FAILED' // 头像经 oss-server 预签名直传失败(presign 或 PUT 阶段)
| 'PROFILE_UPDATE_FAILED' // PATCH /api/me/profile 失败(网络 / 服务端拒绝)
@@ -213,6 +214,7 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>([
'MODEL_ACCESS_FAILED',
'MODEL_ACCESS_DISABLED',
'MODEL_ACCESS_UNSUPPORTED',
+ 'PLAN_CHANGE_NOT_AVAILABLE',
'PROFILE_AVATAR_UPLOAD_FAILED',
'PROFILE_UPDATE_FAILED',
'SHARE_FILE_INVALID',