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(billing): 提示预付下一期时暂不能升级

liugaowei9d6e1ee21681
diff --git a/apps/desktop/src/main/billing/__tests__/index.test.ts b/apps/desktop/src/main/billing/__tests__/index.test.ts
index 86b7cc202e..342a23f25c 100644
--- a/apps/desktop/src/main/billing/__tests__/index.test.ts
+++ b/apps/desktop/src/main/billing/__tests__/index.test.ts
@@ -456,7 +456,7 @@ describe('billing IPC', () => {
method: 'POST',
body: { targetOfferCode: 'plus_month' },
headers: { 'Idempotency-Key': 'desktop:plan-change:12345678' },
- allowedRedactedErrorCodes: ['PLAN_CHANGE_NOT_AVAILABLE'],
+ allowedRedactedErrorCodes: ['PLAN_CHANGE_NOT_AVAILABLE', 'PLAN_CHANGE_RENEWAL_PREPAID'],
});
});
@@ -481,6 +481,32 @@ describe('billing IPC', () => {
});
});
+ it.each([
+ [
+ BILLING_INVOKE.QUOTE_PLAN_CHANGE,
+ { targetOfferCode: 'max_month', idempotencyKey: 'desktop:plan-change:12345678' },
+ ],
+ [BILLING_INVOKE.CONFIRM_PLAN_CHANGE, { planChangeId: 'plan_change_1' }],
+ ])(
+ 'preserves prepaid renewal rejection without exposing upstream text: %s',
+ async (channel, payload) => {
+ const { call, fetch } = harness();
+ fetch.mockRejectedValueOnce(
+ new ServerApiError('PLAN_CHANGE_RENEWAL_PREPAID', 409, 'private upstream detail'),
+ );
+ await expect(call(channel, payload)).rejects.toMatchObject({
+ code: 'PLAN_CHANGE_RENEWAL_PREPAID',
+ message: '[PLAN_CHANGE_RENEWAL_PREPAID] next renewal is already paid',
+ });
+ expect(fetch).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ allowedRedactedErrorCodes: expect.arrayContaining(['PLAN_CHANGE_RENEWAL_PREPAID']),
+ }),
+ );
+ },
+ );
+
it('rejects a plan change quote without a valid idempotency key before network access', async () => {
const { call, fetch } = harness();
await expect(
diff --git a/apps/desktop/src/main/billing/index.ts b/apps/desktop/src/main/billing/index.ts
index a6a2fec42c..b91ce340cf 100644
--- a/apps/desktop/src/main/billing/index.ts
+++ b/apps/desktop/src/main/billing/index.ts
@@ -59,6 +59,9 @@ function assertMainWindowSender(
function throwBillingFetchError(error: unknown): never {
if (error instanceof ServerApiError) {
+ if (error.code === 'PLAN_CHANGE_RENEWAL_PREPAID') {
+ throwIpcError('PLAN_CHANGE_RENEWAL_PREPAID', 'next renewal is already paid');
+ }
if (error.code === 'PLAN_CHANGE_NOT_AVAILABLE') {
throwIpcError('PLAN_CHANGE_NOT_AVAILABLE', 'target plan is not available');
}
@@ -400,7 +403,7 @@ export function createBillingHandlers(
method: 'POST',
body: { targetOfferCode },
headers: { 'Idempotency-Key': idempotencyKey },
- allowedRedactedErrorCodes: ['PLAN_CHANGE_NOT_AVAILABLE'],
+ allowedRedactedErrorCodes: ['PLAN_CHANGE_NOT_AVAILABLE', 'PLAN_CHANGE_RENEWAL_PREPAID'],
}),
projectBillingPlanChange,
);
@@ -410,7 +413,7 @@ export function createBillingHandlers(
return projectResponse(
await invoke<unknown>(
`/api/billing/subscription/plan-changes/${encodeURIComponent(planChangeId)}/confirm`,
- { method: 'POST' },
+ { method: 'POST', allowedRedactedErrorCodes: ['PLAN_CHANGE_RENEWAL_PREPAID'] },
),
projectBillingPlanChange,
);
diff --git a/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx b/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx
index 123bbb2ee3..3eb01b7261 100644
--- a/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx
+++ b/apps/desktop/src/renderer/features/billing/PlanChangeDialog.tsx
@@ -630,9 +630,11 @@ export function PlanChangeStatusDialog({
</div>
<p className="mt-4 max-w-[340px] text-sm text-[var(--text-secondary)]">
{state.error
- ? state.quoteFailureReason === 'TARGET_NOT_ALLOWED'
- ? t('billing.planChange.quoteRejected')
- : t('billing.planChange.requestFailed')
+ ? state.quoteFailureReason === 'RENEWAL_PREPAID'
+ ? t('billing.planChange.renewalPrepaid')
+ : state.quoteFailureReason === 'TARGET_NOT_ALLOWED'
+ ? t('billing.planChange.quoteRejected')
+ : t('billing.planChange.requestFailed')
: state.phase === 'CANCELED'
? t('billing.planChange.canceledBody')
: state.phase === 'EXPIRED'
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 feec1ee4d4..d5bb7e6d41 100644
--- a/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx
+++ b/apps/desktop/src/renderer/features/billing/__tests__/PlanChangeDialog.test.tsx
@@ -146,6 +146,27 @@ describe('PlanChangeStatusDialog stale snapshot handling', () => {
expect(onRefresh).toHaveBeenCalledTimes(1);
});
+ it('explains a prepaid renewal without offering another upgrade or confirmation', () => {
+ render(
+ <PlanChangeStatusDialog
+ state={quoteReadyState({
+ phase: 'FAILED',
+ error: true,
+ quoteFailureReason: 'RENEWAL_PREPAID',
+ })}
+ targetName="Max"
+ onClose={vi.fn()}
+ onConfirm={vi.fn()}
+ onRefresh={vi.fn()}
+ onReselect={vi.fn()}
+ onAbandon={vi.fn()}
+ />,
+ );
+ expect(screen.getByText('billing.planChange.renewalPrepaid')).toBeTruthy();
+ expect(screen.queryByText('billing.planChange.confirm')).toBeNull();
+ expect(screen.queryByText('billing.planChange.chooseAnotherPlan')).toBeNull();
+ });
+
it('explains a rejected target and returns to plan selection', () => {
const onReselect = vi.fn();
render(
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 8d44d56bca..9340d99d5b 100644
--- a/apps/desktop/src/renderer/features/billing/__tests__/usePlanChange.test.ts
+++ b/apps/desktop/src/renderer/features/billing/__tests__/usePlanChange.test.ts
@@ -250,6 +250,7 @@ describe('usePlanChange', () => {
it.each([
['[PLAN_CHANGE_NOT_AVAILABLE] target offer is not allowed', 'TARGET_NOT_ALLOWED'],
+ ['[PLAN_CHANGE_RENEWAL_PREPAID] next renewal is already paid', 'RENEWAL_PREPAID'],
[
'Error invoking remote method: Error: [PRECONDITION_FAILED] subscription changed',
'REQUEST_FAILED',
@@ -269,6 +270,22 @@ describe('usePlanChange', () => {
});
});
+ it('shows prepaid renewal rejection when renewal settles between quote and confirm', async () => {
+ api.quotePlanChange.mockResolvedValue(change());
+ api.confirmPlanChange.mockRejectedValue(
+ new Error('[PLAN_CHANGE_RENEWAL_PREPAID] next renewal is already paid'),
+ );
+ const { result } = renderHook(() => usePlanChange(ACCOUNT_ID, vi.fn()));
+ await act(() => result.current.startQuote('max_month', TARGET_PLAN));
+ await act(() => result.current.confirm());
+ expect(result.current.state).toMatchObject({
+ phase: 'FAILED',
+ error: true,
+ quoteFailureReason: 'RENEWAL_PREPAID',
+ });
+ expect(api.refreshPlanChange).not.toHaveBeenCalled();
+ });
+
it('generates a fresh idempotency key for every new quote attempt', async () => {
// 服务端在新报价时自动撤销旧未完成变更;客户端不再复用失败请求的键。
api.quotePlanChange.mockRejectedValueOnce(new Error('network'));
diff --git a/apps/desktop/src/renderer/features/billing/usePlanChange.ts b/apps/desktop/src/renderer/features/billing/usePlanChange.ts
index b8ccc8943a..cd86da1918 100644
--- a/apps/desktop/src/renderer/features/billing/usePlanChange.ts
+++ b/apps/desktop/src/renderer/features/billing/usePlanChange.ts
@@ -25,7 +25,7 @@ export type PlanChangeTargetSnapshot = Omit<BillingPlanChangeTargetPlan, 'produc
product: Omit<BillingPlanChangeTargetPlan['product'], 'level'> & { level: number | null };
};
-export type PlanChangeQuoteFailureReason = 'TARGET_NOT_ALLOWED' | 'REQUEST_FAILED';
+export type PlanChangeQuoteFailureReason = 'TARGET_NOT_ALLOWED' | 'RENEWAL_PREPAID' | 'REQUEST_FAILED';
export type PlanChangeState = {
open: boolean;
@@ -81,9 +81,9 @@ function phaseForPlanChange(change: BillingPlanChange): PlanChangePhase {
}
function quoteFailureReason(error: unknown): PlanChangeQuoteFailureReason {
- return extractIpcError(error)?.code === 'PLAN_CHANGE_NOT_AVAILABLE'
- ? 'TARGET_NOT_ALLOWED'
- : 'REQUEST_FAILED';
+ const code = extractIpcError(error)?.code;
+ if (code === 'PLAN_CHANGE_RENEWAL_PREPAID') return 'RENEWAL_PREPAID';
+ return code === 'PLAN_CHANGE_NOT_AVAILABLE' ? 'TARGET_NOT_ALLOWED' : 'REQUEST_FAILED';
}
export function usePlanChange(
@@ -204,7 +204,19 @@ export function usePlanChange(
await withRequestLock(session, async () => {
try {
applyChange(await billingApi.confirmPlanChange(change.planChangeId), session);
- } catch {
+ } catch (error) {
+ // 明确的业务拒绝没有发起支付;展示原因并结束本次确认,不把它当网络未知结果。
+ if (quoteFailureReason(error) === 'RENEWAL_PREPAID') {
+ if (mountedRef.current && session === sessionRef.current) {
+ setState((value) => ({
+ ...value,
+ phase: 'FAILED',
+ error: true,
+ quoteFailureReason: 'RENEWAL_PREPAID',
+ }));
+ }
+ return;
+ }
// The confirm may have landed server-side even though the response was
// lost. Re-read the change before restoring anything local, so a
// progressed change is never re-rendered as a confirmable quote.
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 1ee0acc261..086d90bf8d 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -13721,6 +13721,7 @@
"failedTitle": "Plan change failed",
"failedBody": "The plan change did not complete. Your current plan is unchanged.",
"requestFailed": "The plan change request couldn’t be completed. Refresh your subscription status and try again.",
+ "renewalPrepaid": "Your next billing period is already paid. Wait until the current period ends before upgrading.",
"quoteRejected": "This plan isn’t available for your current subscription. Choose another plan.",
"chooseAnotherPlan": "Choose Another Plan",
"resyncHint": "The result could not be confirmed yet. Checking the latest status again…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 3489c5149a..f3baff8122 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -13693,6 +13693,7 @@
"failedTitle": "プラン変更に失敗しました",
"failedBody": "プラン変更は完了しませんでした。現在のプランは変わりません。",
"requestFailed": "プラン変更リクエストを完了できませんでした。サブスクリプションの状態を更新して、もう一度お試しください。",
+ "renewalPrepaid": "次の請求期間の料金はすでに支払い済みです。現在の期間が終了してからアップグレードしてください。",
"quoteRejected": "現在のサブスクリプションではこのプランに変更できません。別のプランを選択してください。",
"chooseAnotherPlan": "別のプランを選択",
"resyncHint": "結果をまだ確認できません。最新の状態をもう一度確認しています…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 2a0fc2ae12..98a77ad5de 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -13693,6 +13693,7 @@
"failedTitle": "플랜 변경 실패",
"failedBody": "플랜 변경이 완료되지 않았습니다. 현재 플랜은 그대로 유지됩니다.",
"requestFailed": "플랜 변경 요청을 완료하지 못했습니다. 구독 상태를 새로고침한 후 다시 시도하세요.",
+ "renewalPrepaid": "다음 결제 기간의 요금이 이미 결제되었습니다. 현재 기간이 끝난 후 업그레이드해 주세요.",
"quoteRejected": "현재 구독에서는 이 플랜으로 변경할 수 없습니다. 다른 플랜을 선택하세요.",
"chooseAnotherPlan": "다른 플랜 선택",
"resyncHint": "결과를 아직 확인할 수 없습니다. 최신 상태를 다시 확인하는 중…",
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 b4d746847d..8da517f567 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -13693,6 +13693,7 @@
"failedTitle": "套餐变更失败",
"failedBody": "套餐变更未完成,当前套餐保持不变。",
"requestFailed": "套餐变更请求未完成,请刷新订阅状态后重试。",
+ "renewalPrepaid": "下一期费用已提前支付,请等待本期结束后再进行升级。",
"quoteRejected": "当前订阅无法切换到这个套餐,请选择其他套餐。",
"chooseAnotherPlan": "选择其他套餐",
"resyncHint": "确认结果暂时无法核实,正在重新确认最新状态…",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 8c67f83f2f..7e98eec045 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -13693,6 +13693,7 @@
"failedTitle": "套餐變更失敗",
"failedBody": "套餐變更未完成,當前套餐保持不變。",
"requestFailed": "套餐變更請求未完成,請重新整理訂閱狀態後重試。",
+ "renewalPrepaid": "下一期費用已提前支付,請等待本期結束後再進行升級。",
"quoteRejected": "當前訂閱無法切換到這個套餐,請選擇其他套餐。",
"chooseAnotherPlan": "選擇其他套餐",
"resyncHint": "確認結果暫時無法核實,正在重新確認最新狀態…",
diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.ts
index c82efcd8b3..3f5193ecb6 100644
--- a/apps/desktop/src/shared/ipc-errors.ts
+++ b/apps/desktop/src/shared/ipc-errors.ts
@@ -262,6 +262,7 @@ export type IpcErrorCode =
| 'MODEL_ACCESS_DISABLED' // 服务端灰度未启用(503)——走手填兜底
| 'MODEL_ACCESS_UNSUPPORTED' // 企业未接入(403)——XD 网关不可用,不重试
| 'MODEL_CATALOG_FETCH_DISABLED' // 模型目录远程拉取被禁用(XDT_DISABLE_MODELS_FETCH),未发起请求
+ | 'PLAN_CHANGE_RENEWAL_PREPAID' // 下一期已付未生效,等待本期结束后升级
| 'PLAN_CHANGE_NOT_AVAILABLE' // 当前订阅不能切换到目标套餐,可返回候选列表重选
| 'RESUME_NOT_AVAILABLE' // 当前订阅已到期、渠道协议失效或状态不可恢复
// 钉钉机器人连接
@@ -458,6 +459,7 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>([
'MODEL_ACCESS_DISABLED',
'MODEL_ACCESS_UNSUPPORTED',
'MODEL_CATALOG_FETCH_DISABLED',
+ 'PLAN_CHANGE_RENEWAL_PREPAID',
'PLAN_CHANGE_NOT_AVAILABLE',
'RESUME_NOT_AVAILABLE',
'DINGTALK_AUTH_FAILED',
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index ef37499666..70fe625ff7 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -11,6 +11,18 @@
> **增量适用原则**:wire protocol 兼容对所有跨端改动生效,不因是小改而豁免。
+## 支付宝已付下一期的升级拒绝
+
+升级报价和确认可返回 HTTP 409 `PLAN_CHANGE_RENEWAL_PREPAID`。Desktop Main 仅放行该
+明确错误码,仍脱敏服务端 message;Renderer 显示本地化提示“下一期费用已提前支付,请等待
+本期结束后再进行升级。”,不从错误文本反推业务状态。确认阶段收到该拒绝时也结束本次
+支付展示,不将其当作网络未知结果重新确认。具体实现和回归见
+`main/billing/index.ts`、`renderer/features/billing/usePlanChange.ts` 与对应测试。
+
+旧客户端仍按 HTTP 409 拒绝操作,显示通用冲突提示;新客户端连接旧服务端保持原行为。
+需服务端与客户端均更新才有完整限制和具体提示,不要求同步部署,也不新增订阅状态。
+支付宝恢复续订的截止资格由服务端下发 `resumable`,客户端不另算 24 小时规则。
+
## 账号用量上限的自动继续
输入投影 `AgentInputProjection` 新增可选字段 `usageLimitWait: { resumeAt } | null`,与 `error`