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.

Connected accounts: a saved fal.ai key's balance and a Replicate token's account

Adarshd36338b87245
diff --git a/docs/public-signup.md b/docs/public-signup.md
index c1256d59..f45211ee 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -604,6 +604,20 @@ account with that provider. The studio's own keys are never used for an account'
attached files to that provider. civitai LoRAs are left out of runs on an account's key (copying
them would use the studio's civitai key). Image to 3D runs on its key too; Assist, text steps and the other tools stay closed.
- An account on a studio set to **Open source only** keeps its keys, but they aren't used.
+- **Balance and account.** Each saved key's card shows what the provider tells about the account
+ behind it, and the account menu (the You sheet on a phone) has **Connected accounts**: one row per
+ key with its balance, or **Add a key** when the account has none. `GET /api/key-info`
+ (`src/server/provider-account-info.ts`) asks fal.ai's account billing call (the balance and the
+ account's name, for a key with the `billing:usage:read` permission; fal.ai's default API keys
+ get a link to the billing page instead) and Replicate's `GET /v1/account` (the account; Replicate
+ has no balance call, so its row links to its billing page). Both are reads that run nothing. The
+ route reads the key through `cloudKey` inside the account's own work, so an account only ever
+ gets its own keys' answers. The owner gets the studio's keys, and a guest gets 401 before any key
+ is read. Nothing is asked on page load: the menu asks when it opens, and Settings when the card
+ scrolls into view. An answer is kept 60 seconds (15 when the provider is busy or out of reach),
+ and **Refresh** asks again at most once every 10 seconds per key. The answer holds only the
+ balance, the account's name and the state, never a key, its last characters or the provider's
+ own words. A check here never marks a key refused or its balance empty.
## When your GPU or key has a problem
@@ -832,7 +846,9 @@ work may read is `src/server/tenant.ts`. Your keys are `src/server/account-keys.
`src/server/secret-box.ts` (encryption), `src/server/provider-keys.ts` (`cloudKey`, the one place a
fal.ai or Replicate key is read) and `src/app/api/account/keys`; their tests are the
`tests/account-keys*.test.ts` files, `tests/secret-box.test.ts`, `tests/byo-keys-static.test.ts` and
-`tests/e2e/byo-keys.mjs` (against stand-in providers). Uploads are `src/app/api/uploads/route.ts` (which makes the
+`tests/e2e/byo-keys.mjs` (against stand-in providers). Connected accounts (a key's balance and account) are
+`src/server/provider-account-info.ts` and `src/app/api/key-info`, tested in `tests/key-info.test.ts` and
+`tests/key-info-ui.test.ts`. Uploads are `src/app/api/uploads/route.ts` (which makes the
proxy's checks itself, `src/server/direct-gate.ts`), the limits are in `src/server/account-files.ts`
and the clean-up in `src/server/account-sweep.ts`. The owner's view of what accounts make is
`src/server/account-admin.ts`. The tests are in `tests/public-signup.test.ts`,
diff --git a/src/app/api/key-info/route.ts b/src/app/api/key-info/route.ts
new file mode 100644
index 00000000..4884e607
--- /dev/null
+++ b/src/app/api/key-info/route.ts
@@ -0,0 +1,27 @@
+import { connection } from "next/server";
+import { GUEST_LIBRARY_MESSAGE } from "@/lib/guest-access";
+import type { KeyInfoAnswer } from "@/lib/key-info";
+import { paidAllowed } from "@/server/account-keys";
+import { requestViewer } from "@/server/auth";
+import { accountsInfo, type KeyOwner } from "@/server/provider-account-info";
+
+const NO_STORE = { "Cache-Control": "no-store" };
+
+/**
+ * Connected accounts (src/lib/key-info.ts): what each saved fal.ai key or Replicate token tells about its provider
+ * account, for the account menu and Settings. Who is asking comes from the session, never from the request's words: the
+ * owner gets the studio's keys, an account its own keys only, and anyone else 401 before any key is read.
+ * `?refresh=1` asks the providers again (at most once every 10 s per key); `?detail=1` adds this month's spend where a
+ * key may read it (Settings). Never a key or the provider's own text.
+ */
+export async function GET(request: Request) {
+ await connection();
+ const viewer = requestViewer(request);
+ if (viewer.kind === "guest") return Response.json({ error: GUEST_LIBRARY_MESSAGE }, { status: 401, headers: NO_STORE });
+ const who: KeyOwner = viewer.kind === "owner" ? { kind: "owner" } : { kind: "account", id: viewer.account.id };
+ // A studio with paid models off doesn't use an account's keys: nothing to show, nothing asked.
+ if (who.kind === "account" && !paidAllowed()) return Response.json({ providers: [] } satisfies KeyInfoAnswer, { headers: NO_STORE });
+ const q = new URL(request.url).searchParams;
+ const providers = await accountsInfo(who, { fresh: q.get("refresh") === "1", detail: q.get("detail") === "1" });
+ return Response.json({ providers } satisfies KeyInfoAnswer, { headers: NO_STORE });
+}
diff --git a/src/components/connect-field.tsx b/src/components/connect-field.tsx
index e8b906a8..65e2abe7 100644
--- a/src/components/connect-field.tsx
+++ b/src/components/connect-field.tsx
@@ -78,6 +78,7 @@ export function ConnectField({
place,
trustSaved = false,
refusal,
+ children,
}: {
name: string;
setting?: PublicSetting;
@@ -106,6 +107,8 @@ export function ConnectField({
trustSaved?: boolean;
/** How a refused address is shown: its one line, and what to do instead. */
refusal?: (line: string) => React.ReactNode;
+ /** Shown under the field (a saved key's provider account: src/components/keys/key-account-details.tsx). */
+ children?: React.ReactNode;
}) {
const qc = useQueryClient();
const inputId = useId();
@@ -134,6 +137,8 @@ export function ConnectField({
void qc.invalidateQueries({ queryKey: ["status"] });
// Settings → AI helper lists what each local LLM server answers with its saved URL, model and key.
void qc.invalidateQueries({ queryKey: ["llm"] });
+ // Connected accounts: a new fal.ai key's or Replicate token's account, or none.
+ if (provider === "fal" || provider === "replicate") void qc.invalidateQueries({ queryKey: ["key-info"] });
};
const run = async () => {
@@ -273,6 +278,7 @@ export function ConnectField({
{hint}
</p>
)}
+ {children}
</div>
);
}
diff --git a/src/components/keys/key-account-details.tsx b/src/components/keys/key-account-details.tsx
new file mode 100644
index 00000000..66d75503
--- /dev/null
+++ b/src/components/keys/key-account-details.tsx
@@ -0,0 +1,186 @@
+"use client";
+
+import { ExternalLink, Loader2 } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { useKeyInfo, useRefreshKeyInfo } from "@/components/keys/use-key-info";
+import { useNow } from "@/components/studio/use-now";
+import { BILLING_URL } from "@/lib/diagnose";
+import { accountWords, checkKeyWords, FAL_BALANCE_HOW, money, noKeyYetWords, updatedWords, type ProviderAccount } from "@/lib/key-info";
+import { CLOUD_KEY, type CloudProvider } from "@/lib/your-keys";
+import { cn } from "@/lib/utils";
+
+/*
+ * Settings: what a saved fal.ai key or Replicate token tells about its provider account, under the key (the owner's
+ * Paid API configuration, an account's Your keys). Asked when the card first scrolls into view, from the same minute-long
+ * cache as the account menu, with this month's spend where the key may read it. A figure the provider doesn't give is
+ * left out, and the provider's billing page is always one link away.
+ */
+
+const PANEL = "rounded-lg bg-muted/60 px-3 py-2.5 text-[13px]";
+
+function Outbound({ href, children, className }: { href: string; children: React.ReactNode; className?: string }) {
+ return (
+ <a href={href} target="_blank" rel="noreferrer" className={cn("inline-flex items-center gap-1 font-medium text-brand-text underline-offset-2 hover:underline", className)}>
+ {children}
+ <ExternalLink aria-hidden className="size-3" />
+ <span className="sr-only"> (opens in a new tab)</span>
+ </a>
+ );
+}
+
+function Row({ label, children, figure }: { label: string; children: React.ReactNode; figure?: boolean }) {
+ return (
+ <>
+ <dt className="text-muted-foreground">{label}</dt>
+ <dd className={cn("min-w-0 truncate", figure && "font-medium tabular-nums")}>{children}</dd>
+ </>
+ );
+}
+
+function Footer({ info, onRefresh, disabled, busy, children }: { info: ProviderAccount | undefined; onRefresh: () => void; disabled: boolean; busy: boolean; children?: React.ReactNode }) {
+ const now = useNow(30_000);
+ return (
+ <div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px]">
+ {children}
+ <span className="ml-auto inline-flex items-center gap-2 text-muted-foreground">
+ {info && <span>{updatedWords(info.checkedAt, Math.max(now, info.checkedAt))}</span>}
+ <button
+ type="button"
+ onClick={onRefresh}
+ disabled={disabled}
+ className="inline-flex min-h-6 items-center gap-1 rounded font-medium [@media(pointer:coarse)]:min-h-11 text-foreground underline-offset-2 hover:underline disabled:pointer-events-none disabled:opacity-50"
+ >
+ {busy && <Loader2 aria-hidden className="size-3 animate-spin" />}
+ Refresh
+ </button>
+ </span>
+ </div>
+ );
+}
+
+/**
+ * The account behind a saved key. `scope`: whose key (the words for a key the provider didn't accept). `refused` and
+ * `emptyNoted`: the card already says the provider stopped accepting the key, or that its balance ran out (Your keys),
+ * so this doesn't say it again.
+ */
+export function KeyAccountDetails({
+ provider,
+ scope,
+ refused,
+ emptyNoted,
+ className,
+}: {
+ provider: CloudProvider;
+ scope: "owner" | "account";
+ refused?: boolean;
+ emptyNoted?: boolean;
+ className?: string;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const [seen, setSeen] = useState(false);
+ useEffect(() => {
+ const el = ref.current;
+ if (!el || seen) return;
+ const io = new IntersectionObserver((entries) => {
+ if (!entries.some((e) => e.isIntersecting)) return;
+ setSeen(true);
+ io.disconnect();
+ });
+ io.observe(el);
+ return () => io.disconnect();
+ }, [seen]);
+ const q = useKeyInfo({ enabled: seen, detail: true });
+ const { refresh, busy, cooling } = useRefreshKeyInfo(true);
+ const { label } = CLOUD_KEY[provider];
+ const info = q.data?.providers.find((x) => x.provider === provider);
+ const footer = (more?: React.ReactNode) => (
+ <Footer info={info} onRefresh={() => void refresh()} disabled={busy || cooling || q.isFetching} busy={busy}>
+ {more}
+ </Footer>
+ );
+
+ let body: React.ReactNode;
+ if (!q.data && !q.isError) {
+ // Until it is seen and answered: two quiet lines in the panel's place, so nothing below moves much.
+ body = (
+ <div aria-hidden className="grid gap-2 py-0.5">
+ <span className="h-3.5 w-44 animate-pulse rounded bg-muted-foreground/15" />
+ <span className="h-3 w-28 animate-pulse rounded bg-muted-foreground/15" />
+ </div>
+ );
+ } else if (info?.state === "check-key") {
+ if (refused) return null;
+ body = <p className="text-[13px]">{checkKeyWords(provider, scope)}</p>;
+ } else if (info?.balance) {
+ // The balance (fal.ai keys that may read it).
+ body = (
+ <>
+ <dl className="grid grid-cols-[max-content_minmax(0,1fr)] gap-x-6 gap-y-1">
+ <Row label="Balance" figure>
+ {money(info.balance)}
+ </Row>
+ {info.account && <Row label="Account">{accountWords(info.account)}</Row>}
+ {info.spentThisMonth && (
+ <Row label="Spent this month" figure>
+ {money(info.spentThisMonth)}
+ </Row>
+ )}
+ </dl>
+ {info.state === "empty" && !emptyNoted && (
+ <p className="mt-2">
+ Your {label} balance is empty. <Outbound href={BILLING_URL[provider]}>Top up on {label}</Outbound>
+ </p>
+ )}
+ {footer(info.state !== "empty" && <Outbound href={BILLING_URL[provider]}>Open {label} billing</Outbound>)}
+ </>
+ );
+ } else if (info?.state === "empty") {
+ if (emptyNoted && !info.account) return null;
+ body = (
+ <>
+ {info.account && (
+ <dl className="mb-2 grid grid-cols-[max-content_minmax(0,1fr)] gap-x-6">
+ <Row label="Account">{accountWords(info.account)}</Row>
+ </dl>
+ )}
+ {!emptyNoted && (
+ <p>
+ Your {label} balance is empty. <Outbound href={BILLING_URL[provider]}>Top up on {label}</Outbound>
+ </p>
+ )}
+ {footer()}
+ </>
+ );
+ } else {
+ // No balance the key may read (Replicate has none; fal.ai's default API keys may not), or no answer: the link.
+ body = (
+ <>
+ {info?.account && (
+ <dl className="mb-2 grid grid-cols-[max-content_minmax(0,1fr)] gap-x-6">
+ <Row label="Account">{accountWords(info.account)}</Row>
+ </dl>
+ )}
+ <p>
+ {label} shows your balance on its billing page. <Outbound href={BILLING_URL[provider]}>See balance on {label}</Outbound>
+ </p>
+ {provider === "fal" && info && (
+ <details className="group mt-2 text-[12px]">
+ <summary className="w-fit cursor-pointer font-medium text-foreground underline-offset-2 hover:underline">Show the balance here</summary>
+ <p className="mt-1 max-w-prose text-muted-foreground">{FAL_BALANCE_HOW}</p>
+ </details>
+ )}
+ {footer()}
+ </>
+ );
+ }
+ return (
+ <div ref={ref} aria-busy={!q.data && !q.isError} className={cn(PANEL, className)}>
+ {body}
+ </div>
+ );
+}
+
+/** Your keys, a card with no key yet: what shows here once one is saved. */
+export function NoKeyYet({ provider }: { provider: CloudProvider }) {
+ return <p className="rounded-lg border border-dashed px-3 py-2.5 text-[12px] text-muted-foreground">{noKeyYetWords(provider)}</p>;
+}
diff --git a/src/components/keys/use-key-info.ts b/src/components/keys/use-key-info.ts
new file mode 100644
index 00000000..fd2bb611
--- /dev/null
+++ b/src/components/keys/use-key-info.ts
@@ -0,0 +1,66 @@
+"use client";
+
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { useEffect, useState } from "react";
+import { KEY_INFO_REFRESH_GAP_MS, KEY_INFO_URL, type KeyInfoAnswer } from "@/lib/key-info";
+
+/*
+ * Connected accounts in the browser: GET /api/key-info, asked only when the account menu or the You sheet opens, or a
+ * Settings card scrolls into view (never on page load), then kept a minute. ["key-info"] is the menu's view,
+ * ["key-info", "detail"] Settings' (with this month's spend where the key may read it). A key added, replaced or
+ * removed invalidates both (["key-info"]).
+ */
+
+export const keyInfoKey = (detail: boolean) => (detail ? ["key-info", "detail"] : ["key-info"]);
+
+async function fetchKeyInfo(detail: boolean, refresh: boolean): Promise<KeyInfoAnswer> {
+ const q = new URLSearchParams({ ...(detail && { detail: "1" }), ...(refresh && { refresh: "1" }) }).toString();
+ const res = await fetch(q ? `${KEY_INFO_URL}?${q}` : KEY_INFO_URL, { headers: { Accept: "application/json" } });
+ if (!res.ok) throw Object.assign(new Error("Couldn't load the accounts"), { status: res.status });
+ return (await res.json()) as KeyInfoAnswer;
+}
+
+/** The saved keys' accounts, once `enabled` (the menu is open, the card was seen). */
+export function useKeyInfo({ enabled, detail = false }: { enabled: boolean; detail?: boolean }) {
+ return useQuery({
+ queryKey: keyInfoKey(detail),
+ queryFn: () => fetchKeyInfo(detail, false),
+ enabled,
+ staleTime: 60_000,
+ refetchOnWindowFocus: false,
+ retry: false,
+ });
+}
+
+/** When this page last asked for a refresh: every Refresh button waits 10 s from it (the server asks no sooner). */
+let lastRefresh = 0;
+
+/** Refresh: ask the providers again, then show the answer. The button waits 10 s after each press. */
+export function useRefreshKeyInfo(detail = false) {
+ const qc = useQueryClient();
+ const [busy, setBusy] = useState(false);
+ const [cooling, setCooling] = useState(() => Date.now() - lastRefresh < KEY_INFO_REFRESH_GAP_MS);
+ useEffect(() => {
+ if (!cooling) return;
+ const t = setTimeout(() => setCooling(false), Math.max(0, lastRefresh + KEY_INFO_REFRESH_GAP_MS - Date.now()));
+ return () => clearTimeout(t);
+ }, [cooling]);
+ const refresh = async () => {
+ if (busy || cooling) return;
+ lastRefresh = Date.now();
+ setCooling(true);
+ setBusy(true);
+ try {
+ const data = await fetchKeyInfo(detail, true);
+ qc.setQueryData(keyInfoKey(detail), data);
+ // Settings' answer holds everything the menu's does; the menu's lacks the spend, so Settings asks again later.
+ if (detail) qc.setQueryData(keyInfoKey(false), data);
+ else void qc.invalidateQueries({ queryKey: keyInfoKey(true), exact: true });
+ } catch {
+ // What was shown stays: the next look asks again.
+ } finally {
+ setBusy(false);
+ }
+ };
+ return { refresh, busy, cooling };
+}
diff --git a/src/components/keys/your-keys.tsx b/src/components/keys/your-keys.tsx
index 71782ce2..8603c390 100644
--- a/src/components/keys/your-keys.tsx
+++ b/src/components/keys/your-keys.tsx
@@ -13,6 +13,7 @@ import { Label } from "@/components/ui/label";
import { ADD_KEY_EVENT, preferEngine, useHydrated, useStatus, useViewer } from "@/lib/api";
import { settingProblem } from "@/lib/connections";
import { CLOUD_KEY, CLOUD_PROVIDERS, type CloudProvider, type KeyInfo, type YourKeys } from "@/lib/your-keys";
+import { KeyAccountDetails, NoKeyYet } from "./key-account-details";
import { cn } from "@/lib/utils";
/**
@@ -58,6 +59,8 @@ function useKeysChanged() {
void qc.invalidateQueries({ queryKey: ["account-keys"] });
void qc.invalidateQueries({ queryKey: ["status"] });
void qc.invalidateQueries({ queryKey: ["models"] });
+ // Connected accounts: a new key's account, or none.
+ void qc.invalidateQueries({ queryKey: ["key-info"] });
};
}
@@ -270,6 +273,7 @@ function KeyCard({ provider, info }: { provider: CloudProvider; info: KeyInfo |
Your {p.label} balance ran out on {day(info.balanceEmptyAt!)}. Add credit on {p.label}, then press Check again.
</p>
)}
+ {info.readable && <KeyAccountDetails provider={provider} scope="account" refused={!!info.rejectedAt} emptyNoted={empty} />}
{checkNote && (
<div aria-live="polite" className="space-y-0.5">
<p className="text-[13px]">{checkNote.words}</p>
@@ -312,7 +316,10 @@ function KeyCard({ provider, info }: { provider: CloudProvider; info: KeyInfo |
)}
</>
) : (
- <KeyForm provider={provider} replacing={!!info} onSaved={() => setReplacing(false)} onCancel={info ? () => setReplacing(false) : undefined} />
+ <>
+ <KeyForm provider={provider} replacing={!!info} onSaved={() => setReplacing(false)} onCancel={info ? () => setReplacing(false) : undefined} />
+ {!info && <NoKeyYet provider={provider} />}
+ </>
)}
</div>
);
diff --git a/src/components/nav/account-menu.tsx b/src/components/nav/account-menu.tsx
index a93a4b7f..19abdd6e 100644
--- a/src/components/nav/account-menu.tsx
+++ b/src/components/nav/account-menu.tsx
@@ -10,6 +10,7 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem,
import { signInHref, signOut, useEngineMode, useViewer } from "@/lib/api";
import type { ViewerKind } from "@/lib/nav-model";
import { cn } from "@/lib/utils";
+import { ConnectedAccounts } from "./connected-accounts";
import { ExploreProgress } from "./explore-progress";
import { useViewerKind } from "./nav-ui";
import { keepHighlight, MENU_HEADING, MENU_ROW_1, NavMenuItem, SHEET_HEADING, SHEET_ROW as SHEET_ROW_BASE } from "./nav-row";
@@ -21,8 +22,10 @@ import { avatarDot, OwnerStatus, usePlaceholdersOn, useShownStatus, VisitorGpu }
* Thanks & licences, the owner's Models & licences and the source on GitHub are in Settings → About. What each viewer
* sees:
* guest Sign up free, Log in · Your GPU (sign up first) · explore · Settings, theme
- * account Signed in as <email> · balance or their own GPU · explore · Settings, Your GPU, theme · Sign out
- * owner Your setup · cloud models, ComfyUI, mode, the owner's GPU, Placeholders on · explore · Settings, theme
+ * account Signed in as <email> · balance or their own GPU · its connected accounts (its own keys' balances, or Add a
+ * key) · explore · Settings, Your GPU, theme · Sign out
+ * owner Your setup · cloud models, ComfyUI, mode, the owner's GPU · connected accounts (the studio's keys'
+ * balances) · Placeholders on · explore · Settings, theme
* The owner's status words exist only in the owner's branch: a guest's or an account's menu never says them.
*/
@@ -115,6 +118,7 @@ function GpuSection({ kind, variant }: { kind: ViewerKind | undefined; variant:
return (
<div className={cn("flex flex-col", item ? "gap-0.5" : "gap-1")}>
<OwnerStatus item={item} />
+ <ConnectedAccounts kind={kind} item={item} />
{placeholders &&
(item ? (
// From xl the bar shows this pill itself, so the menu leaves it out.
@@ -128,7 +132,14 @@ function GpuSection({ kind, variant }: { kind: ViewerKind | undefined; variant:
))}
</div>
);
- if (kind === "guest" || kind === "account") return <VisitorGpu item={item} />;
+ if (kind === "account")
+ return (
+ <>
+ <VisitorGpu item={item} />
+ <ConnectedAccounts kind={kind} item={item} />
+ </>
+ );
+ if (kind === "guest") return <VisitorGpu item={item} />;
return null;
}
diff --git a/src/components/nav/connected-accounts.tsx b/src/components/nav/connected-accounts.tsx
new file mode 100644
index 00000000..4beeedf5
--- /dev/null
+++ b/src/components/nav/connected-accounts.tsx
@@ -0,0 +1,143 @@
+"use client";
+
+import { ExternalLink, KeyRound, RefreshCw } from "lucide-react";
+import { useId } from "react";
+import { useKeyInfo, useRefreshKeyInfo } from "@/components/keys/use-key-info";
+import { IntentLink } from "@/components/intent-link";
+import { DropdownMenuLabel } from "@/components/ui/dropdown-menu";
+import { useEngineMode } from "@/lib/api";
+import { BILLING_URL } from "@/lib/diagnose";
+import { menuLabel, menuValue, savedProviders, type ProviderAccount } from "@/lib/key-info";
+import type { ViewerKind } from "@/lib/nav-model";
+import { CLOUD_KEY, type CloudProvider } from "@/lib/your-keys";
+import { cn } from "@/lib/utils";
+import { MENU_HEADING, NavMenuItem, SHEET_HEADING } from "./nav-row";
+import { Actionable, CHIP, DotSlot, useShownStatus } from "./status-chips";
+
+/*
+ * "Connected accounts" in the account menu and the phone's You sheet: one row per saved fal.ai key or Replicate token,
+ * with its balance (or a link to the provider's billing page, where the key may not read it) and a small Refresh. The
+ * owner sees the studio's keys, an account its own; a guest nothing. The rows come from the status the menu already
+ * has, so they show at once: only the values at their ends wait for /api/key-info, which is asked when the menu opens
+ * (this mounts with it), never on page load.
+ */
+
+const ROW = cn(CHIP, "flex-row items-center gap-3");
+
+/** Where a key the provider didn't accept is fixed. */
+const fixAt = (kind: ViewerKind) => (kind === "owner" ? "/settings#cloud" : "/settings#your-keys");
+
+function Value({ info, loading }: { info: ProviderAccount | undefined; loading: boolean }) {
+ if (loading) return <span aria-hidden className="ml-auto h-3 w-12 animate-pulse rounded bg-muted" />;
+ const v = menuValue(info);
+ if (v.kind === "amount") return <span className="ml-auto font-medium text-foreground tabular-nums">{v.text}</span>;
+ if (v.kind === "empty") return <span className="ml-auto font-medium text-brand-text tabular-nums">{v.text}</span>;
+ if (v.kind === "fix") return <span className="ml-auto font-medium text-foreground">{v.text}</span>;
+ return (
+ <span className="ml-auto inline-flex items-center gap-1">
+ {v.text}
+ <ExternalLink aria-hidden className="size-3" />
+ </span>
+ );
+}
+
+function ProviderRow({ p, kind, item, info, loading }: { p: CloudProvider; kind: ViewerKind; item: boolean; info: ProviderAccount | undefined; loading: boolean }) {
+ const label = CLOUD_KEY[p].label;
+ const body = (
+ <>
+ <DotSlot ok={loading || info?.state === "ok" || info?.state === "link" || !info} />
+ {label}
+ <Value info={info} loading={loading} />
+ </>
+ );
+ const name = loading ? `${label} balance, loading` : menuLabel(p, info);
+ return info?.state === "check-key" ? (
+ <Actionable item={item} className={ROW}>
+ <IntentLink href={fixAt(kind)} aria-label={name}>
+ {body}
+ </IntentLink>
+ </Actionable>
+ ) : (
+ <Actionable item={item} className={ROW}>
+ <a href={BILLING_URL[p]} target="_blank" rel="noreferrer" aria-label={name}>
+ {body}
+ </a>
+ </Actionable>
+ );
+}
+
+function Heading({ item, id, onRefresh, disabled, busy }: { item: boolean; id: string; onRefresh: () => void; disabled: boolean; busy: boolean }) {
+ const icon = <RefreshCw aria-hidden className={cn("size-4", busy && "motion-safe:animate-spin")} />;
+ return item ? (
+ <div className="flex items-center justify-between gap-2 pr-1">
+ <DropdownMenuLabel id={id} className={MENU_HEADING}>
+ Connected accounts
+ </DropdownMenuLabel>
+ <NavMenuItem
+ aria-label="Refresh balances"
+ disabled={disabled}
+ // The menu stays open: the new values show in it.
+ onSelect={(e) => {
+ e.preventDefault();
+ onRefresh();
+ }}
+ className="mt-1 size-8 justify-center gap-0 px-0 text-muted-foreground data-[disabled]:opacity-50 [&_svg]:text-muted-foreground"
+ >
+ {icon}
+ </NavMenuItem>
+ </div>
+ ) : (
+ <div className="mt-1 flex items-center justify-between gap-2">
+ <p id={id} className={cn(SHEET_HEADING, "pb-0")}>
+ Connected accounts
+ </p>
+ <button
+ type="button"
+ aria-label="Refresh balances"
+ disabled={disabled}
+ onClick={onRefresh}
+ className="nav-row -mr-2 grid size-11 shrink-0 place-items-center rounded-full text-muted-foreground disabled:opacity-50"
+ >
+ {icon}
+ </button>
+ </div>
+ );
+}
+
+/** An account with no key yet (on a studio with paid models on): one row to add one, as "Your GPU · Connect" is. */
+function AddKeyRow({ item }: { item: boolean }) {
+ return (
+ <Actionable item={item} className={ROW}>
+ <IntentLink href="/settings#your-keys">
+ <span aria-hidden className="grid w-[var(--nav-icon,16px)] shrink-0 place-items-center">
+ <KeyRound className="size-3.5" />
+ </span>
+ Your keys
+ <span className="ml-auto font-medium text-brand-text">Add a key</span>
+ </IntentLink>
+ </Actionable>
+ );
+}
+
+/** The menu's Connected accounts (`item`: inside the account menu; otherwise the You sheet's rows). */
+export function ConnectedAccounts({ kind, item }: { kind: ViewerKind | undefined; item: boolean }) {
+ const status = useShownStatus();
+ const mode = useEngineMode();
+ const saved = savedProviders(kind, status, mode);
+ const q = useKeyInfo({ enabled: !!saved?.length });
+ const { refresh, busy, cooling } = useRefreshKeyInfo(false);
+ const id = useId();
+ if (!saved || !kind) return null;
+ if (!saved.length) return kind === "account" ? <AddKeyRow item={item} /> : null;
+ // Before the first answer the values wait (a refresh keeps them and turns its icon); an answer that failed shows the
+ // billing links.
+ const loading = q.isPending && q.fetchStatus !== "idle";
+ return (
+ <div role="group" aria-labelledby={id} className="flex flex-col">
+ <Heading item={item} id={id} onRefresh={() => void refresh()} disabled={cooling || loading || busy} busy={busy} />
+ {saved.map((p) => (
+ <ProviderRow key={p} p={p} kind={kind} item={item} info={q.data?.providers.find((x) => x.provider === p)} loading={loading} />
+ ))}
+ </div>
+ );
+}
diff --git a/src/components/nav/status-chips.tsx b/src/components/nav/status-chips.tsx
index 7e3cff5f..42ce21ec 100644
--- a/src/components/nav/status-chips.tsx
+++ b/src/components/nav/status-chips.tsx
@@ -47,14 +47,14 @@ const ComputerNoteLive = dynamic(() => import("@/components/gpu/computer-runner"
type Viewer = NonNullable<StatusInfo["viewer"]>;
/** A status row of the account menu or the You sheet: its dot on the rows' icon column, its words on their label column. */
-const CHIP = "nav-row flex min-h-11 w-full flex-col justify-center gap-1 py-1.5 text-left text-[12px] text-muted-foreground";
+export const CHIP = "nav-row flex min-h-11 w-full flex-col justify-center gap-1 py-1.5 text-left text-[12px] text-muted-foreground";
export function StatusDot({ ok }: { ok: boolean | undefined }) {
return <span aria-hidden className={cn("size-1.5 shrink-0 rounded-full", ok ? "bg-success" : "bg-subtle-foreground")} />;
}
/** A status dot centred in a slot as wide as the rows' icons (16 px in the menu, 18 px in the You sheet: --nav-icon). */
-function DotSlot({ ok }: { ok: boolean | undefined }) {
+export function DotSlot({ ok }: { ok: boolean | undefined }) {
return (
<span aria-hidden className="grid w-[var(--nav-icon,16px)] shrink-0 place-items-center">
<StatusDot ok={ok} />
@@ -66,7 +66,7 @@ function DotSlot({ ok }: { ok: boolean | undefined }) {
* A link or button as a row of a menu (`item`: arrow keys reach it, choosing it closes the menu) or as it is
* elsewhere. The classes go through the menu item, so they win over its defaults.
*/
-function Actionable({ item, className, children }: { item?: boolean; className: string; children: React.ReactElement<{ className?: string }> }) {
+export function Actionable({ item, className, children }: { item?: boolean; className: string; children: React.ReactElement<{ className?: string }> }) {
// A sheet row's words sit on the sheet's gutter (its fill reaches 8 px past it); a menu row's on the menu's.
if (!item) return cloneElement(children, { className: cn("-mx-2 rounded-xl px-2", className, children.props.className) });
return (
diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsx
index f4bacf59..51c39fd6 100644
--- a/src/components/settings-form.tsx
+++ b/src/components/settings-form.tsx
@@ -16,6 +16,7 @@ import { Switch } from "@/components/ui/switch";
import { PLACEHOLDER_SETTING, placeholdersOn } from "@/lib/demo-mode";
import { AccountsChip } from "@/components/accounts-admin";
import { ConnectField, useSettings, type PublicSetting } from "@/components/connect-field";
+import { KeyAccountDetails } from "@/components/keys/key-account-details";
import { GetStarted } from "@/components/get-started";
import { AboutLinks } from "@/components/owner-settings";
import { LlmProviderSettings } from "@/components/llm-provider-settings";
@@ -585,7 +586,9 @@ export function SettingsForm({ prices }: { prices?: string }) {
Get a key <ExternalLink className="size-3" />
</a>
}
- />
+ >
+ {get("falKey")?.isSet && <KeyAccountDetails provider="fal" scope="owner" className="mt-2" />}
+ </ConnectField>
<ConnectField
id="replicate"
name="replicateToken"
@@ -598,7 +601,9 @@ export function SettingsForm({ prices }: { prices?: string }) {
Get a token <ExternalLink className="size-3" />
</a>
}
- />
+ >
+ {get("replicateToken")?.isSet && <KeyAccountDetails provider="replicate" scope="owner" className="mt-2" />}
+ </ConnectField>
<ChoiceField
id="setting-cloud-provider"
label="Preferred provider"
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index d29165e3..50b5ad28 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -180,7 +180,8 @@ export function accountGeneration(method: string, pathname: string): string | un
/**
* A read of an account's own things, which the route (or the proxy, by accountGeneration) scopes to it:
- * the list of its runs, a stored file (the proxy checks whose it is), its GPU, its keys (never a key: their last 4).
+ * the list of its runs, a stored file (the proxy checks whose it is), its GPU, its keys (never a key: their last 4),
+ * and what its own keys tell about its provider accounts (/api/key-info: the balance, never a key).
*/
export function accountOwnRead(pathname: string): boolean {
if (ACCOUNT_LISTS.has(pathname)) return true;
@@ -188,6 +189,7 @@ export function accountOwnRead(pathname: string): boolean {
pathname === "/api/generations" ||
pathname === "/api/account/gpu" ||
pathname === "/api/account/keys" ||
+ pathname === "/api/key-info" ||
ACCOUNT_CANVASES.test(pathname) ||
GPU_READS.has(pathname) ||
COMPUTER_READ.test(pathname) ||
diff --git a/src/lib/key-info.ts b/src/lib/key-info.ts
new file mode 100644
index 00000000..2026b4c4
--- /dev/null
+++ b/src/lib/key-info.ts
@@ -0,0 +1,126 @@
+import { CLOUD_KEY, CLOUD_PROVIDERS, type CloudProvider } from "./your-keys";
+
+/**
+ * Connected accounts: what a saved fal.ai key or Replicate token tells about its provider account (the balance, the
+ * account's name), for Settings and the account menu. The server reads it with the key (src/server/
+ * provider-account-info.ts, GET /api/key-info); the browser only ever gets these fields, never a key, its last
+ * characters or the provider's own text. The owner sees the studio's keys, an account its own keys, a guest nothing.
+ */
+
+/**
+ * What the provider said, as the page shows it:
+ * ok the account answered (a balance when the key may read it)
+ * empty the balance is empty: "Top up"
+ * link no balance the key may read: a link to the provider's billing page
+ * check-key the provider didn't accept the key
+ */
+export type AccountState = "ok" | "empty" | "link" | "check-key";
+
+export interface Money {
+ amount: number;
+ /** An ISO 4217 code, such as "USD". */
+ currency: string;
+}
+
+export interface ProviderAccount {
+ provider: CloudProvider;
+ /** When the provider was asked (ms). */
+ checkedAt: number;
+ state: AccountState;
+ /** The provider account's username (fal.ai: the team's name for a team key), its kind and its full name when given. */
+ account?: { name: string; kind?: "user" | "organization"; fullName?: string };
+ balance?: Money;
+ /** Settings only (?detail=1), for a fal.ai key that may read its usage. */
+ spentThisMonth?: Money;
+ billingUrl: string;
+}
+
+/** GET /api/key-info: one entry per saved key. */
+export interface KeyInfoAnswer {
+ providers: ProviderAccount[];
+}
+
+export const KEY_INFO_URL = "/api/key-info";
+
+/** A refresh asks the provider at most once in this time per key (the server keeps to it; the button waits as long). */
+export const KEY_INFO_REFRESH_GAP_MS = 10_000;
+
+/** "$24.50" in the reader's own number format (the narrow sign: "$", never "US$"); a code it can't format as "24.50 XYZ". */
+export function money(m: Money, locale?: string): string {
+ try {
+ return new Intl.NumberFormat(locale, { style: "currency", currency: m.currency, currencyDisplay: "narrowSymbol" }).format(m.amount);
+ } catch {
+ return `${m.amount.toFixed(2)} ${m.currency}`;
+ }
+}
+
+/** The part of /api/status this reads (StatusInfo in src/lib/api.ts). */
+export interface KeyInfoStatus {
+ providers: Record<string, { configured: boolean } | undefined>;
+ viewer?: { kind: "guest" | "account"; keys?: CloudProvider[]; paidAllowed?: boolean };
+}
+
+/**
+ * The providers whose saved key "Connected accounts" shows: the studio's (owner, not in Open source only), or the
+ * account's own (a studio with paid models on). [] for an account with no key (it gets "Add a key"); null while the
+ * status is unknown and for anyone else (a guest, the owner in Open source only), who gets nothing.
+ */
+export function savedProviders(kind: "owner" | "account" | "guest" | undefined, status: KeyInfoStatus | undefined, engineMode: string): CloudProvider[] | null {
+ if (!status || !kind || kind === "guest") return null;
+ if (kind === "owner") {
+ if (status.viewer || engineMode === "open") return null;
+ return CLOUD_PROVIDERS.filter((p) => status.providers[p]?.configured);
+ }
+ const v = status.viewer;
+ if (v?.kind !== "account" || v.paidAllowed === false) return null;
+ return CLOUD_PROVIDERS.filter((p) => v.keys?.includes(p));
+}
+
+/**
+ * The value at the end of a provider's row in the account menu. `amount`: the balance; `link`: the provider's billing
+ * page; `fix`: the key, in Settings. Undefined info (the answer failed, or the key isn't in it) reads as the link.
+ */
+export function menuValue(info: ProviderAccount | undefined): { text: string; kind: "amount" | "empty" | "link" | "fix" } {
+ if (info?.state === "check-key") return { text: "Check key", kind: "fix" };
+ if (info?.state === "empty") return { text: info.balance ? `${money(info.balance)} · Top up` : "Top up", kind: "empty" };
+ if (info?.state === "ok" && info.balance) return { text: money(info.balance), kind: "amount" };
+ return { text: "See balance", kind: "link" };
+}
+
+/** A row's name for a screen reader: what it says, and where it goes. */
+export function menuLabel(p: CloudProvider, info: ProviderAccount | undefined): string {
+ const { label } = CLOUD_KEY[p];
+ const v = menuValue(info);
+ if (v.kind === "fix") return `${label}: check your key in Settings`;
+ if (v.kind === "amount") return `${label} balance ${v.text}. Opens ${label} billing in a new tab`;
+ if (v.kind === "empty") return `${label} balance empty. Top up on ${label} (opens in a new tab)`;
+ return `See your ${label} balance on ${label} (opens in a new tab)`;
+}
+
+/** "Updated just now", "Updated 4 min ago", "Updated 2 h ago". */
+export function updatedWords(at: number, now: number): string {
+ const s = Math.max(0, now - at) / 1000;
+ if (s < 60) return "Updated just now";
+ if (s < 3600) return `Updated ${Math.floor(s / 60)} min ago`;
+ return `Updated ${Math.floor(s / 3600)} h ago`;
+}
+
+/** "alice (Alice)", "acme (organization)", "my-team". */
+export function accountWords(a: NonNullable<ProviderAccount["account"]>): string {
+ if (a.kind === "organization") return `${a.name} (organization)`;
+ return a.fullName && a.fullName !== a.name ? `${a.name} (${a.fullName})` : a.name;
+}
+
+/** Settings: what a card with no key yet says will show there. */
+export const noKeyYetWords = (p: CloudProvider): string =>
+ p === "fal"
+ ? "When you save a key, this card shows your fal.ai balance or a link to it."
+ : "When you save a token, this card shows your Replicate account and a link to your balance.";
+
+/** Settings: a fal.ai key that may not read its balance (fal.ai's default API keys). */
+export const FAL_BALANCE_HOW =
+ "On fal.ai, make a key with a custom permission list. Add the permission billing:usage:read to the permissions for running models. Then save the new key here.";
+
+/** Settings: the provider didn't accept the saved key when its account was asked. */
+export const checkKeyWords = (p: CloudProvider, scope: "owner" | "account"): string =>
+ `${CLOUD_KEY[p].label} didn't accept this ${p === "replicate" ? "token" : "key"}. ${scope === "owner" ? "Press Test to check it, or save a new one." : "Press Check again, or replace it."}`;
diff --git a/src/server/provider-account-info.ts b/src/server/provider-account-info.ts
new file mode 100644
index 00000000..516ab9a1
--- /dev/null
+++ b/src/server/provider-account-info.ts
@@ -0,0 +1,254 @@
+import "server-only";
+import { createHash } from "node:crypto";
+import { BILLING_URL } from "@/lib/diagnose";
+import type { AccountState, Money, ProviderAccount } from "@/lib/key-info";
+import { KEY_INFO_REFRESH_GAP_MS } from "@/lib/key-info";
+import { CLOUD_PROVIDERS, type CloudProvider } from "@/lib/your-keys";
+import { balanceRefusal, cloudKey, standIn } from "./provider-keys";
+import { testFalKey } from "./providers/fal";
+import { outsideTenant, runAsTenant } from "./tenant";
+
+/**
+ * Connected accounts (src/lib/key-info.ts): what a saved fal.ai key or Replicate token tells about its provider
+ * account. Read-only calls that run nothing and cost nothing:
+ * fal.ai GET api.fal.ai/v1/account/billing?expand=credits: the username and balance, for a key with the
+ * billing:usage:read permission (fal.ai's default API keys get 403: the page links to the billing page),
+ * and, for Settings, GET /v1/models/usage?expand=summary for this month's spend (BILLING or FULL keys).
+ * Replicate GET api.replicate.com/v1/account: the account (Replicate has no balance API: the billing page).
+ *
+ * The key is read only through cloudKey, inside the asker's own tenant (an account only ever gets its own key, the
+ * owner the studio's), and goes only in a request header. Nothing here returns, logs or keeps it: the cache holds a
+ * hash, the answer only ProviderAccount's fields (never the provider's own text), and the log at most the provider and
+ * a status. The provider is asked only when someone opens the menu or Settings, or presses Refresh: an answer is kept
+ * 60 s (15 s when the provider was busy or out of reach), and a refresh asks again at most once every 10 s per key.
+ * This never marks a key refused or its balance empty (account-keys.ts): it only reads.
+ */
+
+export type KeyOwner = { kind: "owner" } | { kind: "account"; id: string };
+
+/** Tests make the wait shorter. */
+export const KEY_INFO = { timeoutMs: 5_000 };
+
+const OK_TTL = 60_000;
+const FAIL_TTL = 15_000;
+const MAX_ENTRIES = 1_000;
+const FAL_API = "https://api.fal.ai";
+const REPLICATE_API = "https://api.replicate.com";
+
+/** The key the asker's info is about: its own key for an account, the studio's for the owner. "" when none is saved. */
+function keyOf(who: KeyOwner, p: CloudProvider): string {
+ return who.kind === "account" ? runAsTenant({ kind: "account", id: who.id }, () => cloudKey(p)) : outsideTenant(() => cloudKey(p));
+}
+
+// ---------------------------------------------------------------------------
+// The cache: in this process's memory only, by a hash of the provider and the key.
+
+interface Slot<T> {
+ at: number;
+ until: number;
+ value?: T;
+ pending?: Promise<T>;
+}
+
+const answers = new Map<string, Slot<ProviderAccount>>();
+const spends = new Map<string, Slot<Money | null>>();
+
+const slotId = (p: CloudProvider, key: string) => createHash("sha256").update(`${p}:${key}`).digest("hex").slice(0, 16);
+
+function keep<T>(map: Map<string, Slot<T>>, id: string, slot: Slot<T>): void {
+ map.delete(id);
+ map.set(id, slot);
+ while (map.size > MAX_ENTRIES) map.delete(map.keys().next().value!);
+}
+
+/**
+ * The kept answer while it is fresh (a refresh: while it is under 10 s old), one request at a time per key, else
+ * `load`'s answer, kept for the time it gives.
+ */
+function cached<T>(map: Map<string, Slot<T>>, id: string, fresh: boolean, load: () => Promise<{ value: T; ttl: number }>): Promise<T> {
+ const s = map.get(id);
+ const now = Date.now();
+ if (s?.pending) return s.pending;
+ if (s && "value" in s && (fresh ? now - s.at < KEY_INFO_REFRESH_GAP_MS : now < s.until)) return Promise.resolve(s.value as T);
+ const pending = load().then(
+ ({ value, ttl }) => {
+ const at = Date.now();
+ keep(map, id, { at, until: at + ttl, value });
+ return value;
+ },
+ (e) => {
+ map.delete(id);
+ throw e;
+ },
+ );
+ keep(map, id, { ...(s && "value" in s ? s : { at: 0, until: 0 }), pending });
+ return pending;
+}
+
+/** Tests only: forget every kept answer. */
+export function clearKeyInfo(): void {
+ answers.clear();
+ spends.clear();
+}
+
+// ---------------------------------------------------------------------------
+// The provider calls: GET only, the key in the Authorization header.
+
+type Got = { status: number; text: string } | { status: "timeout" | "unreachable" };
+
+async function read(url: string, authorization: string): Promise<Got> {
+ try {
+ const res = await fetch(url, { headers: { Authorization: authorization, Accept: "application/json" }, signal: AbortSignal.timeout(KEY_INFO.timeoutMs), redirect: "error" });
+ return { status: res.status, text: await res.text().catch(() => "") };
+ } catch (e) {
+ return { status: (e as Error)?.name === "TimeoutError" ? "timeout" : "unreachable" };
+ }
+}
+
+const falApi = () => standIn("fal") ?? FAL_API;
+const replicateApi = () => standIn("replicate") ?? REPLICATE_API;
+
+/** Only the provider and the status: never a key, a URL or the provider's text. */
+function note(p: CloudProvider, status: number | string): void {
+ console.warn(`[fuobe] key-info ${p}: ${status}`);
+}
+
+/** A status that says nothing about the key: the provider busy, down, or out of reach. Kept a short time. */
+const passing = (g: Got) => typeof g.status !== "number" || g.status === 429 || g.status >= 500;
+
+function json(text: string): Record<string, unknown> {
+ try {
+ const v = JSON.parse(text) as unknown;
+ return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
+ } catch {
+ return {};
+ }
+}
+
+/** A short line of the provider's own data (a username), or undefined. */
+function line(v: unknown, max = 80): string | undefined {
+ if (typeof v !== "string") return undefined;
+ const s = v.replace(/\p{Cc}/gu, "").trim();
+ return s ? s.slice(0, max) : undefined;
+}
+
+function moneyOf(amount: unknown, currency: unknown): Money | undefined {
+ const n = typeof amount === "string" ? Number(amount) : amount;
+ const c = typeof currency === "string" ? currency.trim().toUpperCase() : "";
+ return typeof n === "number" && Number.isFinite(n) && /^[A-Z]{3}$/.test(c) ? { amount: Math.round(n * 100) / 100, currency: c } : undefined;
+}
+
+const answer = (p: CloudProvider, state: AccountState, more: Partial<ProviderAccount> = {}): ProviderAccount => ({
+ provider: p,
+ checkedAt: Date.now(),
+ state,
+ ...more,
+ billingUrl: BILLING_URL[p],
+});
+
+async function falAccount(k: string): Promise<{ value: ProviderAccount; ttl: number }> {
+ const got = await read(`${falApi()}/v1/account/billing?expand=credits`, `Key ${k}`);
+ if (passing(got)) {
+ note("fal", got.status);
+ return { value: answer("fal", "link"), ttl: FAIL_TTL };
+ }
+ const { status, text } = got as { status: number; text: string };
+ if (status === 200) {
+ const body = json(text);
+ const credits = (body.credits && typeof body.credits === "object" ? body.credits : {}) as Record<string, unknown>;
+ const balance = moneyOf(credits.current_balance, credits.currency);
+ const name = line(body.username);
+ return {
+ value: answer("fal", balance ? (balance.amount > 0 ? "ok" : "empty") : "link", { ...(name && { account: { name } }), ...(balance && { balance }) }),
+ ttl: OK_TTL,
+ };
+ }
+ if (balanceRefusal(status, text)) return { value: answer("fal", "empty"), ttl: OK_TTL };
+ if (status === 401) {
+ // Said only when the free key check agrees (the status of a request that doesn't exist): a key fal.ai takes for
+ // runs is never called refused because the Platform API answered otherwise.
+ // It waits no longer than the billing call did: no answer in time is the billing link.
+ let stop: ReturnType<typeof setTimeout> | undefined;
+ const check = await Promise.race([testFalKey(k), new Promise<null>((done) => (stop = setTimeout(() => done(null), KEY_INFO.timeoutMs)))]).finally(() => clearTimeout(stop));
+ if (!check) return { value: answer("fal", "link"), ttl: FAIL_TTL };
+ if (!check.ok && check.reason === "rejected") return { value: answer("fal", "check-key"), ttl: OK_TTL };
+ if (!check.ok && check.reason === "balance") return { value: answer("fal", "empty"), ttl: OK_TTL };
+ }
+ // 403: a key without billing:usage:read (fal.ai's default API keys).
+ return { value: answer("fal", "link"), ttl: OK_TTL };
+}
+
+/** The first day of this month (UTC), as fal.ai's usage API takes it. */
+const monthStart = (now = new Date()) => `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, "0")}-01`;
+
+/** This month's spend on a fal.ai key that may read its usage (BILLING or FULL keys); null when it may not, or can't be summed. */
+async function falSpend(k: string): Promise<{ value: Money | null; ttl: number }> {
+ let total = 0;
+ let currency: string | undefined;
+ let cursor: string | undefined;
+ for (let page = 0; page < 5; page++) {
+ const q = new URLSearchParams({ expand: "summary", start: monthStart(), bound_to_timeframe: "false", limit: "50", ...(cursor && { cursor }) });
+ const got = await read(`${falApi()}/v1/models/usage?${q}`, `Key ${k}`);
+ if (passing(got)) {
+ note("fal", got.status);
+ return { value: null, ttl: FAIL_TTL };
+ }
+ const { status, text } = got as { status: number; text: string };
+ if (status !== 200) return { value: null, ttl: OK_TTL };
+ const body = json(text);
+ for (const r of Array.isArray(body.summary) ? body.summary : []) {
+ const row = (r && typeof r === "object" ? r : {}) as Record<string, unknown>;
+ const m = moneyOf(row.cost_total ?? row.cost, row.currency);
+ if (!m || (currency && m.currency !== currency)) return { value: null, ttl: OK_TTL };
+ currency = m.currency;
+ total += m.amount;
+ }
+ cursor = body.has_more === true ? line(body.next_cursor, 200) : undefined;
+ if (!cursor) return { value: { amount: Math.round(total * 100) / 100, currency: currency ?? "USD" }, ttl: OK_TTL };
+ }
+ // More pages than it reads: no figure rather than a part of one.
+ return { value: null, ttl: OK_TTL };
+}
+
+async function replicateAccount(t: string): Promise<{ value: ProviderAccount; ttl: number }> {
+ const got = await read(`${replicateApi()}/v1/account`, `Bearer ${t}`);
+ if (passing(got)) {
+ note("replicate", got.status);
+ return { value: answer("replicate", "link"), ttl: FAIL_TTL };
+ }
+ const { status, text } = got as { status: number; text: string };
+ if (status === 200) {
+ const body = json(text);
+ const name = line(body.username);
+ const fullName = line(body.name);
+ const kind = body.type === "organization" || body.type === "user" ? body.type : undefined;
+ // Replicate has no balance API: the billing page has it.
+ return { value: answer("replicate", "link", name ? { account: { name, ...(kind && { kind }), ...(fullName && { fullName }) } } : {}), ttl: OK_TTL };
+ }
+ if (balanceRefusal(status, text)) return { value: answer("replicate", "empty"), ttl: OK_TTL };
+ if (status === 401) return { value: answer("replicate", "check-key"), ttl: OK_TTL };
+ return { value: answer("replicate", "link"), ttl: OK_TTL };
+}
+
+// ---------------------------------------------------------------------------
+
+/**
+ * What the asker's saved key for `p` tells about its provider account, or null when no key is saved. `fresh`: ask the
+ * provider again (Refresh), at most once every 10 s per key. `detail`: Settings' view, with this month's spend where the
+ * key may read it.
+ */
+export async function accountInfo(who: KeyOwner, p: CloudProvider, opts: { fresh?: boolean; detail?: boolean } = {}): Promise<ProviderAccount | null> {
+ const key = keyOf(who, p);
+ if (!key) return null;
+ const id = slotId(p, key);
+ const info = await cached(answers, id, !!opts.fresh, () => (p === "fal" ? falAccount(key) : replicateAccount(key)));
+ if (!opts.detail || p !== "fal" || !info.balance) return info;
+ const spent = await cached(spends, id, !!opts.fresh, () => falSpend(key));
+ return spent ? { ...info, spentThisMonth: spent } : info;
+}
+
+/** Every saved key's info, in the providers' order (fal.ai first), asked of the providers side by side. */
+export async function accountsInfo(who: KeyOwner, opts: { fresh?: boolean; detail?: boolean } = {}): Promise<ProviderAccount[]> {
+ const all = await Promise.all(CLOUD_PROVIDERS.map((p) => accountInfo(who, p, opts)));
+ return all.filter((x): x is ProviderAccount => x !== null);
+}
diff --git a/tests/byo-keys-static.test.ts b/tests/byo-keys-static.test.ts
index af8b4b74..15917b9c 100644
--- a/tests/byo-keys-static.test.ts
+++ b/tests/byo-keys-static.test.ts
@@ -48,17 +48,24 @@ describe("nothing else reads the studio's fal.ai or Replicate key", () => {
});
it("names fal.ai's and Replicate's API hosts only in their adapters", () => {
- expect(offenders(/queue\.fal\.run|rest\.fal\.ai|api\.replicate\.com/, ["server/providers/fal.ts", "server/providers/replicate.ts"])).toEqual([]);
- expect(offenders(/`Key \$\{/, ["server/providers/fal.ts"])).toEqual([]);
+ // provider-account-info.ts: the read-only account calls behind Connected accounts (the balance, the account's
+ // name). It takes its key from cloudKey as the adapters do (the next test), inside the asker's own tenant.
+ const callers = ["server/providers/fal.ts", "server/providers/replicate.ts", "server/provider-account-info.ts"];
+ expect(offenders(/queue\.fal\.run|rest\.fal\.ai|api\.fal\.ai|api\.replicate\.com/, callers)).toEqual([]);
+ expect(offenders(/`Key \$\{/, ["server/providers/fal.ts", "server/provider-account-info.ts"])).toEqual([]);
});
it("reads keys in the adapters only through cloudKey", () => {
- for (const f of ["server/providers/fal.ts", "server/providers/replicate.ts", "server/training.ts"]) {
+ for (const f of ["server/providers/fal.ts", "server/providers/replicate.ts", "server/training.ts", "server/provider-account-info.ts"]) {
const text = code(sources.find((s) => s.file === f)!.text);
expect(text, f).not.toMatch(/getSetting\(\s*["'`](falKey|replicateToken)/);
}
expect(code(sources.find((s) => s.file === "server/providers/fal.ts")!.text)).toMatch(/cloudKey\("fal"\)/);
expect(code(sources.find((s) => s.file === "server/providers/replicate.ts")!.text)).toMatch(/cloudKey\("replicate"\)/);
+ // Connected accounts: the asker's key through cloudKey only, inside the account's own tenant for an account.
+ const info = code(sources.find((s) => s.file === "server/provider-account-info.ts")!.text);
+ expect(info).toMatch(/runAsTenant\(\{ kind: "account", id: who\.id \}, \(\) => cloudKey\(p\)\)/);
+ expect(info).not.toMatch(/\b(accountKey|savedSetting|getSetting)\(/);
});
it("sends a run to its provider only through adapterFor, which checks it runs as the run's own account", () => {
diff --git a/tests/fixtures/key-info/README.txt b/tests/fixtures/key-info/README.txt
new file mode 100644
index 00000000..f0b12478
--- /dev/null
+++ b/tests/fixtures/key-info/README.txt
@@ -0,0 +1,12 @@
+Provider answers for the key-info tests (tests/key-info.test.ts). No real key was used.
+
+*.recorded.json: real answers, recorded with no key or an obviously fake key.
+Everything else: the provider's documented sample answers and error shapes.
+fal-403-locked.queue-shape.json: the queue API's answer for a locked account (the same words as
+tests/helpers/fake-cloud.ts). fal.ai doesn't document the Platform API's answer for a locked account.
+
+Sources:
+- https://fal.ai/docs/platform-apis/v1/account/billing
+- https://fal.ai/docs/platform-apis/v1/models/usage
+- https://api.replicate.com/openapi.json (account.get)
+- https://replicate.com/docs/reference/http (rate limits)
diff --git a/tests/fixtures/key-info/fal-401-bad-header.recorded.json b/tests/fixtures/key-info/fal-401-bad-header.recorded.json
new file mode 100644
index 00000000..50298c15
--- /dev/null
+++ b/tests/fixtures/key-info/fal-401-bad-header.recorded.json
@@ -0,0 +1 @@
+{"error":{"type":"authorization_error","message":"Invalid API key or malformed Authorization header"}}
diff --git a/tests/fixtures/key-info/fal-401-bad-key.recorded.json b/tests/fixtures/key-info/fal-401-bad-key.recorded.json
new file mode 100644
index 00000000..20843210
--- /dev/null
+++ b/tests/fixtures/key-info/fal-401-bad-key.recorded.json
@@ -0,0 +1 @@
+{"error":{"type":"authorization_error","message":"Invalid API key"}}
diff --git a/tests/fixtures/key-info/fal-401-no-key.recorded.json b/tests/fixtures/key-info/fal-401-no-key.recorded.json
new file mode 100644
index 00000000..c91a77c3
--- /dev/null
+++ b/tests/fixtures/key-info/fal-401-no-key.recorded.json
@@ -0,0 +1 @@
+{"error":{"type":"authorization_error","message":"API key authentication required"}}
diff --git a/tests/fixtures/key-info/fal-403-locked.queue-shape.json b/tests/fixtures/key-info/fal-403-locked.queue-shape.json
new file mode 100644
index 00000000..21ef6db0
--- /dev/null
+++ b/tests/fixtures/key-info/fal-403-locked.queue-shape.json
@@ -0,0 +1 @@
+{"detail":"User is locked. Reason: Exhausted balance. Top up your balance at fal.ai/dashboard/billing."}
diff --git a/tests/fixtures/key-info/fal-429.json b/tests/fixtures/key-info/fal-429.json
new file mode 100644
index 00000000..0fcf6e2d
--- /dev/null
+++ b/tests/fixtures/key-info/fal-429.json
@@ -0,0 +1 @@
+{"error":{"type":"rate_limited","message":"Rate limit exceeded","request_id":"req_0000"}}
diff --git a/tests/fixtures/key-info/fal-billing-200-credits.json b/tests/fixtures/key-info/fal-billing-200-credits.json
new file mode 100644
index 00000000..2d88627b
--- /dev/null
+++ b/tests/fixtures/key-info/fal-billing-200-credits.json
@@ -0,0 +1 @@
+{"username":"my-team","credits":{"current_balance":24.5,"currency":"USD"}}
diff --git a/tests/fixtures/key-info/fal-billing-200-plain.json b/tests/fixtures/key-info/fal-billing-200-plain.json
new file mode 100644
index 00000000..696095db
--- /dev/null
+++ b/tests/fixtures/key-info/fal-billing-200-plain.json
@@ -0,0 +1 @@
+{"username":"my-team"}
diff --git a/tests/fixtures/key-info/fal-billing-403-no-permission.json b/tests/fixtures/key-info/fal-billing-403-no-permission.json
new file mode 100644
index 00000000..716722ba
--- /dev/null
+++ b/tests/fixtures/key-info/fal-billing-403-no-permission.json
@@ -0,0 +1 @@
+{"error":{"type":"authorization_error","message":"Access denied","request_id":"req_0000"}}
diff --git a/tests/fixtures/key-info/fal-usage-200-summary.json b/tests/fixtures/key-info/fal-usage-200-summary.json
new file mode 100644
index 00000000..4dbfaab8
--- /dev/null
+++ b/tests/fixtures/key-info/fal-usage-200-summary.json
@@ -0,0 +1 @@
+{"summary":[{"endpoint_id":"fal-ai/flux/dev","unit":"image","quantity":4,"unit_price":0.1,"percent_discount":20,"cost_subtotal":0.4,"cost_discount":0.08,"cost_total":0.32,"cost":0.32,"currency":"USD"}],"next_cursor":null,"has_more":false}
diff --git a/tests/fixtures/key-info/replicate-401-bad-key.recorded.json b/tests/fixtures/key-info/replicate-401-bad-key.recorded.json
new file mode 100644
index 00000000..77d64f87
--- /dev/null
+++ b/tests/fixtures/key-info/replicate-401-bad-key.recorded.json
@@ -0,0 +1 @@
+{"title":"Unauthenticated","detail":"You did not pass a valid authentication token","status":401}
diff --git a/tests/fixtures/key-info/replicate-401-no-key.recorded.json b/tests/fixtures/key-info/replicate-401-no-key.recorded.json
new file mode 100644
index 00000000..1d42856a
--- /dev/null
+++ b/tests/fixtures/key-info/replicate-401-no-key.recorded.json
@@ -0,0 +1 @@
+{"title":"Unauthenticated","detail":"You did not pass an authentication token","status":401}
diff --git a/tests/fixtures/key-info/replicate-429.json b/tests/fixtures/key-info/replicate-429.json
new file mode 100644
index 00000000..84fbdcce
--- /dev/null
+++ b/tests/fixtures/key-info/replicate-429.json
@@ -0,0 +1 @@
+{"detail":"Request was throttled. Expected available in 1 second."}
diff --git a/tests/fixtures/key-info/replicate-account-200-org.json b/tests/fixtures/key-info/replicate-account-200-org.json
new file mode 100644
index 00000000..0288932e
--- /dev/null
+++ b/tests/fixtures/key-info/replicate-account-200-org.json
@@ -0,0 +1 @@
+{"type":"organization","username":"acme","name":"Acme Corp, Inc.","github_url":"https://github.com/acme"}
diff --git a/tests/fixtures/key-info/replicate-account-200-user.json b/tests/fixtures/key-info/replicate-account-200-user.json
new file mode 100644
index 00000000..35251512
--- /dev/null
+++ b/tests/fixtures/key-info/replicate-account-200-user.json
@@ -0,0 +1 @@
+{"type":"user","username":"alice","name":"Alice","github_url":"https://github.com/alice","avatar_url":"https://example.com/a.png"}
diff --git a/tests/helpers/fake-cloud.ts b/tests/helpers/fake-cloud.ts
index 4cb92a7b..ad653568 100644
--- a/tests/helpers/fake-cloud.ts
+++ b/tests/helpers/fake-cloud.ts
@@ -7,11 +7,21 @@ import http from "node:http";
* it with `node --experimental-strip-types`.
*
* What a key gets is scripted per key: "good" (works), "broke" (its balance has run out), "echo" (refused, and the
- * error repeats the request's Authorization header, like a proxy that echoes it), "outage" (503: says nothing about the key).
- * Any other key is refused (401).
+ * error repeats the request's Authorization header, like a proxy that echoes it), "outage" (503: says nothing about the key),
+ * "billing" (fal.ai: works, and may also read its account's billing, as a key with billing:usage:read does; a "good" key
+ * gets fal.ai's 403 there, as fal.ai's default API keys do). Any other key is refused (401).
*/
-export type KeyMode = "good" | "broke" | "echo" | "outage";
+export type KeyMode = "good" | "billing" | "broke" | "echo" | "outage";
+
+/** fal.ai's account billing for a "billing" key (its documented sample: tests/fixtures/key-info/fal-billing-200-credits.json). */
+export const FAL_BILLING = { username: "my-team", credits: { current_balance: 24.5, currency: "USD" } };
+/** fal.ai's usage summary for a "billing" key (its documented sample: tests/fixtures/key-info/fal-usage-200-summary.json). */
+export const FAL_USAGE = {
+ summary: [{ endpoint_id: "fal-ai/flux/dev", unit: "image", quantity: 4, unit_price: 0.1, percent_discount: 20, cost_subtotal: 0.4, cost_discount: 0.08, cost_total: 0.32, cost: 0.32, currency: "USD" }],
+ next_cursor: null,
+ has_more: false,
+};
export interface CloudRequest {
method: string;
@@ -83,7 +93,7 @@ async function start(handle: (fake: FakeCloud, req: CloudRequest, res: http.Serv
/** Refuse a request whose key isn't "good": 401, or 403 for an empty balance, or a 401 that echoes the header. */
function refused(fake: FakeCloud, r: CloudRequest, res: http.ServerResponse, key: string | null, broke: { status: number; detail: string }): boolean {
const mode = key ? fake.keys[key] : undefined;
- if (mode === "good") return false;
+ if (mode === "good" || mode === "billing") return false;
if (mode === "broke") json(res, broke.status, { detail: broke.detail });
else if (mode === "outage") json(res, 503, { detail: "Service unavailable" });
else if (mode === "echo") json(res, 401, { detail: `Invalid credentials: ${r.authorization}` });
@@ -110,6 +120,11 @@ export function startFakeFal(port = 0): Promise<FakeCloud> {
if (refused(fake, r, res, key, { status: 403, detail: "User is locked. Reason: Exhausted balance. Top up your balance at fal.ai/dashboard/billing." })) return;
// The key check: the status of a request that doesn't exist.
if (path === `/fal-ai/flux/requests/${ZERO}/status`) return json(res, 404, { status: "NOT_FOUND" });
+ // The Platform API's account billing and usage (api.fal.ai): only a key that may read billing gets them.
+ if (r.method === "GET" && (path === "/v1/account/billing" || path === "/v1/models/usage")) {
+ if (fake.keys[key ?? ""] !== "billing") return json(res, 403, { error: { type: "authorization_error", message: "Access denied", request_id: "req_0000" } });
+ return json(res, 200, path === "/v1/models/usage" ? FAL_USAGE : FAL_BILLING);
+ }
if (r.method === "POST" && path === "/storage/upload/initiate") {
const id = ++n;
return json(res, 200, { upload_url: `${fake.url}/upload/${id}`, file_url: `${fake.url}/files/${id}` });
diff --git a/tests/key-info-ui.test.ts b/tests/key-info-ui.test.ts
new file mode 100644
index 00000000..131ddb9d
--- /dev/null
+++ b/tests/key-info-ui.test.ts
@@ -0,0 +1,149 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { createElement, type ReactNode } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it } from "vitest";
+import { KeyAccountDetails, NoKeyYet } from "@/components/keys/key-account-details";
+import { keyInfoKey } from "@/components/keys/use-key-info";
+import { accountWords, menuLabel, menuValue, money, savedProviders, updatedWords, type KeyInfoStatus, type ProviderAccount } from "@/lib/key-info";
+
+/*
+ * Connected accounts in the page (src/lib/key-info.ts, src/components/keys/key-account-details.tsx,
+ * src/components/nav/connected-accounts.tsx): who gets rows, what each row says, and what Settings shows for each
+ * answer. Plain, positive words: a missing figure is left out and the billing page is always a link away.
+ */
+
+const status = (s: Partial<KeyInfoStatus>): KeyInfoStatus => ({ providers: {}, ...s });
+const fal = (more: Partial<ProviderAccount>): ProviderAccount => ({ provider: "fal", checkedAt: Date.now(), state: "link", billingUrl: "https://fal.ai/dashboard/billing", ...more });
+const rep = (more: Partial<ProviderAccount>): ProviderAccount => ({ provider: "replicate", checkedAt: Date.now(), state: "link", billingUrl: "https://replicate.com/account/billing", ...more });
+
+/** The markup of a Settings card's details, with this answer from /api/key-info already in hand. */
+function details(answer: ProviderAccount[] | null, props: Partial<Parameters<typeof KeyAccountDetails>[0]> = {}) {
+ const client = new QueryClient();
+ if (answer) client.setQueryData(keyInfoKey(true), { providers: answer });
+ const node: ReactNode = createElement(KeyAccountDetails, { provider: "fal", scope: "owner", ...props });
+ return renderToStaticMarkup(createElement(QueryClientProvider, { client }, node));
+}
+const words = (html: string) => html.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").replaceAll("&#x27;", "'").trim();
+const NEVER = /unavailable|unknown|not checked|error|failed|undefined|NaN/i;
+
+describe("who gets Connected accounts", () => {
+ it("the owner: the studio's saved keys, fal.ai first; nothing in Open source only", () => {
+ expect(savedProviders("owner", status({ providers: { replicate: { configured: true }, fal: { configured: true } } }), "both")).toEqual(["fal", "replicate"]);
+ expect(savedProviders("owner", status({ providers: { fal: { configured: false }, replicate: { configured: true } } }), "cloud")).toEqual(["replicate"]);
+ // No key: no rows (the status row already says "add key").
+ expect(savedProviders("owner", status({ providers: { fal: { configured: false } } }), "both")).toEqual([]);
+ expect(savedProviders("owner", status({ providers: { fal: { configured: true } } }), "open")).toBeNull();
+ });
+
+ it("an account: its own keys only, [] (Add a key) with none, nothing when paid models are off", () => {
+ expect(savedProviders("account", status({ providers: { fal: { configured: true } }, viewer: { kind: "account", keys: ["replicate"] } }), "both")).toEqual(["replicate"]);
+ expect(savedProviders("account", status({ viewer: { kind: "account", keys: [] } }), "open")).toEqual([]);
+ expect(savedProviders("account", status({ viewer: { kind: "account" } }), "open")).toEqual([]);
+ expect(savedProviders("account", status({ viewer: { kind: "account", keys: ["fal"], paidAllowed: false } }), "open")).toBeNull();
+ });
+
+ it("a guest, and anyone while the status is unknown: nothing, so nothing is asked", () => {
+ expect(savedProviders("guest", status({ viewer: { kind: "guest", keys: [] } }), "open")).toBeNull();
+ expect(savedProviders(undefined, status({}), "both")).toBeNull();
+ expect(savedProviders("owner", undefined, "both")).toBeNull();
+ // The owner's kind with a visitor's status (a page mid-change): nothing.
+ expect(savedProviders("owner", status({ providers: { fal: { configured: true } }, viewer: { kind: "account", keys: ["fal"] } }), "both")).toBeNull();
+ });
+});
+
+describe("the menu's rows", () => {
+ it("say the balance, an empty balance, the billing link or the key to check", () => {
+ expect(menuValue(fal({ state: "ok", balance: { amount: 24.5, currency: "USD" } }))).toEqual({ text: "$24.50", kind: "amount" });
+ expect(menuValue(fal({ state: "empty", balance: { amount: 0, currency: "USD" } }))).toEqual({ text: "$0.00 · Top up", kind: "empty" });
+ expect(menuValue(rep({ state: "empty" }))).toEqual({ text: "Top up", kind: "empty" });
+ expect(menuValue(fal({ state: "link" }))).toEqual({ text: "See balance", kind: "link" });
+ expect(menuValue(rep({ state: "link", account: { name: "alice" } }))).toEqual({ text: "See balance", kind: "link" });
+ expect(menuValue(fal({ state: "check-key" }))).toEqual({ text: "Check key", kind: "fix" });
+ // No answer (it failed, or the key isn't in it): the billing link, never an error.
+ expect(menuValue(undefined)).toEqual({ text: "See balance", kind: "link" });
+ });
+
+ it("name each row for a screen reader, with where it goes", () => {
+ expect(menuLabel("replicate", rep({}))).toBe("See your Replicate balance on Replicate (opens in a new tab)");
+ expect(menuLabel("fal", fal({ state: "ok", balance: { amount: 24.5, currency: "USD" } }))).toBe("fal.ai balance $24.50. Opens fal.ai billing in a new tab");
+ expect(menuLabel("fal", fal({ state: "check-key" }))).toBe("fal.ai: check your key in Settings");
+ });
+
+ it("format money in the reader's way, and a code Intl can't format plainly", () => {
+ expect(money({ amount: 24.5, currency: "USD" }, "en-US")).toBe("$24.50");
+ expect(money({ amount: 24.5, currency: "USD" }, "en-GB")).toBe("$24.50");
+ expect(money({ amount: 110, currency: "CNY" }, "en-US")).toBe("¥110.00");
+ expect(money({ amount: 3, currency: "ZZZZ" }, "en-US")).toBe("3.00 ZZZZ");
+ });
+
+ it("say how old the answer is, and whose account it is", () => {
+ expect(updatedWords(1_000, 1_000 + 59_000)).toBe("Updated just now");
+ expect(updatedWords(0, 4 * 60_000 + 5_000)).toBe("Updated 4 min ago");
+ expect(updatedWords(0, 2 * 3_600_000 + 1)).toBe("Updated 2 h ago");
+ expect(accountWords({ name: "alice", kind: "user", fullName: "Alice" })).toBe("alice (Alice)");
+ expect(accountWords({ name: "acme", kind: "organization", fullName: "Acme Corp, Inc." })).toBe("acme (organization)");
+ expect(accountWords({ name: "my-team" })).toBe("my-team");
+ });
+});
+
+describe("Settings: a saved key's account", () => {
+ it("fal.ai with the balance: balance, account, this month's spend and the billing page", () => {
+ const html = details([fal({ state: "ok", balance: { amount: 24.5, currency: "USD" }, account: { name: "my-team" }, spentThisMonth: { amount: 3.2, currency: "USD" } })]);
+ const w = words(html);
+ expect(w).toContain("Balance $24.50");
+ expect(w).toContain("Account my-team");
+ expect(w).toContain("Spent this month $3.20");
+ expect(w).toContain("Open fal.ai billing");
+ expect(w).toContain("Updated just now");
+ expect(w).toContain("Refresh");
+ expect(html).toContain('href="https://fal.ai/dashboard/billing" target="_blank" rel="noreferrer"');
+ expect(w).not.toMatch(NEVER);
+ });
+
+ it("fal.ai without balance access: the billing link, and how to show the balance here", () => {
+ const w = words(details([fal({ state: "link" })]));
+ expect(w).toContain("fal.ai shows your balance on its billing page. See balance on fal.ai");
+ expect(w).toContain("Show the balance here");
+ expect(w).toContain("billing:usage:read");
+ expect(w).not.toMatch(NEVER);
+ });
+
+ it("an empty balance says to top up", () => {
+ expect(words(details([fal({ state: "empty", balance: { amount: 0, currency: "USD" } })]))).toContain("Balance $0.00 Your fal.ai balance is empty. Top up on fal.ai");
+ expect(words(details([rep({ state: "empty" })], { provider: "replicate" }))).toContain("Your Replicate balance is empty. Top up on Replicate");
+ // Your keys already says the balance ran out ("Add credit"): the figure stays, the sentence isn't said twice.
+ const noted = words(details([fal({ state: "empty", balance: { amount: 0, currency: "USD" } })], { scope: "account", emptyNoted: true }));
+ expect(noted).toContain("Balance $0.00");
+ expect(noted).not.toContain("is empty");
+ expect(words(details([rep({ state: "empty" })], { provider: "replicate", scope: "account", emptyNoted: true }))).toBe("");
+ });
+
+ it("Replicate: the account and the billing link (Replicate has no balance to read)", () => {
+ const w = words(details([rep({ account: { name: "acme", kind: "organization", fullName: "Acme Corp, Inc." } })], { provider: "replicate" }));
+ expect(w).toContain("Account acme (organization)");
+ expect(w).toContain("Replicate shows your balance on its billing page. See balance on Replicate");
+ expect(w).not.toContain("Show the balance here");
+ expect(w).not.toMatch(NEVER);
+ });
+
+ it("a key the provider didn't accept: what to do, unless the card already says so", () => {
+ expect(words(details([fal({ state: "check-key" })]))).toBe("fal.ai didn't accept this key. Press Test to check it, or save a new one.");
+ expect(words(details([rep({ state: "check-key" })], { provider: "replicate", scope: "account" }))).toBe("Replicate didn't accept this token. Press Check again, or replace it.");
+ expect(words(details([fal({ state: "check-key" })], { scope: "account", refused: true }))).toBe("");
+ });
+
+ it("waits quietly before the card is seen, and falls back to the billing link with no answer", () => {
+ const waiting = details(null);
+ expect(words(waiting)).toBe("");
+ expect(waiting).toContain('aria-busy="true"');
+ // The answer came without this provider (a key removed meanwhile): the link, no figures.
+ expect(words(details([rep({})]))).toContain("See balance on fal.ai");
+ });
+
+ it("a card with no key yet says what will show there", () => {
+ expect(words(renderToStaticMarkup(createElement(NoKeyYet, { provider: "fal" })))).toBe("When you save a key, this card shows your fal.ai balance or a link to it.");
+ expect(words(renderToStaticMarkup(createElement(NoKeyYet, { provider: "replicate" })))).toBe(
+ "When you save a token, this card shows your Replicate account and a link to your balance.",
+ );
+ });
+});
diff --git a/tests/key-info.test.ts b/tests/key-info.test.ts
new file mode 100644
index 00000000..114f698d
--- /dev/null
+++ b/tests/key-info.test.ts
@@ -0,0 +1,397 @@
+import fs from "node:fs";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, onTestFinished, vi, type MockInstance } from "vitest";
+import { NextRequest } from "next/server";
+import { keysSeen, startFakeFal, startFakeReplicate, type FakeCloud } from "./helpers/fake-cloud";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * Connected accounts (GET /api/key-info, src/server/provider-account-info.ts): what a saved fal.ai key or Replicate
+ * token tells about its provider account. The owner gets the studio's keys, an account only its own, a guest nothing
+ * and no provider is asked. The key never shows in an answer, a log line or an error, the provider is asked once a
+ * minute at most (a refresh once every 10 s), and every answer the providers document maps to plain words. The provider
+ * answers are their documented samples and recorded refusals (tests/fixtures/key-info).
+ */
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = tempDir("fuobe-key-info-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_ENGINE_MODE;
+delete process.env.FAL_KEY;
+delete process.env.REPLICATE_API_TOKEN;
+
+const auth = await import("@/server/auth");
+const route = await import("@/app/api/key-info/route");
+const { proxy } = await import("@/proxy");
+const { setSetting } = await import("@/server/settings");
+const { saveAccountKey, removeAccountKey, accountKeyInfo } = await import("@/server/account-keys");
+const { KEY_INFO, clearKeyInfo, accountInfo } = await import("@/server/provider-account-info");
+const { accountOwnRead } = await import("@/lib/guest-access");
+
+const fixture = (name: string): unknown => JSON.parse(fs.readFileSync(path.join(__dirname, "fixtures/key-info", name), "utf8"));
+
+const OWNER_FAL = "owner-key-id-1a2b:owner-key-secret-3c4d";
+const OWNER_REP = "r8_ownerReplicateToken9f8e";
+const A_FAL = "acct-a-key-id-5e6f:acct-a-key-secret-7a8b";
+const A_REP = "r8_accountAReplicateToken1c2d";
+const B_FAL = "acct-b-key-id-9c0d:acct-b-key-secret-1e2f";
+
+let fal: FakeCloud;
+let rep: FakeCloud;
+let A = "";
+let B = "";
+let C = "";
+let cookieA = "";
+let cookieB = "";
+let cookieC = "";
+let ownerCookie = "";
+beforeAll(async () => {
+ fal = await startFakeFal();
+ rep = await startFakeReplicate();
+ globalThis.__fuobeTestFalUrl = fal.url;
+ globalThis.__fuobeTestReplicateUrl = rep.url;
+ fal.keys[OWNER_FAL] = "billing";
+ fal.keys[A_FAL] = "good";
+ fal.keys[B_FAL] = "good";
+ rep.keys[OWNER_REP] = "good";
+ rep.keys[A_REP] = "good";
+ setSetting("falKey", OWNER_FAL);
+ setSetting("replicateToken", OWNER_REP);
+ auth.setPassword("install password");
+ A = auth.createAccount("[email protected]", "long enough").id;
+ B = auth.createAccount("[email protected]", "long enough").id;
+ C = auth.createAccount("[email protected]", "long enough").id;
+ saveAccountKey(A, "fal", A_FAL);
+ saveAccountKey(A, "replicate", A_REP);
+ saveAccountKey(B, "fal", B_FAL);
+ cookieA = `${auth.SESSION_COOKIE}=${auth.createSession(A).value}`;
+ cookieB = `${auth.SESSION_COOKIE}=${auth.createSession(B).value}`;
+ cookieC = `${auth.SESSION_COOKIE}=${auth.createSession(C).value}`;
+ ownerCookie = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+});
+afterAll(async () => {
+ globalThis.__fuobeTestFalUrl = undefined;
+ globalThis.__fuobeTestReplicateUrl = undefined;
+ await fal.close();
+ await rep.close();
+});
+let warn: MockInstance<typeof console.warn>;
+beforeEach(() => {
+ clearKeyInfo();
+ fal.log.length = 0;
+ rep.log.length = 0;
+ fal.script = null;
+ rep.script = null;
+ fal.hang = null;
+ rep.hang = null;
+ warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+});
+afterEach(() => {
+ warn.mockRestore();
+ vi.useRealTimers();
+});
+
+const req = (who: string | null, q = "") =>
+ new Request(`http://localhost:3000/api/key-info${q}`, { headers: { host: "localhost:3000", ...(who && { cookie: who }) } });
+async function ask(who: string | null, q = "") {
+ const res = await route.GET(req(who, q));
+ const text = await res.text();
+ return { status: res.status, text, body: JSON.parse(text), cache: res.headers.get("cache-control") };
+}
+const billingCalls = (log: FakeCloud["log"]) => log.filter((r) => r.path.startsWith("/v1/account/billing")).length;
+const everyKey = [OWNER_FAL, OWNER_REP, A_FAL, A_REP, B_FAL];
+/** No key, and no half of a fal.ai key_id:key_secret, anywhere in `text`. */
+function noKeyIn(text: string) {
+ for (const k of everyKey) {
+ expect(text).not.toContain(k);
+ for (const half of k.split(":")) expect(text).not.toContain(half);
+ expect(text).not.toContain(k.slice(-4));
+ }
+}
+/** What was logged, one line per call, sorted (fal.ai and Replicate are asked side by side). */
+const logged = () =>
+ warn.mock.calls
+ .map((c) => c.join(" "))
+ .sort()
+ .join("\n");
+
+describe("who may ask", () => {
+ it("refuses a guest before any key is read: the route and the proxy, and no provider is asked", async () => {
+ const r = await ask(null);
+ expect(r.status).toBe(401);
+ expect(r.cache).toBe("no-store");
+ expect(r.body.providers).toBeUndefined();
+ const at = proxy(new NextRequest("http://localhost:3000/api/key-info", { headers: { host: "localhost:3000" } }));
+ expect(at.status).toBe(401);
+ expect(fal.log).toEqual([]);
+ expect(rep.log).toEqual([]);
+ });
+
+ it("lets an account's read through the proxy (its own keys only, the route checks who)", () => {
+ expect(accountOwnRead("/api/key-info")).toBe(true);
+ const at = proxy(new NextRequest("http://localhost:3000/api/key-info", { headers: { host: "localhost:3000", cookie: cookieA } }));
+ expect(at.headers.get("x-middleware-next")).toBe("1");
+ });
+
+ it("gives the owner the studio's keys: the balance and the account fal.ai's billing call returns", async () => {
+ const r = await ask(ownerCookie);
+ expect(r.status).toBe(200);
+ expect(r.cache).toBe("no-store");
+ const [f, p] = r.body.providers;
+ expect(f).toMatchObject({ provider: "fal", state: "ok", balance: { amount: 24.5, currency: "USD" }, account: { name: "my-team" }, billingUrl: "https://fal.ai/dashboard/billing" });
+ expect(f.spentThisMonth).toBeUndefined();
+ expect(p).toMatchObject({ provider: "replicate", state: "link", account: { name: "alice", kind: "user" }, billingUrl: "https://replicate.com/account/billing" });
+ expect(keysSeen(fal.log)).toEqual([`Key ${OWNER_FAL}`]);
+ expect(keysSeen(rep.log)).toEqual([`Bearer ${OWNER_REP}`]);
+ // A GET with the key in the header only: never in the address.
+ for (const call of [...fal.log, ...rep.log]) {
+ expect(call.method).toBe("GET");
+ noKeyIn(call.path);
+ }
+ noKeyIn(r.text);
+ });
+
+ it("adds this month's spend for Settings (?detail=1), from fal.ai's usage summary", async () => {
+ const r = await ask(ownerCookie, "?detail=1");
+ expect(r.body.providers[0].spentThisMonth).toEqual({ amount: 0.32, currency: "USD" });
+ const usage = fal.log.find((x) => x.path.startsWith("/v1/models/usage"))!;
+ const q = new URL(usage.path, fal.url).searchParams;
+ expect(q.get("expand")).toBe("summary");
+ expect(q.get("start")).toMatch(/^\d{4}-\d{2}-01$/);
+ // The menu's view never asks for it.
+ fal.log.length = 0;
+ await ask(ownerCookie);
+ expect(fal.log.filter((x) => x.path.startsWith("/v1/models/usage"))).toEqual([]);
+ });
+
+ it("gives an account its own keys only, never the studio's or another account's", async () => {
+ const a = await ask(cookieA);
+ expect(a.status).toBe(200);
+ // fal.ai's default API key may not read billing (403): the billing page link. Replicate: the account.
+ expect(a.body.providers.map((x: { provider: string; state: string }) => [x.provider, x.state])).toEqual([
+ ["fal", "link"],
+ ["replicate", "link"],
+ ]);
+ expect(a.body.providers[0].balance).toBeUndefined();
+ expect(keysSeen(fal.log)).toEqual([`Key ${A_FAL}`]);
+ expect(keysSeen(rep.log)).toEqual([`Bearer ${A_REP}`]);
+ noKeyIn(a.text);
+
+ fal.log.length = 0;
+ rep.log.length = 0;
+ const b = await ask(cookieB);
+ expect(b.body.providers.map((x: { provider: string }) => x.provider)).toEqual(["fal"]);
+ expect(keysSeen(fal.log)).toEqual([`Key ${B_FAL}`]);
+ expect(rep.log).toEqual([]);
+ // Even though the studio's fal.ai key may read its balance, no account's answer ever holds it.
+ expect(b.text).not.toContain("24.5");
+ expect(b.text).not.toContain("my-team");
+ });
+
+ it("asks nothing for an account with no key, and nothing when the studio has paid models off", async () => {
+ const c = await ask(cookieC);
+ expect(c.body).toEqual({ providers: [] });
+ expect(fal.log).toEqual([]);
+ expect(rep.log).toEqual([]);
+ setSetting("engineMode", "open");
+ onTestFinished(() => setSetting("engineMode", "both"));
+ const a = await ask(cookieA);
+ expect(a.body).toEqual({ providers: [] });
+ expect(fal.log).toEqual([]);
+ });
+
+ it("never sends the studio's key when an account's own key can't be opened or was removed", async () => {
+ const D = auth.createAccount("[email protected]", "long enough").id;
+ saveAccountKey(D, "fal", "acct-d-key-id-0000:acct-d-key-secret-0000");
+ removeAccountKey(D, "fal");
+ expect(accountKeyInfo(D).fal).toBeNull();
+ expect(await accountInfo({ kind: "account", id: D }, "fal")).toBeNull();
+ expect(fal.log).toEqual([]);
+ });
+});
+
+describe("the key never shows", () => {
+ it("not in the answer, a log line or an error, even when the provider's error repeats it", async () => {
+ fal.script = (r) => (r.path.startsWith("/v1/account/billing") ? { status: 500, body: { detail: `upstream failed for ${r.authorization}` } } : null);
+ rep.script = (r) => (r.path === "/v1/account" ? { status: 503, body: { detail: `bad gateway: ${r.authorization}` } } : null);
+ const r = await ask(ownerCookie);
+ expect(r.status).toBe(200);
+ expect(r.body.providers.map((x: { state: string }) => x.state)).toEqual(["link", "link"]);
+ noKeyIn(r.text);
+ // The log says the provider and the status, nothing else.
+ expect(logged()).toBe("[fuobe] key-info fal: 500\n[fuobe] key-info replicate: 503");
+ noKeyIn(logged());
+ });
+
+ it("keeps no key in what it caches or answers for a provider that echoes it with 401", async () => {
+ fal.keys["echo-key-id-1234:echo-key-secret-5678"] = "echo";
+ const E = auth.createAccount("[email protected]", "long enough").id;
+ saveAccountKey(E, "fal", "echo-key-id-1234:echo-key-secret-5678");
+ const info = await accountInfo({ kind: "account", id: E }, "fal");
+ expect(info?.state).toBe("check-key");
+ const text = JSON.stringify(info);
+ expect(text).not.toContain("echo-key");
+ expect(logged()).toBe("");
+ });
+
+ it("answers only the documented fields of the provider's account, never its other text", async () => {
+ rep.script = (r) =>
+ r.path === "/v1/account"
+ ? { status: 200, body: { ...(fixture("replicate-account-200-user.json") as object), username: "alice\u0007", api_token: OWNER_REP, extra: "never shown" } }
+ : null;
+ const r = await ask(ownerCookie);
+ const p = r.body.providers[1];
+ expect(Object.keys(p).sort()).toEqual(["account", "billingUrl", "checkedAt", "provider", "state"]);
+ expect(p.account).toEqual({ name: "alice", kind: "user", fullName: "Alice" });
+ expect(r.text).not.toContain("never shown");
+ expect(r.text).not.toContain("github");
+ noKeyIn(r.text);
+ });
+});
+
+describe("how often a provider is asked", () => {
+ it("once a minute: a second look within 60 s is the kept answer", async () => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(new Date("2026-11-06T10:00:00Z"));
+ const first = await ask(ownerCookie);
+ vi.setSystemTime(new Date("2026-11-06T10:00:59Z"));
+ const second = await ask(ownerCookie);
+ expect(second.body).toEqual(first.body);
+ expect(billingCalls(fal.log)).toBe(1);
+ expect(rep.log).toHaveLength(1);
+ vi.setSystemTime(new Date("2026-11-06T10:01:01Z"));
+ await ask(ownerCookie);
+ expect(billingCalls(fal.log)).toBe(2);
+ expect(rep.log).toHaveLength(2);
+ });
+
+ it("a refresh asks again, but never twice in 10 s for the same key", async () => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(new Date("2026-11-06T10:00:00Z"));
+ await ask(cookieA);
+ vi.setSystemTime(new Date("2026-11-06T10:00:05Z"));
+ await ask(cookieA, "?refresh=1");
+ expect(billingCalls(fal.log)).toBe(1);
+ vi.setSystemTime(new Date("2026-11-06T10:00:11Z"));
+ await ask(cookieA, "?refresh=1");
+ expect(billingCalls(fal.log)).toBe(2);
+ expect(rep.log).toHaveLength(2);
+ });
+
+ it("asks once for many looks at the same moment", async () => {
+ const all = await Promise.all([ask(cookieA), ask(cookieA), ask(cookieA, "?refresh=1")]);
+ expect(new Set(all.map((x) => JSON.stringify(x.body))).size).toBe(1);
+ expect(billingCalls(fal.log)).toBe(1);
+ expect(rep.log).toHaveLength(1);
+ });
+
+ it("keeps a busy provider's answer 15 s only", async () => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(new Date("2026-11-06T10:00:00Z"));
+ fal.script = (r) => (r.path.startsWith("/v1/account/billing") ? { status: 429, body: fixture("fal-429.json") } : null);
+ expect((await ask(ownerCookie)).body.providers[0].state).toBe("link");
+ vi.setSystemTime(new Date("2026-11-06T10:00:14Z"));
+ await ask(ownerCookie);
+ expect(billingCalls(fal.log)).toBe(1);
+ fal.script = null;
+ vi.setSystemTime(new Date("2026-11-06T10:00:16Z"));
+ expect((await ask(ownerCookie)).body.providers[0].state).toBe("ok");
+ expect(billingCalls(fal.log)).toBe(2);
+ });
+
+ it("stops waiting after a short time, and shows the billing link", async () => {
+ KEY_INFO.timeoutMs = 300;
+ onTestFinished(() => {
+ KEY_INFO.timeoutMs = 5_000;
+ });
+ fal.hang = (r) => r.path.startsWith("/v1/account/billing");
+ rep.hang = (r) => r.path === "/v1/account";
+ const t = Date.now();
+ const r = await ask(ownerCookie);
+ expect(Date.now() - t).toBeLessThan(3_000);
+ expect(r.body.providers.map((x: { state: string }) => x.state)).toEqual(["link", "link"]);
+ expect(logged()).toBe("[fuobe] key-info fal: timeout\n[fuobe] key-info replicate: timeout");
+ });
+
+ it("waits no longer for fal.ai's key check after a 401: no answer in time is the billing link", async () => {
+ KEY_INFO.timeoutMs = 300;
+ onTestFinished(() => {
+ KEY_INFO.timeoutMs = 5_000;
+ });
+ fal.script = (r) => (r.path.startsWith("/v1/account/billing") ? { status: 401, body: fixture("fal-401-bad-key.recorded.json") } : null);
+ fal.hang = (r) => r.path.endsWith("/status");
+ const t = Date.now();
+ const r = await ask(ownerCookie);
+ expect(Date.now() - t).toBeLessThan(3_000);
+ expect(r.body.providers[0]).toMatchObject({ provider: "fal", state: "link" });
+ noKeyIn(r.text);
+ });
+});
+
+describe("what each documented answer shows", () => {
+ const falAnswer = async (status: number, body: unknown) => {
+ fal.script = (r) => (r.path.startsWith("/v1/account/billing") ? { status, body } : null);
+ clearKeyInfo();
+ return (await ask(ownerCookie)).body.providers[0];
+ };
+ const repAnswer = async (status: number, body: unknown) => {
+ rep.script = (r) => (r.path === "/v1/account" ? { status, body } : null);
+ clearKeyInfo();
+ return (await ask(ownerCookie)).body.providers[1];
+ };
+
+ it("fal.ai: the balance, an empty balance, no credits, no permission, a locked account", async () => {
+ expect(await falAnswer(200, fixture("fal-billing-200-credits.json"))).toMatchObject({ state: "ok", balance: { amount: 24.5, currency: "USD" }, account: { name: "my-team" } });
+ expect(await falAnswer(200, { username: "my-team", credits: { current_balance: 0, currency: "USD" } })).toMatchObject({ state: "empty", balance: { amount: 0, currency: "USD" } });
+ // Without credits (expand not honoured), or a currency that isn't a code: no figure, the link.
+ expect(await falAnswer(200, fixture("fal-billing-200-plain.json"))).toMatchObject({ state: "link", account: { name: "my-team" } });
+ expect((await falAnswer(200, { username: "x", credits: { current_balance: 5, currency: "<b>" } })).balance).toBeUndefined();
+ expect(await falAnswer(403, fixture("fal-billing-403-no-permission.json"))).toMatchObject({ state: "link" });
+ expect((await falAnswer(403, fixture("fal-billing-403-no-permission.json"))).account).toBeUndefined();
+ expect(await falAnswer(403, fixture("fal-403-locked.queue-shape.json"))).toMatchObject({ state: "empty" });
+ });
+
+ it("fal.ai 401: 'Check key' only when fal.ai's key check refuses the key too", async () => {
+ // The studio's key works for runs (its key check passes): a 401 here says nothing about it.
+ expect(await falAnswer(401, fixture("fal-401-bad-key.recorded.json"))).toMatchObject({ state: "link" });
+ // A key fal.ai refuses everywhere.
+ fal.keys[OWNER_FAL] = "echo";
+ onTestFinished(() => {
+ fal.keys[OWNER_FAL] = "billing";
+ });
+ fal.script = null;
+ clearKeyInfo();
+ expect((await ask(ownerCookie)).body.providers[0]).toMatchObject({ state: "check-key" });
+ expect(fal.log.some((r) => r.path.endsWith("/status"))).toBe(true);
+ });
+
+ it("Replicate: the account (a user or an organization), credit gone, a refused token, a busy API", async () => {
+ expect(await repAnswer(200, fixture("replicate-account-200-org.json"))).toMatchObject({ state: "link", account: { name: "acme", kind: "organization", fullName: "Acme Corp, Inc." } });
+ expect(await repAnswer(200, fixture("replicate-account-200-user.json"))).toMatchObject({ state: "link", account: { name: "alice", kind: "user", fullName: "Alice" } });
+ expect(await repAnswer(402, { detail: "You have insufficient credit to run this model. Go to https://replicate.com/account/billing to purchase credit." })).toMatchObject({ state: "empty" });
+ expect(await repAnswer(401, fixture("replicate-401-bad-key.recorded.json"))).toMatchObject({ state: "check-key" });
+ expect(await repAnswer(429, fixture("replicate-429.json"))).toMatchObject({ state: "link" });
+ expect((await repAnswer(429, fixture("replicate-429.json"))).account).toBeUndefined();
+ });
+
+ it("spend: summed in one currency over its pages, and left out when it can't be whole", async () => {
+ const usage = async (pages: unknown[]) => {
+ let n = 0;
+ fal.script = (r) => (r.path.startsWith("/v1/models/usage") ? { status: 200, body: pages[Math.min(n++, pages.length - 1)] } : null);
+ clearKeyInfo();
+ return (await ask(ownerCookie, "?detail=1")).body.providers[0].spentThisMonth;
+ };
+ const row = (cost: number, currency = "USD") => ({ endpoint_id: "fal-ai/flux/dev", unit: "image", quantity: 1, cost_total: cost, cost, currency });
+ expect(await usage([fixture("fal-usage-200-summary.json")])).toEqual({ amount: 0.32, currency: "USD" });
+ expect(await usage([{ summary: [row(1.25)], has_more: true, next_cursor: "Mg==" }, { summary: [row(2)], has_more: false, next_cursor: null }])).toEqual({ amount: 3.25, currency: "USD" });
+ expect(await usage([{ summary: [row(1), row(2, "EUR")], has_more: false }])).toBeUndefined();
+ expect(await usage([{ summary: [row(1)], has_more: true, next_cursor: "Mg==" }])).toBeUndefined();
+ fal.script = (r) => (r.path.startsWith("/v1/models/usage") ? { status: 403, body: fixture("fal-billing-403-no-permission.json") } : null);
+ clearKeyInfo();
+ const r = await ask(ownerCookie, "?detail=1");
+ expect(r.body.providers[0].spentThisMonth).toBeUndefined();
+ expect(r.body.providers[0].balance).toEqual({ amount: 24.5, currency: "USD" });
+ });
+});