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.

Home Start: only this tab's Start runs a job, and its line says when a key can't run the model

Claudefd9ca0e187aa
diff --git a/src/components/home-view.tsx b/src/components/home-view.tsx
index 2d50f14e..7e56a533 100644
--- a/src/components/home-view.tsx
+++ b/src/components/home-view.tsx
@@ -27,8 +27,8 @@ import { MediaThumb } from "@/components/studio/result-media";
import { useEngine, useGenerations, useHydrated, useStatus } from "@/lib/api";
import { EngineSwitch } from "@/components/studio/engine-switch";
import type { Generation } from "@/lib/catalog/types";
-import { connectedEngines, FIRST_RUN_KEY, FIRST_RUN_SCRIPT, nothingConnected as noConnection, showFirstRun } from "@/lib/connections";
-import type { StartQuote } from "@/lib/starter-prices";
+import { issueStartToken, START_PARAM } from "@/lib/composer";
+import { FIRST_RUN_KEY, FIRST_RUN_SCRIPT, nothingConnected as noConnection, showFirstRun, startLine, type StartQuote } from "@/lib/connections";
import { userTitle } from "@/lib/library";
import type { PresetCardData } from "@/lib/preset-cards";
import { cn } from "@/lib/utils";
@@ -192,19 +192,14 @@ export function HomeView({
const locked = engineMode === "both" ? undefined : engineMode;
- // With a prompt, the studio starts the run itself (go=1), or points at the photo it still needs.
- const go = () => router.push(`${mode.href}${prompt.trim() ? `?prompt=${encodeURIComponent(prompt.trim())}&go=1` : ""}`);
- // What Start will run, and what it costs, before it's pressed.
- const quote = quotes?.[mode.id];
- const runsFor = ((): { text: string; other?: "cloud" | "open" | null } | null => {
- if (!status || nothingConnected || !quote) return null;
- const engines = connectedEngines(status);
- const then = mode.id === "image" ? "" : mode.id === "edit" ? " after you add the photo" : "";
- // The other engine is connected: offer it rather than a demo run.
- const other = engineMode === "both" ? (engine === "open" ? engines.cloud && "cloud" : engines.open && "open") || null : null;
- if (engine === "open") return engines.open && quote.open ? { text: `Start runs ${quote.open.name} on your GPU${then} · Free` } : { text: "ComfyUI isn't connected, so Start runs a free demo", other };
- return engines.cloud && quote.cloud ? { text: `Start runs ${quote.cloud.name}${then} · ${quote.cloud.price}` } : { text: "No paid API is connected, so Start runs a free demo", other };
- })();
+ // With a prompt, the studio starts the run itself, or points at the photo it still needs. `go`
+ // carries a one-time token from this tab, so only this button can start a run that way.
+ const go = () => {
+ const p = prompt.trim();
+ router.push(p ? `${mode.href}?prompt=${encodeURIComponent(p)}&${START_PARAM}=${issueStartToken()}` : mode.href);
+ };
+ // What Start will run, and what it costs, before it's pressed (or why it's a demo, and the engine that would run it).
+ const runsFor = status ? startLine(status, quotes?.[mode.id], engine, mode.id as "image" | "video" | "edit") : null;
const focusComposer = () => requestAnimationFrame(() => box.current?.focus());
return (
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index ae34f126..d4a0bf69 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -335,7 +335,7 @@ export function Composer({ docked }: { docked: boolean }) {
toast.dismiss("composer-blocker");
}, [blocking]);
- // Home's Start (go=1): run the handed-over prompt once the models and uploads have settled. A
+ // Home's Start (go=<token>): run the handed-over prompt once the models and uploads have settled. A
// blocker (Edit's photo) gets the usual toast, and its slot is pointed at, instead.
const startRequest = useStartRequest();
const startedFor = useRef(0);
diff --git a/src/components/studio/studio-context.tsx b/src/components/studio/studio-context.tsx
index 0dc3231f..d7dd7d6b 100644
--- a/src/components/studio/studio-context.tsx
+++ b/src/components/studio/studio-context.tsx
@@ -132,8 +132,9 @@ export function StudioProvider({
}
/**
- * Home's Start (`?go=1`): a count the composer runs its draft for, once per increase, after the
- * handed-over prompt is in place (HandoffSync raises it). 0: nothing to start.
+ * Home's Start (`?go=<token>`, the token this tab's Home issued): a count the composer runs its
+ * draft for, once per increase, after the handed-over prompt is in place (HandoffSync raises it).
+ * 0: nothing to start.
*/
export const StartRequestCtx = createContext(0);
diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsx
index 7efa2c76..dca7ac8f 100644
--- a/src/components/studio/studio-page.tsx
+++ b/src/components/studio/studio-page.tsx
@@ -9,7 +9,7 @@ import { toast } from "sonner";
import { SidebarTrigger } from "@/components/ui/sidebar";
import type { Generation, MediaKind, ModelDef, Preset } from "@/lib/catalog/types";
import { useEngine, useGenerations } from "@/lib/api";
-import { handoffKey, mergeHandoff, promptShown, START_PARAM, withoutStart } from "@/lib/composer";
+import { claimStartToken, handoffKey, mergeHandoff, promptShown, START_PARAM, withoutStart } from "@/lib/composer";
import { reuseSignature, withSignatureWords } from "@/lib/catalog/palettes";
import { matchSpokenLanguage } from "@/lib/speech-languages";
import { SoulPresetCards } from "@/components/moodboards/soul-preset-cards";
@@ -347,11 +347,11 @@ interface StudioPageProps {
type DraftProps = Omit<StudioPageProps, "catalog">;
-/** Reports the URL's hand-off params, and whether it asks to start (`go=1`). It reads the URL, so it sits under its own Suspense: the static shell renders without it. */
-function UrlParams({ onChange }: { onChange: (key: string, start: boolean) => void }) {
+/** Reports the URL's hand-off params, and its start token (`go`), if any. It reads the URL, so it sits under its own Suspense: the static shell renders without it. */
+function UrlParams({ onChange }: { onChange: (key: string, start: string | null) => void }) {
const sp = useSearchParams();
const key = handoffKey(sp);
- const start = sp.get(START_PARAM) === "1";
+ const start = sp.get(START_PARAM) || null;
// Layout effect: on a client navigation the prefilled draft is in place before the first paint.
useLayoutEffect(() => onChange(key, start), [key, start, onChange]);
return null;
@@ -364,9 +364,10 @@ function UrlParams({ onChange }: { onChange: (key: string, start: boolean) => vo
* hydrated — are kept. A later change of the params (Animate → Video while on Video) starts a
* fresh draft instead.
*
- * With `go=1` (Home's Start) it then asks the composer to run the draft once (onStart), after the
- * draft was built from the loaded models, and takes `go` out of the address so a reload or Back
- * doesn't run it again.
+ * With `go=<token>` (Home's Start) it then asks the composer to run the draft once (onStart), after
+ * the draft was built from the loaded models, and takes `go` out of the address so a reload or Back
+ * doesn't run it again. Only the one-time token this tab's Home issued starts a run: a `go` in a
+ * link from elsewhere just prefills the studio, so no website or message can spend the user's keys.
*/
function HandoffSync({
startKey,
@@ -384,10 +385,10 @@ function HandoffSync({
onStart: () => void;
}) {
const { setDraft } = useStudioActions();
- const [url, setUrl] = useState<{ key: string; start: boolean } | null>(null);
+ const [url, setUrl] = useState<{ key: string; start: string | null } | null>(null);
const applied = useRef({ key: startKey, ready, base: start, seen: false });
const started = useRef(false);
- const onParams = useCallback((key: string, start: boolean) => setUrl((u) => (u?.key === key && u.start === start ? u : { key, start })), []);
+ const onParams = useCallback((key: string, start: string | null) => setUrl((u) => (u?.key === key && u.start === start ? u : { key, start })), []);
useLayoutEffect(() => {
if (url === null) return;
const a = applied.current;
@@ -401,7 +402,7 @@ function HandoffSync({
}
if (url.start && ready && !started.current) {
started.current = true;
- onStart();
+ if (claimStartToken(url.start)) onStart();
window.history.replaceState(null, "", withoutStart(window.location.href));
}
}, [url, ready, build, setDraft, onNavigate, onStart]);
diff --git a/src/lib/composer.ts b/src/lib/composer.ts
index 211844c0..75f5fa91 100644
--- a/src/lib/composer.ts
+++ b/src/lib/composer.ts
@@ -409,11 +409,43 @@ export function mergeHandoff<D extends DraftShape>(base: D, current: D, next: D)
}
// ---------------------------------------------------------------------------
-// Home's Start: "/image?prompt=…&go=1" runs the handed-over prompt once
+// Home's Start: "/image?prompt=…&go=<token>" runs the handed-over prompt once
-/** The query flag that asks a studio to run its handed-over draft once (Home's Start). */
+/** The query flag that asks a studio to run its handed-over draft once (Home's Start). Its value is a one-time token. */
export const START_PARAM = "go";
+/** Where this tab keeps the token Home's Start just issued (sessionStorage, with a copy in memory). */
+const START_TOKEN_KEY = "fuobe:start";
+let startToken: string | null = null;
+
+/**
+ * Home's Start: a one-time token for `go=<token>`, kept in this tab. A studio runs the hand-off
+ * only when `go` carries it, so a link from anywhere else (another site, an email, a chat) with a
+ * `go` flag only prefills the studio and never starts a job on the user's keys. It is random, not
+ * a counter: a tab that came from elsewhere can't guess one Home left behind.
+ */
+export function issueStartToken(): string {
+ // getRandomValues, not randomUUID: it also works on a plain-http LAN address.
+ const token = Array.from(crypto.getRandomValues(new Uint32Array(3)), (n) => n.toString(36)).join("");
+ startToken = token;
+ try {
+ sessionStorage.setItem(START_TOKEN_KEY, token);
+ } catch {}
+ return token;
+}
+
+/** Whether a `go` value is the token this tab's Home issued. The token is used up either way, so it runs once. */
+export function claimStartToken(value: string | null | undefined): boolean {
+ let stored: string | null = null;
+ try {
+ stored = sessionStorage.getItem(START_TOKEN_KEY);
+ sessionStorage.removeItem(START_TOKEN_KEY);
+ } catch {}
+ const issued = [startToken, stored];
+ startToken = null;
+ return !!value && issued.includes(value);
+}
+
/** The same address without the start flag, so a reload or Back doesn't run it again. */
export function withoutStart(href: string): string {
const u = new URL(href, "http://x");
diff --git a/src/lib/connections.ts b/src/lib/connections.ts
index 10ef4707..faba648f 100644
--- a/src/lib/connections.ts
+++ b/src/lib/connections.ts
@@ -91,8 +91,10 @@ export type EngineModeName = "both" | "open" | "cloud";
export interface ConnectionState {
providers: Record<string, { configured: boolean } | undefined>;
engineMode: EngineModeName;
- /** The first-run guide was dismissed, or something tested green (Settings → `onboarded`). */
+ /** The first-run guide was put away, or something this engine mode uses was connected once (Settings → `onboarded`). */
onboarded?: boolean;
+ /** Settings → Demo mode: auto (a demo when no provider hosts the model), on (always a demo), off (never). */
+ demoMode?: string;
}
const CLOUD_PROVIDERS = ["fal", "replicate", "higgsfield"] as const;
@@ -108,11 +110,43 @@ export function nothingConnected(s: ConnectionState): boolean {
return s.engineMode === "open" ? !c.open : s.engineMode === "cloud" ? !c.cloud : !c.cloud && !c.open;
}
-/** The first-run guide shows until something is connected or it was dismissed. Unknown status: not yet. */
+/** The first-run guide shows until something is connected or it was put away. Unknown status: not yet. */
export function showFirstRun(s: ConnectionState | undefined): boolean {
return !!s && !s.onboarded && nothingConnected(s);
}
+/** What Home's Start runs in a mode: the studio's default model on each engine, the providers that host it, and one run's price on the paid one. */
+export interface StartQuote {
+ cloud: { name: string; price: string; providers: string[] } | null;
+ open: { name: string; providers: string[] } | null;
+}
+
+const PROVIDER_LABEL: Record<string, string> = { fal: "fal.ai", replicate: "Replicate", higgsfield: "Higgsfield", comfyui: "ComfyUI" };
+
+/**
+ * The line under Home's composer, before Start is pressed: the model it runs and its price, or why
+ * it runs a free demo (no key for a provider that hosts that model, the same rule the composer's
+ * "Demo" label follows), plus the other engine when that one would run it for real. Null when
+ * nothing is connected: Home's demo notice says so instead.
+ */
+export function startLine(s: ConnectionState, quote: StartQuote | undefined, engine: "cloud" | "open", mode: "image" | "video" | "edit"): { text: string; other?: "cloud" | "open" } | null {
+ if (!quote || nothingConnected(s)) return null;
+ if (s.demoMode === "on") return { text: "Demo mode is on (Settings), so Start runs a free demo" };
+ const hosted = (q: { providers: string[] } | null) => !!q && q.providers.some((p) => s.providers[p]?.configured);
+ const otherEngine = engine === "open" ? "cloud" : "open";
+ const other = s.engineMode === "both" && hosted(quote[otherEngine]) ? otherEngine : undefined;
+ const then = mode === "edit" ? " after you add the photo" : "";
+ if (engine === "open" && quote.open && hosted(quote.open)) return { text: `Start runs ${quote.open.name} on your GPU${then} · Free` };
+ if (engine === "cloud" && quote.cloud && hosted(quote.cloud)) return { text: `Start runs ${quote.cloud.name}${then} · ${quote.cloud.price}` };
+ const q = quote[engine];
+ const connected = connectedEngines(s)[engine];
+ const hosts = q ? q.providers.map((p) => PROVIDER_LABEL[p] ?? p).join(" or ") : "";
+ let why: string;
+ if (!connected) why = engine === "open" ? "ComfyUI isn't connected" : "No paid API is connected";
+ else why = q ? `${q.name} needs ${engine === "open" ? hosts : `a ${hosts} key`}` : "No model is set for this";
+ return { text: `${why}, so Start ${s.demoMode === "off" ? "can't run it yet" : "runs a free demo"}`, ...(other && { other }) };
+}
+
/**
* This browser's last answer to showFirstRun ("1" or "0"). Home paints the guide in its static
* shell, before the status is known, so it doesn't push the page down when it arrives; the
diff --git a/src/lib/starter-prices.ts b/src/lib/starter-prices.ts
index 2c3692e1..ee36ef4d 100644
--- a/src/lib/starter-prices.ts
+++ b/src/lib/starter-prices.ts
@@ -1,5 +1,6 @@
import { getModel } from "@/lib/catalog";
import { estimateCost } from "@/lib/catalog/plan";
+import type { StartQuote } from "@/lib/connections";
import { formatCost } from "@/lib/format";
import { EDIT_STUDIO, IMAGE_STUDIO, VIDEO_STUDIO } from "@/lib/studios";
@@ -17,11 +18,7 @@ export function starterPriceLine(): string {
return [quote(IMAGE_STUDIO.defaultModels.cloud, () => "an image"), quote(VIDEO_STUDIO.defaultModels.cloud, (d) => (d ? `a ${d} s clip` : "a clip"))].filter(Boolean).join(" · ");
}
-/** What Home's Start runs in a mode: the studio's default model on each engine, and what one run costs on the paid one. */
-export interface StartQuote {
- cloud: { name: string; price: string } | null;
- open: { name: string } | null;
-}
+export type { StartQuote };
/** Home's Start quotes, by mode (image, video, edit), so the price is known before a paid run starts. */
export function startQuotes(): Record<"image" | "video" | "edit", StartQuote> {
@@ -29,9 +26,11 @@ export function startQuotes(): Record<"image" | "video" | "edit", StartQuote> {
const cloud = getModel(d.cloud);
const open = getModel(d.open);
const usd = cloud ? estimateCost(cloud, { ...cloud.defaults }) : null;
+ // The providers that host each model: a key for another one runs it as a demo.
+ const providers = (m: NonNullable<typeof cloud>) => [...new Set(m.routes.map((r) => r.provider))];
return {
- cloud: cloud ? { name: cloud.name, price: usd ? `about ${formatCost(usd)} ${what(cloud.defaults?.duration)}` : "priced by the provider" } : null,
- open: open ? { name: open.name } : null,
+ cloud: cloud ? { name: cloud.name, price: usd ? `about ${formatCost(usd)} ${what(cloud.defaults?.duration)}` : "priced by the provider", providers: providers(cloud) } : null,
+ open: open ? { name: open.name, providers: providers(open) } : null,
};
};
return {
diff --git a/tests/home-start.test.ts b/tests/home-start.test.ts
index 0ce179d8..9dc32696 100644
--- a/tests/home-start.test.ts
+++ b/tests/home-start.test.ts
@@ -1,5 +1,6 @@
-import { describe, expect, it } from "vitest";
-import { blockerFor, firstMissingSlot, handoffKey, startStep, withoutStart } from "@/lib/composer";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { blockerFor, claimStartToken, firstMissingSlot, handoffKey, issueStartToken, startStep, withoutStart } from "@/lib/composer";
+import { startLine, type ConnectionState } from "@/lib/connections";
import { startQuotes } from "@/lib/starter-prices";
import { EDIT_STUDIO, IMAGE_STUDIO } from "@/lib/studios";
@@ -26,10 +27,78 @@ describe("the start flag", () => {
expect(firstMissingSlot(IMAGE_STUDIO.slots, {})).toBeUndefined();
});
- it("says what Start runs and costs in each mode", () => {
+ it("says what Start runs and costs in each mode, and which providers host it", () => {
const q = startQuotes();
- expect(q.image).toEqual({ cloud: { name: "Nano Banana Pro", price: expect.stringMatching(/^about \$[\d.]+ an image$/) }, open: { name: expect.any(String) } });
+ expect(q.image).toEqual({
+ cloud: { name: "Nano Banana Pro", price: expect.stringMatching(/^about \$[\d.]+ an image$/), providers: expect.arrayContaining(["fal", "replicate"]) },
+ open: { name: expect.any(String), providers: ["comfyui"] },
+ });
expect(q.video.cloud?.price).toMatch(/^about \$[\d.]+ a 5 s clip$/);
+ expect(q.video.cloud?.providers).not.toContain("replicate");
expect(q.edit.cloud?.price).toMatch(/an edit$/);
});
});
+
+describe("the start token", () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("runs only the Start this tab's Home pressed, once", () => {
+ const token = issueStartToken();
+ expect(token).toMatch(/^[a-z0-9]{10,}$/);
+ // A link from another site carries go=1, or a guess: it only prefills.
+ expect(claimStartToken("1")).toBe(false);
+ // That try used the token up as well.
+ expect(claimStartToken(token)).toBe(false);
+ const next = issueStartToken();
+ expect(next).not.toBe(token);
+ expect(claimStartToken(next)).toBe(true);
+ // Reload, Back, or the same address pasted again: nothing runs.
+ expect(claimStartToken(next)).toBe(false);
+ expect(claimStartToken(null)).toBe(false);
+ });
+
+ it("survives a full page load in the same tab (sessionStorage), not a new tab", () => {
+ const store = new Map<string, string>();
+ vi.stubGlobal("sessionStorage", { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => store.set(k, v), removeItem: (k: string) => store.delete(k) });
+ const token = issueStartToken();
+ expect(store.get("fuobe:start")).toBe(token);
+ expect(claimStartToken(token)).toBe(true);
+ expect(store.has("fuobe:start")).toBe(false);
+ });
+});
+
+describe("the line under Home's composer", () => {
+ const q = startQuotes();
+ const state = (configured: string[], extra: Partial<ConnectionState> = {}): ConnectionState => ({
+ providers: Object.fromEntries(["fal", "replicate", "higgsfield", "comfyui", "llm"].map((p) => [p, { configured: configured.includes(p) }])),
+ engineMode: "both",
+ demoMode: "auto",
+ ...extra,
+ });
+
+ it("names the paid model and its price when a key for one of its providers is set", () => {
+ expect(startLine(state(["fal"]), q.video, "cloud", "video")?.text).toMatch(/^Start runs Seedance 2\.5 · about \$[\d.]+ a 5 s clip$/);
+ expect(startLine(state(["replicate"]), q.image, "cloud", "image")?.text).toMatch(/^Start runs Nano Banana Pro · about/);
+ expect(startLine(state(["fal"]), q.edit, "cloud", "edit")?.text).toMatch(/^Start runs Nano Banana Pro after you add the photo · /);
+ });
+
+ it("says it's a demo when the key set is for a provider that doesn't host the model", () => {
+ // Only Replicate: Seedance 2.5 is on fal.ai and Higgsfield.
+ expect(startLine(state(["replicate"]), q.video, "cloud", "video")).toEqual({ text: "Seedance 2.5 needs a fal.ai or Higgsfield key, so Start runs a free demo" });
+ // Only Higgsfield: Nano Banana Pro is on fal.ai and Replicate.
+ expect(startLine(state(["higgsfield"]), q.image, "cloud", "image")?.text).toMatch(/^Nano Banana Pro needs a fal\.ai or Replicate key, so Start runs a free demo$/);
+ // Demo mode off: it won't run at all.
+ expect(startLine(state(["higgsfield"], { demoMode: "off" }), q.image, "cloud", "image")?.text).toMatch(/so Start can't run it yet$/);
+ expect(startLine(state(["fal"], { demoMode: "on" }), q.image, "cloud", "image")?.text).toMatch(/Demo mode is on/);
+ });
+
+ it("offers the other engine when that one would run it for real", () => {
+ expect(startLine(state(["comfyui"]), q.image, "cloud", "image")).toEqual({ text: "No paid API is connected, so Start runs a free demo", other: "open" });
+ expect(startLine(state(["comfyui"]), q.image, "open", "image")?.text).toMatch(/^Start runs .+ on your GPU · Free$/);
+ expect(startLine(state(["fal"]), q.image, "open", "image")).toEqual({ text: "ComfyUI isn't connected, so Start runs a free demo", other: "cloud" });
+ // A Replicate key doesn't run Seedance, so it isn't offered for Video.
+ expect(startLine(state(["replicate"]), q.video, "open", "video")).toEqual({ text: "ComfyUI isn't connected, so Start runs a free demo" });
+ // Nothing connected: Home's demo notice says it instead.
+ expect(startLine(state([]), q.image, "cloud", "image")).toBeNull();
+ });
+});