Skip to content

Commit fbb6487

Browse files
fix(cli): billing checkout needs a readable plan and price, and Enter no longer blocks the wait
- An unreadable or stand-in plan at the start opens no checkout, attended or not. - A missing price opens no checkout, attended or not. - The Enter prompt and the payment poll run together: paying on the page ends the prompt and the command, the timeout applies, and a late Enter opens nothing.
1 parent 45ba996 commit fbb6487

3 files changed

Lines changed: 127 additions & 47 deletions

File tree

‎docs/packages/cli.mdx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2263,8 +2263,10 @@ allowance or estimate what the next video will cost.
22632263
Opens the HyperFrames plans or credits page in the browser and prints the price:
22642264
Pro's monthly price, or the credits that cover `--needed` and what they cost. At
22652265
a terminal, Enter opens Stripe's checkout; with no terminal (CI, a coding agent)
2266-
the checkout link is printed instead. Then it waits until the account shows the
2267-
change, so an agent's run carries on by itself. The page is on
2266+
the checkout link is printed instead. When the plan or the price can't be read,
2267+
it opens no checkout and leaves the page to finish on. It waits until the account
2268+
shows the change, whether or not Enter was pressed, so an agent's run carries on
2269+
by itself. The page is on
22682270
the web app at hyperframes.studio. `HYPERFRAMES_PLANS_URL` and
22692271
`HYPERFRAMES_CREDITS_URL` point it at another page.
22702272

‎packages/cli/src/commands/billing.test.ts‎

Lines changed: 69 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,34 +5,47 @@ import type { Plan } from "../heygen/plan.js";
55

66
const opened = vi.hoisted(() => [] as string[]);
77
const checkouts = vi.hoisted(() => [] as { kind: string; missing?: number }[]);
8-
const state = vi.hoisted(() => ({ plans: [] as (Plan | null)[], unattended: true, enters: 0 }));
8+
const state = vi.hoisted(() => ({
9+
plans: [] as (Plan | null)[],
10+
afterPlans: { plan: "pro", credits: 1_000_000 } as Plan | null,
11+
unattended: true,
12+
enters: 0,
13+
enterHeld: false,
14+
noPrice: false,
15+
}));
916

1017
vi.mock("../auth/browser.js", () => ({
1118
openBrowser: async (url: string) => void opened.push(url),
1219
}));
1320
vi.mock("../utils/attendedTerminal.js", () => ({ isUnattended: () => state.unattended }));
1421
vi.mock("node:readline/promises", () => ({
1522
createInterface: () => ({
16-
question: async () => void state.enters++,
23+
question: (_prompt: string, opts?: { signal?: AbortSignal }) =>
24+
state.enterHeld
25+
? new Promise((_, reject) => opts?.signal?.addEventListener("abort", reject))
26+
: Promise.resolve(void state.enters++),
1727
close: () => undefined,
1828
}),
1929
}));
2030
vi.mock("../heygen/plan.js", async (importOriginal) => {
2131
const real = await importOriginal<typeof import("../heygen/plan.js")>();
2232
return {
2333
...real,
24-
readPlan: async () => (state.plans.length ? state.plans.shift()! : pro(1_000_000)),
25-
readOffer: async () => ({
26-
pro: { amount: 2500, currency: "usd" },
27-
addon: {
28-
unitsPerBlock: 1000,
29-
unitAmount: 100,
30-
currency: "usd",
31-
min: 1,
32-
max: 100,
33-
recommended: 25,
34-
},
35-
}),
34+
readPlan: async () => (state.plans.length ? state.plans.shift()! : state.afterPlans),
35+
readOffer: async () =>
36+
state.noPrice
37+
? {}
38+
: {
39+
pro: { amount: 2500, currency: "usd" },
40+
addon: {
41+
unitsPerBlock: 1000,
42+
unitAmount: 100,
43+
currency: "usd",
44+
min: 1,
45+
max: 100,
46+
recommended: 25,
47+
},
48+
},
3649
createCheckout: async (kind: string, _offer: unknown, missing?: number) => {
3750
checkouts.push({ kind, missing });
3851
return "https://checkout.stripe.com/c/pay/cs_test_1";
@@ -48,8 +61,9 @@ const { default: billing } = await import("./billing.js");
4861
afterEach(() => {
4962
opened.length = 0;
5063
checkouts.length = 0;
51-
state.enters = 0;
64+
Object.assign(state, { afterPlans: pro(1_000_000), enters: 0, enterHeld: false, noPrice: false });
5265
vi.restoreAllMocks();
66+
vi.useRealTimers();
5367
consumeCommandResult();
5468
});
5569

@@ -64,10 +78,14 @@ async function billingRun(
6478
vi.spyOn(console, "log").mockImplementation((line: string) => void logged.push(line));
6579
vi.spyOn(console, "error").mockImplementation(() => undefined);
6680
vi.useFakeTimers();
67-
const done = runCommand(billing, { rawArgs });
81+
const failed = runCommand(billing, { rawArgs }).then(
82+
() => undefined,
83+
(error: unknown) => error,
84+
);
6885
await vi.advanceTimersByTimeAsync(2000);
69-
await done;
86+
const error = await failed;
7087
vi.useRealTimers();
88+
if (error) throw error;
7189
return logged.join("\n");
7290
}
7391

@@ -105,6 +123,40 @@ describe("billing subscribe", () => {
105123
expect(checkouts).toEqual([]);
106124
expect(out).toContain("Could not read your plan");
107125
});
126+
127+
it.each<[string, Plan | null, boolean]>([
128+
["an unreadable plan, unattended", null, true],
129+
["a stand-in plan, unattended", { plan: "none", credits: 0, mock: true }, true],
130+
["an unreadable plan, attended", null, false],
131+
])("opens no checkout from %s at the start", async (_label, before, unattended) => {
132+
const out = await billingRun([before, pro(0)], unattended);
133+
expect(checkouts).toEqual([]);
134+
expect(state.enters).toBe(0);
135+
expect(out).toContain("Could not read your plan");
136+
});
137+
138+
it.each([true, false])(
139+
"opens no checkout when the price cannot be read (unattended: %s)",
140+
async (unattended) => {
141+
state.noPrice = true;
142+
const out = await billingRun([free, pro(0)], unattended);
143+
expect(checkouts).toEqual([]);
144+
expect(out).toContain("Could not read the price");
145+
},
146+
);
147+
148+
it("carries on when the person pays on the page and never presses Enter", async () => {
149+
state.enterHeld = true;
150+
const out = await billingRun([free, pro(0)], false);
151+
expect(out).toContain("✓ Done");
152+
expect(checkouts).toEqual([]);
153+
});
154+
155+
it("times out while the Enter prompt is still waiting", async () => {
156+
Object.assign(state, { enterHeld: true, afterPlans: free });
157+
await expect(billingRun([free], false, ["subscribe", "--timeout", "1"])).rejects.toThrow();
158+
expect(checkouts).toEqual([]);
159+
});
108160
});
109161

110162
describe("billing top-up", () => {

‎packages/cli/src/commands/billing.ts‎

Lines changed: 54 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -38,32 +38,49 @@ function priceLine(
3838

3939
type Done = (p: Plan | null) => boolean;
4040

41+
const readFromTheServer = (p: Plan | null): p is Plan => !!p && !p.mock;
42+
const NO_PLAN = "Could not read your plan, so no checkout opened. Finish on the page.";
43+
44+
async function payOrShowTheNewPrice(
45+
kind: "plans" | "credits",
46+
offer: Offer,
47+
done: Done,
48+
shown: string,
49+
stop: AbortSignal,
50+
needed?: number,
51+
): Promise<string | undefined> {
52+
const now = await readPlan();
53+
if (stop.aborted) return undefined;
54+
if (!readFromTheServer(now)) return void console.log(NO_PLAN);
55+
if (done(now)) return undefined;
56+
const missing = needed ? needed - now.credits : undefined;
57+
const line = priceLine(kind, offer, missing, needed) ?? shown;
58+
if (line !== shown) {
59+
console.log(line);
60+
return line;
61+
}
62+
const link = await createCheckout(kind, offer, missing);
63+
if (!stop.aborted) await openBrowser(link);
64+
return undefined;
65+
}
66+
4167
async function checkoutOnEnterAtTheCurrentPrice(
4268
kind: "plans" | "credits",
4369
offer: Offer,
4470
done: Done,
45-
shown: string | undefined,
71+
shown: string,
72+
stop: AbortSignal,
4673
needed?: number,
4774
) {
4875
const rl = createInterface({ input: process.stdin, output: process.stdout });
4976
try {
50-
for (;;) {
51-
await rl.question("Press Enter to pay ");
52-
const now = await readPlan();
53-
if (!now || now.mock) {
54-
console.log("Could not read your plan, so no checkout opened. Finish on the page.");
55-
return;
56-
}
57-
if (done(now)) return;
58-
const missing = needed ? needed - now.credits : undefined;
59-
const line = priceLine(kind, offer, missing, needed);
60-
if (line === shown) {
61-
await openBrowser(await createCheckout(kind, offer, missing));
62-
return;
63-
}
64-
if (line) console.log(line);
65-
shown = line;
77+
for (let price: string | undefined = shown; price; ) {
78+
await rl.question("Press Enter to pay, or finish on the page ", { signal: stop });
79+
price = await payOrShowTheNewPrice(kind, offer, done, price, stop, needed);
6680
}
81+
} catch (error) {
82+
if (!stop.aborted) throw error;
83+
console.log();
6784
} finally {
6885
rl.close();
6986
}
@@ -73,16 +90,20 @@ async function offerCheckoutOrPrintTheLink(
7390
kind: "plans" | "credits",
7491
before: Plan | null,
7592
done: Done,
93+
stop: AbortSignal,
7694
needed?: number,
7795
) {
96+
if (!readFromTheServer(before)) return void console.log(NO_PLAN);
7897
const offer = await readOffer();
79-
const missing = needed ? needed - (before?.credits ?? 0) : undefined;
98+
const missing = needed ? needed - before.credits : undefined;
8099
const line = priceLine(kind, offer, missing, needed);
81-
if (line) console.log(line);
100+
if (!line)
101+
return void console.log("Could not read the price, so no checkout opened. Finish on the page.");
102+
console.log(line);
82103
try {
83104
if (isUnattended())
84105
console.log(`Checkout link: ${c.accent(await createCheckout(kind, offer, missing))}`);
85-
else await checkoutOnEnterAtTheCurrentPrice(kind, offer, done, line, needed);
106+
else await checkoutOnEnterAtTheCurrentPrice(kind, offer, done, line, stop, needed);
86107
} catch (error) {
87108
console.error(c.error(error instanceof Error ? error.message : String(error)));
88109
}
@@ -134,21 +155,26 @@ export default defineCommand({
134155
});
135156
console.log(`${action === "subscribe" ? "Plans" : "Credits"} page: ${c.accent(url)}`);
136157
await openBrowser(url);
137-
await offerCheckoutOrPrintTheLink(
158+
console.log("Waiting for the person to finish ...");
159+
const stop = new AbortController();
160+
const paying = offerCheckoutOrPrintTheLink(
138161
action === "subscribe" ? "plans" : "credits",
139162
before,
140163
done,
164+
stop.signal,
141165
needed,
142166
);
143-
console.log("Waiting for the person to finish ...");
144167
const deadline = Date.now() + (Number(args.timeout) || 600) * 1000;
145-
while (Date.now() < deadline) {
168+
let now: Plan | null = null;
169+
while (!done(now) && Date.now() < deadline) {
146170
await new Promise((r) => setTimeout(r, 2000));
147-
const now = await readPlan();
148-
if (done(now)) {
149-
console.log(c.success(`✓ Done: ${describe(now)}. Carry on.`));
150-
return;
151-
}
171+
now = await readPlan();
172+
}
173+
stop.abort();
174+
await paying;
175+
if (done(now)) {
176+
console.log(c.success(`✓ Done: ${describe(now)}. Carry on.`));
177+
return;
152178
}
153179
console.error(
154180
c.error(

0 commit comments

Comments
 (0)