fix(cli): billing re-reads the account on Enter and sells nothing it can't price (#7226)

Two holes in `billing subscribe` / `billing add-credits`:

- After paying on the pricing page, "Press Enter to pay" was still waiting. Pressing it before the
  next 2-second poll opened a second Stripe checkout. Enter now reads the plan again: nothing opens
  when the page has already covered it, and a partial top-up on the page is priced from the new
  balance.
- One failed first plan read made the account look like Free with 0 credits: it offered Pro to a
  Pro account and priced add-on credits for the whole run, not the shortfall. The first read is
  retried; if the plan still can't be read, no terminal checkout opens and the page finishes it.


Claude-Session: https://claude.ai/code/session_01HebQXN7wsMK6GqT3MNtqXw

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
WaterrrForever
2026-11-05 12:05:26 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 2af37ac0c3
commit 5f7b85c5d7
2 changed files with 126 additions and 16 deletions
+73 -1
View File
@@ -20,6 +20,7 @@ const held = vi.hoisted(() => ({
headerCalls: 0,
holdHeadersAfter: undefined as number | undefined,
stallPoll: false,
reads: undefined as Array<{ plan: string; credits: number } | null> | undefined,
}));
vi.mock("../telemetry/events.js", () => ({
@@ -67,6 +68,7 @@ vi.mock("../heygen/plan.js", async (importOriginal) => {
readPlan: async (stop?: AbortSignal) => {
if (++plan.calls > 1 && held.stallPoll)
return new Promise((resolve) => stop?.addEventListener("abort", () => resolve(null)));
if (held.reads) return held.reads[Math.min(plan.calls, held.reads.length) - 1];
return {
plan: plan.calls === 1 || !never.paid ? "none" : "pro",
credits: plan.calls === 1 || !never.paid ? 0 : 500,
@@ -103,6 +105,7 @@ afterEach(() => {
headerCalls: 0,
holdHeadersAfter: undefined,
stallPoll: false,
reads: undefined,
});
vi.restoreAllMocks();
consumeCommandResult();
@@ -203,6 +206,73 @@ describe("billing at a terminal", () => {
});
});
describe("billing when the page may already have been paid", () => {
it("makes no second checkout when Enter is pressed after the page took the payment", async () => {
terminal.attended = true;
terminal.enter = true;
const log = vi.spyOn(console, "log").mockImplementation(() => undefined);
vi.useFakeTimers();
const done = runCommand(billing, { rawArgs: ["subscribe"] });
await vi.advanceTimersByTimeAsync(2000);
await done;
vi.useRealTimers();
expect(terminal.checkouts).toBe(0);
expect(log.mock.calls.flat().join("\n")).toContain("no second checkout");
});
it("buys only what is still short when the page sold part of it before Enter", async () => {
terminal.attended = true;
terminal.enter = true;
never.paid = false;
held.reads = [
{ plan: "pro", credits: 1000 },
{ plan: "pro", credits: 4000 },
{ plan: "pro", credits: 4000 },
];
vi.spyOn(console, "log").mockImplementation(() => undefined);
vi.spyOn(console, "error").mockImplementation(() => undefined);
vi.useFakeTimers();
const done = runCommand(billing, {
rawArgs: ["add-credits", "--needed", "5000", "--timeout", "4"],
});
await vi.advanceTimersByTimeAsync(6000);
await done;
vi.useRealTimers();
expect(terminal.args.map((a) => a[2])).toEqual([1000]);
});
it("sells nothing from the terminal when the account's plan cannot be read", async () => {
never.paid = false;
held.reads = [null];
vi.spyOn(console, "log").mockImplementation(() => undefined);
const error = vi.spyOn(console, "error").mockImplementation(() => undefined);
vi.useFakeTimers();
const done = runCommand(billing, {
rawArgs: ["add-credits", "--needed", "5000", "--timeout", "6"],
});
await vi.advanceTimersByTimeAsync(8000);
await done;
vi.useRealTimers();
expect(terminal.checkouts).toBe(0);
expect(error.mock.calls.flat().join("\n")).toContain("Could not read this account's plan");
});
it("prices from the balance when the first plan read fails once, not from zero", async () => {
never.paid = false;
held.reads = [null, { plan: "pro", credits: 4000 }];
vi.spyOn(console, "log").mockImplementation(() => undefined);
vi.spyOn(console, "error").mockImplementation(() => undefined);
vi.useFakeTimers();
const done = runCommand(billing, {
rawArgs: ["add-credits", "--needed", "5000", "--timeout", "4"],
});
await vi.advanceTimersByTimeAsync(6000);
await done;
vi.useRealTimers();
expect(terminal.args.map((a) => a[2])).toEqual([1000]);
});
});
describe("billing outcomes", () => {
it("keeps waiting after a failed checkout, because the open pricing page can still take the payment", async () => {
const { CheckoutError } = await import("../heygen/plan.js");
@@ -295,12 +365,14 @@ describe("billing once the wait has ended", () => {
it("opens no checkout page when the purchase lands while Enter's checkout is being created", async () => {
terminal.attended = true;
terminal.enter = true;
const free = { plan: "none", credits: 0 };
held.reads = [free, free, { plan: "pro", credits: 500 }];
vi.spyOn(console, "log").mockImplementation(() => undefined);
const checkout = release<string>();
held.checkout = checkout.promise;
vi.useFakeTimers();
const done = runCommand(billing, { rawArgs: ["subscribe"] });
await vi.advanceTimersByTimeAsync(2000);
await vi.advanceTimersByTimeAsync(4000);
checkout.resolve("https://checkout.stripe.com/c/pay/cs_late");
await done;
vi.useRealTimers();
+53 -15
View File
@@ -41,51 +41,86 @@ function priceLine(
const WAIT_TIMEOUT_EXIT = 124;
function refuseUnreadCheckout(): null {
console.error(
c.error(
"Could not read this account's plan, so no checkout opens from here. Finish on the page.",
),
);
return null;
}
type CheckoutSource = { skill?: string; baseline?: number };
type AtEnter = () => Promise<{ covered: true } | { covered: false; missing?: number }>;
async function openCheckout(
kind: "plans" | "credits",
offer: Offer,
missing: number | undefined,
signal: AbortSignal,
source: CheckoutSource,
source: CheckoutSource & { atEnter: AtEnter; needed?: number },
): Promise<void> {
const { atEnter, needed, ...from } = source;
if (isUnattended()) {
const link = await createCheckout(kind, offer, missing, { ...source, stop: signal });
const link = await createCheckout(kind, offer, missing, { ...from, stop: signal });
if (!signal.aborted) console.log(`Checkout link: ${c.accent(link)}`);
return;
}
const rl = createInterface({ input: process.stdin, output: process.stdout });
try {
await rl.question("Press Enter to pay ", { signal });
await rl.question("Press Enter to pay here (not if you already paid on the page) ", { signal });
} finally {
rl.close();
}
if (signal.aborted) return;
const link = await createCheckout(kind, offer, missing, { ...source, stop: signal });
const fresh = await atEnter();
if (signal.aborted) return;
if (fresh.covered) {
console.log("The page has taken the payment, so no second checkout opens.");
return;
}
const line = priceLine(kind, offer, fresh.missing, needed);
if (line && line !== priceLine(kind, offer, missing, needed)) console.log(line);
const link = await createCheckout(kind, offer, fresh.missing, { ...from, stop: signal });
if (!signal.aborted) await openBrowser(link);
}
async function offerCheckout(
kind: "plans" | "credits",
before: Plan | null,
before: Plan,
signal: AbortSignal,
needed: number | undefined,
source: CheckoutSource,
done: (p: Plan | null) => boolean,
): Promise<CheckoutError | null> {
const offer = await readOffer(signal);
if (signal.aborted) return null;
const missing = needed ? needed - (before?.credits ?? 0) : undefined;
const shortBy = (p: Plan) => (needed ? needed - p.credits : undefined);
const missing = shortBy(before);
const line = priceLine(kind, offer, missing, needed);
if (line) console.log(line);
const atEnter: AtEnter = async () => {
const now = await readPlan(signal);
if (done(now)) return { covered: true };
return { covered: false, missing: now ? shortBy(now) : missing };
};
try {
await openCheckout(kind, offer, missing, signal, source);
await openCheckout(kind, offer, missing, signal, { ...source, atEnter, needed });
return null;
} catch (error) {
return signal.aborted ? null : reportCheckoutFailure(error);
}
}
async function readPlanBefore(stop: AbortSignal): Promise<Plan | null> {
for (let attempt = 1; ; attempt++) {
const plan = await readPlan(stop);
if (plan || attempt === 3 || stop.aborted) return plan;
await new Promise((r) => setTimeout(r, 1000));
}
}
function reportCheckoutFailure(error: unknown): CheckoutError | null {
console.error(c.error(error instanceof Error ? error.message : String(error)));
if (!(error instanceof CheckoutError)) return null;
@@ -132,7 +167,7 @@ export default defineCommand({
const stop = new AbortController();
const atDeadline = setTimeout(() => stop.abort(), deadline - Date.now());
atDeadline.unref?.();
const before = await readPlan(stop.signal);
const before = await readPlanBefore(stop.signal);
const done = (p: Plan | null) =>
action === "subscribe"
? !!p && p.plan !== "none"
@@ -162,13 +197,16 @@ export default defineCommand({
clearTimeout(atDeadline);
stop.abort();
});
const checkoutFailure = await offerCheckout(
action === "subscribe" ? "plans" : "credits",
before,
stop.signal,
needed,
{ skill, baseline: before?.credits },
);
const checkoutFailure = before
? await offerCheckout(
action === "subscribe" ? "plans" : "credits",
before,
stop.signal,
needed,
{ skill, baseline: before.credits },
done,
)
: refuseUnreadCheckout();
if (checkoutFailure?.reason === "checkout_unavailable") {
giveUp.abort();
failCommand();