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.

Hosted runs in the studio: the price on Run, the balance chip, the place in line

Adarsh4cb11c87b861
diff --git a/src/app/providers.tsx b/src/app/providers.tsx
index 2a964351..3d2de78d 100644
--- a/src/app/providers.tsx
+++ b/src/app/providers.tsx
@@ -10,6 +10,8 @@ import { toast } from "sonner";
import { AUTH_CHANNEL, takeNotice, type ViewerInfo } from "@/lib/api";
/** The GPU pre-flight's guided fix: loaded after the page, listening for "fuobe:gpu-setup". */
+// A run the billing service refused (only on a studio that set one up): loaded when it is needed.
+const BillingCard = dynamic(() => import("@/components/billing-card").then((m) => m.BillingCard), { ssr: false });
const GuidedFixHost = dynamic(() => import("@/components/gpu/guided-fix").then((m) => m.GuidedFixHost), { ssr: false });
/** "Use the ComfyUI on this computer": runs the person's jobs from this browser while it's open. */
const ComputerRunnerHost = dynamic(() => import("@/components/gpu/computer-runner").then((m) => m.ComputerRunnerHost), { ssr: false });
@@ -55,6 +57,7 @@ export function Providers({ children }: { children: React.ReactNode }) {
<Toaster position="top-center" gap={8} offset={29} />
<GuestPrompt />
<AddKeyPrompt />
+ <BillingCard />
<GuidedFixHost />
<ComputerRunnerHost />
</TooltipProvider>
diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsx
index 64d22313..e95f2d63 100644
--- a/src/components/app-sidebar.tsx
+++ b/src/components/app-sidebar.tsx
@@ -46,6 +46,7 @@ import { awayFix, openConnect, useComputerSupport } from "@/components/gpu/open-
import { usePagePlace } from "@/components/gpu/use-page-place";
import { ownGpuOf, signInHref, signOut, useEngineMode, useHydrated, useStatus, useViewer, VIEWER_KEY, type StatusInfo } from "@/lib/api";
import { deviceLabel } from "@/lib/gpu/readiness";
+import { safeLink, useInterest } from "@/lib/hosted";
import { useModKey } from "@/lib/keys";
import { fullScreenStudio, groupId, NAV_CLOSED_KEY, navActive, NEW_CREATION_HREF, parseClosed, scrollFades, sidebarCookie, SIDEBAR_STATE_SCRIPT, sidebarOpenFromCookie } from "@/lib/nav";
import { cn } from "@/lib/utils";
@@ -436,7 +437,7 @@ function ViewerRow() {
* guest is sent to sign up first; anyone else without one opens "Connect your GPU"; a connected one says whether it
* answers.
*/
-function YourGpuChip({ gpu, guest }: { gpu: NonNullable<StatusInfo["viewer"]>["gpu"]; guest: boolean }) {
+function YourGpuChip({ gpu, guest, hosted }: { gpu: NonNullable<StatusInfo["viewer"]>["gpu"]; guest: boolean; hosted?: boolean }) {
const cls = "flex w-full flex-col gap-1 rounded-md px-2 py-1.5 text-left text-[12px] text-muted-foreground transition-colors hover:bg-accent group-data-[collapsible=icon]:hidden";
const g = gpu;
// ComfyUI on this computer is closed, or runs without Fuobe's setting: the finder, at that step (elsewhere: /connect).
@@ -467,7 +468,8 @@ function YourGpuChip({ gpu, guest }: { gpu: NonNullable<StatusInfo["viewer"]>["g
const body = (
<span className="flex items-center gap-2">
<StatusDot ok={false} /> Your GPU
- <span className="ml-auto font-medium text-brand-text">Connect</span>
+ {/* Runs go to this studio's GPUs too (hosted runs): one's own is an option. */}
+ <span className={cn("ml-auto font-medium", hosted ? "text-muted-foreground" : "text-brand-text")}>{hosted ? "Optional" : "Connect"}</span>
</span>
);
return guest ? (
@@ -481,6 +483,73 @@ function YourGpuChip({ gpu, guest }: { gpu: NonNullable<StatusInfo["viewer"]>["g
);
}
+/**
+ * The balance chip (a studio with a billing service, src/server/billing.ts): the service's own words for what the
+ * account has left and when it refills, and a menu with its detail lines, its links, its offer, and the way to run for
+ * free on one's own GPU or keys.
+ */
+function BalanceChip({ viewer }: { viewer: NonNullable<StatusInfo["viewer"]> }) {
+ const b = viewer.balance!;
+ const interest = useInterest();
+ const cls = "flex w-full flex-col gap-1 rounded-md px-2 py-1.5 text-left text-[12px] text-muted-foreground transition-colors hover:bg-accent group-data-[collapsible=icon]:hidden";
+ const refill = b.refillAt ? refillWords(b.refillAt) : null;
+ const action = safeLink(b.action?.url);
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button type="button" className={cls} aria-label={`${b.chip}${refill ? `, ${refill}` : ""}`}>
+ <span className="flex items-center gap-2">
+ <StatusDot ok={b.amount > 0} /> <span className="truncate font-medium text-foreground">{b.chip}</span>
+ {refill && <span className="ml-auto shrink-0">{refill}</span>}
+ </span>
+ {b.sub && <span className="truncate text-[11px]">{b.sub}</span>}
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent side="top" align="start" className="w-64">
+ <DropdownMenuLabel className="text-[12px] font-normal text-muted-foreground">{b.text}</DropdownMenuLabel>
+ {b.detail.map((d, i) => (
+ <div key={i} className="flex justify-between gap-3 px-2 py-1 text-[12px]">
+ <span className="text-muted-foreground">{d.label}</span>
+ <span className="text-right">{d.text}</span>
+ </div>
+ ))}
+ <DropdownMenuSeparator />
+ {action && b.action && (
+ <DropdownMenuItem asChild>
+ <a href={action} target={action.startsWith("/") ? undefined : "_blank"} rel="noopener noreferrer">
+ {b.action.label}
+ </a>
+ </DropdownMenuItem>
+ )}
+ {b.offer && <DropdownMenuItem onSelect={() => interest.mutate(b.offer!.key)}>{b.offer.label}</DropdownMenuItem>}
+ {(viewer.links ?? []).map((l, i) => {
+ const href = safeLink(l.url);
+ return href ? (
+ <DropdownMenuItem key={i} asChild>
+ <a href={href} target={href.startsWith("/") ? undefined : "_blank"} rel="noopener noreferrer">
+ {l.label}
+ </a>
+ </DropdownMenuItem>
+ ) : null;
+ })}
+ <DropdownMenuItem asChild>
+ <IntentLink href="/connect">
+ <Cpu /> Use your own GPU or keys (free)
+ </IntentLink>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+/** "refills in 5 h", in the visitor's own time. */
+function refillWords(at: number): string {
+ const ms = at - Date.now();
+ if (ms <= 0) return "refills soon";
+ const h = Math.round(ms / 3_600_000);
+ return h >= 1 ? `refills in ${h} h` : `refills in ${Math.max(1, Math.round(ms / 60_000))} min`;
+}
+
/**
* Who is signed in (public sign-up): an account's email, with Settings, Your GPU and Sign out. Nothing
* for the owner or a guest. In the rail it's the initial alone; on a phone the menu opens upward. Until hydrated it is
@@ -635,7 +704,11 @@ export function AppSidebar() {
<SidebarFooter className="gap-1 border-t border-sidebar-border" onClick={closeOnLink}>
{computer && <ComputerNote />}
{status?.viewer ? (
- <YourGpuChip gpu={status.viewer.gpu} guest={status.viewer.kind === "guest"} />
+ status.viewer.balance ? (
+ <BalanceChip viewer={status.viewer} />
+ ) : (
+ <YourGpuChip gpu={status.viewer.gpu} guest={status.viewer.kind === "guest"} hosted={!!status.viewer.hosted} />
+ )
) : ownerGpu ? (
<>
{mode !== "open" && (
diff --git a/src/components/billing-card.tsx b/src/components/billing-card.tsx
new file mode 100644
index 00000000..9ad0f590
--- /dev/null
+++ b/src/components/billing-card.tsx
@@ -0,0 +1,84 @@
+"use client";
+
+import { useQueryClient } from "@tanstack/react-query";
+import { Cpu, ExternalLink, Gauge } from "lucide-react";
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { BILLING_EVENT, safeLink, useInterest, type BillingRefusalDetail } from "@/lib/hosted";
+
+/**
+ * One card for a run the billing service refused (x-fuobe-billing; src/server/billing.ts): the service's own words,
+ * its link (opened as given) or its offer ("Tell me when"), and the way to run for free on one's own GPU. A changed
+ * price shows the new one; Run again sends it. Mounted once, in the app's providers. Public code has no words of its
+ * own about prices: they all come from the service.
+ */
+export function BillingCard() {
+ const [refusal, setRefusal] = useState<BillingRefusalDetail | null>(null);
+ const [open, setOpen] = useState(false);
+ const interest = useInterest();
+ const qc = useQueryClient();
+ useEffect(() => {
+ const onRefusal = (e: Event) => {
+ const d = (e as CustomEvent<BillingRefusalDetail>).detail;
+ setRefusal(d);
+ setOpen(true);
+ // A new price (or the balance it was refused for): the composer and the chip ask again.
+ void qc.invalidateQueries({ queryKey: ["hosted-quote"] });
+ void qc.invalidateQueries({ queryKey: ["status"] });
+ };
+ window.addEventListener(BILLING_EVENT, onRefusal);
+ return () => window.removeEventListener(BILLING_EVENT, onRefusal);
+ }, [qc]);
+ const r = refusal;
+ const link = safeLink(r?.action?.url);
+ const changed = r?.code === "price-changed";
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent className="sm:max-w-sm">
+ <DialogHeader>
+ <div className="mb-1 grid size-10 place-items-center rounded-xl bg-primary text-primary-foreground">
+ <Gauge className="size-5" />
+ </div>
+ <DialogTitle>{changed ? "The price changed" : "This run didn't start"}</DialogTitle>
+ <DialogDescription>{r?.error}</DialogDescription>
+ {changed && r?.quote?.text && (
+ <p className="text-[13px] text-muted-foreground">
+ Now: <span className="font-medium text-foreground">{r.quote.text}</span>
+ {r.quote.sub ? ` · ${r.quote.sub}` : ""}. Press Generate again to run it at this price.
+ </p>
+ )}
+ {r?.offer && <p className="text-[13px] text-muted-foreground">{r.offer.text}</p>}
+ </DialogHeader>
+ <DialogFooter className="gap-2 sm:justify-between">
+ <Button asChild variant="ghost" size="sm" onClick={() => setOpen(false)}>
+ <Link href="/connect">
+ <Cpu /> Use your own GPU (free)
+ </Link>
+ </Button>
+ <div className="flex gap-2">
+ {r?.offer && (
+ <Button size="sm" variant="secondary" disabled={interest.isPending} onClick={() => interest.mutate(r.offer!.key, { onSuccess: () => setOpen(false) })}>
+ {r.offer.label}
+ </Button>
+ )}
+ {link && r?.action && (
+ <Button asChild size="sm">
+ <a href={link} target={link.startsWith("/") ? undefined : "_blank"} rel="noopener noreferrer">
+ {r.action.label}
+ {!link.startsWith("/") && <ExternalLink />}
+ </a>
+ </Button>
+ )}
+ {!link && !r?.offer && (
+ <Button size="sm" onClick={() => setOpen(false)}>
+ OK
+ </Button>
+ )}
+ </div>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/home/home-islands.tsx b/src/components/home/home-islands.tsx
index 9e2f4918..51563256 100644
--- a/src/components/home/home-islands.tsx
+++ b/src/components/home/home-islands.tsx
@@ -234,7 +234,8 @@ export function StartSteps() {
},
{
title: "Sign up free.",
- text: "A free account runs open models on your own GPU, never on ours.",
+ // Hosted runs on: runs may go to this studio's GPUs too.
+ text: viewer?.hosted ? "Runs on this studio's GPUs, or on your own." : "A free account runs open models on your own GPU, never on ours.",
action:
viewer?.kind === "account" ? (
done("You’re signed in")
diff --git a/src/components/login-form.tsx b/src/components/login-form.tsx
index af1d54e3..e4a95d5e 100644
--- a/src/components/login-form.tsx
+++ b/src/components/login-form.tsx
@@ -6,7 +6,7 @@ import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
-import { announceAuthChange, rememberViewer, signOut, useViewer } from "@/lib/api";
+import { announceAuthChange, rememberViewer, signOut, useStatus, useViewer } from "@/lib/api";
import { safeNext } from "@/lib/safe-redirect";
import { cn } from "@/lib/utils";
@@ -27,6 +27,7 @@ export function LoginForm() {
const router = useRouter();
const pathname = usePathname();
const viewer = useViewer();
+ const status = useStatus();
const open = !!viewer.data?.publicSignup;
const [chosen, setChosen] = useState<Mode | null>(null);
const mode: Mode = !open ? "owner" : (chosen ?? (params.get("owner") === "1" ? "owner" : params.get("signup") === "1" ? "signup" : "login"));
@@ -57,6 +58,8 @@ export function LoginForm() {
router.replace(s ? `${pathname}?${s}` : pathname, { scroll: false });
};
+ // Hosted runs (this studio's GPUs take an account's runs): a new account isn't sent to connect a GPU first.
+ const hosted = !!status.data?.viewer?.hosted;
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
@@ -71,7 +74,8 @@ export function LoginForm() {
// Settings' Your GPU (its Sign up free): the welcome page is that same choice.
const q = new URLSearchParams({ welcome: "1" });
if (after !== "/" && !after.startsWith("/connect") && !after.startsWith("/settings#your-gpu")) q.set("next", after);
- const dest = mode === "signup" ? new URL(`/connect?${q}`, window.location.origin).toString() : after;
+ // With hosted runs on, a GPU of its own is optional: straight back to where it was.
+ const dest = mode === "signup" && !hosted ? new URL(`/connect?${q}`, window.location.origin).toString() : after;
rememberViewer(mode === "owner" ? "owner" : "account");
announceAuthChange();
window.location.assign(dest);
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index 1e2f70a3..558a27af 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -17,6 +17,7 @@ import { dualEngine } from "@/lib/catalog/engines";
import { locksByDefault } from "@/lib/catalog/palettes";
import { DEFAULT_LOOK, lookCard } from "@/lib/catalog/soul-cards";
import { formatsOf } from "@/lib/av/formats";
+import { quoteBody, useHostedQuote, useSettled, type RunOn } from "@/lib/hosted";
import { CONNECT_GPU_EVENT, enhance, useClipFacts, useCreateGeneration, useElements, useEngine, useHydrated, useStatus } from "@/lib/api";
import { usePagePlace } from "@/components/gpu/use-page-place";
import { applyMentions, type StudioElement } from "@/lib/catalog/elements";
@@ -552,6 +553,18 @@ export function Composer({ docked }: { docked: boolean }) {
return { mentions, sketched, signed, request: m ? stripMotionPaths(sketched.request, m) : sketched.request };
};
const { mentions, sketched, signed } = prepare(draft);
+ // Hosted runs: an open model may run on this studio's GPUs. Its price there is the server's (the words of the
+ // studio's billing service, or free), asked again 300 ms after a change. With the account's own GPU online, that
+ // GPU is the default; the person can pick either.
+ const viewerInfo = status?.viewer;
+ const ownOnline = !!viewerInfo?.gpu.connected && !!viewerInfo.gpu.online;
+ const [runOnPick, setRunOn] = useState<RunOn | null>(null);
+ const runOn: RunOn = runOnPick ?? (ownOnline ? "own" : "pool");
+ const hostedHere = !!viewerInfo?.hosted && model?.engine === "open";
+ const poolPrice = hostedHere && runOn === "pool";
+ const priceBody = useSettled(poolPrice ? quoteBody(signed.request, runOn) : null);
+ const hostedQuote = useHostedQuote(priceBody).data?.quote;
+ const priceUnavailable = poolPrice && hostedQuote?.code === "paused";
const resolvesOnServer = mentions.mentioned.length > 0 || !!draft.slots.mask?.ref || !!draft.slots.sketch?.ref;
// Plan with stand-ins for attachments that are missing or still uploading, so the cost and the
@@ -685,7 +698,10 @@ export function Composer({ docked }: { docked: boolean }) {
() => submitRef.current(true),
model?.kind,
);
- create.mutate(skipGpu ? ({ ...sent.request, gpuCheck: "skip" } as typeof sent.request) : sent.request, {
+ // Hosted runs: where it should go, and the price shown (the server checks both; a higher price comes back to confirm).
+ const hosted = viewerInfo?.hosted ? { place: runOn, ...(poolPrice && hostedQuote && { shown: { amount: hostedQuote.amount, priceVersion: hostedQuote.priceVersion } }) } : {};
+ const body = { ...sent.request, ...hosted, ...(skipGpu && { gpuCheck: "skip" }) } as typeof sent.request;
+ create.mutate(body, {
// Accepted: nothing to try again (a card opened later never starts this run a second time).
onSuccess: () => dropGpuRetry(),
// Stopped by the GPU pre-flight, or refused with its own card: the guided fix or the card is open already, so no error toast on top.
@@ -751,11 +767,14 @@ export function Composer({ docked }: { docked: boolean }) {
const alternativeHref = alternative && `${alternative.href}${video?.startsWith("/api/files/") ? `&video=${encodeURIComponent(video)}` : ""}`;
const demo = !!(model && placeholdersOn(status?.demoMode));
// On the open engine every run is free on the GPU: said even before the run can be planned (no voice sample, no clip yet).
- const costText = costLabel({ demo, cost: cost ?? (engine === "open" && model ? 0 : null), unknown: loraPriceUnknown }, formatCost);
+ const ownCostText = costLabel({ demo, cost: cost ?? (engine === "open" && model ? 0 : null), unknown: loraPriceUnknown }, formatCost);
// An account's paid run is billed to its own provider account (Your keys), or still needs that key.
const payer = paidThrough(model, status);
const missingKey = needsKey(model, status)?.[0];
- const payerText = payer && cost ? ` · ${billedTo(payer)}` : missingKey ? ` · ${addKeyLabel(missingKey).toLowerCase()}` : "";
+ const ownPayerText = payer && cost ? ` · ${billedTo(payer)}` : missingKey ? ` · ${addKeyLabel(missingKey).toLowerCase()}` : "";
+ // On this studio's GPUs: the quote's words (none from the server: free, as the open engine always is).
+ const costText = poolPrice ? (priceUnavailable ? "Price unavailable" : hostedQuote?.text || ownCostText) : ownCostText;
+ const payerText = poolPrice ? "" : ownPayerText;
// Attachments: only when something is attached, a required slot is still empty, or none of a "one of these" group is filled (U8).
const kinds = [...attach.kinds];
@@ -1276,11 +1295,22 @@ export function Composer({ docked }: { docked: boolean }) {
/>
<span className="contents max-sm:hidden">{styleChips}</span>
</div>
+ {hostedHere && viewerInfo?.gpu.connected && (
+ <button
+ type="button"
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => setRunOn(runOn === "own" ? "pool" : "own")}
+ aria-label={`Runs on ${runOn === "own" ? "your GPU" : "this studio's GPUs"}. Switch`}
+ className="shrink-0 rounded-md px-1.5 py-0.5 text-[12px] text-muted-foreground underline decoration-border-strong underline-offset-2 hover:text-foreground"
+ >
+ {runOn === "own" ? "Your GPU" : "This studio's GPUs"}
+ </button>
+ )}
{costText && (
<Tooltip>
<TooltipTrigger asChild>
<span className="shrink-0 text-[12px] font-medium text-muted-foreground tabular-nums">
- <span className="sm:hidden">{costLabel({ demo, cost, compact: true, unknown: loraPriceUnknown }, formatCost)}</span>
+ <span className="sm:hidden">{poolPrice ? costText : costLabel({ demo, cost, compact: true, unknown: loraPriceUnknown }, formatCost)}</span>
<span className="hidden sm:inline">
{costText}
{payerText}
@@ -1288,7 +1318,11 @@ export function Composer({ docked }: { docked: boolean }) {
</span>
</TooltipTrigger>
<TooltipContent className="max-w-72">
- {demo
+ {poolPrice
+ ? priceUnavailable
+ ? "Runs on this studio's GPUs are paused for a moment. Try again soon, or run on your own GPU."
+ : (hostedQuote?.sub ?? "Runs on this studio's GPUs")
+ : demo
? "Placeholder results are on (Settings), so outputs are free stand-ins"
: cost === 0
? "Runs on your own GPU"
@@ -1307,7 +1341,7 @@ export function Composer({ docked }: { docked: boolean }) {
<Button
size="icon"
onClick={submit}
- disabled={create.isPending || signature.lock.isPending}
+ disabled={create.isPending || signature.lock.isPending || priceUnavailable}
aria-label={blocker ? `Generate — ${blocker.message}` : "Generate"}
// Blocked, it stays the brand colour (paler, the arrow still 3:1 or more): pressing it still says what's missing and points at it.
className={cn("size-10 shrink-0 rounded-full", blocker && "bg-primary/70 hover:bg-primary/80")}
diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsx
index a0427973..afa7d57d 100644
--- a/src/components/studio/feed.tsx
+++ b/src/components/studio/feed.tsx
@@ -1,6 +1,7 @@
"use client";
import { Cloud, Copy, Cpu, Download, FolderDown, Heart, MoreHorizontal, RotateCcw, Sparkles, Trash2, Wrench, X } from "lucide-react";
+import { lineWords } from "@/lib/hosted";
import { openGpuSetup } from "@/hooks/use-gpu";
import { useLocalJob } from "@/components/gpu/computer-runner";
import { jobFraction, jobWords } from "@/lib/relay";
@@ -333,7 +334,16 @@ export const GenerationGroup = memo(function GenerationGroup({ g, newest }: { g:
))}
<span className="before:mr-1.5 before:content-['·']">{timeAgo(g.createdAt)}</span>
{/* A run its provider never took (a refused key, an empty balance) cost nothing: said, not priced. */}
- {g.costUsd && g.notBilled ? (
+ {/* On this studio's GPUs (hosted runs): the billing service's words for its charge, or that it cost nothing. */}
+ {g.queue ? <span className="before:mr-1.5 before:content-['·']">{lineWords(g.queue)}</span> : null}
+ {g.stage === "checking" ? <span className="before:mr-1.5 before:content-['·']">Checking</span> : null}
+ {g.place === "pool" ? (
+ g.notCharged ? (
+ <span className="before:mr-1.5 before:content-['·']">Not charged</span>
+ ) : g.charge ? (
+ <span className="before:mr-1.5 before:content-['·']">{g.charge}</span>
+ ) : null
+ ) : g.costUsd && g.notBilled ? (
<span className="before:mr-1.5 before:content-['·']">Not billed</span>
) : g.costUsd ? (
<span className="font-mono before:mr-1.5 before:content-['·']">{formatCost(g.costUsd)}</span>
diff --git a/src/lib/api.ts b/src/lib/api.ts
index c2ddecf5..8bdfec9a 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -31,6 +31,7 @@ import { postFile } from "./upload";
import type { ShareCreated, ShareInfo, ShareListItem, SharePatch, ShareRequest } from "./share";
import type { AccessSummary } from "./model-access";
import { ADD_KEY_HEADER, isCloudProvider, type CloudProvider } from "./your-keys";
+import { BILLING_EVENT, BILLING_HEADER, type BillingAction, type BillingRefusalDetail, type HostedBalance } from "./hosted";
export interface Asset {
id: string;
@@ -846,6 +847,12 @@ export interface StatusInfo {
gpu: { connected: boolean; mode?: "computer" | "link"; online?: boolean; comfy?: "down" | "no-setting"; device?: string; vramBytes?: number };
keys?: CloudProvider[];
paidAllowed?: boolean;
+ /** Hosted runs (FUOBE_HOSTED_RUNS=1): runs may go to this studio's GPUs, so a GPU of one's own is optional. */
+ hosted?: boolean;
+ /** The billing service's words for the account's balance (src/server/billing.ts). */
+ balance?: HostedBalance;
+ links?: BillingAction[];
+ notice?: { id: string; text: string; url?: string };
};
/**
* The owner's ComfyUI runs on the owner's computer (Settings): what the owner's Fuobe tab there last said. Never
@@ -1295,7 +1302,8 @@ export function askToSignUp(action: RefusalAction = "upload"): void {
export function useAskBeforeUpload(): () => boolean {
const guest = useIsGuest();
const seen = useStatus().data?.viewer;
- const nowhere = seen?.kind === "account" && !seen.gpu.connected && !seen.keys?.length;
+ // With hosted runs on, an account adds pictures for runs on this studio's GPUs: the upload says if a kind isn't taken.
+ const nowhere = seen?.kind === "account" && !seen.gpu.connected && !seen.keys?.length && !seen.hosted;
return useCallback(() => {
if (guest) askToSignUp("upload");
else if (nowhere) window.dispatchEvent(new CustomEvent<RefusalDetail>(CONNECT_GPU_EVENT, { detail: { action: "upload" } }));
@@ -1352,6 +1360,16 @@ export function watchGuestRefusals(): void {
markRefusalShown(res);
window.dispatchEvent(new CustomEvent(ADD_KEY_EVENT, { detail: { provider: addKey } }));
}
+ // A run the billing service refused (its own words, and a link or an offer): the billing card opens.
+ const billing = res.status >= 400 ? res.headers.get(BILLING_HEADER) : null;
+ if (billing && refusalCard("gpu", window.location)) {
+ markRefusalShown(res);
+ res
+ .clone()
+ .json()
+ .then((b: Omit<BillingRefusalDetail, "code">) => window.dispatchEvent(new CustomEvent<BillingRefusalDetail>(BILLING_EVENT, { detail: { ...b, code: billing } })))
+ .catch(() => {});
+ }
// A run the GPU pre-flight stopped (something missing on the viewer's ComfyUI): the guided fix opens with its plan.
if (res.status === 409 && res.headers.get("x-fuobe-gpu-setup") === "1") {
res
diff --git a/src/lib/hosted.ts b/src/lib/hosted.ts
new file mode 100644
index 00000000..6d0a6e9a
--- /dev/null
+++ b/src/lib/hosted.ts
@@ -0,0 +1,132 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { useMutation, useQuery } from "@tanstack/react-query";
+import { toast } from "sonner";
+import type { GenerationRequest } from "./catalog/types";
+
+/**
+ * The browser's side of hosted runs and the optional billing service (src/server/hosted.ts, src/server/billing.ts).
+ * Every word about a price or a balance comes from the server at runtime: the billing service's own words.
+ */
+
+export interface BillingAction {
+ label: string;
+ url: string;
+}
+
+export interface BillingOffer {
+ key: string;
+ text: string;
+ label: string;
+}
+
+/** The billing service's quote for a run on this studio's GPUs (no service: free, `text` empty). */
+export interface HostedQuote {
+ allowed: boolean;
+ amount: number;
+ priceVersion: string;
+ text: string;
+ sub?: string;
+ code?: string;
+ etaS?: number | null;
+ action?: BillingAction;
+ offer?: BillingOffer;
+}
+
+/** The billing service's words for an account's balance (the sidebar chip and its menu). */
+export interface HostedBalance {
+ amount: number;
+ chip: string;
+ text: string;
+ sub?: string;
+ refillAt?: number | null;
+ detail: { label: string; text: string }[];
+ action?: BillingAction;
+ offer?: BillingOffer;
+}
+
+/** A run the billing service refused (x-fuobe-billing): its words, and what the person can do next. */
+export interface BillingRefusalDetail {
+ code: string;
+ error: string;
+ action?: BillingAction;
+ offer?: BillingOffer;
+ quote?: HostedQuote;
+}
+
+/** Fired for every refusal marked x-fuobe-billing (watchGuestRefusals): the billing card opens. */
+export const BILLING_EVENT = "fuobe:billing";
+
+/** The header a billing refusal carries. */
+export const BILLING_HEADER = "x-fuobe-billing";
+
+/** "Run on": the account's own GPU, or this studio's. */
+export type RunOn = "own" | "pool";
+
+/** A link the service sent is opened as given, only when it is a plain https (or same-site) link. */
+export function safeLink(url: string | undefined): string | undefined {
+ if (!url) return undefined;
+ if (url.startsWith("/") && !url.startsWith("//")) return url;
+ try {
+ return new URL(url).protocol === "https:" ? url : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** A value that settles 300 ms after it stops changing (the composer asks for a new price then, not on every key). */
+export function useSettled<T>(value: T, ms = 300): T {
+ const [v, setV] = useState(value);
+ useEffect(() => {
+ const t = setTimeout(() => setV(value), ms);
+ return () => clearTimeout(t);
+ }, [value, ms]);
+ return v;
+}
+
+/**
+ * The price of a run on this studio's GPUs: `?preview=1` with `place: "pool"`. `body` is the request as JSON (null:
+ * nothing to price). The answer's `quote` is absent when the run would go to the person's own GPU or key.
+ */
+export function useHostedQuote(body: string | null) {
+ return useQuery({
+ queryKey: ["hosted-quote", body],
+ enabled: !!body,
+ staleTime: 10_000,
+ retry: false,
+ queryFn: async (): Promise<{ place?: "pool"; quote?: HostedQuote } | null> => {
+ const res = await fetch("/api/generations?preview=1", { method: "POST", headers: { "Content-Type": "application/json" }, body: body! });
+ if (!res.ok) return null;
+ const b = (await res.json()) as { place?: "pool"; quote?: HostedQuote };
+ return { place: b.place, quote: b.quote };
+ },
+ });
+}
+
+/** The request as the price check sends it: the run, plus where it should go. */
+export function quoteBody(req: GenerationRequest | null, runOn: RunOn): string | null {
+ return req ? JSON.stringify({ ...req, place: runOn }) : null;
+}
+
+/** "Tell me when": an offer's click goes to the billing service, which counts it. */
+export function useInterest() {
+ return useMutation({
+ mutationFn: async (key: string) => {
+ const res = await fetch("/api/billing/interest", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ key }) });
+ const b = (await res.json().catch(() => ({}))) as { text?: string; error?: string };
+ if (!res.ok) throw new Error(b.error ?? "Not available right now");
+ return b.text ?? "Thanks.";
+ },
+ onSuccess: (text) => toast.success(text),
+ onError: (e) => toast.error((e as Error).message),
+ });
+}
+
+/** "In line · 3rd · about 40 s": a waiting run's place on this studio's GPUs. */
+export function lineWords(q: { place: number; etaSeconds: number | null }): string {
+ const n = q.place;
+ const ord = n % 100 >= 11 && n % 100 <= 13 ? "th" : ({ 1: "st", 2: "nd", 3: "rd" } as Record<number, string>)[n % 10] ?? "th";
+ const eta = q.etaSeconds === null ? "" : q.etaSeconds < 60 ? ` · about ${Math.max(5, Math.round(q.etaSeconds / 5) * 5)} s` : ` · about ${Math.round(q.etaSeconds / 60)} min`;
+ return n === 1 ? `Next in line${eta}` : `In line · ${n}${ord}${eta}`;
+}
diff --git a/tests/hosted-runs.test.ts b/tests/hosted-runs.test.ts
index bc469150..8080185c 100644
--- a/tests/hosted-runs.test.ts
+++ b/tests/hosted-runs.test.ts
@@ -66,7 +66,7 @@ const post = (body: unknown) => {
return generationsRoute.POST(new Request("http://localhost:3000/api/generations", { method: "POST", headers: headers({ "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }), body: text }));
};
const upload = (bytes: Buffer, type: string, name: string) =>
- uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: headers({ "content-type": type, "x-file-name": name, "content-length": String(bytes.length) }), body: bytes }));
+ uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: headers({ "content-type": type, "x-file-name": name, "content-length": String(bytes.length) }), body: new Uint8Array(bytes) }));
describe("hosted runs off (the default)", () => {
it("an account with no GPU or key: runs and uploads say Connect your GPU, and the status says nothing new", async () => {