Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Billing card: a service-chosen title and tone, and a run that starts once a hold clears

Adarsh538e6dd5b187
diff --git a/docs/billing-hook.md b/docs/billing-hook.md
index 67b3b00a..d000c0af 100644
--- a/docs/billing-hook.md
+++ b/docs/billing-hook.md
@@ -322,6 +322,21 @@ run for free on one's own GPU.
| `busy`, `paused` | 503 |
| `blocked`, `not-offered`, `closed` | 403 |
+A reserve refusal may also say how the card looks. Every field is optional; an answer without them gets the card
+above, unchanged.
+
+| Field | What the card does |
+|---|---|
+| `title` | Its heading, in place of "This run didn't start" (one line, up to 80 characters). |
+| `tone: "info"` | A friendly look: an info icon in the brand colour, never a warning colour, and no other place offered (the way to one's own GPU is left out). |
+| `links` | Up to two more links, `[{ label, url }]` (labels up to 40 characters; `url` a same-site path or https), shown before `action`. |
+| `waitFor: { url, everyMs }` | A same-site path (an address on another site is left out) that the page asks with a GET, never cached, every `everyMs` (2 to 60 seconds; 4 by default) while the card is open, for 10 minutes at most. Once it answers `{ "ready": true }`, the card says "All set", sends the same run once more by itself as a new press (a fresh request id), and closes when it has started. While it waits, the card's links open in a new tab, so the card stays. |
+
+```json
+{ "ok": false, "code": "blocked", "text": "One more step and your run starts.", "title": "One quick step",
+ "tone": "info", "action": { "label": "Details", "url": "/your-page" }, "waitFor": { "url": "/your-page/ready", "everyMs": 4000 } }
+```
+
## Holds and the outbox
Every row a run makes (its jobs, and every step its chains queue) carries the reserve's hold. The server stamps it; a
diff --git a/src/components/billing-card.tsx b/src/components/billing-card.tsx
index 83fe5f05..2fba9c5e 100644
--- a/src/components/billing-card.tsx
+++ b/src/components/billing-card.tsx
@@ -1,29 +1,38 @@
"use client";
import { useQueryClient } from "@tanstack/react-query";
-import { Cpu, ExternalLink, Gauge } from "lucide-react";
+import { Check, Cpu, ExternalLink, Gauge, Info, Loader2 } from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useStatus } from "@/lib/api";
-import { BILLING_EVENT, refreshPriceChecks, safeLink, useInterest, type BillingRefusalDetail } from "@/lib/hosted";
+import { BILLING_EVENT, refreshPriceChecks, safeLink, useInterest, waitUntilReady, type BillingRefusalDetail } from "@/lib/hosted";
+import { cn } from "@/lib/utils";
/**
* One card for a run the billing service refused (x-fuobe-billing; src/server/billing.ts): the service's own words,
* its link (opened as given) or its offer ("Tell me when"), and the way to run for free on one's own GPU. A changed
* price shows the new one; Run again sends it. Mounted once, in the app's providers. Public code has no words of its
* own about prices: they all come from the service.
+ *
+ * The service may also set the card's heading (`title`), a friendly look (`tone: "info"`: an info icon, no other place
+ * offered), more links (`links`), and an address to wait on (`waitFor`): while the card is open it asks that address
+ * every few seconds (10 minutes at most), and once it answers ready, the card says so and sends the same run again by
+ * itself, as a new press. Links open in a new tab then, so the waiting card stays.
*/
export function BillingCard() {
const [refusal, setRefusal] = useState<BillingRefusalDetail | null>(null);
const [open, setOpen] = useState(false);
+ /** waitFor: asking, ready (the run is being sent), or none. */
+ const [phase, setPhase] = useState<"none" | "waiting" | "ready">("none");
const interest = useInterest();
const qc = useQueryClient();
useEffect(() => {
const onRefusal = (e: Event) => {
const d = (e as CustomEvent<BillingRefusalDetail>).detail;
setRefusal(d);
+ setPhase(d.waitFor && d.runFresh ? "waiting" : "none");
setOpen(true);
// A new price (or the balance it was refused for): the composer and the chip ask again.
refreshPriceChecks(qc);
@@ -33,8 +42,26 @@ export function BillingCard() {
return () => window.removeEventListener(BILLING_EVENT, onRefusal);
}, [qc]);
const r = refusal;
+ // While the card is open and waiting: ask the service's address; once ready, send the run once more by itself.
+ useEffect(() => {
+ if (!open || phase !== "waiting" || !r?.waitFor || !r.runFresh) return;
+ const stop = new AbortController();
+ const run = r.runFresh;
+ void waitUntilReady(r.waitFor.url, r.waitFor.everyMs, { signal: stop.signal }).then(async (ready) => {
+ if (!ready || stop.signal.aborted) return;
+ setPhase("ready");
+ const started = await run();
+ if (started) {
+ void qc.invalidateQueries({ queryKey: ["generations"] });
+ setTimeout(() => setOpen(false), 1200);
+ } else setPhase("none");
+ });
+ return () => stop.abort();
+ }, [open, phase, r, qc]);
const link = safeLink(r?.action?.url);
const changed = r?.code === "price-changed";
+ const info = r?.tone === "info";
+ const waits = phase !== "none";
const [sending, setSending] = useState(false);
const runAgain = changed ? r?.runAgain : undefined;
// Hosted runs: the way to the account's own GPU says what it does. Connected: the same run, sent there now; else the
@@ -51,15 +78,35 @@ export function BillingCard() {
void qc.invalidateQueries({ queryKey: ["generations"] });
}
};
+ /** A service link as a button: same-site in this tab, unless the card waits (a new tab keeps it), else a new tab. */
+ const linkButton = (a: { label: string; url: string }, variant: "default" | "secondary", key?: string) => {
+ const href = safeLink(a.url);
+ if (!href) return null;
+ const local = href.startsWith("/");
+ return (
+ <Button key={key} asChild size="sm" variant={variant} className={cn(info && "w-full sm:w-auto")}>
+ <a href={href} target={local && !waits ? undefined : "_blank"} rel="noopener noreferrer">
+ {a.label}
+ {!local && <ExternalLink />}
+ </a>
+ </Button>
+ );
+ };
+ const extra = (r?.links ?? []).slice(0, 2);
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
- <div className="mb-1 grid size-10 place-items-center rounded-xl bg-primary text-primary-foreground">
- <Gauge className="size-5" />
+ <div
+ className={cn(
+ "mb-1 grid size-10 place-items-center rounded-xl",
+ phase === "ready" ? "bg-brand-faint text-brand-text" : info ? "bg-brand-faint text-brand-text" : "bg-primary text-primary-foreground",
+ )}
+ >
+ {phase === "ready" ? <Check className="size-5" /> : info ? <Info className="size-5" /> : <Gauge className="size-5" />}
</div>
- <DialogTitle>{changed ? "The price changed" : "This run didn't start"}</DialogTitle>
- <DialogDescription>{r?.error}</DialogDescription>
+ <DialogTitle>{phase === "ready" ? "All set" : changed ? "The price changed" : (r?.title ?? "This run didn't start")}</DialogTitle>
+ <DialogDescription>{phase === "ready" ? "Starting your run…" : r?.error}</DialogDescription>
{changed && r?.quote?.text && (
<p className="text-[13px] text-muted-foreground">
Now: <span className="font-medium text-foreground">{r.quote.text}</span>
@@ -67,45 +114,57 @@ export function BillingCard() {
</p>
)}
{r?.offer && <p className="text-[13px] text-muted-foreground">{r.offer.text}</p>}
+ {phase === "waiting" && (
+ <p className="flex items-center gap-2 text-[13px] text-muted-foreground" role="status">
+ <Loader2 className="size-3.5 animate-spin" /> Waiting
+ </p>
+ )}
</DialogHeader>
- <DialogFooter className="gap-2 sm:justify-between">
- {runOwn ? (
- <Button variant="ghost" size="sm" disabled={sending} onClick={() => void sendAgain(runOwn)}>
- <Cpu /> Run on your GPU
- </Button>
+ {phase !== "ready" &&
+ (info ? (
+ <DialogFooter className="flex-col gap-2 sm:flex-row sm:justify-end">
+ {extra.map((a, i) => linkButton(a, "default", `l${i}`))}
+ {link && r?.action && linkButton(r.action, extra.length ? "secondary" : "default")}
+ {!link && !extra.length && (
+ <Button size="sm" onClick={() => setOpen(false)}>
+ OK
+ </Button>
+ )}
+ </DialogFooter>
) : (
- <Button asChild variant="ghost" size="sm" onClick={() => setOpen(false)}>
- <Link href="/connect">
- <Cpu /> {hosted ? "Connect your GPU" : "Use your own GPU (free)"}
- </Link>
- </Button>
- )}
- <div className="flex gap-2">
- {r?.offer && (
- <Button size="sm" variant="secondary" disabled={interest.isPending} onClick={() => interest.mutate(r.offer!.key, { onSuccess: () => setOpen(false) })}>
- {r.offer.label}
- </Button>
- )}
- {link && r?.action && (
- <Button asChild size="sm">
- <a href={link} target={link.startsWith("/") ? undefined : "_blank"} rel="noopener noreferrer">
- {r.action.label}
- {!link.startsWith("/") && <ExternalLink />}
- </a>
- </Button>
- )}
- {runAgain && (
- <Button size="sm" disabled={sending} onClick={() => void sendAgain()}>
- Run at this price
- </Button>
- )}
- {!link && !r?.offer && !runAgain && (
- <Button size="sm" onClick={() => setOpen(false)}>
- OK
- </Button>
- )}
- </div>
- </DialogFooter>
+ <DialogFooter className="gap-2 sm:justify-between">
+ {runOwn ? (
+ <Button variant="ghost" size="sm" disabled={sending} onClick={() => void sendAgain(runOwn)}>
+ <Cpu /> Run on your GPU
+ </Button>
+ ) : (
+ <Button asChild variant="ghost" size="sm" onClick={() => setOpen(false)}>
+ <Link href="/connect">
+ <Cpu /> {hosted ? "Connect your GPU" : "Use your own GPU (free)"}
+ </Link>
+ </Button>
+ )}
+ <div className="flex gap-2">
+ {r?.offer && (
+ <Button size="sm" variant="secondary" disabled={interest.isPending} onClick={() => interest.mutate(r.offer!.key, { onSuccess: () => setOpen(false) })}>
+ {r.offer.label}
+ </Button>
+ )}
+ {extra.map((a, i) => linkButton(a, "secondary", `l${i}`))}
+ {link && r?.action && linkButton(r.action, "default")}
+ {runAgain && (
+ <Button size="sm" disabled={sending} onClick={() => void sendAgain()}>
+ Run at this price
+ </Button>
+ )}
+ {!link && !r?.offer && !runAgain && !extra.length && (
+ <Button size="sm" onClick={() => setOpen(false)}>
+ OK
+ </Button>
+ )}
+ </div>
+ </DialogFooter>
+ ))}
</DialogContent>
</Dialog>
);
diff --git a/src/lib/api.ts b/src/lib/api.ts
index c23b5eeb..248a73d9 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -40,7 +40,7 @@ import type { AccessSummary } from "./model-access";
import { ADD_KEY_HEADER, isCloudProvider, type CloudProvider } from "./your-keys";
import type { Diagnosis } from "./diagnose";
import type { OwnSetup } from "./own-setup";
-import { BILLING_EVENT, BILLING_HEADER, refreshPriceChecks, type BillingAction, type BillingRefusalDetail, type HostedBalance } from "./hosted";
+import { BILLING_EVENT, BILLING_HEADER, freshBody, refreshPriceChecks, type BillingAction, type BillingRefusalDetail, type HostedBalance } from "./hosted";
import { knownPlace, notePlaceName, placeOf, type Place } from "./place-name";
import { noteServiceCopy, type ServiceCopy } from "./service-copy";
import { ENGINE_KEY, ENGINE_SLOT_KEY, engineSlot, SHARED_SLOT, slotToCache, storedEngine, type EngineSlot, type SlotFacts } from "./engine-pref";
@@ -1845,7 +1845,14 @@ export function watchGuestRefusals(): void {
billing === "price-changed" && method === "POST" && q && resendable(input, init) ? () => sendRunAgain(input, init, { [RUN_SHOWN_HEADER]: shownHeader(q) }) : undefined;
// Hosted runs: the same run on the account's own GPU, for the card's "Run on your GPU".
const own = method === "POST" && resendable(input, init) ? againAt(input, init, "own") : undefined;
- window.dispatchEvent(new CustomEvent<BillingRefusalDetail>(BILLING_EVENT, { detail: { ...b, code: billing, ...(again && { runAgain: again }), ...(own && { runOwn: own }) } }));
+ // A run the service lets start once something clears (waitFor): the same run as a new press, sent by the card.
+ const fresh =
+ b.waitFor && method === "POST" && resendable(input, init)
+ ? () => sendRunAgain(input, { ...init, ...(typeof init?.body === "string" && { body: freshBody(init.body, newPressId) }) }, {})
+ : undefined;
+ window.dispatchEvent(
+ new CustomEvent<BillingRefusalDetail>(BILLING_EVENT, { detail: { ...b, code: billing, ...(again && { runAgain: again }), ...(own && { runOwn: own }), ...(fresh && { runFresh: fresh }) } }),
+ );
})
.catch(() => {});
}
diff --git a/src/lib/hosted.ts b/src/lib/hosted.ts
index 98d85506..1360d40c 100644
--- a/src/lib/hosted.ts
+++ b/src/lib/hosted.ts
@@ -62,12 +62,63 @@ export interface BillingRefusalDetail {
action?: BillingAction;
offer?: BillingOffer;
quote?: HostedQuote;
+ /** The card's heading, when the service gives one (else "This run didn't start"). */
+ title?: string;
+ /** "info": a friendly look (an info icon, no warning colour, no other place offered). */
+ tone?: "info";
+ /** Up to two more links the service sends. */
+ links?: BillingAction[];
+ /** A same-site address the card asks while open; once it answers { ready: true }, the run is sent again by itself. */
+ waitFor?: { url: string; everyMs: number };
+ /** The same run sent again as a new press (a fresh request id), for waitFor (true when it started). */
+ runFresh?: () => Promise<boolean>;
/** A changed price: the same run sent again at the new price (true when it started). */
runAgain?: () => Promise<boolean>;
/** The same run sent again on the account's own GPU (true when it started). */
runOwn?: () => Promise<boolean>;
}
+/** The most a card waits on its waitFor address (src/server/billing.ts CARD_WAIT). */
+export const CARD_WAIT_MOST_MS = 10 * 60_000;
+
+/**
+ * Ask `url` (same site, GET, never cached) every `everyMs` until it answers `{ ready: true }`: true then; false once
+ * `mostMs` has passed or `signal` stops it. A failed or odd answer is asked again at the next turn.
+ */
+export async function waitUntilReady(
+ url: string,
+ everyMs: number,
+ o: { signal?: AbortSignal; mostMs?: number; fetcher?: typeof fetch; now?: () => number; sleep?: (ms: number) => Promise<void> } = {},
+): Promise<boolean> {
+ if (!url.startsWith("/") || url.startsWith("//")) return false;
+ const now = o.now ?? Date.now;
+ const sleep = o.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
+ const fetcher = o.fetcher ?? fetch;
+ const end = now() + (o.mostMs ?? CARD_WAIT_MOST_MS);
+ while (!o.signal?.aborted && now() < end) {
+ await sleep(everyMs);
+ if (o.signal?.aborted) return false;
+ try {
+ const res = await fetcher(url, { cache: "no-store", credentials: "same-origin", ...(o.signal && { signal: o.signal }) });
+ if (res.ok && ((await res.json()) as { ready?: unknown })?.ready === true) return true;
+ } catch {
+ // asked again at the next turn
+ }
+ }
+ return false;
+}
+
+/** A run's body sent again as a new press: a fresh `requestId` when it has one (studio runs do), else the same body. */
+export function freshBody(body: string, id: () => string): string {
+ try {
+ const o = JSON.parse(body) as unknown;
+ if (o && typeof o === "object" && !Array.isArray(o) && typeof (o as { requestId?: unknown }).requestId === "string") return JSON.stringify({ ...o, requestId: id() });
+ } catch {
+ // not JSON: as it was
+ }
+ return body;
+}
+
/** Fired for every refusal marked x-fuobe-billing (watchGuestRefusals): the billing card opens. */
export const BILLING_EVENT = "fuobe:billing";
diff --git a/src/server/billing.ts b/src/server/billing.ts
index 33f6288e..35b10d8a 100644
--- a/src/server/billing.ts
+++ b/src/server/billing.ts
@@ -73,6 +73,59 @@ export interface Action {
url: string;
}
+/**
+ * How the card for a refused run looks, when the service says (docs/billing-hook.md): its heading (`title`), a friendly
+ * look (`tone: "info"`), up to two more links (`links`), and a same-site address the page asks while the card is open
+ * (`waitFor`): once it answers `{ ready: true }`, the page sends the run once more by itself. Absent: the card as before.
+ */
+export interface CardLook {
+ title?: string;
+ tone?: "info";
+ links?: Action[];
+ waitFor?: { url: string; everyMs: number };
+}
+
+/** The most a card waits on `waitFor`, and how often it may ask. */
+export const CARD_WAIT = { mostMs: 10 * 60_000, everyMinMs: 2000, everyMaxMs: 60_000, everyMs: 4000 } as const;
+
+const oneLine = (v: unknown, max: number): string | undefined =>
+ typeof v === "string" && v.trim() && v.length <= max && !/[\u0000-\u001f\u007f]/.test(v) ? v.trim() : undefined;
+/** A link the page may open: a same-site path, or https. */
+const cardUrl = (v: unknown): string | undefined => {
+ const u = oneLine(v, 500);
+ if (!u) return undefined;
+ if (u.startsWith("/") && !u.startsWith("//") && !u.startsWith("/\\")) return u;
+ try {
+ return new URL(u).protocol === "https:" ? u : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+/** The card's look from a service's answer, checked: anything that isn't right is left out. */
+export function cardLook(a: unknown): CardLook {
+ const o = (a ?? {}) as Record<string, unknown>;
+ const title = oneLine(o.title, 80);
+ const links = Array.isArray(o.links)
+ ? o.links
+ .slice(0, 2)
+ .map((l) => ({ label: oneLine((l as Action | null)?.label, 40), url: cardUrl((l as Action | null)?.url) }))
+ .filter((l): l is Action => !!l.label && !!l.url)
+ : [];
+ const w = o.waitFor as { url?: unknown; everyMs?: unknown } | null | undefined;
+ const wUrl = cardUrl(w?.url);
+ const every = Number(w?.everyMs);
+ return {
+ ...(title && { title }),
+ ...(o.tone === "info" && { tone: "info" as const }),
+ ...(links.length && { links }),
+ // a same-site address only: the page asks it with the person's own cookie
+ ...(wUrl?.startsWith("/") && {
+ waitFor: { url: wUrl, everyMs: Number.isFinite(every) ? Math.min(CARD_WAIT.everyMaxMs, Math.max(CARD_WAIT.everyMinMs, Math.round(every))) : CARD_WAIT.everyMs },
+ }),
+ };
+}
+
/** An offer the person can ask about; a click sends POST /v1/interest with its key. */
export interface Offer {
key: string;
@@ -176,7 +229,7 @@ export type ReserveAnswer =
/** The hold is made, and the run waits until then (epoch ms) before it enters the line (absent: at once). */
startAt?: number;
}
- | { ok: false; code: RefuseCode | "price-changed"; text: string; quote?: Quote; action?: Action; offer?: Offer };
+ | ({ ok: false; code: RefuseCode | "price-changed"; text: string; quote?: Quote; action?: Action; offer?: Offer } & CardLook);
export interface Balance {
amount: number;
diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.ts
index 9a214af8..473419d9 100644
--- a/src/server/hosted-run.ts
+++ b/src/server/hosted-run.ts
@@ -12,6 +12,7 @@ import {
BILLING_HEADER,
BILLING_WAIT,
billingConfigured,
+ cardLook,
cachedPolicy,
forgetBalance,
FREE_QUOTE,
@@ -758,7 +759,7 @@ export async function reservePool(
if (!press || press.gaveUp()) queueRequestRelease(requestId);
})();
}
- return { ok: false, refusal: billingRefusal(a.code, a.text, { ...(a.quote && { quote: a.quote }), ...(a.action && { action: a.action }), ...(a.offer && { offer: a.offer }) }) };
+ return { ok: false, refusal: billingRefusal(a.code, a.text, { ...(a.quote && { quote: a.quote }), ...(a.action && { action: a.action }), ...(a.offer && { offer: a.offer }), ...cardLook(a) }) };
}
forgetBalance(account.id);
// A later start (the day's GPU time used up, an hourly limit): the hold is made, and the run waits until then.
diff --git a/tests/billing-card-wait.test.ts b/tests/billing-card-wait.test.ts
new file mode 100644
index 00000000..cdd113a0
--- /dev/null
+++ b/tests/billing-card-wait.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vitest";
+import { freshBody, waitUntilReady } from "@/lib/hosted";
+
+/** A clock that moves only when the wait sleeps. */
+function fakeTime() {
+ let t = 0;
+ return { now: () => t, sleep: async (ms: number) => void (t += ms) };
+}
+
+const answer = (body: unknown, ok = true) => new Response(JSON.stringify(body), { status: ok ? 200 : 500, headers: { "Content-Type": "application/json" } });
+
+describe("the billing card's wait", () => {
+ it("asks the address at its pace until it answers ready, through odd answers and failures", async () => {
+ const time = fakeTime();
+ const asked: number[] = [];
+ const replies = [answer({ ready: false }), answer({}, false), answer("nope"), answer({ ready: true })];
+ const fetcher = (async (url: string, init?: RequestInit) => {
+ expect(url).toBe("/ready");
+ expect(init?.cache).toBe("no-store");
+ asked.push(time.now());
+ const r = replies.shift();
+ if (!r) throw new Error("asked too often");
+ return r;
+ }) as typeof fetch;
+ expect(await waitUntilReady("/ready", 4000, { fetcher, ...time })).toBe(true);
+ expect(asked).toEqual([4000, 8000, 12000, 16000]);
+ });
+
+ it("stops after its time, when stopped, or for an address on another site", async () => {
+ const time = fakeTime();
+ let n = 0;
+ const fetcher = (async () => {
+ n++;
+ return answer({ ready: false });
+ }) as typeof fetch;
+ expect(await waitUntilReady("/ready", 60_000, { fetcher, mostMs: 10 * 60_000, ...time })).toBe(false);
+ expect(n).toBe(10);
+ const stop = new AbortController();
+ stop.abort();
+ expect(await waitUntilReady("/ready", 1000, { fetcher, signal: stop.signal, ...time })).toBe(false);
+ expect(await waitUntilReady("https://evil.example/ready", 1000, { fetcher, ...time })).toBe(false);
+ expect(await waitUntilReady("//evil.example/ready", 1000, { fetcher, ...time })).toBe(false);
+ expect(n).toBe(10);
+ });
+
+ it("sends the run again as a new press: a fresh request id, the rest as it was", () => {
+ const body = JSON.stringify({ modelId: "m", prompt: "p", requestId: "old" });
+ expect(JSON.parse(freshBody(body, () => "new"))).toEqual({ modelId: "m", prompt: "p", requestId: "new" });
+ expect(freshBody('{"modelId":"m"}', () => "new")).toBe('{"modelId":"m"}');
+ expect(freshBody("not json", () => "new")).toBe("not json");
+ });
+});
diff --git a/tests/billing-hook.test.ts b/tests/billing-hook.test.ts
index c81b22a8..753a1686 100644
--- a/tests/billing-hook.test.ts
+++ b/tests/billing-hook.test.ts
@@ -223,6 +223,46 @@ describe("the billing hook with a service", () => {
}
});
+ it("passes the service's card look through, checked: its title, tone, links and a same-site address to wait on", async () => {
+ resetRates();
+ fake.refuse = {
+ code: "blocked",
+ text: "One more step first.",
+ title: "One quick step",
+ tone: "info",
+ action: { label: "More", url: "/more" },
+ links: [{ label: "Open it", url: "https://example.com/inbox" }, { label: "Bad", url: "javascript:alert(1)" }, { label: "Third", url: "/x" }],
+ waitFor: { url: "/ready", everyMs: 10 },
+ };
+ const r = await post({ ...run(), shown: { amount: 7, priceVersion: "v7" } });
+ expect(r.status).toBe(403);
+ expect(r.headers.get("x-fuobe-billing")).toBe("blocked");
+ expect(await r.json()).toMatchObject({
+ error: "One more step first.",
+ code: "blocked",
+ title: "One quick step",
+ tone: "info",
+ action: { label: "More", url: "/more" },
+ links: [{ label: "Open it", url: "https://example.com/inbox" }],
+ waitFor: { url: "/ready", everyMs: 2000 },
+ });
+ // an answer without them: the card as before
+ resetRates();
+ fake.refuse = { code: "closed", text: "Closed." };
+ const plain = (await (await post({ ...run(), shown: { amount: 7, priceVersion: "v7" } })).json()) as Record<string, unknown>;
+ for (const k of ["title", "tone", "links", "waitFor"]) expect(plain).not.toHaveProperty(k);
+ });
+
+ it("checks a card look: only a same-site address to wait on, one-line words, https or same-site links, a sane pace", () => {
+ expect(billing.cardLook({ waitFor: { url: "https://evil.example/ready", everyMs: 4000 } })).toEqual({});
+ expect(billing.cardLook({ waitFor: { url: "//evil.example/ready" } })).toEqual({});
+ expect(billing.cardLook({ waitFor: { url: "/ready" } })).toEqual({ waitFor: { url: "/ready", everyMs: 4000 } });
+ expect(billing.cardLook({ waitFor: { url: "/ready", everyMs: 10 * 60_000 } })).toEqual({ waitFor: { url: "/ready", everyMs: 60_000 } });
+ expect(billing.cardLook({ title: "Two\nlines", tone: "loud" })).toEqual({});
+ expect(billing.cardLook({ title: "x".repeat(81) })).toEqual({});
+ expect(billing.cardLook(null)).toEqual({});
+ });
+
it("service down: runs on this install's GPUs are refused in plain words with no word of a pause, and a run on the account's own GPU still goes", async () => {
fake.down = "error";
const r = await post({ ...run(), shown: { amount: 7, priceVersion: "v7" } });
diff --git a/tests/helpers/fake-billing.ts b/tests/helpers/fake-billing.ts
index e92b212c..d0761bb5 100644
--- a/tests/helpers/fake-billing.ts
+++ b/tests/helpers/fake-billing.ts
@@ -44,7 +44,7 @@ export interface FakeBilling {
/** Answer every call with HTTP 503 (the service "down"), or never answer. */
down: false | "error" | "hang";
/** Refuse reserves with this code (and words). */
- refuse: null | { code: string; text: string };
+ refuse: null | ({ code: string; text: string } & Record<string, unknown>);
/** The policy every account gets. */
policy: Record<string, unknown>;
/** The policy a guest gets (GET /v1/policy with no account); null: the same as an account. */
@@ -108,7 +108,7 @@ export async function startFakeBilling(): Promise<FakeBilling> {
const requestId = String(b.requestId);
const again = [...f.holds.entries()].find(([, h]) => h.requestId === requestId);
if (again) return json(200, { ok: true, holdId: again[0], amount: again[1].amount, boostMs: 7000, maxWaitMs: 700_000, text: `${again[1].amount} units`, ...f.reserveExtra });
- if (f.refuse) return json(200, { ok: false, code: f.refuse.code, text: f.refuse.text });
+ if (f.refuse) return json(200, { ok: false, ...f.refuse });
const shown = b.shown as { amount: number; priceVersion: string };
if (f.price.amount > shown.amount) return json(200, { ok: false, code: "price-changed", text: `The price is now ${f.price.amount} units.`, quote: quote() });
const id = `h_${++holdN}`;