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.

Where runs go: one order, a Run on list, and a pick kept for every device

Adarshabca84d7dbbf
diff --git a/docs/SELF-HOSTING.md b/docs/SELF-HOSTING.md
index 108615f4..d4d3e2dc 100644
--- a/docs/SELF-HOSTING.md
+++ b/docs/SELF-HOSTING.md
@@ -136,7 +136,7 @@ A file that looks like the note but was changed (it has a password or a sign-in
| `WORLDCAST_URL`, `WORLDCAST_TOKEN` | The WorldCast worker's address (also a Settings field) and its shared secret, sent as a Bearer header on every call; set the same `WORLDCAST_TOKEN` where the worker runs. The token has no Settings field yet. Without one, keep the worker on `127.0.0.1` ([worldcast.md](workers/worldcast.md)) |
| `FUOBE_HOSTED_RUNS=1` | With public sign-up: accounts with no GPU of their own may run on this install's GPUs: its workers, or its own ComfyUI when that is on this machine ([Hosted runs](public-signup.md#hosted-runs)). Off by default. A billing service or `FUOBE_HOSTED_FREE=1` must answer for these runs |
| `FUOBE_HOSTED_FREE=1` | With no billing service: hosted runs are free for every account, within the install's own limits. Without it (and without a billing service) hosted runs stay closed |
-| `FUOBE_PLACE_NAME` | The name visitors read for this install's GPUs while hosted runs are on ("Runs on Ana's render box", "Made on: Ana's render box"), at most 40 characters. Also Settings → Workers → Name for your GPUs, which wins over it; a billing service's own name for them wins over both. Unset: "Our GPUs". Nothing reads it while hosted runs are off |
+| `FUOBE_PLACE_NAME` | The name visitors read for this install's GPUs while hosted runs are on ("Runs on Ana's render box", "Made on: Ana's render box"), at most 40 characters. Also Settings → Workers → Name for your GPUs, which wins over it; a billing service's own name for them wins over both. Unset: "Our GPUs". Nothing reads it while hosted runs are off. The table that keeps where each account picked its runs to go (`account_run_on`) is made on every install and stays empty, and unread, while hosted runs are off |
| `FUOBE_POOL_WAIT_MIN` | How long a hosted run may wait in line before a GPU first takes it, in minutes (default `30`) |
| `FUOBE_POOL_MEDIA_INPUTS` | The kinds of input file a run on the workers may send them, comma-separated: `image` (default) or `image,video,audio`. Clips and sound go only to workers that make each clip and sound again before their ComfyUI reads it (worker protocol 2 with ffmpeg set, [Clips and sound](gpu-workers.md#clips-and-sound)). A hosted run takes a kind only when this and the billing service's policy (`uploads`) both allow it, so set it together with `FUOBE_HOSTED_RUNS` and `FUOBE_BILLING_URL` when the policy opens clips and sound |
| `FUOBE_CATALOG_VERSION` | The catalog version accounts' job tickets are made for ([Job tickets and the PC's ceiling](gpu-workers.md#job-tickets-and-the-pcs-ceiling)), as 64 hex characters. Unset: the studio computes it from its own composer and catalog files, which is what a server running from its own checkout wants. Set it only when the server runs without those files |
diff --git a/docs/public-signup.md b/docs/public-signup.md
index 2494035f..c02390ba 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -650,8 +650,27 @@ With it on:
one price. The run goes to this install's GPUs: its workers, when Settings says ComfyUI runs on workers
([gpu-workers.md](gpu-workers.md)), or else its own ComfyUI server, only when that is on this machine. An install
whose ComfyUI runs on the owner's computer doesn't offer hosted runs.
-- An account whose own GPU is online runs there by default. The composer shows where a run goes ("Your GPU", or the
- place name of this install's GPUs), and the person can pick either.
+- Where an account's runs go is one order: a place the run names (a one-off "Run on …", Retry, which goes back to
+ where the run ran), then what only one place can run (a model this install's GPUs don't take runs on the account's
+ own GPU; a cloud-only model on its key), then the account's own pick, then the install's default. With no pick, an
+ account whose own GPU is online runs there first, unless the billing service's policy puts this install's GPUs first
+ (`prefer: "pool"`).
+- **Run on**: for an account with a choice for an item (its GPU, or a key that runs the item's cloud version), the
+ composer's price chip opens a list ("Free ▾"): this install's GPUs, Your GPU (with a green dot while it answers; it
+ can be picked while it doesn't, and the check before Run then offers **Run on …** for that run), and Your fal.ai or
+ Replicate key with its price. A tool page's place chip lists the same rows, and Settings → Your GPU starts with
+ **Where your runs go**. A pick applies at once and holds for the account's later runs on every device: it is kept on
+ the server (`PUT /api/account/run-on`, `src/server/run-on.ts`), sent in the status to that account only, and read by
+ every run and price check that names no place. A pick of the account's GPU sends its runs there without asking,
+ even while it doesn't answer; a pick of this install's GPUs or of the key sends open runs here first (the key runs
+ what has a cloud version, on the Cloud engine). Forgetting the GPU or removing the key drops a pick of it ("Your runs
+ go to … now."), and a deleted account's pick goes with it.
+- An account that ran on its own GPU or key before hosted runs went on (and has picked nothing since) sees one note
+ above its run button, in a studio or on a tool page: "Runs now go to …, free." with **Keep my GPU as the default**
+ (or key) and **OK**. Both keep a pick, so the note shows once for the account, on any device.
+- A connected GPU runs what this install's GPUs don't take with the first press ("Free · your GPU"). A key runs such an
+ item only when the key is the account's pick; otherwise the press shows "Run with your fal.ai key · ≈ $0.04" (one run,
+ its price first) and Connect your GPU. A key is never billed by a press that showed "Free".
- Visitors read this install's GPUs by one place name: "Runs on our GPUs", "Made on: Our GPUs", "Run on Our GPUs".
The billing service's policy sets it (`placeName`); without one, Settings → Workers → Name for your GPUs, else
`FUOBE_PLACE_NAME`, else "Our GPUs". It is never sent while hosted runs are off.
@@ -695,7 +714,8 @@ Two optional services can go with it:
The code is `src/server/hosted.ts` (the switch, the place, the line), `src/server/hosted-run.ts` (the run route's side
and the gate), `src/server/account-tool-run.ts` (a tool's run), `src/server/run-stamp.ts` (what every row of a run
-carries) and `src/lib/hosted.ts` (the browser's side). The tests are `tests/hosted-runs.test.ts`,
+carries), `src/server/run-on.ts` (the account's pick of where its runs go) and `src/lib/hosted.ts` (the browser's
+side). The tests are `tests/hosted-runs.test.ts`, `tests/run-on.test.ts`,
`tests/hosted-tool-runs.test.ts`, `tests/pool-account-runs.test.ts`, `tests/billing-hook.test.ts`,
`tests/billing-release.test.ts` and `tests/moderation-hook.test.ts`.
diff --git a/src/app/api/account/gpu/route.ts b/src/app/api/account/gpu/route.ts
index 579ad1c2..2596253e 100644
--- a/src/app/api/account/gpu/route.ts
+++ b/src/app/api/account/gpu/route.ts
@@ -7,7 +7,9 @@ import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES } from "@/server/account-files";
import { clearAccountLoras } from "@/server/account-loras";
import { forgetComputer } from "@/server/computer/tasks";
import { dropSnapshots } from "@/server/gpu/snapshots";
+import { poolReady } from "@/server/hosted";
import { hit } from "@/server/rate";
+import { clearRunOnFor } from "@/server/run-on";
/**
* "Your GPU" (public sign-up): the account's own ComfyUI, where its runs go. Either the ComfyUI on the person's own
@@ -129,5 +131,7 @@ export async function DELETE(request: Request) {
setAccountGpu(a.id, null);
clearAccountLoras(a.id);
forgetComputer(`acct:${a.id}`);
- return Response.json({ gpu: null });
+ // Its runs went to this GPU by its own pick (hosted runs): that pick goes, and the page says where runs go now.
+ const runOnCleared = poolReady() && clearRunOnFor(a.id, { gpu: true });
+ return Response.json({ gpu: null, ...(runOnCleared && { runOnCleared: true }) });
}
diff --git a/src/app/api/account/keys/[provider]/route.ts b/src/app/api/account/keys/[provider]/route.ts
index e6b9ad2d..c9e3e043 100644
--- a/src/app/api/account/keys/[provider]/route.ts
+++ b/src/app/api/account/keys/[provider]/route.ts
@@ -2,7 +2,9 @@ import { z } from "zod";
import { isCloudProvider, NOT_ACCOUNT_KEYS, type CloudProvider } from "@/lib/your-keys";
import { accountKeyInfo, cleanKey, removeAccountKey, saveAccountKey } from "@/server/account-keys";
import { accountKeyRecord, LoginGuard, requestAccount } from "@/server/auth";
+import { poolReady } from "@/server/hosted";
import { hit, unhit } from "@/server/rate";
+import { clearRunOnFor } from "@/server/run-on";
import { SecretBoxError } from "@/server/secret-box";
import { checkKey, runsGoingMessage, runsOnKey, stopRunsOnKey } from "@/server/your-keys";
@@ -91,5 +93,8 @@ export async function DELETE(request: Request, ctx: RouteContext<"/api/account/k
if (going.length && !stopRuns) return answer(409, { code: "runs-going", count: going.length, error: runsGoingMessage(going.length, false) });
if (going.length) await stopRunsOnKey(id, provider);
removeAccountKey(id, provider);
- return answer(200, { keys: accountKeyInfo(id) });
+ // Its runs went to this key by its own pick (hosted runs): with no key left for it, that pick goes, and the page says
+ // where runs go now.
+ const runOnCleared = poolReady() && clearRunOnFor(id, { key: provider });
+ return answer(200, { keys: accountKeyInfo(id), ...(runOnCleared && { runOnCleared: true }) });
}
diff --git a/src/app/api/account/run-on/route.ts b/src/app/api/account/run-on/route.ts
new file mode 100644
index 00000000..2b9d2211
--- /dev/null
+++ b/src/app/api/account/run-on/route.ts
@@ -0,0 +1,56 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { requestAccount, accountGpu } from "@/server/auth";
+import { accountProviders } from "@/server/account-keys";
+import { poolReady } from "@/server/hosted";
+import { runOnOf, setRunOn, type RunOnPick } from "@/server/run-on";
+
+/**
+ * Where an account's runs go (hosted runs on): this install's GPUs ("site"), its own GPU ("gpu"), or its own fal.ai or
+ * Replicate key ("key", for what has a cloud version; `key` names the provider). The Run on list, Settings → Your GPU and
+ * the one-time note write it; every later run that names no place follows it, on every device. GET reads it (none: the
+ * install's default). Accounts only, each its own. While hosted runs are off this route doesn't exist (404).
+ */
+const NO_STORE = { "Cache-Control": "no-store" };
+const answer = (status: number, body: Record<string, unknown>) => Response.json(body, { status, headers: NO_STORE });
+const notHere = () => answer(404, { error: "Not found" });
+
+const Body = z
+ .object({
+ runOn: z.enum(["site", "gpu", "key"]),
+ key: z.enum(["fal", "replicate"]).optional(),
+ })
+ .strict();
+
+const shown = (pick: RunOnPick | null) => (pick ? { runOn: pick.runOn, ...(pick.runKey && { runKey: pick.runKey }) } : { runOn: null });
+
+export async function GET(request: Request): Promise<Response> {
+ await connection();
+ if (!poolReady()) return notHere();
+ const a = requestAccount(request);
+ if (!a) return notHere();
+ return answer(200, shown(runOnOf(a.id)));
+}
+
+export async function PUT(request: Request): Promise<Response> {
+ if (!poolReady()) return notHere();
+ const a = requestAccount(request);
+ if (!a) return notHere();
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return answer(400, { error: "Pick where your runs go." });
+ const { runOn, key } = parsed.data;
+ // Only a place the account has: its GPU connected, its key saved (the provider it names, else its first).
+ if (runOn === "gpu" && !accountGpu(a.id))
+ return answer(409, {
+ error: "Connect your GPU first.",
+ code: "connect-gpu",
+ });
+ let runKey: RunOnPick["runKey"];
+ if (runOn === "key") {
+ const keys = accountProviders(a.id);
+ runKey = key && keys.includes(key) ? key : keys.includes("fal") ? "fal" : keys[0];
+ if (!runKey) return answer(409, { error: "Add your key first.", code: "add-key" });
+ }
+ setRunOn(a.id, { runOn, ...(runKey && { runKey }) });
+ return answer(200, shown(runOnOf(a.id)));
+}
diff --git a/src/components/gpu/account-gpu-section.tsx b/src/components/gpu/account-gpu-section.tsx
index 4aa514e9..577d8403 100644
--- a/src/components/gpu/account-gpu-section.tsx
+++ b/src/components/gpu/account-gpu-section.tsx
@@ -2,6 +2,7 @@
import { ConnectChoice } from "@/components/gpu/connect-choice";
import { PairedComfyUIs } from "@/components/gpu/fuobe-connect";
+import { WhereRunsGo } from "@/components/gpu/where-runs-go";
import { useHydrated, useStatus, useViewer } from "@/lib/api";
/**
@@ -25,6 +26,8 @@ export function AccountGpuSection() {
</p>
</div>
<div className="min-w-0 space-y-4">
+ {/* Hosted runs: where the account's runs go, first. */}
+ {hosted && <WhereRunsGo />}
<ConnectChoice />
<PairedComfyUIs className="sm:max-w-[36rem]" />
</div>
diff --git a/src/components/gpu/trouble.tsx b/src/components/gpu/trouble.tsx
index 827fe10d..db02cc9b 100644
--- a/src/components/gpu/trouble.tsx
+++ b/src/components/gpu/trouble.tsx
@@ -1,7 +1,7 @@
"use client";
import { useQueryClient, type QueryClient } from "@tanstack/react-query";
-import { CreditCard, ExternalLink, KeyRound, Loader2, Play, RefreshCw, RotateCcw, Settings2, Shuffle, Stethoscope, Monitor } from "lucide-react";
+import { CreditCard, ExternalLink, KeyRound, Loader2, Play, RefreshCw, RotateCcw, Server, Settings2, Shuffle, Stethoscope, Monitor } from "lucide-react";
import Link from "next/link";
import { useState } from "react";
import { toast } from "sonner";
@@ -49,6 +49,7 @@ const ICONS: Record<TroubleActionKind, typeof Play> = {
"start-gpu": Play,
pair: RefreshCw,
"use-computer": Monitor,
+ "run-on-site": Server,
};
/** The first button stands out (the one most likely to help); the rest are quieter. */
@@ -63,6 +64,8 @@ export interface TroubleHandlers {
onPickModel?: () => void;
/** "Use this computer": the caller switches runs to the ComfyUI on this computer. */
onUseComputer?: () => void;
+ /** "Run on Our GPUs": the caller sends this run once to this install's GPUs (hosted runs). */
+ onRunOnSite?: () => void;
}
/**
@@ -78,6 +81,7 @@ export function TroubleActions({ actions, handlers = {}, max, skip = [], classNa
if (a.kind === "run-with-key") return !!handlers.onRunWithKey;
if (a.kind === "pick-model") return !!handlers.onPickModel;
if (a.kind === "use-computer") return !!handlers.onUseComputer;
+ if (a.kind === "run-on-site") return !!handlers.onRunOnSite;
return true;
});
const shown = max ? usable.slice(0, max) : usable;
@@ -124,7 +128,9 @@ export function TroubleActions({ actions, handlers = {}, max, skip = [], classNa
? handlers.onPickModel
: a.kind === "use-computer"
? handlers.onUseComputer
- : undefined;
+ : a.kind === "run-on-site"
+ ? handlers.onRunOnSite
+ : undefined;
return (
<button
key={a.kind}
diff --git a/src/components/gpu/where-runs-go.tsx b/src/components/gpu/where-runs-go.tsx
new file mode 100644
index 00000000..8bf1afb9
--- /dev/null
+++ b/src/components/gpu/where-runs-go.tsx
@@ -0,0 +1,43 @@
+"use client";
+
+import { RunOnList } from "@/components/studio/run-on";
+import { useStatus } from "@/lib/api";
+import { placeOf } from "@/lib/place-name";
+import { placeRows } from "@/lib/run-place";
+import { useSetRunOn } from "@/lib/run-on";
+import { cn } from "@/lib/utils";
+
+/**
+ * Settings → Your GPU, at the top while hosted runs are on: "Where your runs go", the same rows as the Run on list (this
+ * studio's GPUs, the account's GPU, its key), kept for every device. With nothing of its own, one line instead. Nothing
+ * while hosted runs are off (self-hosters keep today's page).
+ */
+export function WhereRunsGo({ className }: { className?: string }) {
+ const v = useStatus().data?.viewer;
+ const setRunOn = useSetRunOn();
+ if (!v?.hosted || v.kind !== "account") return null;
+ const place = placeOf(v.placeName);
+ const keys = v.paidAllowed === false ? [] : (v.keys ?? []);
+ const provider = v.runKey && keys.includes(v.runKey) ? v.runKey : keys.includes("fal") ? "fal" : keys[0];
+ const rows = placeRows(v, { key: provider ? { provider } : null, cloud: true });
+ return (
+ <div id="where-runs-go" className={cn("scroll-mt-28 space-y-1.5 rounded-xl border p-3 sm:max-w-[36rem] md:scroll-mt-20", className)}>
+ <h3 className="px-2.5 text-[13px] font-semibold">Where your runs go</h3>
+ {rows ? (
+ <>
+ {/* No verb agrees with the place name (it may be one GPU or many). */}
+ <p className="px-2.5 text-[12px] text-muted-foreground">Runs on {place.text}: nothing to set up. Your own GPU or key is there whenever you want it.</p>
+ <RunOnList
+ rows={rows.rows}
+ footer={null}
+ label="Where your runs go"
+ disabled={setRunOn.isPending}
+ onPick={(id) => setRunOn.mutate({ runOn: id, ...(id === "key" && provider && { key: provider }) })}
+ />
+ </>
+ ) : (
+ <p className="px-2.5 text-[12px] text-muted-foreground">Your runs go to {place.text}. Connect a GPU or add a key to have a choice.</p>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/gpu/your-gpu.tsx b/src/components/gpu/your-gpu.tsx
index 4cd07d86..2e9f5014 100644
--- a/src/components/gpu/your-gpu.tsx
+++ b/src/components/gpu/your-gpu.tsx
@@ -11,6 +11,8 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useStatus, type GpuTroubleView } from "@/lib/api";
import { canSaveAnyway } from "@/lib/diagnose";
+import { placeOf } from "@/lib/place-name";
+import { runsGoNowText, useSetRunOn } from "@/lib/run-on";
import { responseError, toastError } from "@/lib/refusals";
import { cn } from "@/lib/utils";
@@ -77,6 +79,7 @@ export function YourGpu({ className, onLinked }: { className?: string; onLinked?
const live = viewer?.gpu;
// Hosted runs: runs go to this studio's GPUs too, so these words say what goes to Your GPU, not "your runs".
const hosted = !!viewer?.hosted;
+ const setRunOn = useSetRunOn();
const [url, setUrl] = useState("");
const [token, setToken] = useState("");
const [busy, setBusy] = useState<"test" | "save" | "anyway" | "remove" | null>(null);
@@ -107,6 +110,12 @@ export function YourGpu({ className, onLinked }: { className?: string; onLinked?
qc.setQueryData(["account-gpu"], { gpu: r.gpu });
linked();
if (r.offline) toast(hosted ? "Your address is saved. Runs on Your GPU start as soon as it answers." : "Your address is saved. Your runs start as soon as your GPU answers.");
+ // Hosted runs: runs stay on this studio's GPUs unless the person sends them here, with one press.
+ else if (hosted && viewer?.runOn !== "gpu")
+ toast.success("Your GPU is connected.", {
+ description: "You can change this any time from Free ▾, next to the run button.",
+ action: { label: "Use it for my runs", onClick: () => setRunOn.mutate({ runOn: "gpu" }) },
+ });
else toast.success(hosted ? "Your GPU is connected." : "Your GPU is connected. Runs go to your ComfyUI now.");
setUrl("");
setToken("");
@@ -155,9 +164,12 @@ export function YourGpu({ className, onLinked }: { className?: string; onLinked?
const remove = async () => {
setBusy("remove");
try {
- qc.setQueryData(["account-gpu"], await call<GpuState>("DELETE"));
+ const r = await call<GpuState & { runOnCleared?: true }>("DELETE");
+ qc.setQueryData(["account-gpu"], { gpu: r.gpu });
void qc.invalidateQueries({ queryKey: ["status"] });
setInfo(null);
+ // Hosted runs: the account's runs went to this GPU by its pick, so they go to this studio's GPUs now.
+ if (r.runOnCleared && hosted) toast(runsGoNowText(placeOf(viewer?.placeName)), { id: "run-on" });
} catch (e) {
toastError(e);
} finally {
diff --git a/src/components/keys/your-keys.tsx b/src/components/keys/your-keys.tsx
index 9a2343d9..6d1411ae 100644
--- a/src/components/keys/your-keys.tsx
+++ b/src/components/keys/your-keys.tsx
@@ -13,6 +13,9 @@ import { ADD_KEY_EVENT, preferEngine, useHydrated, useStatus, useViewer } from "
import { settingProblem } from "@/lib/connections";
import { CLOUD_KEY, CLOUD_PROVIDERS, keySavedText, type CloudProvider, type KeyInfo, type YourKeys } from "@/lib/your-keys";
import { engineAfterKeySave } from "@/lib/engine-pref";
+import { placeOf } from "@/lib/place-name";
+import { placeRows } from "@/lib/run-place";
+import { runsGoNowText } from "@/lib/run-on";
import { cn } from "@/lib/utils";
/**
@@ -184,14 +187,17 @@ function KeyCard({ provider, info }: { provider: CloudProvider; info: KeyInfo |
const [replacing, setReplacing] = useState(false);
const [confirm, setConfirm] = useState<null | { going?: string }>(null);
const [busy, setBusy] = useState(false);
+ const viewer = useStatus().data?.viewer;
const remove = async (stopRuns: boolean) => {
setBusy(true);
try {
- await call(`/api/account/keys/${provider}`, "DELETE", stopRuns ? { stopRuns: true } : {});
+ const r = await call<{ runOnCleared?: true }>(`/api/account/keys/${provider}`, "DELETE", stopRuns ? { stopRuns: true } : {});
setConfirm(null);
changed();
toast.success(`Your ${p.label} key is removed.`);
+ // Hosted runs: the account's runs went to this key by its pick, so they go to this studio's GPUs now.
+ if (r.runOnCleared && viewer?.hosted) toast(runsGoNowText(placeOf(viewer.placeName)), { id: "run-on" });
} catch (e) {
const k = e as KeyError;
if (k.body?.code === "runs-going") setConfirm({ going: k.message });
@@ -285,6 +291,10 @@ export function AccountKeysSection({ prices }: { prices?: string }) {
// Hosted runs: the limits below are a key's own (runs on this studio's GPUs have theirs).
const hosted = !!viewer?.hosted;
if (!hydrated || !account || paidOff) return null;
+ // Hosted runs: where the account's runs go now (Settings → Your GPU changes it).
+ const keys = viewer?.keys ?? [];
+ const runKey = viewer?.runKey && keys.includes(viewer.runKey) ? viewer.runKey : keys.includes("fal") ? "fal" : keys[0];
+ const goesTo = hosted && viewer ? (placeRows(viewer, { key: runKey ? { provider: runKey } : null, cloud: true })?.rows.find((r) => r.selected)?.label ?? placeOf(viewer.placeName).label) : null;
return (
<section id="your-keys" aria-labelledby="your-keys-title" className="grid scroll-mt-28 grid-cols-[minmax(0,1fr)] gap-6 border-b py-8 md:scroll-mt-20 md:grid-cols-[260px_minmax(0,1fr)]">
<div className="min-w-0">
@@ -296,6 +306,14 @@ export function AccountKeysSection({ prices }: { prices?: string }) {
</p>
</div>
<div className="grid min-w-0 gap-4">
+ {goesTo && (
+ <p className="text-[13px] text-muted-foreground">
+ Where your runs go: <span className="font-medium text-foreground">{goesTo}</span> ·{" "}
+ <a href="#where-runs-go" className="font-medium text-brand-text underline-offset-2 hover:underline">
+ Change
+ </a>
+ </p>
+ )}
<ul className="grid gap-1.5 text-[13px] text-muted-foreground">
{prices && (
<li>
diff --git a/src/components/nav/status-chips.tsx b/src/components/nav/status-chips.tsx
index d216ffe8..d00c3f39 100644
--- a/src/components/nav/status-chips.tsx
+++ b/src/components/nav/status-chips.tsx
@@ -54,10 +54,10 @@ export function StatusDot({ ok }: { ok: boolean | undefined }) {
}
/** 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 }) {
+function DotSlot({ ok, hidden }: { ok: boolean | undefined; hidden?: boolean }) {
return (
<span aria-hidden className="grid w-[var(--nav-icon,16px)] shrink-0 place-items-center">
- <StatusDot ok={ok} />
+ {!hidden && <StatusDot ok={ok} />}
</span>
);
}
@@ -80,7 +80,7 @@ function Actionable({ item, className, children }: { item?: boolean; className:
* "Your GPU": a visitor's own (public sign-up), never the install's, or the owner's computer. A guest is sent to sign up
* first; anyone else without one opens "Connect your GPU"; a connected one says whether it answers.
*/
-export function YourGpuChip({ gpu, guest, hosted, item }: { gpu: Viewer["gpu"]; guest: boolean; hosted?: boolean; item?: boolean }) {
+export function YourGpuChip({ gpu, guest, hosted, quiet, item }: { gpu: Viewer["gpu"]; guest: boolean; hosted?: boolean; quiet?: boolean; item?: boolean }) {
const g = gpu;
// ComfyUI on this computer is closed, or runs without Fuobe's setting: the finder, at that step (elsewhere: /connect).
const fix = awayFix(g.connected ? g : undefined, useComputerSupport());
@@ -89,8 +89,11 @@ export function YourGpuChip({ gpu, guest, hosted, item }: { gpu: Viewer["gpu"];
const inner = (
<>
<span className="flex w-full items-center gap-3">
- <DotSlot ok={g.online} /> Your GPU
- <span className="ml-auto">{g.online ? "online" : g.comfy === "down" ? "ComfyUI not running" : g.comfy === "no-setting" ? "needs a setting" : shortState(g.trouble?.cause)}</span>
+ {/* Hosted runs, a GPU its runs don't go to (quiet): a green dot while it answers, and nothing else about it. */}
+ {quiet && !g.online ? <DotSlot ok={undefined} hidden /> : <DotSlot ok={g.online} />} Your GPU
+ {!quiet && (
+ <span className="ml-auto">{g.online ? "online" : g.comfy === "down" ? "ComfyUI not running" : g.comfy === "no-setting" ? "needs a setting" : shortState(g.trouble?.cause)}</span>
+ )}
</span>
{(g.device || vram || g.mode === "computer") && (
<span className="truncate pl-7 text-[11px]">{[g.mode === "computer" && "Your computer", deviceLabel(g.device), vram && `${vram} VRAM`].filter(Boolean).join(" · ")}</span>
@@ -324,7 +327,9 @@ export function VisitorGpu({ item }: { item?: boolean }) {
const v = status?.viewer;
if (!v) return null;
if (v.balance) return item ? <BalanceSection viewer={v} /> : <BalanceChip viewer={v} />;
- return <YourGpuChip gpu={v.gpu} guest={v.kind === "guest"} hosted={!!v.hosted} item={item} />;
+ // Hosted runs: its GPU, when its runs don't go there (its pick, or this studio's GPUs first), says only that it answers.
+ const quiet = !!v.hosted && v.runOn !== "gpu" && (!!v.runOn || v.prefer === "pool");
+ return <YourGpuChip gpu={v.gpu} guest={v.kind === "guest"} hosted={!!v.hosted} quiet={quiet} item={item} />;
}
/** The owner's "Placeholders on", while it is on (the owner's runs only make placeholders). */
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index fccf8f90..76e2434f 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -15,15 +15,18 @@ import { useToday } from "@/hooks/use-today";
import { estimateCost, imageLimit, layoutCanvas, planGeneration, routesFor, type Plan } from "@/lib/catalog/plan";
import type { Engine, InputSlot, MediaKind, ModelDef, Operation, Preset, PresetRoute, VideoFormat } from "@/lib/catalog/types";
import { LYRICS_PARAM, SONG_ID_PARAM, songFormat, songToolProblem, withSongId } from "@/lib/lyrics";
-import { dualEngine } from "@/lib/catalog/engines";
+import { dualEngine, onEngine } 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 { poolRunState, quoteBody, useHostedQuote, useSettled, type RunOn } from "@/lib/hosted";
-import { composerOnPool, composerPlace } from "@/lib/run-place";
+import { composerOnPool, composerPlace, placeRows, type RunOnPick } from "@/lib/run-place";
+import { useSetRunOn } from "@/lib/run-on";
+import { RunOnChip } from "./run-on";
+import { PlaceIntro } from "./place-intro";
import { PoolNote } from "./pool-note";
-import { modelOwnSetup, poolRunsModel } from "@/lib/pool-rules";
-import { controlSetup, keyOnlySetup, movedToOwnText } from "@/lib/own-setup-controls";
+import { modelOwnSetup, pickerRules, poolRunsModel } from "@/lib/pool-rules";
+import { controlSetup, keyOnlySetup } from "@/lib/own-setup-controls";
import { ownSetupDetail, ownSetupLabel, ownSetupShort } from "@/lib/own-setup";
import { OwnSetupChip, useOwnSetupPress, useOwnSetupViewer } from "@/components/own-setup";
import { HoldFilesCtx } from "@/lib/held-files";
@@ -99,9 +102,9 @@ import { qwen21Note } from "@/lib/qwen21-speed";
import { H3_TIER_PARAM, h3TierNote } from "@/lib/gpu/h3-tier";
import { formatCost } from "@/lib/format";
import { toastError } from "@/lib/refusals";
-import { addKeyLabel, billedTo, CLOUD_KEY, needsKey, paidThrough, startingModel } from "@/lib/your-keys";
+import { addKeyLabel, billedTo, CLOUD_KEY, cloudVersion, needsKey, paidThrough, startingModel } from "@/lib/your-keys";
import { gpuBeforeRun, onCloudKey } from "@/lib/before-run";
-import type { TroubleAction } from "@/lib/diagnose";
+import { withKeyAction, type TroubleAction } from "@/lib/diagnose";
import { TroubleActions, TroubleDetails } from "@/components/gpu/trouble";
import { cn } from "@/lib/utils";
import { h3ReferenceProblem, openReferenceMode } from "@/lib/h3-references";
@@ -338,14 +341,16 @@ export function Composer({ docked }: { docked: boolean }) {
}, []);
const pickerOps = config.pickerOps ?? config.ops;
- // For a viewer with no GPU of its own (hosted runs), the open models this studio's GPUs keep off stay in the list with
+ // For a viewer whose runs go to this studio's GPUs (hosted runs), the open models they keep off stay in the list with
// what runs them (their own-setup label, src/lib/pool-rules.ts), as the models that run on a visitor's own setup only
- // do: Run then opens that setup.
+ // do: Run then opens that setup, or runs it on the viewer's own GPU at once. Only a viewer with no GPU of its own is
+ // moved off an untouched default they keep off (poolOff, below).
const poolRules = status?.viewer?.hosted && !status.viewer.gpu.connected ? status.viewer.pool : undefined;
+ const labelRules = pickerRules(status?.viewer);
const models = useMemo(() => filterModels(catalog.models, { kind: config.kind, ops: pickerOps }), [catalog.models, config.kind, pickerOps]);
const setupViewer = useOwnSetupViewer();
const pressSetup = useOwnSetupPress();
- const modelSetup = useCallback((m: ModelDef) => (setupViewer ? modelOwnSetup(poolRules, m) : null), [setupViewer, poolRules]);
+ const modelSetup = useCallback((m: ModelDef) => (setupViewer ? modelOwnSetup(labelRules, m) : null), [setupViewer, labelRules]);
const model: ModelDef | undefined = catalog.getModel(draft.modelId);
// MiniMax H3 on your GPU has a References mode (Pika H3 Flex): reference clips and voice or music clips beside the images.
const refMode = config.ops.includes("ref2v") ? openReferenceMode(model) : null;
@@ -658,13 +663,15 @@ export function Composer({ docked }: { docked: boolean }) {
};
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, unless the studio puts its own GPUs first; the person can pick either.
+ // studio's billing service, or free), asked again 300 ms after a change. Where the run goes, in one order: the
+ // account's own pick (the Run on list, kept on the server for every device), else its own GPU while online unless
+ // the studio puts its own GPUs first. A place named for one run only ("Run on …") is sent with that run.
const viewerInfo = status?.viewer;
const ownOnline = !!viewerInfo?.gpu.connected && !!viewerInfo.gpu.online;
- const [runOnPick, setRunOn] = useState<RunOn | null>(null);
- // (The place the run names: none when the default is the studio's GPUs only because the studio puts them first.)
- const { runOn, place: runPlace } = composerPlace(runOnPick, ownOnline, viewerInfo?.prefer === "pool");
+ const runOnPicked = viewerInfo?.hosted ? viewerInfo.runOn : undefined;
+ const setRunOn = useSetRunOn();
+ // (The place the run names: none when the default is the studio's GPUs only because they go first.)
+ const { runOn, place: runPlace } = composerPlace(null, runOnPicked, ownOnline, viewerInfo?.prefer === "pool");
const hostedHere = !!viewerInfo?.hosted && model?.engine === "open";
// The name visitors read for this studio's GPUs ("Our GPUs"): said only while hosted runs are on.
const sitePlace = placeOf(viewerInfo?.placeName);
@@ -835,7 +842,34 @@ export function Composer({ docked }: { docked: boolean }) {
// strip's, every 30 s; nothing here asks the GPU) shows what is wrong and its fixes before Run. A run started anyway
// waits for the GPU. One of the account's keys that runs this tool's cloud version is offered too (an explicit click:
// it spends the person's own credit).
- const gpuDown = gpuBeforeRun({ viewer: status?.viewer, model, engine, onPool: hostedHere && runOn === "pool", preset, has, getModel: catalog.getModel });
+ // Hosted runs: the key that runs this item's cloud version (a row of the Run on list, "Run with your fal.ai key"), and
+ // its price there, so a key is offered with its price and a press that showed "Free" never bills it.
+ const keyTwin =
+ viewerInfo?.hosted && viewerInfo.kind === "account" && viewerInfo.paidAllowed !== false && model ? cloudVersion(preset, model, viewerInfo.keys ?? [], has, catalog.getModel) : null;
+ const keyPrice = (() => {
+ const m = keyTwin ? catalog.getModel(keyTwin.modelId) : undefined;
+ if (!m) return null;
+ try {
+ const usd = estimateCost(onEngine(m, "cloud"), draft.params, 1, (keyTwin?.op ?? op) as Operation | undefined, false, today);
+ return usd != null && usd > 0 ? `≈ ${formatCost(usd)}` : null;
+ } catch {
+ return null;
+ }
+ })();
+ // What this studio's GPUs take (no label of an own setup), so the check before Run offers a run on them only then.
+ const siteTakes = !!viewerInfo?.hosted && !!model && model.engine === "open" && !modelSetup(model) && !poolSetup;
+ const gpuDown = gpuBeforeRun({
+ viewer: status?.viewer,
+ model,
+ engine,
+ onPool: hostedHere && runOn === "pool",
+ preset,
+ has,
+ getModel: catalog.getModel,
+ hosted: !!viewerInfo?.hosted,
+ site: siteTakes ? sitePlace : null,
+ keyPrice,
+ });
// "Run with your fal.ai key". While hosted runs are on: this run, once, on the tool's cloud version and that key; the
// engine switch stays where it was, so the next run goes where runs go (the person picks Cloud themselves to stay
// there). Otherwise (as always): the switch moves to Cloud, and once it has moved the tool to its cloud model, it runs.
@@ -855,11 +889,18 @@ export function Composer({ docked }: { docked: boolean }) {
setEngine("cloud");
setCloudRun(true);
};
+ // "Run on Our GPUs": this run, once, on this studio's GPUs; the account's pick stays as it was.
+ const onRunOnSite = () => submitRef.current(undefined, undefined, "pool");
+ // A choice before Run for an item this studio's GPUs can't run, for an account whose key runs its cloud version (and no
+ // GPU): run it once on the key, at its price, or connect a GPU. Nothing runs until one is pressed.
+ const [keyChoice, setKeyChoice] = useState(false);
// `skip` is true only from the guided fix's "Run anyway" (a click handler passes its event here). `withKey`: this run
- // only, on the cloud version that action names and the account's key (hosted runs on; see onRunWithKey).
- const submit = (skip?: unknown, withKey?: TroubleAction) => {
+ // only, on the cloud version that action names and the account's key (hosted runs on; see onRunWithKey). `once`: a
+ // place for this run only (hosted runs: "Run on Our GPUs", or the account's GPU for what only it runs).
+ const submit = (skip?: unknown, withKey?: TroubleAction, once?: "own" | "pool"): void => {
const skipGpu = skip === true;
+ setKeyChoice(false);
if (exact) {
// An exact orbit: the still filmed along the orbit's numbers (Fly around), priced in its panel.
const stop = !exactImage ? "Add a start frame to film an exact orbit" : fly.preview.data?.blocker;
@@ -870,18 +911,21 @@ export function Composer({ docked }: { docked: boolean }) {
return;
}
if (keyToAdd && model && !create.isPending) return openAddKey(keyToAdd, model.id);
- if (!blocker && gpuSetup && !skipGpu && !withKey && !create.isPending) return openGpuFix();
+ if (!blocker && gpuSetup && !skipGpu && !withKey && once !== "pool" && !create.isPending) return openGpuFix();
// It runs on the visitor's own setup: Run opens it (Connect your GPU, Add your key, a guest's sign-up), and nothing
- // is sent. An account that has it (its own GPU, or the key that runs it) is moved there, to run with the next press.
- if (!blocker && poolSetup && !withKey) {
- if (pressSetup(poolSetup)) {
- setRunOn("own");
- toast(movedToOwnText(!!viewerInfo?.gpu.connected), { id: "composer-blocker" });
+ // is sent. An account that has its GPU runs it there with this press (the chip said "Free · your GPU"). One whose key
+ // runs its cloud version runs it there only when its key is where its runs go; otherwise it picks, at the key's price.
+ if (!blocker && poolSetup && !withKey && !once) {
+ if (viewerInfo?.gpu.connected && poolSetup.need === "gpu") return submitRef.current(skip, undefined, "own");
+ if (keyTwin && keyPrice && !viewerInfo?.gpu.connected) {
+ if (runOnPicked === "key") return submitRef.current(skip, withKeyAction(keyTwin.provider, keyTwin.modelId, keyTwin.op, keyPrice));
+ return void setKeyChoice(true);
}
+ if (pressSetup(poolSetup)) return submitRef.current(skip, undefined, "own");
return;
}
// Refused by the price check (Run is off; Enter in the prompt lands here too): its words, and nothing is sent.
- if (!blocker && poolRefused && poolState && !withKey) return void toast(poolState.text, { id: "composer-blocker" });
+ if (!blocker && poolRefused && poolState && !withKey && !once) return void toast(poolState.text, { id: "composer-blocker" });
if (blocker || create.isPending || signature.lock.isPending) {
if (blocker) {
// One blocker toast at a time (pressing Generate again replaces it), gone once a run starts.
@@ -910,15 +954,17 @@ export function Composer({ docked }: { docked: boolean }) {
);
// Hosted runs: where it should go, and the price shown (the server checks both; a higher price comes back to confirm).
// A run on the account's key names neither: the key is where it goes.
- const hosted = viewerInfo?.hosted && !withKey ? { ...(runPlace && { place: runPlace }), ...(poolPrice && hostedQuote && { shown: { amount: hostedQuote.amount, priceVersion: hostedQuote.priceVersion } }) } : {};
+ const placeNow = once ?? runPlace;
+ const shownHere = poolPrice && !once && hostedQuote;
+ const hosted = viewerInfo?.hosted && !withKey ? { ...(placeNow && { place: placeNow }), ...(shownHere && { shown: { amount: hostedQuote.amount, priceVersion: hostedQuote.priceVersion } }) } : {};
// Open palette lock: the images are recoloured to the palette by a chained step (POST /api/palettes/lock).
// (An account's lock runs on this studio's GPUs only: sent there by name.)
if (sent.lock) {
const request = withKey ? onCloudKey(sent.request, withKey) : sent.request;
- return signature.lock.mutate({ request, colors: sent.lock.colors, ...hosted, ...(poolPrice && !withKey && { place: "pool" as const }) }, { onError: (e) => toastError(e) });
+ return signature.lock.mutate({ request, colors: sent.lock.colors, ...hosted, ...(poolPrice && !withKey && once !== "own" && { place: "pool" as const }) }, { onError: (e) => toastError(e) });
}
// If the server's pre-flight stops it (409 gpu-setup), the guided fix that opens can try again, or run it anyway.
- if (!withKey)
+ if (!withKey && once !== "pool")
setGpuRetry(
() => submitRef.current(),
() => submitRef.current(true),
@@ -1054,6 +1100,42 @@ export function Composer({ docked }: { docked: boolean }) {
const exactPrice = exact ? fly.price : "";
const costText = exactPrice || (poolPrice ? (poolState?.refused ? poolState.text : hostedQuote?.text || ownCostText) : ownCostText);
const payerText = poolPrice ? "" : ownPayerText;
+ // Hosted runs: the Run on list, for an account with a choice for this item (its GPU, or a key that runs its cloud
+ // version): the price chip opens it ("Free ▾"). On the Cloud engine, for an account whose runs go to its key, so it
+ // has the way back. An item this studio's GPUs don't take for this account runs on its GPU, said so, with no list.
+ const siteMissed = runOn === "pool" && shownOn === "own";
+ const onKeyNow = engine === "cloud" && runOnPicked === "key" && model?.engine === "cloud" && !!payer;
+ const runOnRows =
+ !viewerInfo?.hosted || exact || demo
+ ? null
+ : hostedHere
+ ? placeRows(
+ viewerInfo,
+ { key: keyTwin && { provider: keyTwin.provider, price: keyPrice }, siteRuns: siteTakes && !siteMissed },
+ { text: hostedQuote?.allowed ? hostedQuote.text : undefined, wait: poolState?.wait },
+ )
+ : onKeyNow
+ ? placeRows(viewerInfo, { key: { provider: viewerInfo.runKey ?? payer, price: cost ? `≈ ${formatCost(cost)}` : null }, cloud: true })
+ : null;
+ const ownGpuHere = hostedHere && !!viewerInfo?.gpu.connected && siteMissed && !runOnRows;
+ const runOnText = runOnRows?.on === "gpu" || ownGpuHere ? "Free · your GPU" : runOnRows?.on === "key" ? `${costText} · your key` : costText;
+ const runOnTip =
+ runOnRows?.on === "gpu"
+ ? `Runs on your own GPU${viewerInfo?.gpu.online ? "" : " · not answering right now"}`
+ : runOnRows?.on === "key"
+ ? `Estimated cost, billed to ${billedTo(viewerInfo?.runKey ?? payer ?? "fal")}`
+ : runOnRows?.note
+ ? runOnRows.note
+ : poolState?.refused
+ ? (poolState.sub ?? poolState.text)
+ : [hostedQuote?.sub ?? `Runs on ${sitePlace.text}`, poolState?.wait].filter(Boolean).join(" · ");
+ /** A pick from the Run on list: kept for the account; the key runs on the Cloud engine, the others on Open source. */
+ const pickRunOn = (id: RunOnPick) => {
+ const key = id === "key" ? (keyTwin?.provider ?? viewerInfo?.runKey ?? payer ?? undefined) : undefined;
+ setRunOn.mutate({ runOn: id, ...(key && { key }) });
+ if (id === "key" && engine !== "cloud") setEngine("cloud");
+ if (id !== "key" && onKeyNow) setEngine("open");
+ };
// 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];
@@ -1774,30 +1856,32 @@ 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(shownOn === "own" ? "pool" : "own")}
- aria-label={`Runs on ${shownOn === "own" ? "your GPU" : sitePlace.text}. Change where it runs`}
- 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"
- >
- {shownOn === "own" ? "Your GPU" : sitePlace.label}
- </button>
+ {runOnRows && runOnText && (
+ <RunOnChip
+ rows={runOnRows.rows}
+ text={runOnText}
+ tooltip={runOnTip}
+ ariaLabel={`${runOnRows.on === "gpu" ? "Runs on your GPU" : runOnRows.on === "key" ? "Runs with your key" : `Runs on ${sitePlace.text}`}. Change where it runs`}
+ onPick={pickRunOn}
+ pending={setRunOn.isPending}
+ className={cn(poolRefused && runOnRows.on === "site" && "max-w-48")}
+ />
)}
- {costText && (
+ {!runOnRows && costText && (
<Tooltip>
<TooltipTrigger asChild>
<span className={cn("shrink-0 text-[12px] font-medium text-muted-foreground tabular-nums", poolRefused && "min-w-0 shrink truncate max-sm:hidden")} data-pool-refused={poolRefused || undefined}>
<span className="sm:hidden">{exactPrice ? fly.compactPrice : poolPrice ? costText : keyOnly && cost == null ? ownSetupShort(keyOnly) : costLabel({ demo, cost: cost ?? freeHere, compact: true, unknown: loraPriceUnknown, gpu: gpuRun }, formatCost)}</span>
<span className="hidden sm:inline">
- {costText}
+ {ownGpuHere ? runOnText : costText}
{payerText}
</span>
</span>
</TooltipTrigger>
<TooltipContent className="max-w-72">
- {poolPrice
+ {ownGpuHere
+ ? "This one runs on your own GPU."
+ : poolPrice
? poolState?.refused
? (poolState.sub ?? poolState.text)
: [hostedQuote?.sub ?? `Runs on ${sitePlace.text}`, poolState?.wait].filter(Boolean).join(" · ")
@@ -1894,7 +1978,29 @@ export function Composer({ docked }: { docked: boolean }) {
<span className="font-medium text-foreground">{gpuDown.words}</span> A run you start now waits for it.
</p>
<TroubleDetails details={gpuDown.details} />
- <TroubleActions actions={gpuDown.actions} skip={["retry"]} handlers={{ onRunWithKey }} />
+ <TroubleActions actions={gpuDown.actions} skip={["retry"]} handlers={{ onRunWithKey, onRunOnSite }} />
+ </div>
+ )}
+ {/* Once, for an account whose runs moved to this studio's GPUs when hosted runs went on. */}
+ <PlaceIntro run="Generate" onKeep={(r) => r === "key" && engine !== "cloud" && setEngine("cloud")} />
+ {/* An item that runs on an own GPU, for an account whose key runs its cloud version: one run on the key, at its price. */}
+ {keyChoice && poolSetup && keyTwin && keyPrice && (
+ <div role="note" aria-live="polite" className="mx-1 mt-2 space-y-1.5 rounded-xl border border-dashed px-3 py-2 text-[12px] leading-snug text-muted-foreground">
+ <p>
+ <span className="font-medium text-foreground">This one runs on your own GPU.</span>{" "}
+ {"vramGb" in poolSetup && poolSetup.vramGb ? `It needs a GPU with ${poolSetup.vramGb} GB of memory. ` : ""}
+ Your {CLOUD_KEY[keyTwin.provider].label} key runs its cloud version.
+ </p>
+ <div className="flex flex-wrap gap-1.5">
+ <TroubleActions actions={[withKeyAction(keyTwin.provider, keyTwin.modelId, keyTwin.op, keyPrice)]} handlers={{ onRunWithKey }} />
+ <button
+ type="button"
+ onClick={() => (setKeyChoice(false), window.dispatchEvent(new Event(CONNECT_GPU_EVENT)))}
+ className="inline-flex h-7 w-fit items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent"
+ >
+ Connect your GPU
+ </button>
+ </div>
</div>
)}
{outcome && (
diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsx
index 5fc0c435..dd20b8eb 100644
--- a/src/components/studio/feed.tsx
+++ b/src/components/studio/feed.tsx
@@ -22,6 +22,8 @@ import { onCloudKey } from "@/lib/before-run";
import { TroubleActions, TroubleDetails } from "@/components/gpu/trouble";
import { useCreateGeneration, useGenerationActions, useMakingPoolRuns, usePlaceName, useStatus } from "@/lib/api";
import { knownPlace } from "@/lib/place-name";
+import { runOnSiteAction } from "@/lib/diagnose";
+import { offersRunOnSite, retryRequest } from "@/lib/run-place";
import { placeholdersOn } from "@/lib/demo-mode";
import { useSoulFinish } from "./soul-finish";
import { elapsed, formatCost, leftLabel, notePace, ratioValue, timeAgo, timeLeft } from "@/lib/format";
@@ -170,6 +172,9 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {
export function FailedTile({ g, ratio, onRetry }: { g: Generation; ratio: number; onRetry: () => void }) {
const create = useCreateGeneration();
const trouble = g.status === "failed" ? g.trouble : undefined;
+ // Hosted runs: a run that failed on the person's own GPU can run once on this studio's GPUs instead.
+ const site = usePlaceName();
+ const onSite = !!trouble && offersRunOnSite(g, !!site);
// A run on this studio's GPUs that couldn't finish: one plain sentence (the server's), nothing technical.
const poolFailed = g.place === "pool" && g.status === "failed";
return (
@@ -189,10 +194,13 @@ export function FailedTile({ g, ratio, onRetry }: { g: Generation; ratio: number
{trouble && (
<TroubleActions
className="mt-2"
- actions={trouble.actions}
+ actions={onSite && site ? [runOnSiteAction(site.label), ...trouble.actions] : trouble.actions}
skip={["retry"]}
max={3}
- handlers={{ onRunWithKey: (a) => create.mutate(onCloudKey(g.request, a), { onError: (e) => toastError(e) }) }}
+ handlers={{
+ onRunWithKey: (a) => create.mutate(onCloudKey(g.request, a), { onError: (e) => toastError(e) }),
+ onRunOnSite: () => create.mutate({ ...g.request, place: "pool" } as Generation["request"], { onError: (e) => toastError(e) }),
+ }}
/>
)}
<div className="mt-2 flex flex-wrap gap-1.5">
@@ -502,6 +510,9 @@ export function Feed({
const [open, setOpen] = useState<{ id: string; index: number } | null>(null);
const create = useCreateGeneration();
const making = useMakingPoolRuns();
+ // Hosted runs: Retry sends a run to the place it ran (read through a ref: the feed's callbacks stay the same).
+ const hosted = !!useStatus().data?.viewer?.hosted;
+ const hostedRef = useRef(hosted);
// Fuobe Soul results get their look's grade and overlay here, once.
useSoulFinish(items);
// Groups get stable callbacks that read the latest props through refs.
@@ -510,6 +521,7 @@ export function Feed({
useEffect(() => {
createRef.current = create;
reuseRef.current = onReuse;
+ hostedRef.current = hosted;
});
const hasReuse = !!onReuse;
const aiTag = useAiTag();
@@ -517,7 +529,7 @@ export function Feed({
const api = useMemo<FeedApi>(
() => ({
open: openAt,
- retry: (g) => createRef.current.mutate(g.request, { onError: (e) => toastError(e) }),
+ retry: (g) => createRef.current.mutate(retryRequest(g, hostedRef.current), { onError: (e) => toastError(e) }),
reuse: hasReuse ? (g) => reuseRef.current?.(g) : undefined,
runner: { onOpen: openAt, onReuse: hasReuse ? (g) => reuseRef.current?.(g) : undefined },
...(aiTag && { aiTag }),
diff --git a/src/components/studio/place-intro.tsx b/src/components/studio/place-intro.tsx
new file mode 100644
index 00000000..1e3531b4
--- /dev/null
+++ b/src/components/studio/place-intro.tsx
@@ -0,0 +1,98 @@
+"use client";
+
+import { useEffect } from "react";
+import { toast } from "sonner";
+import { useHydrated, useStatus } from "@/lib/api";
+import { placeIntro, type PlaceIntro as Intro } from "@/lib/place-intro";
+import type { RunOnPick } from "@/lib/run-place";
+import { useSetRunOn } from "@/lib/run-on";
+import { cn } from "@/lib/utils";
+
+/**
+ * The one-time note above a run button for an account whose runs moved to this studio's GPUs when hosted runs went on
+ * (src/lib/place-intro.ts says who and the words). Both buttons keep a pick on the server, so it shows once for the
+ * account, on any device. `onKeep`: what the page does besides (the composer moves its engine to Cloud for a key).
+ */
+
+function useIntro(run: string): {
+ intro: Intro | null;
+ keep: (runOn: RunOnPick) => void;
+ busy: boolean;
+} {
+ const hydrated = useHydrated();
+ const v = useStatus().data?.viewer;
+ const setRunOn = useSetRunOn();
+ const intro = hydrated ? placeIntro(v, run) : null;
+ return {
+ intro,
+ keep: (runOn) =>
+ setRunOn.mutate({
+ runOn,
+ ...(runOn === "key" && intro?.keep.key && { key: intro.keep.key }),
+ }),
+ busy: setRunOn.isPending,
+ };
+}
+
+/** The composer's note, a dismissible line above Generate. */
+export function PlaceIntro({ run, onKeep, className }: { run: string; onKeep?: (runOn: "gpu" | "key") => void; className?: string }) {
+ const { intro, keep, busy } = useIntro(run);
+ if (!intro) return null;
+ return (
+ <div
+ role="note"
+ data-place-intro=""
+ className={cn(
+ "mx-1 mt-2 flex flex-wrap items-center gap-x-3 gap-y-1.5 rounded-xl border border-dashed px-3 py-2 text-[12px] leading-snug text-muted-foreground",
+ className,
+ )}
+ >
+ <p className="min-w-0 flex-1 basis-56">
+ <span className="font-medium text-foreground">{intro.lead}</span> {intro.rest}
+ </p>
+ <div className="flex flex-wrap gap-1.5">
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => (keep(intro.keep.runOn), onKeep?.(intro.keep.runOn))}
+ className="inline-flex h-7 w-fit items-center rounded-full bg-highlight px-2.5 text-[12px] font-medium text-highlight-foreground hover:opacity-90 disabled:opacity-60"
+ >
+ {intro.keep.label}
+ </button>
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => keep("site")}
+ className="inline-flex h-7 w-fit items-center rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent disabled:opacity-60"
+ >
+ OK
+ </button>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * A tool page's note (its place chip has no line above its Run): the same words and buttons, once per page, as a note
+ * that stays until one is pressed.
+ */
+export function PlaceIntroNote({ run }: { run: string }) {
+ const { intro, keep } = useIntro(run);
+ const lead = intro?.lead;
+ useEffect(() => {
+ if (!intro) return;
+ toast(intro.lead, {
+ id: "place-intro",
+ description: intro.rest,
+ duration: Infinity,
+ action: {
+ label: intro.keep.label,
+ onClick: () => keep(intro.keep.runOn),
+ },
+ cancel: { label: "OK", onClick: () => keep("site") },
+ });
+ // Once per note: its words change only when the viewer does.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [lead]);
+ return null;
+}
diff --git a/src/components/studio/run-on.tsx b/src/components/studio/run-on.tsx
new file mode 100644
index 00000000..c8b24f92
--- /dev/null
+++ b/src/components/studio/run-on.tsx
@@ -0,0 +1,152 @@
+"use client";
+
+import { ChevronDown } from "lucide-react";
+import { forwardRef, useState } from "react";
+import { useIsMobile } from "@/hooks/use-mobile";
+import { RUN_ON_FOOTER, type RunOnPick, type RunOnRow } from "@/lib/run-place";
+import { cn } from "@/lib/utils";
+import { ResponsivePanel } from "./responsive-panel";
+
+/**
+ * "Run on": where an account's runs go while hosted runs are on (this studio's GPUs, its own GPU, its own key), for a
+ * person who has a choice for this item (src/lib/run-place.ts placeRows). A pick applies at once and holds for its next
+ * runs on every device (src/lib/run-on.ts). The composer's price chip opens it ("Free ▾"); a tool page's place chip
+ * lists the same rows; Settings → Your GPU shows them as "Where your runs go".
+ */
+
+/** The rows as a radio list: the place, the line under it, a green dot for a GPU that answers. */
+export function RunOnList({
+ rows,
+ onPick,
+ footer = RUN_ON_FOOTER,
+ disabled,
+ label = "Run on",
+ className,
+}: {
+ rows: readonly RunOnRow[];
+ onPick: (id: RunOnPick) => void;
+ /** Under the rows (none: null). */
+ footer?: string | null;
+ disabled?: boolean;
+ /** The list's name for screen readers. */
+ label?: string;
+ className?: string;
+}) {
+ return (
+ <div className={cn("space-y-0.5", className)}>
+ <div role="radiogroup" aria-label={label} className="space-y-0.5">
+ {rows.map((r) => (
+ <button
+ key={r.id}
+ type="button"
+ role="radio"
+ aria-checked={r.selected}
+ data-run-on={r.id}
+ disabled={disabled}
+ onClick={() => r.selected || onPick(r.id)}
+ // Phones: rows of 48 px or more.
+ className={cn(
+ "flex min-h-12 w-full items-center gap-3 rounded-lg px-2.5 py-1.5 text-left transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50 disabled:opacity-60 sm:min-h-10",
+ r.selected && "bg-brand-faint hover:bg-brand-faint",
+ )}
+ >
+ <span
+ aria-hidden
+ className={cn("grid size-4 shrink-0 place-items-center rounded-full border", r.selected ? "border-primary" : "border-border-strong")}
+ >
+ {r.selected && <span className="size-2 rounded-full bg-primary" />}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[13px] font-medium">{r.label}</span>
+ <span className="flex min-w-0 items-center gap-1.5 text-[12px] text-muted-foreground">
+ {r.online && <span aria-hidden className="size-1.5 shrink-0 rounded-full bg-success" />}
+ <span className="min-w-0 truncate">{r.sub}</span>
+ </span>
+ </span>
+ </button>
+ ))}
+ </div>
+ {footer && <p className="px-2.5 pt-1.5 text-[12px] text-muted-foreground">{footer}</p>}
+ </div>
+ );
+}
+
+/** The chip's button: the price words and a caret ("Free ▾", "Free · your GPU ▾", "≈ $0.04 · your key ▾"). */
+const RunOnButton = forwardRef<HTMLButtonElement, React.ComponentProps<"button"> & { text: string; short?: string }>(function RunOnButton(
+ { text, short, className, ...props },
+ ref,
+) {
+ return (
+ <button
+ ref={ref}
+ type="button"
+ {...props}
+ className={cn(
+ "inline-flex h-7 max-w-full min-w-0 shrink-0 items-center gap-0.5 rounded-md px-1.5 text-[12px] font-medium text-muted-foreground tabular-nums transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50",
+ className,
+ )}
+ >
+ {short ? (
+ <>
+ <span className="truncate sm:hidden">{short}</span>
+ <span className="hidden truncate sm:inline">{text}</span>
+ </>
+ ) : (
+ <span className="truncate">{text}</span>
+ )}
+ <ChevronDown aria-hidden className="size-3 shrink-0 opacity-70" />
+ </button>
+ );
+});
+
+/**
+ * The composer's price chip with its Run on list: the price words and a caret; it opens a popover (desktop) or a bottom
+ * sheet (phone) titled "Run on". `tooltip`: where the run goes and the wait ("Runs on our GPUs · Next in line").
+ */
+export function RunOnChip({
+ rows,
+ text,
+ short,
+ tooltip,
+ ariaLabel,
+ onPick,
+ pending,
+ className,
+}: {
+ rows: readonly RunOnRow[];
+ /** The chip's words without the caret. */
+ text: string;
+ /** Shorter words on phones. */
+ short?: string;
+ tooltip?: React.ReactNode;
+ ariaLabel: string;
+ onPick: (id: RunOnPick) => void;
+ pending?: boolean;
+ className?: string;
+}) {
+ const [open, setOpen] = useState(false);
+ // A phone's sheet says the title in its own header; the desktop popover says it here.
+ const mobile = useIsMobile();
+ return (
+ <ResponsivePanel
+ open={open}
+ onOpenChange={setOpen}
+ title="Run on"
+ tooltip={open ? undefined : tooltip}
+ align="end"
+ focusSelf
+ className="w-[min(92vw,320px)] p-1.5"
+ trigger={<RunOnButton text={text} short={short} aria-label={ariaLabel} data-run-on-chip="" className={className} />}
+ >
+ {!mobile && <p className="px-2.5 pt-1 pb-1.5 text-[13px] font-semibold">Run on</p>}
+ <RunOnList
+ rows={rows}
+ disabled={pending}
+ onPick={(id) => {
+ onPick(id);
+ setOpen(false);
+ }}
+ />
+ </ResponsivePanel>
+ );
+}
diff --git a/src/components/studio/run-place-chip.tsx b/src/components/studio/run-place-chip.tsx
index 617524ac..674d2157 100644
--- a/src/components/studio/run-place-chip.tsx
+++ b/src/components/studio/run-place-chip.tsx
@@ -13,11 +13,14 @@ import { CONNECT_GPU_EVENT, signInHref, useHydrated, useStatus, useViewer } from
import { formatCost } from "@/lib/format";
import { placeOf, type Place } from "@/lib/place-name";
import { quoteBody, useHostedQuote, useSettled } from "@/lib/hosted";
-import { checkedPool, openCheckPlace, runPlace, type RunAudience, type RunPlace, type RunPlaceInput } from "@/lib/run-place";
+import { checkedPool, openCheckPlace, placeRows, runPlace, type RunAudience, type RunOnPick, type RunPlace, type RunPlaceInput } from "@/lib/run-place";
+import { useSetRunOn } from "@/lib/run-on";
import { cn } from "@/lib/utils";
import { chipBase, chipIdle } from "./chip";
import { EngineSwitch } from "./engine-switch";
+import { PlaceIntroNote } from "./place-intro";
import { ResponsivePanel } from "./responsive-panel";
+import { RunOnList } from "./run-on";
const ICONS: Record<RunPlace["where"], typeof Cloud> = { cloud: Cloud, gpu: Cpu, pool: Server, browser: MonitorPlay, unavailable: Lock };
@@ -26,7 +29,7 @@ const ICONS: Record<RunPlace["where"], typeof Cloud> = { cloud: Cloud, gpu: Cpu,
* before, so a chip never says "Not available here" to the owner and then takes it back. With it, the account's own GPU
* and its first key (who its paid runs are billed to).
*/
-export function useRunViewer(): { audience: RunAudience; gpu: boolean; hosted: boolean; preferPool: boolean; payer: RunPlaceInput["payer"]; place: Place } | null {
+export function useRunViewer(): { audience: RunAudience; gpu: boolean; hosted: boolean; preferPool: boolean; runOn?: RunOnPick; payer: RunPlaceInput["payer"]; place: Place } | null {
const hydrated = useHydrated();
const viewer = useViewer().data;
const status = useStatus().data;
@@ -38,6 +41,8 @@ export function useRunViewer(): { audience: RunAudience; gpu: boolean; hosted: b
gpu: !!status?.viewer?.gpu.connected,
hosted: !!status?.viewer?.hosted,
preferPool: !!status?.viewer?.hosted && status.viewer.prefer === "pool",
+ // Where the account picked its runs to go (hosted runs only).
+ ...(status?.viewer?.hosted && status.viewer.runOn && { runOn: status.viewer.runOn }),
payer: keys.includes("fal") ? "fal" : (keys[0] ?? null),
place: placeOf(status?.viewer?.hosted ? status.viewer.placeName : null),
};
@@ -46,7 +51,10 @@ export function useRunViewer(): { audience: RunAudience; gpu: boolean; hosted: b
/** The place and price for this viewer (null until the viewer is known). */
export function useRunPlace(input: Omit<RunPlaceInput, "audience" | "format" | "gpu" | "hosted" | "preferPool" | "payer" | "place">): RunPlace | null {
const who = useRunViewer();
- return who ? runPlace({ ...input, ...who, format: formatCost }) : null;
+ if (!who) return null;
+ const { runOn: _runOn, ...facts } = who;
+ void _runOn;
+ return runPlace({ ...input, ...facts, format: formatCost });
}
/**
@@ -67,7 +75,12 @@ export function useOpenRunPlace(models: readonly string[], request: GenerationRe
// This studio's GPUs only on the server's word (as the studio composer asks it): a model it doesn't offer there, or
// no complete run to check yet, is your GPU (connect it, or sign up).
const pool = mayPool ? checkedPool(checked, o.count) : undefined;
- return runPlace({ engine: "open", models, ...viewer, hosted: !!pool, pool, format: formatCost });
+ const { runOn: _runOn, ...facts } = viewer;
+ void _runOn;
+ const shown = runPlace({ engine: "open", models, ...facts, hosted: !!pool, pool, format: formatCost });
+ // This studio's GPUs don't take this run for this viewer (the check said so), or the tool runs on its own GPU only: the
+ // Run on list isn't offered.
+ return o.ownGpuOnly || (mayPool && checked !== undefined && !pool) ? { ...shown, siteRuns: false } : shown;
}
/**
@@ -82,6 +95,7 @@ export function RunPlaceChip({
onEngine,
pending,
compact,
+ runLabel = "Run",
className,
}: {
place: RunPlace | null;
@@ -94,101 +108,119 @@ export function RunPlaceChip({
pending?: boolean;
/** On phones, the icon and the price only (the icon alone when there is no price); the panel says the rest. */
compact?: boolean;
+ /** The page's run button ("Run", "Render"), for the one-time note about where runs go. */
+ runLabel?: string;
className?: string;
}) {
const [open, setOpen] = useState(false);
+ // Hosted runs: the Run on list for an account with a GPU of its own, on an open run this studio's GPUs take too.
+ const viewer = useStatus().data?.viewer;
+ const setRunOn = useSetRunOn();
+ const openRun = !!place && (place.where === "pool" || place.where === "gpu") && !place.setup && engine !== "cloud";
+ const rows = openRun ? placeRows(viewer, { siteRuns: place.siteRuns }, { text: place.where === "pool" ? place.price : undefined }) : null;
const pathname = usePathname();
const press = useOwnSetupPress();
// A phone's sheet says the title and the tip in its own header; the desktop popover says them here.
const mobile = useIsMobile();
if (!place) return null;
const Icon = ICONS[place.where];
+ // Once, for an account whose runs moved to this studio's GPUs when hosted runs went on (a tool page starts runs too).
+ const intro = openRun ? <PlaceIntroNote run={runLabel} /> : null;
const price = pending && !place.price ? "…" : place.price;
const canSwitch = !!(engine && onEngine && (place.where === "cloud" || place.where === "gpu" || place.where === "pool"));
const many = (steps?.length ?? 0) > 1;
// A compact chip on a phone: the label goes (the price stays), so the composer's other controls keep their room.
const iconOnly = compact && !price;
return (
- <ResponsivePanel
- open={open}
- onOpenChange={setOpen}
- title={place.title}
- description={place.tip}
- align="end"
- focusSelf
- trigger={
- <button
- type="button"
- data-run-place={place.where}
- aria-label={`${place.title}${place.model ? ` on ${place.model}` : ""}${place.price ? `, ${place.price}` : ""}. ${canSwitch ? "Details and engine" : "Details"}`}
- title={compact ? [place.label, place.price].filter(Boolean).join(" · ") : undefined}
- className={cn(chipBase, chipIdle, "max-w-full min-w-0", iconOnly && "max-sm:px-2.5", className)}
- >
- <Icon className="size-3.5 shrink-0" />
- <span className={cn("min-w-0 truncate max-sm:max-w-[9rem]", compact && "max-sm:hidden")}>{place.label}</span>
- {price && (
- <>
- <span aria-hidden className={cn("opacity-50", compact && "max-sm:hidden")}>
- ·
- </span>
- <span className="shrink-0 tabular-nums">{price}</span>
- </>
- )}
- </button>
- }
- >
- <div className="space-y-3 text-[13px]">
- {!mobile && (
- <div>
- <p className="font-semibold">{place.title}</p>
- <p className="mt-0.5 text-[12px] leading-snug text-pretty text-muted-foreground">{place.tip}</p>
- </div>
- )}
- {many && (
- <ul className="space-y-1">
- {steps!.map((s) => (
- <li key={`${s.label}-${s.modelName}`} className="flex min-w-0 items-baseline justify-between gap-3">
- <span className="min-w-0 truncate">
- <span className="text-muted-foreground">{s.label}</span> · {s.modelName}
+ <>
+ {intro}
+ <ResponsivePanel
+ open={open}
+ onOpenChange={setOpen}
+ title={place.title}
+ description={place.tip}
+ align="end"
+ focusSelf
+ trigger={
+ <button
+ type="button"
+ data-run-place={place.where}
+ aria-label={`${place.title}${place.model ? ` on ${place.model}` : ""}${place.price ? `, ${place.price}` : ""}. ${canSwitch ? "Details and engine" : "Details"}`}
+ title={compact ? [place.label, place.price].filter(Boolean).join(" · ") : undefined}
+ className={cn(chipBase, chipIdle, "max-w-full min-w-0", iconOnly && "max-sm:px-2.5", className)}
+ >
+ <Icon className="size-3.5 shrink-0" />
+ <span className={cn("min-w-0 truncate max-sm:max-w-[9rem]", compact && "max-sm:hidden")}>{place.label}</span>
+ {price && (
+ <>
+ <span aria-hidden className={cn("opacity-50", compact && "max-sm:hidden")}>
+ ·
</span>
- {place.where === "cloud" && s.costUsd != null && <span className="shrink-0 font-mono text-[12px] text-muted-foreground tabular-nums">{s.costUsd === 0 ? "Free" : `≈ ${formatCost(s.costUsd)}`}</span>}
- </li>
- ))}
- </ul>
- )}
- {place.price && (
- <p className="flex items-baseline justify-between gap-3 border-t pt-2 font-medium">
- <span>{many ? "In all" : "Price"}</span>
- <span className="font-mono tabular-nums">{place.price}</span>
- </p>
- )}
- {place.needs === "signup" && (
- <Button asChild size="sm" className="w-full">
- <Link href={signInHref("signup", pathname)}>Sign up free</Link>
- </Button>
- )}
- {place.setup && place.needs && place.needs !== "signup" && (
- <Button size="sm" className="w-full" onClick={() => (setOpen(false), press(place.setup))}>
- {place.needs === "key" ? "Add your key" : "Connect your GPU"}
- </Button>
- )}
- {!place.setup && place.needs === "gpu" && (
- <Button size="sm" className="w-full" onClick={() => (setOpen(false), window.dispatchEvent(new Event(CONNECT_GPU_EVENT)))}>
- Connect your GPU
- </Button>
- )}
- {!place.setup && place.needs === "key" && (
- <Button size="sm" className="w-full" onClick={() => (setOpen(false), openAddKey("fal"))}>
- Add your key
- </Button>
- )}
- {canSwitch && (
- <div className="flex flex-wrap items-center justify-between gap-2 border-t pt-3">
- <span className="text-[12px] font-medium text-muted-foreground">Engine</span>
- <EngineSwitch value={engine!} onChange={onEngine!} size="sm" compact={false} />
- </div>
- )}
- </div>
- </ResponsivePanel>
+ <span className="shrink-0 tabular-nums">{price}</span>
+ </>
+ )}
+ </button>
+ }
+ >
+ <div className="space-y-3 text-[13px]">
+ {!mobile && (
+ <div>
+ <p className="font-semibold">{place.title}</p>
+ <p className="mt-0.5 text-[12px] leading-snug text-pretty text-muted-foreground">{place.tip}</p>
+ </div>
+ )}
+ {many && (
+ <ul className="space-y-1">
+ {steps!.map((s) => (
+ <li key={`${s.label}-${s.modelName}`} className="flex min-w-0 items-baseline justify-between gap-3">
+ <span className="min-w-0 truncate">
+ <span className="text-muted-foreground">{s.label}</span> · {s.modelName}
+ </span>
+ {place.where === "cloud" && s.costUsd != null && <span className="shrink-0 font-mono text-[12px] text-muted-foreground tabular-nums">{s.costUsd === 0 ? "Free" : `≈ ${formatCost(s.costUsd)}`}</span>}
+ </li>
+ ))}
+ </ul>
+ )}
+ {place.price && (
+ <p className="flex items-baseline justify-between gap-3 border-t pt-2 font-medium">
+ <span>{many ? "In all" : "Price"}</span>
+ <span className="font-mono tabular-nums">{place.price}</span>
+ </p>
+ )}
+ {place.needs === "signup" && (
+ <Button asChild size="sm" className="w-full">
+ <Link href={signInHref("signup", pathname)}>Sign up free</Link>
+ </Button>
+ )}
+ {place.setup && place.needs && place.needs !== "signup" && (
+ <Button size="sm" className="w-full" onClick={() => (setOpen(false), press(place.setup))}>
+ {place.needs === "key" ? "Add your key" : "Connect your GPU"}
+ </Button>
+ )}
+ {!place.setup && place.needs === "gpu" && (
+ <Button size="sm" className="w-full" onClick={() => (setOpen(false), window.dispatchEvent(new Event(CONNECT_GPU_EVENT)))}>
+ Connect your GPU
+ </Button>
+ )}
+ {!place.setup && place.needs === "key" && (
+ <Button size="sm" className="w-full" onClick={() => (setOpen(false), openAddKey("fal"))}>
+ Add your key
+ </Button>
+ )}
+ {rows && (
+ <div className="border-t pt-2">
+ <p className="px-2.5 pb-1 text-[12px] font-medium text-muted-foreground">Run on</p>
+ <RunOnList rows={rows.rows} disabled={setRunOn.isPending} onPick={(id) => setRunOn.mutate({ runOn: id })} />
+ </div>
+ )}
+ {canSwitch && (
+ <div className="flex flex-wrap items-center justify-between gap-2 border-t pt-3">
+ <span className="text-[12px] font-medium text-muted-foreground">Engine</span>
+ <EngineSwitch value={engine!} onChange={onEngine!} size="sm" compact={false} />
+ </div>
+ )}
+ </div>
+ </ResponsivePanel>
+ </>
);
}
diff --git a/src/instrumentation.ts b/src/instrumentation.ts
index 867f8e9c..eafc5832 100644
--- a/src/instrumentation.ts
+++ b/src/instrumentation.ts
@@ -23,6 +23,9 @@ export async function register() {
const { ensureRelaySweep } = await import("./server/computer/tasks");
const { onAccountDeleted } = await import("./server/account-files");
ensureRelaySweep(onAccountDeleted);
+ // Where a deleted account's runs went (its pick of a place, hosted runs) goes with it.
+ const { clearRunOn } = await import("./server/run-on");
+ onAccountDeleted(clearRunOn);
// Faceless / Explainer renders whose narration was timed while the server was down continue with their scenes.
const { ensureFacelessRunner } = await import("./server/faceless");
ensureFacelessRunner();
diff --git a/src/lib/api.ts b/src/lib/api.ts
index aa2a23a8..c7b96f68 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -972,6 +972,13 @@ export interface StatusInfo {
* "key" starts its engine switch on Cloud (src/lib/engine-pref.ts).
*/
runOn?: "site" | "gpu" | "key";
+ /** With `runOn` "key": the provider whose key runs them. */
+ runKey?: CloudProvider;
+ /**
+ * The account ran on its own GPU or key before it first ran on this studio's GPUs, and picked no place since: the
+ * one-time note (src/components/studio/place-intro.tsx) says where runs go now. Only with `hosted`.
+ */
+ ranOwn?: true;
/** The words a preset card shows when its run would go to this studio's GPUs ("Try free"), from the server. None: no words. */
cardText?: string;
/** What this studio's GPUs keep off, for a viewer with no GPU of its own: its pickers leave it out (src/lib/pool-rules.ts). */
diff --git a/src/lib/before-run.ts b/src/lib/before-run.ts
index 6932cd5a..db33ca61 100644
--- a/src/lib/before-run.ts
+++ b/src/lib/before-run.ts
@@ -7,7 +7,8 @@
*/
import { dualEngine } from "./catalog/engines";
import type { Engine, GenerationRequest } from "./catalog/types";
-import { withKeyAction, type Diagnosis, type TroubleAction } from "./diagnose";
+import { runOnSiteAction, withKeyAction, type Diagnosis, type TroubleAction } from "./diagnose";
+import type { Place } from "./place-name";
import { cloudVersion, type CloudProvider } from "./your-keys";
type Routed = { id: string; engine: string; engines?: Engine[]; routes: { provider: string }[] };
@@ -43,6 +44,12 @@ export function gpuBeforeRun(o: {
preset?: Parameters<typeof cloudVersion>[0];
has: (id: string) => boolean;
getModel: (id: string) => Routed | undefined;
+ /** Hosted runs are on: a key's offer then says its price, and with none known isn't made (never a key billed unpriced). */
+ hosted?: boolean;
+ /** Hosted runs, for an item this install's GPUs take: their name. "Run on Our GPUs" then comes first (this run, once). */
+ site?: Place | null;
+ /** The key's price for this run's cloud version ("≈ $0.04"), when known. */
+ keyPrice?: string | null;
}): BeforeRun | null {
const { viewer, model } = o;
if (viewer?.kind !== "account" || !model || o.onPool) return null;
@@ -51,7 +58,8 @@ export function gpuBeforeRun(o: {
const gpu = viewer.gpu;
if (!toOwnGpu || !gpu.connected || gpu.mode !== "link" || gpu.online !== false) return null;
// The cloud version itself (its model and operation there), so one click runs it, once.
- const twin = viewer.paidAllowed !== false ? cloudVersion(o.preset, model, viewer.keys ?? [], o.has, o.getModel) : null;
+ const found = viewer.paidAllowed !== false ? cloudVersion(o.preset, model, viewer.keys ?? [], o.has, o.getModel) : null;
+ const twin = found && (!o.hosted || o.keyPrice) ? found : null;
const base: TroubleAction[] = gpu.trouble?.actions ?? [
{ kind: "check-gpu", label: "Check my GPU" },
{ kind: "gpu-settings", label: "Open Settings → Your GPU", target: "/settings#your-gpu" },
@@ -59,7 +67,11 @@ export function gpuBeforeRun(o: {
return {
words: gpu.trouble?.words ?? GPU_OFF_WORDS,
...(gpu.trouble?.details && { details: gpu.trouble.details }),
- actions: [...base.filter((a) => a.kind !== "retry" && a.kind !== "run-with-key"), ...(twin ? [withKeyAction(twin.provider, twin.modelId, twin.op)] : [])],
+ actions: [
+ ...(o.site ? [runOnSiteAction(o.site.label)] : []),
+ ...base.filter((a) => a.kind !== "retry" && a.kind !== "run-with-key" && a.kind !== "run-on-site"),
+ ...(twin ? [withKeyAction(twin.provider, twin.modelId, twin.op, o.hosted ? o.keyPrice : undefined)] : []),
+ ],
};
}
diff --git a/src/lib/diagnose.ts b/src/lib/diagnose.ts
index bd9facd9..7e5b6312 100644
--- a/src/lib/diagnose.ts
+++ b/src/lib/diagnose.ts
@@ -75,7 +75,12 @@ export type TroubleActionKind =
/** Pair a ComfyUI with a code (/connect): no web address needed. */
| "pair"
/** Run on the ComfyUI on this computer instead. */
- | "use-computer";
+ | "use-computer"
+ /**
+ * Hosted runs: run this once on this install's GPUs ("Run on Our GPUs"), offered only where they take it. One-off:
+ * the account's pick of where its runs go stays as it was.
+ */
+ | "run-on-site";
export interface TroubleAction {
kind: TroubleActionKind;
@@ -169,17 +174,21 @@ const A = {
pair: (): TroubleAction => ({ kind: "pair", label: "Pair with a code", target: "/connect" }),
pick: (): TroubleAction => ({ kind: "pick-model", label: "Pick another model" }),
credit: (p: CloudProvider): TroubleAction => ({ kind: "add-credit", label: `Add credit on ${CLOUD_KEY[p].label}`, target: BILLING_URL[p] }),
- withKey: (p: CloudProvider): TroubleAction => ({ kind: "run-with-key", label: `Run with your ${CLOUD_KEY[p].label} key`, target: p }),
+ withKey: (p: CloudProvider, price?: string | null): TroubleAction => ({ kind: "run-with-key", label: `Run with your ${CLOUD_KEY[p].label} key${price ? ` · ${price}` : ""}`, target: p }),
};
/**
* "Run with your fal.ai key": offered on a GPU trouble when the account has a key that runs this tool's cloud version
- * (`modelId`). An explicit click: it spends the person's own credit.
+ * (`modelId`). An explicit click: it spends the person's own credit, so with its price when known ("Run with your
+ * fal.ai key · ≈ $0.04").
*/
-export function withKeyAction(p: CloudProvider, modelId?: string, op?: string): TroubleAction {
- return { ...A.withKey(p), ...(modelId && { modelId }), ...(modelId && op && { op }) };
+export function withKeyAction(p: CloudProvider, modelId?: string, op?: string, price?: string | null): TroubleAction {
+ return { ...A.withKey(p, price), ...(modelId && { modelId }), ...(modelId && op && { op }) };
}
+/** "Run on Our GPUs": this run, once, on this install's GPUs (hosted runs), by the name visitors read for them. */
+export const runOnSiteAction = (placeLabel: string): TroubleAction => ({ kind: "run-on-site", label: `Run on ${placeLabel}` });
+
// ---------------------------------------------------------------------------
// Your GPU
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index 5a637b3a..87b1ed78 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -202,6 +202,7 @@ export function accountOwnRead(pathname: string): boolean {
pathname === "/api/generations" ||
pathname === "/api/account/gpu" ||
pathname === "/api/account/keys" ||
+ pathname === "/api/account/run-on" ||
ACCOUNT_CANVASES.test(pathname) ||
GPU_READS.has(pathname) ||
COMPUTER_READ.test(pathname) ||
@@ -254,6 +255,8 @@ export function accountMayChange(method: string, pathname: string, search: strin
if (method === "POST" && pathname === "/api/auth/logout") return true;
if ((method === "PUT" || method === "DELETE") && pathname === "/api/account/gpu") return true;
if ((method === "PUT" || method === "DELETE") && /^\/api\/account\/keys\/(fal|replicate)$/.test(pathname)) return true;
+ // Where its runs go (hosted runs: the Run on list, Settings, the one-time note). The route keeps its own pick only.
+ if (method === "PUT" && pathname === "/api/account/run-on") return true;
// GPU pre-flight: checking its own ComfyUI (reads only; the routes check the target and the request themselves).
if ((method === "POST" && pathname === "/api/gpu/check") || (method === "PUT" && pathname === "/api/gpu/inventory")) return true;
// Running its own jobs on its own computer, and pairing (or unpairing) its own ComfyUI.
diff --git a/src/lib/place-intro.ts b/src/lib/place-intro.ts
new file mode 100644
index 00000000..cf1338ff
--- /dev/null
+++ b/src/lib/place-intro.ts
@@ -0,0 +1,48 @@
+import { placeOf } from "./place-name";
+import { CLOUD_KEY, type CloudProvider } from "./your-keys";
+
+/**
+ * The one-time note for an account whose runs moved when hosted runs went on (src/components/studio/place-intro.tsx):
+ * it had a GPU or a key of its own, ran on it before it first ran on this install's GPUs (`ranOwn`, from the server),
+ * and has picked no place since. Its two buttons both keep a pick on the server, so the note never comes back, on any
+ * device: "Keep my GPU as the default" (or key) keeps the old place; OK keeps this install's GPUs. Pure, for its tests.
+ */
+
+export interface PlaceIntroViewer {
+ kind?: "guest" | "account";
+ hosted?: boolean;
+ placeName?: string;
+ runOn?: string;
+ ranOwn?: boolean;
+ gpu: { connected: boolean };
+ keys?: CloudProvider[];
+}
+
+export interface PlaceIntro {
+ /** The first words, in bold. */
+ lead: string;
+ rest: string;
+ /** The first button: keep the old place as the default. */
+ keep: { label: string; runOn: "gpu" | "key"; key?: CloudProvider };
+}
+
+/** The note for this viewer, or null. `run`: the page's own button ("Generate", "Render", "Run"). */
+export function placeIntro(v: PlaceIntroViewer | undefined | null, run: string): PlaceIntro | null {
+ if (!v?.hosted || v.kind !== "account" || !v.ranOwn || v.runOn) return null;
+ const place = placeOf(v.placeName);
+ if (v.gpu.connected) {
+ return {
+ lead: `Runs now go to ${place.text}, free.`,
+ rest: `Your GPU is one tap away: Free ▾, next to ${run}.`,
+ keep: { label: "Keep my GPU as the default", runOn: "gpu" },
+ };
+ }
+ const keys = v.keys ?? [];
+ const key = keys.includes("fal") ? "fal" : keys[0];
+ if (!key) return null;
+ return {
+ lead: `Open models now run free on ${place.text}.`,
+ rest: `Your ${CLOUD_KEY[key].label} key still runs the cloud models: pick Cloud in the model list.`,
+ keep: { label: "Keep my key as the default", runOn: "key", key },
+ };
+}
diff --git a/src/lib/pool-rules.ts b/src/lib/pool-rules.ts
index 482fbffe..75457f0f 100644
--- a/src/lib/pool-rules.ts
+++ b/src/lib/pool-rules.ts
@@ -139,3 +139,15 @@ export function tryFreeFor(
const rules = viewer.gpu.connected ? undefined : viewer.pool;
return { text: viewer.cardText, runs: (p) => p.open && poolRunsPreset(rules, p.id) };
}
+
+/**
+ * The rules a viewer's pickers label with (hosted runs): for every viewer whose runs go to this studio's GPUs, a GPU of
+ * its own or not. A viewer with a GPU sees what they keep off labelled "Runs on your own GPU", and that runs there at
+ * once; one whose runs go to its own GPU (its pick, or an install that puts it first) sees no labels. Undefined while
+ * hosted runs are off, or with nothing kept off.
+ */
+export function pickerRules(v: { hosted?: boolean; prefer?: "pool"; runOn?: string; gpu: { connected: boolean }; pool?: PoolRules } | undefined): PoolRules | undefined {
+ if (!v?.hosted || !v.pool) return undefined;
+ const here = !v.gpu.connected || v.runOn === "site" || v.runOn === "key" || (!v.runOn && v.prefer === "pool");
+ return here ? v.pool : undefined;
+}
diff --git a/src/lib/run-on.ts b/src/lib/run-on.ts
new file mode 100644
index 00000000..de887ddb
--- /dev/null
+++ b/src/lib/run-on.ts
@@ -0,0 +1,73 @@
+"use client";
+
+import { useMutation, useQueryClient, type QueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import type { StatusInfo } from "./api";
+import { refreshPriceChecks } from "./hosted";
+import type { Place } from "./place-name";
+import type { RunOnPick } from "./run-place";
+import type { CloudProvider } from "./your-keys";
+
+/**
+ * The browser's side of where an account's runs go (hosted runs; src/server/run-on.ts): the Run on list, Settings →
+ * Your GPU, the one-time note and "Use it for my runs" write the account's pick with one call, kept on the server for
+ * every device. The page follows it at once (the status is updated before the server answers).
+ */
+
+export const RUN_ON_PATH = "/api/account/run-on";
+
+/** Said once when a place the runs went to is gone (its key removed, its GPU forgotten). */
+export const runsGoNowText = (place: Place): string => `Your runs go to ${place.text} now.`;
+
+/** The account's pick as the page shows it at once, before the server answers. */
+export function noteRunOn(qc: QueryClient, runOn: RunOnPick | null, runKey?: CloudProvider): void {
+ qc.setQueryData<StatusInfo>(["status"], (s) => {
+ if (!s?.viewer) return s;
+ const { runOn: _r, runKey: _k, ranOwn: _o, ...viewer } = s.viewer;
+ void _r;
+ void _k;
+ void _o;
+ return {
+ ...s,
+ viewer: {
+ ...viewer,
+ ...(runOn && { runOn }),
+ ...(runOn === "key" && runKey && { runKey }),
+ },
+ };
+ });
+}
+
+/** Keep the account's pick (PUT /api/account/run-on). Throws the server's words when it can't. */
+export async function putRunOn(runOn: RunOnPick, key?: CloudProvider): Promise<{ runOn: RunOnPick | null; runKey?: CloudProvider }> {
+ const res = await fetch(RUN_ON_PATH, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ runOn, ...(key && { key }) }),
+ });
+ const b = (await res.json().catch(() => ({}))) as {
+ runOn?: RunOnPick | null;
+ runKey?: CloudProvider;
+ error?: string;
+ };
+ if (!res.ok) throw new Error(b.error ?? "That didn't save. Try once more.");
+ return { runOn: b.runOn ?? null, ...(b.runKey && { runKey: b.runKey }) };
+}
+
+/**
+ * Pick where the account's runs go: shown at once, kept on the server, and the status and the price checks asked again
+ * (the price and the line follow the place). A refusal puts the status back and says why.
+ */
+export function useSetRunOn() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: ({ runOn, key }: { runOn: RunOnPick; key?: CloudProvider }) => putRunOn(runOn, key),
+ onMutate: ({ runOn, key }) => noteRunOn(qc, runOn, key),
+ onSuccess: (r) => noteRunOn(qc, r.runOn, r.runKey),
+ onError: (e) => toast((e as Error).message, { id: "run-on" }),
+ onSettled: () => {
+ void qc.invalidateQueries({ queryKey: ["status"] });
+ refreshPriceChecks(qc);
+ },
+ });
+}
diff --git a/src/lib/run-place.ts b/src/lib/run-place.ts
index 85f279a2..73fc19b3 100644
--- a/src/lib/run-place.ts
+++ b/src/lib/run-place.ts
@@ -2,6 +2,7 @@ import { RUN_SHOWN_HEADER, shownHeader } from "./guest-access";
import { ownSetupDetail, ownSetupLabel, type OwnSetup } from "./own-setup";
import { placeOf, type Place } from "./place-name";
import { lineWords } from "./pool-line";
+import { deviceLabel } from "./gpu/readiness";
import { billedTo, CLOUD_KEY, type CloudProvider } from "./your-keys";
/**
@@ -72,6 +73,8 @@ export interface RunPlace {
model?: string;
/** It runs on the visitor's own setup (own-setup.ts): the send button opens that setup (`needs` says which). */
setup?: OwnSetup;
+ /** False: this studio's GPUs don't take this run for this viewer (hosted runs), so there is no Run on choice for it. */
+ siteRuns?: boolean;
}
const list = (names: readonly string[]) => (names.length < 2 ? (names[0] ?? "") : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`);
@@ -206,16 +209,28 @@ export function mainModel(steps: readonly { modelName: string; costUsd: number |
return best?.modelName;
}
+/** Where an account picked its runs to go (the Run on list; hosted runs): this studio's GPUs, its own GPU, or its key. */
+export type RunOnPick = "site" | "gpu" | "key";
+
/**
- * Where a studio composer's run goes, with hosted runs on: the person's pick, else its own GPU while that is online
- * (unless the studio puts its own GPUs first), else this studio's GPUs. `place` is what the run names beside the request:
- * none when the default is this studio's GPUs only because the studio puts them first, so the server decides, and a
+ * Where a studio composer's run goes, with hosted runs on, in one order: a place picked for this run (`pick`), then the
+ * account's remembered pick (`runOn`): its own GPU, sent there even while it doesn't answer (never moved anywhere else
+ * without a word: the check before Run says so and offers a run elsewhere); this studio's GPUs first (a pick of them,
+ * or of its key, whose runs come here on the Open source engine). With no pick: its own GPU while that is online (unless
+ * the studio puts its own GPUs first), else this studio's GPUs. `place` is what the run names beside the request: none
+ * when this studio's GPUs go first while its own GPU is online, so the server decides (it reads the same pick), and a
* model this studio's GPUs don't take still runs on the account's own GPU.
*/
-export function composerPlace(pick: "own" | "pool" | null, ownOnline: boolean, preferPool: boolean): { runOn: "own" | "pool"; place: "own" | "pool" | undefined } {
+export function composerPlace(
+ pick: "own" | "pool" | null,
+ runOn: RunOnPick | null | undefined,
+ ownOnline: boolean,
+ preferPool: boolean,
+): { runOn: "own" | "pool"; place: "own" | "pool" | undefined } {
if (pick) return { runOn: pick, place: pick };
+ if (runOn === "gpu") return { runOn: "own", place: "own" };
if (!ownOnline) return { runOn: "pool", place: "pool" };
- return preferPool ? { runOn: "pool", place: undefined } : { runOn: "own", place: "own" };
+ return preferPool || runOn === "site" || runOn === "key" ? { runOn: "pool", place: undefined } : { runOn: "own", place: "own" };
}
/**
@@ -236,10 +251,107 @@ export function composerOnPool(place: "own" | "pool" | undefined, checked: { pla
* to that GPU, and the check says so). Null: no check (the owner, hosted runs off, a tool for the person's own GPU only,
* or a viewer whose runs go to its own GPU).
*/
-export function openCheckPlace(v: { audience: RunAudience; gpu: boolean; hosted: boolean; preferPool: boolean } | null, ownGpuOnly = false): "pool" | undefined | null {
+export function openCheckPlace(
+ v: { audience: RunAudience; gpu: boolean; hosted: boolean; preferPool: boolean; runOn?: RunOnPick | null } | null,
+ ownGpuOnly = false,
+): "pool" | undefined | null {
if (!v || ownGpuOnly || v.audience === "owner" || !v.hosted) return null;
if (!v.gpu) return "pool";
- return v.preferPool ? undefined : null;
+ // Its own GPU, by its own pick: the run goes there (the server reads the same pick), so nothing is priced here.
+ if (v.runOn === "gpu") return null;
+ return v.preferPool || v.runOn === "site" || v.runOn === "key" ? undefined : null;
+}
+
+/**
+ * A run's request to send again (Retry): with hosted runs on, to the place it ran, named, so it never moves (a run on this
+ * studio's GPUs stays there, one on the person's own GPU or key stays there), whatever the account's pick says now.
+ * Hosted runs off: the request as it was.
+ */
+export function retryRequest<R extends object>(g: { request: R; place?: "pool" }, hosted: boolean): R {
+ return hosted ? { ...g.request, place: g.place === "pool" ? "pool" : "own" } : g.request;
+}
+
+/**
+ * "Run on Our GPUs" on a run that failed on the person's own GPU (hosted runs): an open run that ran there. One-off: it
+ * is sent again here, named, and the account's pick stays as it was.
+ */
+export const offersRunOnSite = (g: { place?: "pool"; engine: string; status: string }, hosted: boolean): boolean => hosted && g.place !== "pool" && g.engine === "open" && g.status === "failed";
+
+/** One row of the Run on list: a place, the line under it, and whether this item's runs go there now. */
+export interface RunOnRow {
+ id: RunOnPick;
+ /** "Our GPUs", "Your GPU", "Your fal.ai key". */
+ label: string;
+ /** "Free · Next in line · about 40 s", "Free · RTX 4090", "≈ $0.04 · billed to your fal.ai account". */
+ sub: string;
+ /** Your GPU: it answers now (a green dot). Not answering is said in `sub`; the row can still be picked. */
+ online?: boolean;
+ /** This item's next run goes here. */
+ selected: boolean;
+}
+
+/** The Run on list for one item, and where its next run goes. */
+export interface RunOnRows {
+ rows: RunOnRow[];
+ /** Where the next run goes (the chip's words follow it). */
+ on: RunOnPick;
+ /** The remembered place can't run this item, so this run goes to this studio's GPUs: said in the chip's tooltip. */
+ note?: string;
+}
+
+/** What the Run on list knows of the viewer (the status's viewer). */
+export interface RunOnViewer {
+ kind?: "guest" | "account";
+ hosted?: boolean;
+ prefer?: "pool";
+ placeName?: string;
+ runOn?: RunOnPick;
+ gpu: { connected: boolean; online?: boolean; device?: string };
+}
+
+/** The footer under the list: a pick holds for later runs too. */
+export const RUN_ON_FOOTER = "Your next runs go here too.";
+
+/** The words of a key's row: its price first when known, and who bills it. */
+export const keyRowSub = (p: CloudProvider, price?: string | null): string => (price ? `${price} · billed to ${billedTo(p)}` : `Billed to ${billedTo(p)}`);
+
+/**
+ * The Run on list for an item (hosted runs; an account only): this studio's GPUs always, its own GPU when one is
+ * connected (picking it is allowed while it doesn't answer: the check before Run says so), and the key that runs this
+ * item's cloud version (`item.key`, with its price when known). Null when there is nothing to choose: hosted runs off, a
+ * guest, no GPU and no key for this item ("No control without a choice"), or an item this studio's GPUs can't run (its
+ * label says where it runs instead). `quote`: the price check's words for a run here, and where it would stand in line.
+ * `item.cloud`: the item is on its cloud version now (the Cloud engine), so a pick of the key runs it there; on its open
+ * version a pick of the key runs it on this studio's GPUs (the key runs what has a cloud version only).
+ */
+export function placeRows(
+ viewer: RunOnViewer | undefined | null,
+ item: { key?: { provider: CloudProvider; price?: string | null } | null; siteRuns?: boolean; cloud?: boolean },
+ quote: { text?: string; wait?: string } = {},
+): RunOnRows | null {
+ if (!viewer?.hosted || viewer.kind !== "account" || item.siteRuns === false) return null;
+ const gpu = viewer.gpu.connected ? viewer.gpu : null;
+ const key = item.key ?? null;
+ if (!gpu && !key) return null;
+ const place = placeOf(viewer.placeName);
+ // Where the next run goes: the pick when this item runs there; with none, its own GPU while that is online on an
+ // install that puts it first (composerPlace), else this studio's GPUs.
+ const picked = viewer.runOn;
+ let on: RunOnPick = "site";
+ let note: string | undefined;
+ if (picked === "gpu" && gpu) on = "gpu";
+ else if (picked === "key") {
+ if (key && item.cloud) on = "key";
+ else if (!key) note = `Runs on ${place.text}. This one has no cloud version.`;
+ } else if (!picked && gpu?.online && viewer.prefer !== "pool") on = "gpu";
+ const rows: RunOnRow[] = [{ id: "site", label: place.label, sub: [quote.text || "Free", quote.wait].filter(Boolean).join(" · "), selected: on === "site" }];
+ if (gpu) {
+ // "RTX 4090", not ComfyUI's whole device name.
+ const device = deviceLabel(gpu.device).replace(/^NVIDIA\s+(GeForce\s+)?/i, "");
+ rows.push({ id: "gpu", label: "Your GPU", sub: gpu.online ? ["Free", device].filter(Boolean).join(" · ") : "Free · not answering right now", ...(gpu.online && { online: true }), selected: on === "gpu" });
+ }
+ if (key) rows.push({ id: "key", label: `Your ${CLOUD_KEY[key.provider].label} key`, sub: keyRowSub(key.provider, key.price), selected: on === "key" });
+ return { rows, on, ...(note && { note }) };
}
/** Drawn in this browser (a Kinetic template, Click to Ad's end card): the same place and price whoever looks. */
diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.ts
index 60cc77d3..511f086f 100644
--- a/src/server/account-gpu.ts
+++ b/src/server/account-gpu.ts
@@ -16,6 +16,7 @@ import { balance as billingBalance, policy as billingPolicy, type Action, type B
import { poolReady } from "./hosted";
import { placeName } from "./place-name";
import { poolOwnModels } from "./pool-own-setup";
+import { ranOwnFirst, runOnOf, type RunOn } from "./run-on";
import { poolRulesOf, type PoolRules, type PresetModel } from "@/lib/pool-rules";
import { diagnoseAddress, diagnoseGpu, gpuHostOf, type Diagnosis, type GpuFailure, type GpuPlace, type GpuStage } from "@/lib/diagnose";
@@ -330,6 +331,17 @@ export interface VisitorView {
prefer?: "pool";
/** The name visitors read for this install's GPUs ("Runs on Our GPUs"; src/server/place-name.ts). Only with `hosted`. */
placeName?: string;
+ /**
+ * Where the account's runs go, as it picked (run-on.ts; only with `hosted`, only to that account). Absent: the
+ * install's default. `runKey`: with "key", the provider whose key runs them.
+ */
+ runOn?: RunOn;
+ runKey?: CloudProvider;
+ /**
+ * The account ran on its own GPU or key before it first ran on this install's GPUs, and has picked no place yet:
+ * the one-time note says runs go to this install's GPUs now (only with `hosted`, only to that account).
+ */
+ ranOwn?: true;
/**
* The words a preset card shows when its run would go to this install's GPUs (the billing service's policy, such as
* "Try free"; with no service, "Try free": those runs are free). Absent: the cards show none.
@@ -399,9 +411,19 @@ export async function visitorStatus(account: Account | null) {
if (p?.hosted) viewer.placeName = placeName(p);
const card = p?.hosted && typeof p.cardText === "string" ? p.cardText.trim().slice(0, 40) : "";
if (card) viewer.cardText = card;
+ // The account's own pick of where its runs go, and whether the one-time note is for it (it had runs on its own GPU
+ // or key before, and has picked nothing yet).
+ if (account && p?.hosted) {
+ const pick = runOnOf(account.id, keys);
+ if (pick) {
+ viewer.runOn = pick.runOn;
+ if (pick.runKey) viewer.runKey = pick.runKey;
+ } else if ((gpu || keys.length) && ranOwnFirst(account.id)) viewer.ranOwn = true;
+ }
// What this studio's GPUs keep off, the open models they can't run right now among it: shown in the pickers with
- // what the visitor needs to run them on its own setup.
- const rules = p?.hosted && !gpu ? poolRulesOf(p, presetModels(), poolOwnModels()) : undefined;
+ // what the visitor needs to run them on its own setup. For every viewer, a GPU of its own or not: its runs go
+ // there first too, and the label says what runs on its own GPU instead.
+ const rules = p?.hosted ? poolRulesOf(p, presetModels(), poolOwnModels()) : undefined;
if (rules) viewer.pool = rules;
if (account && p?.links?.length) viewer.links = p.links;
if (account && p?.notice) viewer.notice = p.notice;
diff --git a/src/server/db.ts b/src/server/db.ts
index 9d850ba9..a6ec8f85 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -1194,6 +1194,8 @@ function open(): Database.Database {
db.exec(SKILL_TABLES);
// An account's own canvases (account-canvas.ts): not a numbered migration, so branches never clash over its place.
db.exec(ACCOUNT_CANVAS_TABLES);
+ // Where an account's runs go, as it picked (run-on.ts): read only while hosted runs are on, empty otherwise.
+ db.exec(RUN_ON_TABLES);
// Its list reads this small summary, never every board's pages (a table made before it had the column gets it).
if (!(db.prepare("PRAGMA table_info(account_canvases)").all() as { name: string }[]).some((c) => c.name === "summary_json")) {
addColumn(db, "ALTER TABLE account_canvases ADD COLUMN summary_json TEXT");
@@ -1228,6 +1230,17 @@ const ACCOUNT_CANVAS_TABLES = `CREATE TABLE IF NOT EXISTS account_canvases (
);
CREATE INDEX IF NOT EXISTS account_canvases_account ON account_canvases(account_id, updated_at DESC);`;
+/**
+ * Where an account's runs go while hosted runs are on, as it picked (run-on.ts): this install's GPUs, its own GPU, or
+ * its own key (`run_key`: which provider's). No row: the install's default. Not a numbered migration either.
+ */
+const RUN_ON_TABLES = `CREATE TABLE IF NOT EXISTS account_run_on (
+ account_id TEXT PRIMARY KEY,
+ run_on TEXT NOT NULL CHECK (run_on IN ('site', 'gpu', 'key')),
+ run_key TEXT CHECK (run_key IS NULL OR run_key IN ('fal', 'replicate')),
+ updated_at INTEGER NOT NULL
+ );`;
+
/**
* The runs let in whose rows are still being made (a tool's start that awaits before it makes them), counted until they
* exist (pool-limits.ts openAdmission).
diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.ts
index 1ba1ad32..312f08b8 100644
--- a/src/server/hosted-run.ts
+++ b/src/server/hosted-run.ts
@@ -46,6 +46,7 @@ import { needsGpu, ownSetupHere, poolCardRefuses, requestOwnSetup } from "./pool
import { ADD_KEY_HEADER } from "@/lib/your-keys";
import { placeOf, type Place } from "@/lib/place-name";
import { placeFor, placeOfAccount } from "./place-name";
+import { rememberedPlace } from "./run-on";
export { poolCardRefuses };
@@ -167,6 +168,17 @@ const askPlace = (place: Place): Refusal => ({ status: 409, body: { error: ownGp
/** Does the policy put runs on this install's GPUs first, before the account's own GPU? */
const prefersPool = (p: Policy | null | undefined): boolean => !!p?.hosted && p.prefer === "pool";
+/**
+ * Where the account's own pick sends a run that names no place (run-on.ts, hosted runs only): "own" its GPU, at once and
+ * never asked about; "pool" this install's GPUs first, as if the policy put them first for this account (what they
+ * can't take still runs on its own GPU); undefined with no pick, or for a run that names its place (a one-off: Retry,
+ * "Run on …", the first picture of a GPU's setup), which the pick never changes.
+ */
+const pickedPlace = (account: Account | null, wish: PlaceWish): PlaceWish => (account && !wish ? rememberedPlace(account.id) : undefined);
+
+/** This install's GPUs go first for this run: the policy says so, or the account picked them. */
+const poolFirst = (p: Policy | null | undefined, picked: PlaceWish): boolean => prefersPool(p) || picked === "pool";
+
/** May a run of this kind use this install's GPUs under the policy (`kinds` absent: every kind)? */
export const kindAllowed = (p: Pick<Policy, "kinds">, kind: RunFacts["kind"]): boolean => p.kinds?.[kind] !== false;
@@ -425,9 +437,16 @@ export function poolRequest(req: GenerationRequest, p: Pick<Policy, "limits"> |
* offered, LoRAs, inputs, a step no worker takes, 3D) goes to its own GPU, even while that GPU doesn't answer. Only a run
* this install's GPUs would take, that named no place, whose own GPU doesn't answer, is asked about (never moved there,
* and charged, unasked).
+ *
+ * One order (the place a run names, then what only one place can run, then the account's own pick, then the policy):
+ * a run that names no place follows the account's pick (run-on.ts): its own GPU, at once and never asked about; or this
+ * install's GPUs first, whatever the policy prefers. What these GPUs can't take still runs on its own GPU.
*/
export async function decidePlace(account: Account, asked: GenerationRequest, wish: PlaceWish): Promise<PlaceDecision> {
if (!hostedRunsOn() || wish === "own" || !poolReady()) return OWN;
+ // The account's own pick, for a run that names no place: its GPU at once, or this install's GPUs first.
+ const picked = pickedPlace(account, wish);
+ if (picked === "own") return OWN;
let planned: Planned;
try {
planned = runOnPool(account.id, () => previewGeneration(asked));
@@ -445,10 +464,10 @@ export async function decidePlace(account: Account, asked: GenerationRequest, wi
// call to the billing service); when none is kept, it is read while the GPU is checked.
let p = cachedPolicy(account.id);
let ownOffline = false;
- if (ownFallback && !prefersPool(p)) {
+ if (ownFallback && !poolFirst(p, picked)) {
const [online, read] = await Promise.all([ownGpuOnline(account.id), p === undefined ? billingPolicy(account.id) : Promise.resolve(p)]);
p = read;
- if (!prefersPool(p)) {
+ if (!poolFirst(p, picked)) {
if (online) return OWN;
ownOffline = true;
}
@@ -649,6 +668,9 @@ export async function poolQuote(
o: { addr?: () => string | null } = {},
): Promise<{ planned: Planned | null; quote: Quote; line: PoolLine } | null> {
if (!hostedRunsOn() || wish === "own" || !poolReady()) return null;
+ // The account's own pick, as its run would follow it: its GPU (no price here), or this install's GPUs first.
+ const picked = pickedPlace(account, wish);
+ if (picked === "own") return null;
// A guest is priced under the billing service's policy for guests (none set: as an account would be, once signed up).
const p = await billingPolicy(account?.id ?? null);
// Priced for the outputs it would make: the studio's cap per run, and the policy's when lower (as the run is).
@@ -665,7 +687,7 @@ export async function poolQuote(
}
if (planned.route.provider !== "comfyui") return null;
const hasGpu = !!account && !!accountGpu(account.id);
- if (account && hasGpu && wish !== "pool" && !prefersPool(p) && (await ownGpuOnline(account.id))) return null;
+ if (account && hasGpu && wish !== "pool" && !poolFirst(p, picked) && (await ownGpuOnline(account.id))) return null;
if (p && !p.hosted) return null;
const line = (facts: { ahead: number; etaS: number | null }, q?: Quote): PoolLine => ({ place: Math.max(0, facts.ahead) + 1, etaSeconds: q?.etaS ?? facts.etaS ?? null });
// What this install's GPUs won't take goes to the viewer's own GPU when it has one (as the run would); otherwise the
@@ -784,13 +806,15 @@ export function toolGate(
*/
export async function decideToolPlace(account: Account, steps: ToolRunStep[], wish: PlaceWish): Promise<ToolPlaceDecision> {
if (!hostedRunsOn() || wish === "own" || !poolReady() || !steps.length) return OWN;
+ const picked = pickedPlace(account, wish);
+ if (picked === "own") return OWN;
const ownFallback = !!accountGpu(account.id) && wish !== "pool";
let p = cachedPolicy(account.id);
let ownOffline = false;
- if (ownFallback && !prefersPool(p)) {
+ if (ownFallback && !poolFirst(p, picked)) {
const [online, read] = await Promise.all([ownGpuOnline(account.id), p === undefined ? billingPolicy(account.id) : Promise.resolve(p)]);
p = read;
- if (!prefersPool(p)) {
+ if (!poolFirst(p, picked)) {
if (online) return OWN;
ownOffline = true;
}
@@ -820,9 +844,11 @@ export async function toolPoolQuote(
o: { addr?: () => string | null } = {},
): Promise<{ quote: Quote; line: PoolLine } | null> {
if (!hostedRunsOn() || wish === "own" || !poolReady() || !steps.length) return null;
+ const picked = pickedPlace(account, wish);
+ if (picked === "own") return null;
const p = await billingPolicy(account?.id ?? null);
const hasGpu = !!account && !!accountGpu(account.id);
- if (account && hasGpu && wish !== "pool" && !prefersPool(p) && (await ownGpuOnline(account.id))) return null;
+ if (account && hasGpu && wish !== "pool" && !poolFirst(p, picked) && (await ownGpuOnline(account.id))) return null;
if (p && !p.hosted) return null;
const gate = toolGate(p, account?.id ?? null, steps);
if (gate === "unplanned") return null;
@@ -853,5 +879,7 @@ export async function toolPoolQuote(
*/
export function poolMayTake(account: Account | null, wish: PlaceWish): boolean {
if (!hostedRunsOn() || wish === "own" || !poolReady()) return false;
- return !account || !accountGpu(account.id) || wish === "pool" || prefersPool(cachedPolicy(account.id));
+ const picked = pickedPlace(account, wish);
+ if (picked === "own") return false;
+ return !account || !accountGpu(account.id) || wish === "pool" || poolFirst(cachedPolicy(account.id), picked);
}
diff --git a/src/server/run-on.ts b/src/server/run-on.ts
new file mode 100644
index 00000000..d75ca4e1
--- /dev/null
+++ b/src/server/run-on.ts
@@ -0,0 +1,116 @@
+import "server-only";
+import { isCloudProvider, type CloudProvider } from "@/lib/your-keys";
+import { accountProviders } from "./account-keys";
+import { accountGpu } from "./auth";
+import { db } from "./db";
+
+/**
+ * Where an account's runs go, as it picked (hosted runs: the Run on list, Settings → Your GPU, the one-time note):
+ * "site" this install's GPUs, "gpu" its own GPU, "key" its own fal.ai or Replicate key for what has a cloud version
+ * (the rest on this install's GPUs). No row: the install's default (the billing service's policy). A table of its own,
+ * made in db.ts (RUN_ON_TABLES), read only while hosted runs are on, and empty on every install where they are off.
+ *
+ * The pick names a place the account has: a pick of its GPU or key is dropped once that GPU is forgotten or that key is
+ * removed (clearRunOnFor; runOnOf drops one left behind), and its runs go to this install's GPUs again.
+ */
+
+export type RunOn = "site" | "gpu" | "key";
+
+export interface RunOnPick {
+ runOn: RunOn;
+ /** With "key": the provider whose key runs it. */
+ runKey?: CloudProvider;
+}
+
+export const isRunOn = (v: unknown): v is RunOn => v === "site" || v === "gpu" || v === "key";
+
+/** The pick as kept, or null (none kept). */
+export function getRunOn(accountId: string): RunOnPick | null {
+ const r = db().prepare("SELECT run_on, run_key FROM account_run_on WHERE account_id = ?").get(accountId) as
+ { run_on: string; run_key: string | null } | undefined;
+ if (!r || !isRunOn(r.run_on)) return null;
+ return {
+ runOn: r.run_on,
+ ...(r.run_on === "key" && isCloudProvider(r.run_key) && { runKey: r.run_key }),
+ };
+}
+
+/** Keep the account's pick (one row per account: a new pick replaces the old one). */
+export function setRunOn(accountId: string, pick: RunOnPick): void {
+ db()
+ .prepare(
+ `INSERT INTO account_run_on (account_id, run_on, run_key, updated_at) VALUES (?, ?, ?, ?)
+ ON CONFLICT(account_id) DO UPDATE SET run_on = excluded.run_on, run_key = excluded.run_key, updated_at = excluded.updated_at`,
+ )
+ .run(accountId, pick.runOn, pick.runOn === "key" ? (pick.runKey ?? null) : null, Date.now());
+}
+
+/** Forget the account's pick (a deleted account; nothing kept means the install's default). */
+export function clearRunOn(accountId: string): void {
+ db().prepare("DELETE FROM account_run_on WHERE account_id = ?").run(accountId);
+}
+
+/**
+ * The account's GPU was forgotten, or one of its keys removed: a pick of that place is dropped (its runs go to this
+ * install's GPUs again). True when it was dropped, so the page says where runs go now.
+ */
+export function clearRunOnFor(accountId: string, gone: { gpu: true } | { key: CloudProvider }): boolean {
+ const pick = getRunOn(accountId);
+ if (!pick) return false;
+ const drop = "gpu" in gone ? pick.runOn === "gpu" : pick.runOn === "key" && (!pick.runKey || pick.runKey === gone.key || !accountProviders(accountId).length);
+ if (drop) clearRunOn(accountId);
+ return drop;
+}
+
+/**
+ * The pick the account's runs follow: its kept pick while the place it names is still there (a GPU connected; a key
+ * this server can open), else none (and a pick left behind is dropped). `keys`: the providers it has a key for, when
+ * the caller has them already.
+ */
+export function runOnOf(accountId: string, keys?: CloudProvider[]): RunOnPick | null {
+ const pick = getRunOn(accountId);
+ if (!pick) return null;
+ if (pick.runOn === "gpu" && !accountGpu(accountId)) {
+ clearRunOn(accountId);
+ return null;
+ }
+ if (pick.runOn === "key") {
+ const has = keys ?? accountProviders(accountId);
+ if (!has.length) {
+ clearRunOn(accountId);
+ return null;
+ }
+ // The provider it named is gone but another key is there: that one runs it.
+ if (!pick.runKey || !has.includes(pick.runKey)) return { runOn: "key", runKey: has.includes("fal") ? "fal" : has[0] };
+ }
+ return pick;
+}
+
+/**
+ * Where the remembered pick sends a run that names no place of its own (hosted-run.ts): "own" for the account's GPU;
+ * "pool" for this install's GPUs (a pick of the key is carried by the page as the Cloud engine, so a run that comes
+ * here open runs on this install's GPUs); undefined with no pick (the install's default).
+ */
+export function rememberedPlace(accountId: string): "own" | "pool" | undefined {
+ const r = db().prepare("SELECT run_on FROM account_run_on WHERE account_id = ?").get(accountId) as { run_on: string } | undefined;
+ if (!r) return undefined;
+ if (r.run_on === "gpu") return accountGpu(accountId) ? "own" : undefined;
+ return r.run_on === "site" || r.run_on === "key" ? "pool" : undefined;
+}
+
+/**
+ * Has the account run on its own GPU or key before it ever ran on this install's GPUs (its own history: a run with no
+ * place "pool", older than its first run there)? Then hosted runs going on moved its runs, and the one-time note says
+ * so. An account that connected its GPU or saved its key after its first run here never ran elsewhere first.
+ */
+export function ranOwnFirst(accountId: string): boolean {
+ const r = db()
+ .prepare(
+ `SELECT MIN(CASE WHEN json_extract(request_json, '$.place') = 'pool' THEN created_at END) AS site,
+ MIN(CASE WHEN COALESCE(json_extract(request_json, '$.place'), '') <> 'pool' AND provider IN ('comfyui', 'fal', 'replicate') THEN created_at END) AS own
+ FROM generations WHERE json_extract(request_json, '$.account') = ?`,
+ )
+ .get(accountId) as { site: number | null; own: number | null } | undefined;
+ if (!r?.own) return false;
+ return r.site === null || r.own < r.site;
+}
diff --git a/tests/hosted-pickers.test.ts b/tests/hosted-pickers.test.ts
index b097920c..6eeccb79 100644
--- a/tests/hosted-pickers.test.ts
+++ b/tests/hosted-pickers.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { poolRulesOf, poolRunsModel, poolRunsPreset, presetOffered, tryFreeFor } from "@/lib/pool-rules";
+import { modelOwnSetup, pickerRules, poolRulesOf, poolRunsModel, poolRunsPreset, presetOffered, tryFreeFor } from "@/lib/pool-rules";
/*
* For a visitor with no GPU of its own (hosted runs), pickers label what this studio's GPUs keep off (the policy's
@@ -66,6 +66,28 @@ describe("what pickers label for a visitor with no GPU of its own", () => {
});
});
+describe("labels for a viewer with a GPU of its own (hosted runs)", () => {
+ const pool = { deny: ["oss-x"] };
+ const open = { id: "oss-x", kind: "image" as const, engine: "open" };
+ const gpu = { connected: true };
+ it("its runs go to this studio's GPUs (their default, or its pick of them or its key): what they keep off is labelled", () => {
+ for (const v of [{ hosted: true, prefer: "pool" as const, gpu, pool }, { hosted: true, runOn: "site", gpu, pool }, { hosted: true, runOn: "key", gpu, pool }]) {
+ expect(pickerRules(v)).toEqual(pool);
+ expect(modelOwnSetup(pickerRules(v), open)?.need).toBe("gpu");
+ }
+ });
+ it("its runs go to its own GPU (its pick, or an install that puts it first): no labels", () => {
+ expect(pickerRules({ hosted: true, prefer: "pool", runOn: "gpu", gpu, pool })).toBeUndefined();
+ expect(pickerRules({ hosted: true, gpu, pool })).toBeUndefined();
+ });
+ it("no GPU of its own: labelled as before; hosted runs off or nothing kept off: none", () => {
+ expect(pickerRules({ hosted: true, gpu: { connected: false }, pool })).toEqual(pool);
+ expect(pickerRules({ hosted: false, gpu: { connected: false }, pool })).toBeUndefined();
+ expect(pickerRules({ hosted: true, gpu: { connected: false } })).toBeUndefined();
+ expect(pickerRules(undefined)).toBeUndefined();
+ });
+});
+
describe("presets kept off with their model or the kind they make", () => {
const presets = [
{ id: "app-face", model: { id: "oss-face", kind: "image" as const } },
diff --git a/tests/hosted-price-check.test.ts b/tests/hosted-price-check.test.ts
index ebc6960f..4c55490e 100644
--- a/tests/hosted-price-check.test.ts
+++ b/tests/hosted-price-check.test.ts
@@ -222,7 +222,7 @@ describe("a run's state after a refresh or on a second device", () => {
});
describe("what this install's GPUs keep off, in the status", () => {
- it("is told to a visitor with no GPU of its own, only when the policy keeps something off, and never with hosted runs off", async () => {
+ it("is told to every visitor, a GPU of its own or not, only when the policy keeps something off, and never with hosted runs off", async () => {
process.env.FUOBE_BILLING_URL = fake.url;
process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
fake.policy = { ...FAKE_POLICY, pool: { deny: ["oss-z-image-turbo"], apps: { deny: ["app-x"] } }, kinds: { model3d: false } };
@@ -237,9 +237,10 @@ describe("what this install's GPUs keep off, in the status", () => {
expect(s.viewer.pool?.apps?.deny).toEqual(expect.arrayContaining(["app-x", ...offWithModel]));
expect(s.viewer.pool?.apps?.deny).not.toContain(PRESETS.find((p) => p.open && !offWithModel.includes(p.id))!.id);
expect((await visitorStatus(null)).viewer.pool).toEqual(s.viewer.pool);
- // Its own GPU runs what this install's GPUs don't: nothing is left out of its pickers.
+ // A GPU of its own: told too, so its pickers label what runs on its own GPU while its runs go to this install's GPUs
+ // (src/lib/pool-rules.ts pickerRules; none while its runs go to its own GPU).
auth.setAccountGpu(a, { mode: "computer" });
- expect((await visitorStatus(auth.accountById(a)!)).viewer.pool).toBeUndefined();
+ expect((await visitorStatus(auth.accountById(a)!)).viewer.pool).toEqual(s.viewer.pool);
auth.setAccountGpu(a, null);
billing.resetBillingCache();
fake.policy = { ...FAKE_POLICY };
diff --git a/tests/hosted-words.test.ts b/tests/hosted-words.test.ts
index 36f69dd1..4732f390 100644
--- a/tests/hosted-words.test.ts
+++ b/tests/hosted-words.test.ts
@@ -229,3 +229,35 @@ describe("the pages a visitor reads while hosted runs are on", () => {
expect(textOf(render(createElement(EngineSwitch, { value: "open", onChange: () => {} })))).not.toMatch(FORBIDDEN);
});
});
+
+describe("where runs go: the Run on list, Settings and the one-time note", () => {
+ const gpu = { connected: true, online: true, device: "cuda:0 NVIDIA GeForce RTX 4090" };
+ it("plain words, the place by its name, and no verb that agrees with it", async () => {
+ const { placeRows, RUN_ON_FOOTER } = await import("@/lib/run-place");
+ const { placeIntro } = await import("@/lib/place-intro");
+ const { runsGoNowText } = await import("@/lib/run-on");
+ const { runOnSiteAction, withKeyAction } = await import("@/lib/diagnose");
+ const agrees = /(Studio North GPUs|our GPUs|Our GPUs)\s+(is|are|was|were|make|makes|run|runs|has|have|need|needs)\b/;
+ for (const place of [NAMED, DEFAULT]) {
+ const viewer = { kind: "account" as const, hosted: true, prefer: "pool" as const, placeName: place.label, gpu };
+ const rows = [
+ ...placeRows(viewer, { key: { provider: "fal", price: "≈ $0.04" } }, { text: "Free", wait: "Next in line · about 40 s" })!.rows,
+ ...placeRows({ ...viewer, runOn: "gpu", gpu: { connected: true, online: false } }, { key: { provider: "replicate" } })!.rows,
+ ].flatMap((r) => [r.label, r.sub]);
+ const note = placeRows({ ...viewer, runOn: "key" }, { key: null })!.note!;
+ const intros = [placeIntro({ ...viewer, ranOwn: true }, "Generate")!, placeIntro({ ...viewer, ranOwn: true, gpu: { connected: false }, keys: ["fal"] }, "Run")!].flatMap((i) => [i.lead, i.rest, i.keep.label]);
+ state.status = hostedStatus({ placeName: place.label, gpu, keys: ["fal"] });
+ const settings = textOf(render(createElement((await import("@/components/gpu/where-runs-go")).WhereRunsGo)));
+ state.status = hostedStatus({ placeName: place.label });
+ const nothing = textOf(render(createElement((await import("@/components/gpu/where-runs-go")).WhereRunsGo)));
+ const words = [...rows, note, ...intros, RUN_ON_FOOTER, runsGoNowText(place), runOnSiteAction(place.label).label, withKeyAction("fal", "m", "t2i", "≈ $0.04").label, settings, nothing];
+ for (const w of words) {
+ expect(w, w).not.toMatch(FORBIDDEN);
+ expect(w, w).not.toMatch(agrees);
+ }
+ expect(settings).toContain("Where your runs go");
+ expect(settings).toContain(`Runs on ${place.text}: nothing to set up.`);
+ expect(nothing).toContain(`Your runs go to ${place.text}. Connect a GPU or add a key to have a choice.`);
+ }
+ });
+});
diff --git a/tests/own-graceful-ui.test.ts b/tests/own-graceful-ui.test.ts
index dd17ce22..78ef6ea4 100644
--- a/tests/own-graceful-ui.test.ts
+++ b/tests/own-graceful-ui.test.ts
@@ -67,6 +67,38 @@ describe("the check before Run", () => {
});
});
+describe("the check before Run while hosted runs are on", () => {
+ const place = { label: "Studio North GPUs", text: "Studio North GPUs" };
+ const base = { model: h3, engine: "open" as const, preset: fpv, has, getModel, hosted: true };
+ it("a GPU picked as the place that doesn't answer: Run on <the place> first, for this run only", () => {
+ const shown = gpuBeforeRun({ ...base, viewer: account(offline), site: place })!;
+ expect(shown.actions[0]).toEqual({ kind: "run-on-site", label: "Run on Studio North GPUs" });
+ expect(shown.actions.map((a) => a.kind)).toEqual(["run-on-site", "start-gpu", "check-gpu", "gpu-settings"]);
+ });
+ it("an item only its own GPU runs: no Run on <the place>", () => {
+ expect(gpuBeforeRun({ ...base, viewer: account(offline), site: null })!.actions.map((a) => a.kind)).not.toContain("run-on-site");
+ });
+ it("a key's offer says its price, and with no price known it isn't made", () => {
+ const priced = gpuBeforeRun({ ...base, viewer: account(offline, ["fal"]), site: place, keyPrice: "≈ $0.20" })!;
+ expect(priced.actions.at(-1)).toEqual(withKeyAction("fal", "minimax-h3", "i2v", "≈ $0.20"));
+ expect(priced.actions.at(-1)?.label).toBe("Run with your fal.ai key · ≈ $0.20");
+ expect(gpuBeforeRun({ ...base, viewer: account(offline, ["fal"]), site: place })!.actions.map((a) => a.kind)).not.toContain("run-with-key");
+ });
+ it("hosted runs off: the same buttons as before (no place, the key's offer without a price)", () => {
+ const off = gpuBeforeRun({ viewer: account(offline, ["fal"]), model: h3, engine: "open", preset: fpv, has, getModel, keyPrice: "≈ $0.20" })!;
+ expect(off.actions.map((a) => a.kind)).toEqual(["start-gpu", "check-gpu", "gpu-settings", "run-with-key"]);
+ expect(off.actions.at(-1)?.label).toBe("Run with your fal.ai key");
+ });
+ it("Run on <the place> shows only where the page can send the run there", () => {
+ const actions = [{ kind: "run-on-site" as const, label: "Run on Studio North GPUs" }, ...stopped.actions];
+ expect(render(createElement(TroubleActions, { actions }))).not.toContain("Run on Studio North GPUs");
+ const html = render(createElement(TroubleActions, { actions, handlers: { onRunOnSite: () => {} } }));
+ expect(html).toContain("Run on Studio North GPUs");
+ // First, in the main style.
+ expect(html.indexOf("Run on Studio North GPUs")).toBeLessThan(html.indexOf("Start your pod"));
+ });
+});
+
describe("Run with your key on a failed run", () => {
it("asks for the same run on the cloud version: its model and operation there, without the open graph's settings", () => {
const req = { feature: "video" as const, modelId: "oss-minimax-h3", presetId: "motion-fpv-drone", op: "i2v" as const, prompt: "", inputs: { images: ["/files/a.png"] }, params: { duration: 6, extra: { quality: "draft" } } };
diff --git a/tests/place-intro.test.ts b/tests/place-intro.test.ts
new file mode 100644
index 00000000..e58d5ba4
--- /dev/null
+++ b/tests/place-intro.test.ts
@@ -0,0 +1,66 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it, vi } from "vitest";
+
+/*
+ * The one-time note for an account whose runs moved to this studio's GPUs when hosted runs went on: it had a GPU or a
+ * key of its own and ran there before it first ran here (the server's `ranOwn`), and has picked no place since. Both
+ * buttons keep a pick on the server ("Keep my GPU as the default" its GPU; OK this studio's GPUs), so it shows once for
+ * the account, on any device. `{Run}` is the page's own button.
+ */
+
+vi.mock("@/lib/api", async (load) => ({ ...(await load<typeof import("@/lib/api")>()), useHydrated: () => true }));
+
+const { placeIntro } = await import("@/lib/place-intro");
+const { PlaceIntro } = await import("@/components/studio/place-intro");
+
+const gpu = { connected: true };
+const none = { connected: false };
+const base = { kind: "account" as const, hosted: true, ranOwn: true, placeName: "Studio North GPUs" };
+
+describe("who gets the note", () => {
+ it("an account with its GPU that ran there first, and no pick yet", () => {
+ expect(placeIntro({ ...base, gpu }, "Generate")).toEqual({
+ lead: "Runs now go to Studio North GPUs, free.",
+ rest: "Your GPU is one tap away: Free ▾, next to Generate.",
+ keep: { label: "Keep my GPU as the default", runOn: "gpu" },
+ });
+ });
+ it("a key only: open models run here now, its key still runs the cloud ones", () => {
+ expect(placeIntro({ ...base, gpu: none, keys: ["replicate"] }, "Render")).toEqual({
+ lead: "Open models now run free on Studio North GPUs.",
+ rest: "Your Replicate key still runs the cloud models: pick Cloud in the model list.",
+ keep: { label: "Keep my key as the default", runOn: "key", key: "replicate" },
+ });
+ });
+ it("no one else: a pick made, no run elsewhere first, nothing of its own, a guest, hosted runs off", () => {
+ expect(placeIntro({ ...base, gpu, runOn: "site" }, "Run")).toBeNull();
+ expect(placeIntro({ ...base, gpu, ranOwn: false }, "Run")).toBeNull();
+ expect(placeIntro({ ...base, gpu: none, keys: [] }, "Run")).toBeNull();
+ expect(placeIntro({ ...base, kind: "guest", gpu }, "Run")).toBeNull();
+ expect(placeIntro({ ...base, hosted: false, gpu }, "Run")).toBeNull();
+ expect(placeIntro(undefined, "Run")).toBeNull();
+ });
+ it("the default name reads inside the sentence", () => {
+ expect(placeIntro({ ...base, placeName: undefined, gpu }, "Run")?.lead).toBe("Runs now go to our GPUs, free.");
+ });
+});
+
+describe("the note above Generate", () => {
+ const render = (viewer: object | undefined) => {
+ const client = new QueryClient();
+ if (viewer) client.setQueryData(["status"], { providers: {}, demoMode: "off", engineMode: "both", cloudProvider: "auto", viewer });
+ return renderToStaticMarkup(createElement(QueryClientProvider, { client }, createElement(PlaceIntro, { run: "Generate" })));
+ };
+ it("its two buttons, the first the old place", () => {
+ const html = render({ ...base, gpu });
+ expect(html).toContain("Runs now go to Studio North GPUs, free.");
+ expect(html.indexOf("Keep my GPU as the default")).toBeLessThan(html.indexOf(">OK<"));
+ });
+ it("nothing once a pick is made, or while hosted runs are off", () => {
+ expect(render({ ...base, gpu, runOn: "gpu" })).toBe("");
+ expect(render({ ...base, hosted: false, gpu })).toBe("");
+ expect(render(undefined)).toBe("");
+ });
+});
diff --git a/tests/run-on.test.ts b/tests/run-on.test.ts
new file mode 100644
index 00000000..2ba28e2e
--- /dev/null
+++ b/tests/run-on.test.ts
@@ -0,0 +1,300 @@
+import fs from "node:fs";
+import http from "node:http";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { listenOnFreePort, startFakeBilling, FAKE_POLICY, type FakeBilling } from "./helpers/fake-billing";
+import { startFakeComfy, type FakeComfy } from "./helpers/fake-comfy-runner";
+import { tempDir } from "./helpers/temp-dir";
+
+/*
+ * Where an account's runs go, as it picked (hosted runs): this install's GPUs, its own GPU, or its key. PUT
+ * /api/account/run-on keeps the pick for the account, on the server (every device); the status sends it to that
+ * account only; every run and price check that names no place follows it in one order (a place the run names, then the
+ * pick, then the policy); it goes when the place it names goes (the GPU forgotten, the key removed) and with the
+ * account. While hosted runs are off the route doesn't exist and nothing reads the table.
+ */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+process.env.FUOBE_DATA_DIR = tempDir("fuobe-run-on-");
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+for (const k of ["FUOBE_PASSWORD", "FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN", "FUOBE_MODERATION_URL", "FUOBE_PLACE_NAME"]) delete process.env[k];
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const probe = http.createServer();
+const comfyPort = await listenOnFreePort(probe);
+await new Promise<void>((r) => probe.close(() => r()));
+const comfy: FakeComfy = await startFakeComfy({ output: "image", delayMs: 0 }, comfyPort);
+process.env.COMFYUI_URL = comfy.url;
+
+const auth = await import("@/server/auth");
+const route = await import("@/app/api/account/run-on/route");
+const gpuRoute = await import("@/app/api/account/gpu/route");
+const keyRoute = await import("@/app/api/account/keys/[provider]/route");
+const billing = await import("@/server/billing");
+const keys = await import("@/server/account-keys");
+const runOn = await import("@/server/run-on");
+const { visitorStatus, noteGpuState } = await import("@/server/account-gpu");
+const { decidePlace, poolMayTake, poolQuote } = await import("@/server/hosted-run");
+const { onAccountDeleted } = await import("@/server/account-files");
+const { removeAccount } = await import("@/server/account-sweep");
+const { db } = await import("@/server/db");
+const { accountMayChange, accountOwnRead } = await import("@/lib/guest-access");
+
+const GPU_URL = "https://my-gpu.example.com";
+const req = { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox in the snow" };
+
+let fake: FakeBilling;
+const ids: Record<string, string> = {};
+const cookies: Record<string, string> = {};
+beforeAll(async () => {
+ fake = await startFakeBilling();
+ auth.setPassword("install password");
+ for (const name of ["ana", "ben", "cy"]) {
+ ids[name] = auth.createAccount(`${name}@example.com`, "long enough").id;
+ cookies[name] = `${auth.SESSION_COOKIE}=${auth.createSession(ids[name]).value}`;
+ }
+ // The registration src/instrumentation.ts makes at start.
+ onAccountDeleted(runOn.clearRunOn);
+});
+afterAll(async () => {
+ globalThis.__fuobeTestDiskFree = undefined;
+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];
+ await fake.close();
+ await comfy.close();
+});
+beforeEach(() => {
+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];
+ billing.resetBillingCache();
+ fake.policy = { ...FAKE_POLICY };
+ for (const id of Object.values(ids)) {
+ runOn.clearRunOn(id);
+ if (auth.accountById(id)) auth.setAccountGpu(id, null);
+ }
+});
+
+const hostedOn = (prefer?: "pool") => {
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ if (prefer) {
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+ fake.policy = { ...FAKE_POLICY, prefer };
+ } else process.env.FUOBE_HOSTED_FREE = "1";
+};
+
+const call = (method: "GET" | "PUT", who: string, body?: unknown) => {
+ const text = body === undefined ? undefined : JSON.stringify(body);
+ const r = new Request("http://localhost:3000/api/account/run-on", { method, headers: { cookie: cookies[who], host: "localhost:3000", "content-type": "application/json" }, body: text });
+ return method === "GET" ? route.GET(r) : route.PUT(r);
+};
+const read = async (r: Response) => ({ status: r.status, body: (await r.json()) as Record<string, unknown> });
+
+/** An account's GPU at a web address, said to answer (or not) without calling it. */
+const gpuOf = (who: string, online = true) => {
+ auth.setAccountGpu(ids[who], { url: GPU_URL });
+ noteGpuState(ids[who], GPU_URL, online, { info: { device: "cuda:0 NVIDIA GeForce RTX 4090" } });
+};
+
+describe("hosted runs off (every self-hosted install by default)", () => {
+ it("the route doesn't exist and the status says nothing of a pick", async () => {
+ expect((await call("PUT", "ana", { runOn: "site" })).status).toBe(404);
+ expect((await call("GET", "ana")).status).toBe(404);
+ runOn.setRunOn(ids.ana, { runOn: "site" });
+ gpuOf("ana");
+ const s = await visitorStatus(auth.accountById(ids.ana)!);
+ expect(JSON.stringify(s.viewer)).not.toMatch(/runOn|runKey|ranOwn/);
+ });
+ it("no run reads it: a run goes where it went before", async () => {
+ runOn.setRunOn(ids.ana, { runOn: "site" });
+ gpuOf("ana");
+ expect((await decidePlace(auth.accountById(ids.ana)!, req, undefined)).kind).toBe("own");
+ expect(poolMayTake(auth.accountById(ids.ana)!, undefined)).toBe(false);
+ });
+});
+
+describe("the route (hosted runs on)", () => {
+ beforeEach(() => hostedOn());
+
+ it("is an account's own: listed for accounts by its exact path", () => {
+ expect(accountMayChange("PUT", "/api/account/run-on", "")).toBe(true);
+ expect(accountMayChange("POST", "/api/account/run-on", "")).toBe(false);
+ expect(accountMayChange("PUT", "/api/account/run-on/x", "")).toBe(false);
+ expect(accountOwnRead("/api/account/run-on")).toBe(true);
+ });
+
+ it("keeps a pick per account, and one account never sees or changes another's", async () => {
+ gpuOf("ana");
+ expect(await read(await call("PUT", "ana", { runOn: "gpu" }))).toEqual({ status: 200, body: { runOn: "gpu" } });
+ expect(await read(await call("GET", "ana"))).toEqual({ status: 200, body: { runOn: "gpu" } });
+ expect(await read(await call("GET", "ben"))).toEqual({ status: 200, body: { runOn: null } });
+ expect((await call("PUT", "ben", { runOn: "site" })).status).toBe(200);
+ expect(runOn.getRunOn(ids.ana)).toEqual({ runOn: "gpu" });
+ expect(runOn.getRunOn(ids.ben)).toEqual({ runOn: "site" });
+ // A new pick replaces the old one: one row per account.
+ expect((await call("PUT", "ana", { runOn: "site" })).status).toBe(200);
+ expect(db().prepare("SELECT COUNT(*) AS n FROM account_run_on WHERE account_id = ?").get(ids.ana)).toEqual({ n: 1 });
+ });
+
+ it("only a place the account has: a GPU connected, a key saved", async () => {
+ expect(await read(await call("PUT", "ana", { runOn: "gpu" }))).toMatchObject({ status: 409, body: { code: "connect-gpu" } });
+ expect(await read(await call("PUT", "ana", { runOn: "key" }))).toMatchObject({ status: 409, body: { code: "add-key" } });
+ keys.saveAccountKey(ids.ana, "replicate", "r8_test_key_for_ana");
+ // The key it names when it has it, else the one it has.
+ expect(await read(await call("PUT", "ana", { runOn: "key", key: "fal" }))).toEqual({ status: 200, body: { runOn: "key", runKey: "replicate" } });
+ keys.removeAccountKey(ids.ana, "replicate");
+ });
+
+ it("refuses anything else, and is nobody's but an account's", async () => {
+ expect((await call("PUT", "ana", { runOn: "cloud" })).status).toBe(400);
+ expect((await call("PUT", "ana", { runOn: "site", extra: 1 })).status).toBe(400);
+ const guest = await route.PUT(new Request("http://localhost:3000/api/account/run-on", { method: "PUT", headers: { host: "localhost:3000" }, body: JSON.stringify({ runOn: "site" }) }));
+ expect(guest.status).toBe(404);
+ });
+});
+
+describe("the status (hosted runs on)", () => {
+ beforeEach(() => hostedOn());
+
+ it("sends the pick to that account only, never to a guest", async () => {
+ gpuOf("ana");
+ runOn.setRunOn(ids.ana, { runOn: "gpu" });
+ expect((await visitorStatus(auth.accountById(ids.ana)!)).viewer).toMatchObject({ hosted: true, runOn: "gpu" });
+ expect((await visitorStatus(auth.accountById(ids.ben)!)).viewer).not.toHaveProperty("runOn");
+ expect(JSON.stringify((await visitorStatus(null)).viewer)).not.toMatch(/runOn|runKey|ranOwn/);
+ });
+
+ it("a key's pick names its provider", async () => {
+ keys.saveAccountKey(ids.ben, "fal", "fal_key_id:fal_key_secret_for_ben");
+ runOn.setRunOn(ids.ben, { runOn: "key", runKey: "fal" });
+ expect((await visitorStatus(auth.accountById(ids.ben)!)).viewer).toMatchObject({ runOn: "key", runKey: "fal" });
+ keys.removeAccountKey(ids.ben, "fal");
+ });
+
+ it("a pick whose place is gone is dropped (its runs go to this install's GPUs again)", async () => {
+ runOn.setRunOn(ids.ana, { runOn: "gpu" });
+ expect((await visitorStatus(auth.accountById(ids.ana)!)).viewer).not.toHaveProperty("runOn");
+ expect(runOn.getRunOn(ids.ana)).toBeNull();
+ runOn.setRunOn(ids.ana, { runOn: "key", runKey: "fal" });
+ expect((await visitorStatus(auth.accountById(ids.ana)!)).viewer).not.toHaveProperty("runOn");
+ expect(runOn.getRunOn(ids.ana)).toBeNull();
+ });
+
+ it("the one-time note: only for an account with a GPU or key that ran there before it ever ran here, and no pick yet", async () => {
+ const row = (account: string, place: "pool" | null, at: number) =>
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, created_at, updated_at) VALUES (?, 'image', 'oss-z-image-turbo', 'open', 'comfyui', 't2i', 'image', 'done', ?, ?, ?)",
+ )
+ .run(`g-${account}-${at}`, JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", account, ...(place && { place }) }), at, at);
+ const ranOwn = async (who: string) => !!(await visitorStatus(auth.accountById(ids[who])!)).viewer.ranOwn;
+ gpuOf("ana");
+ expect(await ranOwn("ana")).toBe(false);
+ row(ids.ana, null, 1000);
+ expect(await ranOwn("ana")).toBe(true);
+ // A run here later doesn't change it; a pick (OK or Keep my GPU) ends it on every device.
+ row(ids.ana, "pool", 2000);
+ expect(await ranOwn("ana")).toBe(true);
+ runOn.setRunOn(ids.ana, { runOn: "site" });
+ expect(await ranOwn("ana")).toBe(false);
+ // An account that ran here first and connected its GPU after never ran elsewhere first: no note.
+ row(ids.cy, "pool", 1000);
+ row(ids.cy, null, 3000);
+ gpuOf("cy");
+ expect(await ranOwn("cy")).toBe(false);
+ // Nothing of its own (no GPU, no key): nothing to keep, no note.
+ row(ids.ben, null, 1000);
+ expect(await ranOwn("ben")).toBe(false);
+ });
+});
+
+describe("one decision order for a run that names no place (hosted runs on)", () => {
+ it("no pick: the install's default (its own GPU first while online, unless the policy puts these GPUs first)", async () => {
+ hostedOn();
+ gpuOf("ana", true);
+ expect((await decidePlace(auth.accountById(ids.ana)!, req, undefined)).kind).toBe("own");
+ billing.resetBillingCache();
+ hostedOn("pool");
+ expect((await decidePlace(auth.accountById(ids.ana)!, req, undefined)).kind).toBe("pool");
+ });
+
+ it("its GPU picked: there at once, online or not, never asked about, whatever the policy prefers", async () => {
+ hostedOn("pool");
+ for (const online of [true, false]) {
+ gpuOf("ana", online);
+ runOn.setRunOn(ids.ana, { runOn: "gpu" });
+ expect((await decidePlace(auth.accountById(ids.ana)!, req, undefined)).kind).toBe("own");
+ expect(await poolQuote(auth.accountById(ids.ana)!, req, undefined)).toBeNull();
+ expect(poolMayTake(auth.accountById(ids.ana)!, undefined)).toBe(false);
+ }
+ });
+
+ it("these GPUs picked: here first, even with its own GPU online on an install that puts it first", async () => {
+ hostedOn();
+ gpuOf("ana", true);
+ runOn.setRunOn(ids.ana, { runOn: "site" });
+ expect((await decidePlace(auth.accountById(ids.ana)!, req, undefined)).kind).toBe("pool");
+ expect((await poolQuote(auth.accountById(ids.ana)!, req, undefined))?.quote).toBeTruthy();
+ expect(poolMayTake(auth.accountById(ids.ana)!, undefined)).toBe(true);
+ });
+
+ it("these GPUs picked while its own GPU doesn't answer: here, never the question about its GPU", async () => {
+ hostedOn();
+ gpuOf("ana", false);
+ // With no pick that is asked about (409, "Run on …").
+ const asked = await decidePlace(auth.accountById(ids.ana)!, req, undefined);
+ expect(asked.kind === "refuse" && asked.refusal.status).toBe(409);
+ runOn.setRunOn(ids.ana, { runOn: "site" });
+ expect((await decidePlace(auth.accountById(ids.ana)!, req, undefined)).kind).toBe("pool");
+ });
+
+ it("a place the run names wins over the pick, and never changes it (Retry, Run on …)", async () => {
+ hostedOn();
+ gpuOf("ana", true);
+ runOn.setRunOn(ids.ana, { runOn: "gpu" });
+ expect((await decidePlace(auth.accountById(ids.ana)!, req, "pool")).kind).toBe("pool");
+ runOn.setRunOn(ids.ana, { runOn: "site" });
+ expect((await decidePlace(auth.accountById(ids.ana)!, req, "own")).kind).toBe("own");
+ expect(runOn.getRunOn(ids.ana)).toEqual({ runOn: "site" });
+ });
+
+ it("what these GPUs don't take still runs on its own GPU when these GPUs are picked", async () => {
+ hostedOn();
+ gpuOf("ana", true);
+ runOn.setRunOn(ids.ana, { runOn: "site" });
+ const loras = { ...req, loras: [{ file: "x.safetensors", url: "https://huggingface.co/x/x.safetensors" }] };
+ expect((await decidePlace(auth.accountById(ids.ana)!, loras, undefined)).kind).toBe("own");
+ });
+});
+
+describe("a pick goes when its place goes", () => {
+ beforeEach(() => hostedOn());
+
+ it("forgetting the GPU drops a pick of it, and the answer says so (the page says where runs go now)", async () => {
+ gpuOf("ana");
+ runOn.setRunOn(ids.ana, { runOn: "gpu" });
+ const r = await read(await gpuRoute.DELETE(new Request("http://localhost:3000/api/account/gpu", { method: "DELETE", headers: { cookie: cookies.ana, host: "localhost:3000" } })));
+ expect(r).toMatchObject({ status: 200, body: { gpu: null, runOnCleared: true } });
+ expect(runOn.getRunOn(ids.ana)).toBeNull();
+ // A pick of these GPUs stays.
+ gpuOf("ana");
+ runOn.setRunOn(ids.ana, { runOn: "site" });
+ const kept = await read(await gpuRoute.DELETE(new Request("http://localhost:3000/api/account/gpu", { method: "DELETE", headers: { cookie: cookies.ana, host: "localhost:3000" } })));
+ expect(kept.body).not.toHaveProperty("runOnCleared");
+ expect(runOn.getRunOn(ids.ana)).toEqual({ runOn: "site" });
+ });
+
+ it("removing the key drops a pick of it", async () => {
+ keys.saveAccountKey(ids.ben, "fal", "fal_key_id:fal_key_secret_for_ben");
+ runOn.setRunOn(ids.ben, { runOn: "key", runKey: "fal" });
+ const ctx = { params: Promise.resolve({ provider: "fal" }) } as Parameters<typeof keyRoute.DELETE>[1];
+ const r = await read(await keyRoute.DELETE(new Request("http://localhost:3000/api/account/keys/fal", { method: "DELETE", headers: { cookie: cookies.ben, host: "localhost:3000", "content-type": "application/json" }, body: "{}" }), ctx));
+ expect(r).toMatchObject({ status: 200, body: { runOnCleared: true } });
+ expect(runOn.getRunOn(ids.ben)).toBeNull();
+ });
+
+ it("goes with a deleted account (registered at start in instrumentation.ts)", async () => {
+ expect(fs.readFileSync("src/instrumentation.ts", "utf8")).toMatch(/onAccountDeleted\(clearRunOn\)/);
+ runOn.setRunOn(ids.cy, { runOn: "site" });
+ await removeAccount(ids.cy);
+ expect(db().prepare("SELECT COUNT(*) AS n FROM account_run_on WHERE account_id = ?").get(ids.cy)).toEqual({ n: 0 });
+ });
+});
diff --git a/tests/run-place.test.ts b/tests/run-place.test.ts
index 9c79dbca..bac17aed 100644
--- a/tests/run-place.test.ts
+++ b/tests/run-place.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { placeOf } from "@/lib/place-name";
import { quoteBody } from "@/lib/hosted";
-import { checkedPool, composerOnPool, composerPlace, IN_BROWSER, mainModel, openCheckPlace, placePrice, refusedBeforeRun, runPlace, toolPoolPrice, withPoolRefusal, type RunPlaceInput } from "@/lib/run-place";
+import { checkedPool, composerOnPool, composerPlace, IN_BROWSER, mainModel, offersRunOnSite, openCheckPlace, placePrice, placeRows, refusedBeforeRun, retryRequest, runPlace, toolPoolPrice, withPoolRefusal, type RunPlaceInput } from "@/lib/run-place";
import { RUN_SHOWN_HEADER, shownHeader } from "@/lib/guest-access";
import { lineWords } from "@/lib/pool-line";
@@ -200,17 +200,117 @@ describe("the main model of a pipeline", () => {
});
describe("where a composer's run goes, and the place it names", () => {
- it("the person's pick, named", () => {
- expect(composerPlace("own", false, true)).toEqual({ runOn: "own", place: "own" });
- expect(composerPlace("pool", true, false)).toEqual({ runOn: "pool", place: "pool" });
+ it("a place picked for this run, named", () => {
+ expect(composerPlace("own", undefined, false, true)).toEqual({ runOn: "own", place: "own" });
+ expect(composerPlace("pool", undefined, true, false)).toEqual({ runOn: "pool", place: "pool" });
+ // A one-off place wins over the remembered pick.
+ expect(composerPlace("pool", "gpu", true, false)).toEqual({ runOn: "pool", place: "pool" });
+ expect(composerPlace("own", "site", true, true)).toEqual({ runOn: "own", place: "own" });
});
it("its own GPU while online, named; this studio's GPUs when it isn't, named", () => {
- expect(composerPlace(null, true, false)).toEqual({ runOn: "own", place: "own" });
- expect(composerPlace(null, false, false)).toEqual({ runOn: "pool", place: "pool" });
- expect(composerPlace(null, false, true)).toEqual({ runOn: "pool", place: "pool" });
+ expect(composerPlace(null, undefined, true, false)).toEqual({ runOn: "own", place: "own" });
+ expect(composerPlace(null, undefined, false, false)).toEqual({ runOn: "pool", place: "pool" });
+ expect(composerPlace(null, undefined, false, true)).toEqual({ runOn: "pool", place: "pool" });
});
it("this studio's GPUs first while its own GPU is online: shown, but not named, so the server can still use its own GPU", () => {
- expect(composerPlace(null, true, true)).toEqual({ runOn: "pool", place: undefined });
+ expect(composerPlace(null, undefined, true, true)).toEqual({ runOn: "pool", place: undefined });
+ });
+ it("the remembered GPU: named, online or not, whatever the studio prefers (never moved without a word)", () => {
+ for (const online of [true, false]) for (const prefer of [true, false]) expect(composerPlace(null, "gpu", online, prefer)).toEqual({ runOn: "own", place: "own" });
+ });
+ it("the remembered studio's GPUs (or key, whose open runs come here): first, even where its own GPU would be", () => {
+ for (const pick of ["site", "key"] as const) {
+ expect(composerPlace(null, pick, true, false)).toEqual({ runOn: "pool", place: undefined });
+ expect(composerPlace(null, pick, true, true)).toEqual({ runOn: "pool", place: undefined });
+ expect(composerPlace(null, pick, false, false)).toEqual({ runOn: "pool", place: "pool" });
+ }
+ });
+});
+
+describe("the place a tool's price check names, with the remembered pick", () => {
+ const v = { audience: "account" as const, gpu: true, hosted: true, preferPool: false };
+ it("its own GPU picked: no check here (the run goes there)", () => {
+ expect(openCheckPlace({ ...v, preferPool: true, runOn: "gpu" })).toBeNull();
+ });
+ it("this studio's GPUs or the key picked: checked with no place, so the server decides as for the run", () => {
+ expect(openCheckPlace({ ...v, runOn: "site" })).toBeUndefined();
+ expect(openCheckPlace({ ...v, runOn: "key" })).toBeUndefined();
+ });
+ it("no pick: as before", () => {
+ expect(openCheckPlace(v)).toBeNull();
+ expect(openCheckPlace({ ...v, preferPool: true })).toBeUndefined();
+ expect(openCheckPlace({ ...v, gpu: false, runOn: "gpu" })).toBe("pool");
+ expect(openCheckPlace({ ...v, hosted: false, runOn: "site" })).toBeNull();
+ });
+});
+
+describe("Retry and Run on <the place> on a run's tile", () => {
+ const request = { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" };
+ it("Retry names the place the run ran (hosted runs on), so the pick never moves it", () => {
+ expect(retryRequest({ request, place: "pool" }, true)).toEqual({ ...request, place: "pool" });
+ expect(retryRequest({ request }, true)).toEqual({ ...request, place: "own" });
+ });
+ it("hosted runs off: the request as it was", () => {
+ expect(retryRequest({ request, place: "pool" }, false)).toBe(request);
+ expect(retryRequest({ request }, false)).toBe(request);
+ });
+ it("Run on <the place>: an open run that failed on the person's own GPU, while hosted runs are on", () => {
+ expect(offersRunOnSite({ engine: "open", status: "failed" }, true)).toBe(true);
+ expect(offersRunOnSite({ engine: "open", status: "failed", place: "pool" }, true)).toBe(false);
+ expect(offersRunOnSite({ engine: "cloud", status: "failed" }, true)).toBe(false);
+ expect(offersRunOnSite({ engine: "open", status: "canceled" }, true)).toBe(false);
+ expect(offersRunOnSite({ engine: "open", status: "failed" }, false)).toBe(false);
+ });
+});
+
+describe("the Run on list", () => {
+ const account = { kind: "account" as const, hosted: true, prefer: "pool" as const, placeName: "Studio North GPUs", gpu: { connected: false } };
+ const gpu = { connected: true, online: true, device: "cuda:0 NVIDIA GeForce RTX 4090 : cudaMallocAsync" };
+ const quote = { text: "Free", wait: "Next in line · about 40 s" };
+ it("no control without a choice: none for a guest, hosted runs off, nothing of one's own, or an item only one's own runs", () => {
+ expect(placeRows({ ...account, kind: "guest", gpu }, {}, quote)).toBeNull();
+ expect(placeRows({ ...account, hosted: false, gpu }, {}, quote)).toBeNull();
+ expect(placeRows(account, {}, quote)).toBeNull();
+ expect(placeRows(account, { key: null }, quote)).toBeNull();
+ expect(placeRows({ ...account, gpu }, { siteRuns: false }, quote)).toBeNull();
+ expect(placeRows(undefined, {}, quote)).toBeNull();
+ });
+ it("a GPU: this studio's GPUs first and picked by default, its GPU with a green dot and its card", () => {
+ expect(placeRows({ ...account, gpu }, {}, quote)).toEqual({
+ on: "site",
+ rows: [
+ { id: "site", label: "Studio North GPUs", sub: "Free · Next in line · about 40 s", selected: true },
+ { id: "gpu", label: "Your GPU", sub: "Free · RTX 4090", online: true, selected: false },
+ ],
+ });
+ });
+ it("a GPU that doesn't answer: said, never greyed out, and picking it stays allowed", () => {
+ const r = placeRows({ ...account, runOn: "gpu", gpu: { connected: true, online: false } }, {}, quote)!;
+ expect(r.on).toBe("gpu");
+ expect(r.rows[1]).toEqual({ id: "gpu", label: "Your GPU", sub: "Free · not answering right now", selected: true });
+ });
+ it("a key that runs this item's cloud version: its price first, and who bills it", () => {
+ const r = placeRows(account, { key: { provider: "fal", price: "≈ $0.04" } }, quote)!;
+ expect(r.rows.map((x) => x.label)).toEqual(["Studio North GPUs", "Your fal.ai key"]);
+ expect(r.rows[1].sub).toBe("≈ $0.04 · billed to your fal.ai account");
+ expect(placeRows(account, { key: { provider: "replicate" } }, quote)!.rows[1]).toMatchObject({ label: "Your Replicate key", sub: "Billed to your Replicate account" });
+ });
+ it("the remembered key: picked on the item's cloud version; on its open version the run is here", () => {
+ const keyed = { ...account, runOn: "key" as const };
+ expect(placeRows(keyed, { key: { provider: "fal", price: "≈ $0.04" }, cloud: true }, quote)!.on).toBe("key");
+ expect(placeRows(keyed, { key: { provider: "fal", price: "≈ $0.04" } }, quote)!.on).toBe("site");
+ });
+ it("the remembered key on an item with no cloud version: here this once, and the chip says why", () => {
+ const r = placeRows({ ...account, runOn: "key", gpu }, { key: null }, quote)!;
+ expect(r.on).toBe("site");
+ expect(r.note).toBe("Runs on Studio North GPUs. This one has no cloud version.");
+ });
+ it("no pick on an install that puts one's own GPU first: its GPU while it answers", () => {
+ expect(placeRows({ ...account, prefer: undefined, gpu }, {}, quote)!.on).toBe("gpu");
+ expect(placeRows({ ...account, prefer: undefined, gpu: { connected: true, online: false } }, {}, quote)!.on).toBe("site");
+ });
+ it("this studio's row says Free when the check has no words yet, and the name falls back to Our GPUs", () => {
+ expect(placeRows({ ...account, placeName: undefined, gpu }, {})!.rows[0]).toEqual({ id: "site", label: "Our GPUs", sub: "Free", selected: true });
});
});
diff --git a/tests/self-host-unchanged.test.ts b/tests/self-host-unchanged.test.ts
index 442e550c..7778d3b5 100644
--- a/tests/self-host-unchanged.test.ts
+++ b/tests/self-host-unchanged.test.ts
@@ -241,4 +241,29 @@ describe("a self-hosted install with hosted runs off", () => {
}
expect(engineAfterKeySave(false)).toBe("cloud");
});
+
+ it("where runs go: the route doesn't exist, nothing reads a pick, and the composer and tools pick as before", async () => {
+ vi.doMock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+ const route = await import("@/app/api/account/run-on/route");
+ const { setRunOn } = await import("@/server/run-on");
+ const { decidePlace } = await import("@/server/hosted-run");
+ const { composerPlace, openCheckPlace, placeRows, retryRequest } = await import("@/lib/run-place");
+ const { pickerRules } = await import("@/lib/pool-rules");
+ const a = auth.createAccount("[email protected]", "long enough");
+ const cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a.id).value}`;
+ const put = await route.PUT(new Request("http://localhost:3000/api/account/run-on", { method: "PUT", headers: { cookie, host: "localhost:3000" }, body: JSON.stringify({ runOn: "site" }) }));
+ expect(put.status).toBe(404);
+ expect((await route.GET(new Request("http://localhost:3000/api/account/run-on", { headers: { cookie, host: "localhost:3000" } }))).status).toBe(404);
+ // A pick left in the table changes nothing while hosted runs are off.
+ setRunOn(a.id, { runOn: "site" });
+ expect((await visitorStatus(a)).viewer).not.toHaveProperty("runOn");
+ expect((await decidePlace(a, { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" }, undefined)).kind).toBe("own");
+ // The browser: no pick is sent, so the composer, the tools' price check, the Run on list and Retry are as before.
+ expect(composerPlace(null, undefined, true, false)).toEqual({ runOn: "own", place: "own" });
+ expect(openCheckPlace({ audience: "account", gpu: true, hosted: false, preferPool: false })).toBeNull();
+ expect(placeRows({ kind: "account", gpu: { connected: true, online: true } }, { key: { provider: "fal" } })).toBeNull();
+ const request = { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" };
+ expect(retryRequest({ request }, false)).toBe(request);
+ expect(pickerRules({ gpu: { connected: true }, pool: { deny: ["x"] } })).toBeUndefined();
+ });
});