fix(credits): remove off-session credit auto-recharge

Merged
SW
3mo ago
+235-1108

Implements the first defect in recoupable/chat#1960. Row 3 of that issue's PR matrix.

The credit gate charged a saved card off-session unless the customer had opted out via a Stripe customer metadata key (auto_recharge_opt_out) they had to know existed to set. Over the 30 days to 2026-08-17 it collected $0. Per the decision recorded on the issue it is removed rather than inverted to opt-in: an opt-in top-up would be a feature with a known-zero conversion rate and a live card-charging blast radius.

A charge now requires an action the account took: POST /api/credits/sessions.

What changes

The gate — lib/credits/autoRechargeOrFail.ts → lib/credits/checkCreditsAvailable.ts

The charge branch (old L78-86), the opt-out consent gate (old L56) and the in-thread credit increment are gone. What remains reads remaining_credits and reports. 120 lines → 61.

Renamed deliberately: a function called autoRechargeOrFail that never auto-recharges is exactly the kind of drift this issue exists to remove. The eight credit-gated call sites go through ensureCreditsOrShortCircuit, whose signature is unchanged, so none of them needed edits for this.

Deleted

FileWhy
lib/stripe/getAutoRechargeOptOut.ts, setAutoRechargeOptOut.tsNothing to opt out of
lib/billing/getAutoRechargeHandler.ts, updateAutoRechargeHandler.tsNo setting to read or write
lib/billing/validateAutoRechargeParams.ts, validateUpdateAutoRechargeBody.tsValidators for the deleted handlers
app/api/accounts/[id]/auto-recharge/route.tsGET, PATCH and OPTIONS all go
lib/stripe/notifyCreditsTopupPaymentIntent.ts + its stripeWebhookHandler callSee below
6 test files for the above

notifyCreditsTopupPaymentIntent fired only for PaymentIntents stamped purpose === "credits_auto_recharge". No such PaymentIntent can be created any more, so the hook was dead. I checked that no surviving path loses its notification: manual top-ups notify from checkout.session.completed via notifyCreditsTopupSession, subscription charges via invoice.paid, and the consented off-session top-up stamps credits_topup, which this hook never matched.

chargeCustomerOffSession is kept. It has a second caller, createCreditsSessionHandler L21, which is the consented POST /api/credits/sessions path where a human asked to buy credits and charging a saved card is the right thing to do. grep -rn chargeCustomerOffSession lib app outside tests now returns exactly that one call site.

Constants — CREDIT_AUTO_RECHARGE_PURPOSE deleted. CREDIT_AUTO_RECHARGE_CREDITS → CREDIT_SHORTFALL_TOPUP_CREDITS and CREDIT_AUTO_RECHARGE_FALLBACK_SUCCESS_URL → CREDIT_SHORTFALL_SUCCESS_URL. The issue listed all three as deletions in this PR, but two are still load-bearing: they size the Checkout Session that a 402 still mints. They are renamed here so no AUTO_RECHARGE identifier survives, and deleted by the follow-on PR that stops minting the session.

declineReason off the 402. It could only ever be populated by an off-session charge, so with no charge in the gate it is unreachable rather than optional. Removed from AutoRechargeOrFailResult, InsufficientCreditsBody and ensureCreditsOrShortCircuit. It stays on POST /api/credits/sessions, where a real decline still happens, so open-agents' credits-topup dialog (which parses that response, not the 402) is unaffected. The buildInsufficientCreditsResponse docstring claiming the two shapes are interchangeable is corrected, since that claim is what invited the field onto the 402 in the first place.

Verification

TDD, red before green:

  1. Wrote lib/credits/__tests__/checkCreditsAvailable.test.ts first, with the new contract (no charge on any path, no opt-out read, no declineReason). Ran it: RED — Cannot find module '@/lib/credits/checkCreditsAvailable', 1 failed / no tests.
  2. Implemented. GREEN — 7 passed.
  3. Rewrote ensureCreditsOrShortCircuit.test.ts against the new module, including a test that a declineReason on the gate result is still not put on the body. Ran it: RED (mocked module no longer imported). Implemented. GREEN.

Full runs:

CheckResult
vitest run lib/credits lib/stripe lib/billing lib/research lib/socials lib/chat app/api/webhooks app/api/credits app/api/accounts220 files / 1253 tests passed
eslint on every file in the diffclean (one prettier/prettier from the const rename, fixed)
tsc --noEmit202 errors, identical to the count on the unmodified checkout, and zero in any file this PR touches. All 202 are pre-existing test-fixture type mismatches in lib/tasks, lib/trigger, lib/chats, lib/credits/__tests__/getCreditUsage.test.ts and similar
grep -rn "AUTO_RECHARGE|AutoRecharge|autoRecharge|auto_recharge|auto-recharge" lib appno matches

Stale prose also corrected in handleResearch.ts, handleArtistResearch.ts and app/api/subscriptions/card-on-file/route.ts, all of which described auto-recharge as the reason their code exists.

Not yet done: the issue's live Done-when check (a credit-gated endpoint on a zero-balance account with a saved card returns 402 with no new PaymentIntent on that Stripe customer) against the preview deployment. Flagging rather than implying it.

Merge order

  1. docs#299 — the contract
  2. chat#1961 — removes the account-modal toggle that calls the route this PR deletes. Must land before this PR or production keeps a switch that 404s.
  3. This PR
  4. The follow-on PR that stops minting a Checkout Session on every 402, which is branched off this one.

Summary by cubic

Removes off-session credit auto-recharge so the credit gate never charges saved cards. Previously it charged unless a hidden Stripe opt-out existed; now the gate checks balance and returns 402 with a Checkout URL, and charges only happen via POST /api/credits/sessions.

  • Replaces @/lib/credits/autoRechargeOrFail with @/lib/credits/checkCreditsAvailable: no charging, no Stripe opt-out read, no in-thread credit increment. ensureCreditsOrShortCircuit still short-circuits with a 402; call sites remain unchanged.
  • Deletes /api/accounts/[id]/auto-recharge (GET/PATCH/OPTIONS) and related handlers/validators and Stripe helpers (getAutoRechargeOptOut, setAutoRechargeOptOut).
  • Drops declineReason from 402 responses; it remains on POST /api/credits/sessions. Updates comments/docs to describe current behavior only.
  • Removes auto-recharge PaymentIntent notifications and the webhook call; manual top-ups still notify from checkout.session.completed, subscriptions from invoice.paid.
  • Renames constants: CREDIT_AUTO_RECHARGE_CREDITS → CREDIT_SHORTFALL_TOPUP_CREDITS; CREDIT_AUTO_RECHARGE_FALLBACK_SUCCESS_URL → CREDIT_SHORTFALL_SUCCESS_URL (https://app.recoupable.dev); deletes CREDIT_AUTO_RECHARGE_PURPOSE. Keeps chargeCustomerOffSession for the consented POST /api/credits/sessions path.
  • Clarifies card-on-file route docs: saving a card enables future POST /api/credits/sessions top-ups and never authorizes a charge on its own.

Migration

  • Remove any UI and calls to /api/accounts/[id]/auto-recharge; they now 404.
  • Stop reading declineReason from 402 responses; only handle it on POST /api/credits/sessions.
  • Update callers using the fallback success URL to CREDIT_SHORTFALL_SUCCESS_URL.

Summary by CodeRabbit

  • New Features

    • Added credit availability checks that direct customers to a hosted top-up checkout when their balance is insufficient.
    • Standardized credit-shortfall redirects across research, chat, and social features.
    • Saved cards can now support future credit top-ups without re-entering payment details.
  • Changes

    • Removed automatic recharge settings and automatic balance replenishment.
    • Credit-shortfall responses now provide clearer balance and top-up information.
    • Removed automated top-up payment notifications.