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.

Settings: links to a section land on it; fal.ai balance steps link to the keys page

Adarsh0c0ef7075fe2
diff --git a/src/components/gpu/account-gpu-section.tsx b/src/components/gpu/account-gpu-section.tsx
index b39ed519..b71915ab 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 { useHashAnchor } from "@/components/use-hash-anchor";
import { useHydrated, useViewer } from "@/lib/api";
/**
@@ -11,7 +12,10 @@ import { useHydrated, useViewer } from "@/lib/api";
export function AccountGpuSection() {
const hydrated = useHydrated();
const account = useViewer().data?.account;
- if (!hydrated || !account) return null;
+ const shown = hydrated && !!account;
+ // A link to /settings#your-gpu arrives before this section exists: it is scrolled to once it does.
+ useHashAnchor("your-gpu", shown);
+ if (!shown) return null;
return (
<section id="your-gpu" aria-labelledby="your-gpu-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">
diff --git a/src/components/keys/key-account-details.tsx b/src/components/keys/key-account-details.tsx
index 66d75503..9ba10e89 100644
--- a/src/components/keys/key-account-details.tsx
+++ b/src/components/keys/key-account-details.tsx
@@ -1,11 +1,11 @@
"use client";
-import { ExternalLink, Loader2 } from "lucide-react";
+import { ChevronDown, ExternalLink, Loader2 } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useKeyInfo, useRefreshKeyInfo } from "@/components/keys/use-key-info";
import { useNow } from "@/components/studio/use-now";
import { BILLING_URL } from "@/lib/diagnose";
-import { accountWords, checkKeyWords, FAL_BALANCE_HOW, money, noKeyYetWords, updatedWords, type ProviderAccount } from "@/lib/key-info";
+import { accountWords, checkKeyWords, FAL_BALANCE_HOW, FAL_BALANCE_PERMISSION, money, noKeyYetWords, updatedWords, type ProviderAccount } from "@/lib/key-info";
import { CLOUD_KEY, type CloudProvider } from "@/lib/your-keys";
import { cn } from "@/lib/utils";
@@ -58,6 +58,33 @@ function Footer({ info, onRefresh, disabled, busy, children }: { info: ProviderA
);
}
+/**
+ * Under a fal.ai key that may not read its balance: the three steps to a key that may, from fal.ai's keys page, and
+ * what the added permission lets Fuobe do. Folded, with the chevron Settings' other folded rows use.
+ */
+function FalBalanceHow() {
+ const { title, steps, why } = FAL_BALANCE_HOW;
+ return (
+ <details className="group mt-2 text-[12px]">
+ <summary className="flex min-h-6 w-fit cursor-pointer list-none items-center gap-1 font-medium [@media(pointer:coarse)]:min-h-11 text-foreground underline-offset-2 hover:underline [&::-webkit-details-marker]:hidden">
+ {title}
+ <ChevronDown aria-hidden className="size-3.5 text-muted-foreground transition-transform group-open:rotate-180" />
+ </summary>
+ <ol className="mt-1.5 max-w-prose list-decimal space-y-1 pl-4 text-muted-foreground marker:text-muted-foreground">
+ <li>
+ {steps.open.before} <Outbound href={CLOUD_KEY.fal.keysUrl}>{steps.open.link}</Outbound> {steps.open.after}
+ </li>
+ <li>
+ {steps.pick.before} <code className="rounded bg-background px-1 font-mono text-[11px] text-foreground">{FAL_BALANCE_PERMISSION}</code>
+ {steps.pick.after}
+ </li>
+ <li>{steps.save}</li>
+ </ol>
+ <p className="mt-1.5 max-w-prose text-muted-foreground">{why}</p>
+ </details>
+ );
+}
+
/**
* The account behind a saved key. `scope`: whose key (the words for a key the provider didn't accept). `refused` and
* `emptyNoted`: the card already says the provider stopped accepting the key, or that its balance ran out (Your keys),
@@ -163,12 +190,7 @@ export function KeyAccountDetails({
<p>
{label} shows your balance on its billing page. <Outbound href={BILLING_URL[provider]}>See balance on {label}</Outbound>
</p>
- {provider === "fal" && info && (
- <details className="group mt-2 text-[12px]">
- <summary className="w-fit cursor-pointer font-medium text-foreground underline-offset-2 hover:underline">Show the balance here</summary>
- <p className="mt-1 max-w-prose text-muted-foreground">{FAL_BALANCE_HOW}</p>
- </details>
- )}
+ {provider === "fal" && info && <FalBalanceHow />}
{footer()}
</>
);
diff --git a/src/components/keys/your-keys.tsx b/src/components/keys/your-keys.tsx
index 8603c390..de673ed6 100644
--- a/src/components/keys/your-keys.tsx
+++ b/src/components/keys/your-keys.tsx
@@ -10,6 +10,7 @@ import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import { useHashAnchor } from "@/components/use-hash-anchor";
import { ADD_KEY_EVENT, preferEngine, useHydrated, useStatus, useViewer } from "@/lib/api";
import { settingProblem } from "@/lib/connections";
import { CLOUD_KEY, CLOUD_PROVIDERS, type CloudProvider, type KeyInfo, type YourKeys } from "@/lib/your-keys";
@@ -333,7 +334,10 @@ export function AccountKeysSection({ prices }: { prices?: string }) {
const q = useYourKeys(!!account);
// A studio with paid models off takes no keys: the section isn't shown.
const paidOff = useStatus().data?.viewer?.paidAllowed === false || q.data?.paidAllowed === false;
- if (!hydrated || !account || paidOff) return null;
+ const shown = hydrated && !!account && !paidOff;
+ // A link to /settings#your-keys arrives before this section exists: it is scrolled to once it does.
+ useHashAnchor("your-keys", shown);
+ if (!shown) return 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">
diff --git a/src/components/owner-settings.tsx b/src/components/owner-settings.tsx
index ec234f3e..17fe058f 100644
--- a/src/components/owner-settings.tsx
+++ b/src/components/owner-settings.tsx
@@ -10,6 +10,7 @@ import { Button } from "@/components/ui/button";
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import { useHashAnchor } from "@/components/use-hash-anchor";
import { announceAuthChange, leaveNotice, rememberViewer, signInHref, signOut, useHydrated, useViewer } from "@/lib/api";
import { FUOBE_REPO } from "@/lib/connections";
import { cn } from "@/lib/utils";
@@ -114,6 +115,8 @@ function AccountSection({ email }: { email: string }) {
const [error, setError] = useState("");
// The password was wrong (403): only then is its field marked, not for "too many tries" or no answer.
const [wrong, setWrong] = useState(false);
+ // A link to /settings#account arrives before this section exists: it is scrolled to once it does.
+ useHashAnchor("account", true);
const remove = async (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsx
index 51c39fd6..a3615bc5 100644
--- a/src/components/settings-form.tsx
+++ b/src/components/settings-form.tsx
@@ -17,6 +17,7 @@ import { PLACEHOLDER_SETTING, placeholdersOn } from "@/lib/demo-mode";
import { AccountsChip } from "@/components/accounts-admin";
import { ConnectField, useSettings, type PublicSetting } from "@/components/connect-field";
import { KeyAccountDetails } from "@/components/keys/key-account-details";
+import { hashId, keepInView } from "@/components/use-hash-anchor";
import { GetStarted } from "@/components/get-started";
import { AboutLinks } from "@/components/owner-settings";
import { LlmProviderSettings } from "@/components/llm-provider-settings";
@@ -519,11 +520,11 @@ export function SettingsForm({ prices }: { prices?: string }) {
const get = (n: string) => settings.data?.find((s) => s.name === n);
const set = (n: string) => (v: string) => save.mutate({ [n]: v });
// Deep links (/settings#comfyui) arrive while the form is still a skeleton, so the browser finds
- // no anchor: scroll to it once the sections exist.
+ // no anchor: scroll to it once the sections exist, and keep it there while the page above it settles.
const loaded = !settings.isLoading;
useEffect(() => {
- if (!loaded || !window.location.hash) return;
- document.getElementById(decodeURIComponent(window.location.hash.slice(1)))?.scrollIntoView({ block: "start" });
+ const el = loaded ? document.getElementById(hashId(window.location.hash)) : null;
+ return el ? keepInView(el) : undefined;
}, [loaded]);
if (settings.isLoading)
diff --git a/src/components/use-hash-anchor.ts b/src/components/use-hash-anchor.ts
new file mode 100644
index 00000000..9fe92f76
--- /dev/null
+++ b/src/components/use-hash-anchor.ts
@@ -0,0 +1,79 @@
+"use client";
+
+import { useEffect } from "react";
+
+/*
+ * A Settings section reached by a link to its #id: /settings#your-keys from the account menu's "Add a key", a model
+ * picker or a refused run, /settings#cloud from the owner's "Check key". These sections render only after the page is
+ * hydrated, so the browser finds no anchor when the page loads. Sections above them also grow when their own data
+ * arrives (Your GPU looks for ComfyUI on this computer), which pushes the section out of view after a jump to it, and
+ * what is below them may still be loading, so the page can end before the section reaches the top. Once the section
+ * exists, this scrolls to it and keeps it at the top while the page settles. The hold ends when the reader scrolls,
+ * taps, clicks or types, or after HOLD_MS.
+ */
+
+/** The longest time a section is held at the top. */
+export const HOLD_MS = 10_000;
+
+/** The reader takes over: the hold ends at once. */
+export const READER_EVENTS = ["wheel", "touchstart", "pointerdown", "keydown"] as const;
+
+/**
+ * Scrolls `el` to the top (its scroll-margin applies) and keeps it there while anything above it changes size. Returns
+ * the function that ends the hold early.
+ */
+export function keepInView(el: Element, holdMs = HOLD_MS): () => void {
+ let done = false;
+ let top = 0;
+ // The page ended before the section could reach the top (what is below it was still loading).
+ let short = false;
+ const page = document.documentElement;
+ const align = () => {
+ el.scrollIntoView({ block: "start" });
+ top = el.getBoundingClientRect().top;
+ short = window.scrollY + window.innerHeight >= page.scrollHeight - 1;
+ };
+ const ro = new ResizeObserver(() => {
+ if (done) return;
+ if (!el.isConnected) return stop();
+ if (short || Math.abs(el.getBoundingClientRect().top - top) > 1) align();
+ });
+ // Everything that sits above the section in the page: its earlier siblings, and those of each element around it.
+ for (let n: Element | null = el; n && n !== document.body; n = n.parentElement) {
+ for (let s = n.previousElementSibling; s; s = s.previousElementSibling) ro.observe(s);
+ }
+ // And the whole page: it grows when what is below loads (room to scroll the section up), or when a part is put above.
+ ro.observe(page);
+ const timer = setTimeout(stop, holdMs);
+ for (const t of READER_EVENTS) window.addEventListener(t, stop, { capture: true, passive: true });
+ function stop() {
+ if (done) return;
+ done = true;
+ ro.disconnect();
+ clearTimeout(timer);
+ for (const t of READER_EVENTS) window.removeEventListener(t, stop, { capture: true });
+ }
+ align();
+ return stop;
+}
+
+/** The id the page's address points to ("your-keys" for /settings#your-keys), or "". */
+export function hashId(hash: string): string {
+ try {
+ return decodeURIComponent(hash.replace(/^#/, ""));
+ } catch {
+ return "";
+ }
+}
+
+/**
+ * For a section with this `id`: once `ready` (the section is in the page), and when the address points to it, scroll
+ * to it and hold it in view while the page settles.
+ */
+export function useHashAnchor(id: string, ready: boolean): void {
+ useEffect(() => {
+ if (!ready || hashId(window.location.hash) !== id) return;
+ const el = document.getElementById(id);
+ return el ? keepInView(el) : undefined;
+ }, [id, ready]);
+}
diff --git a/src/lib/key-info.ts b/src/lib/key-info.ts
index 2026b4c4..7c4471e9 100644
--- a/src/lib/key-info.ts
+++ b/src/lib/key-info.ts
@@ -117,9 +117,22 @@ export const noKeyYetWords = (p: CloudProvider): string =>
? "When you save a key, this card shows your fal.ai balance or a link to it."
: "When you save a token, this card shows your Replicate account and a link to your balance.";
-/** Settings: a fal.ai key that may not read its balance (fal.ai's default API keys). */
-export const FAL_BALANCE_HOW =
- "On fal.ai, make a key with a custom permission list. Add the permission billing:usage:read to the permissions for running models. Then save the new key here.";
+/** The fal.ai permission that lets a key read its account's balance and usage. */
+export const FAL_BALANCE_PERMISSION = "billing:usage:read";
+
+/**
+ * Settings: how to see the balance here, under a fal.ai key that may not read it (fal.ai's default API keys). Step 1
+ * links to fal.ai's keys page; the permission's name is shown as fal.ai writes it, so it can be found there.
+ */
+export const FAL_BALANCE_HOW = {
+ title: "How to see your balance here",
+ steps: {
+ open: { before: "Open your", link: "fal.ai keys page", after: "and make a new key." },
+ pick: { before: "For its permissions, choose your own list. Pick the ones in the API preset, then add", after: "." },
+ save: "Save the new key here in place of this one.",
+ },
+ why: "That permission only reads your balance and what you spent. Fuobe uses it to show them here, and for nothing else.",
+} as const;
/** Settings: the provider didn't accept the saved key when its account was asked. */
export const checkKeyWords = (p: CloudProvider, scope: "owner" | "account"): string =>
diff --git a/tests/hash-anchor.test.ts b/tests/hash-anchor.test.ts
new file mode 100644
index 00000000..df689772
--- /dev/null
+++ b/tests/hash-anchor.test.ts
@@ -0,0 +1,174 @@
+import fs from "node:fs";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { HOLD_MS, hashId, keepInView, READER_EVENTS } from "@/components/use-hash-anchor";
+
+/*
+ * A link to a Settings section (/settings#your-keys from the account menu's "Add a key"): the section exists only after
+ * hydration, and Your GPU above it grows when its own data arrives. keepInView (src/components/use-hash-anchor.ts)
+ * scrolls to the section once it exists and holds it at the top while the page above settles, until the reader takes
+ * over or the hold runs out.
+ */
+
+class FakeResizeObserver {
+ static last: FakeResizeObserver | null = null;
+ observed: unknown[] = [];
+ off = false;
+ constructor(private cb: () => void) {
+ FakeResizeObserver.last = this;
+ }
+ observe(el: unknown) {
+ this.observed.push(el);
+ }
+ disconnect() {
+ this.off = true;
+ }
+ /** Something it watches changed size. */
+ fire() {
+ if (!this.off) this.cb();
+ }
+}
+
+/**
+ * body > main > [header, Your GPU, Your keys], with Your keys at `top` px from the window's top. The page is `height` px
+ * tall in a 900 px window: scrolling the section to the top (80 px, its scroll margin) needs room below it.
+ */
+function settingsPage(top = 336, height = 4000) {
+ const body = { name: "body" };
+ const banner = { name: "banner", previousElementSibling: null };
+ const main = { name: "main", parentElement: body, previousElementSibling: banner };
+ const header = { name: "header", previousElementSibling: null };
+ const gpu = { name: "gpu", previousElementSibling: header };
+ const page = { name: "html", scrollHeight: height };
+ const at = { top };
+ const scrolls: ScrollIntoViewOptions[] = [];
+ const keys = {
+ name: "keys",
+ parentElement: main,
+ previousElementSibling: gpu,
+ isConnected: true,
+ getBoundingClientRect: () => ({ top: at.top }),
+ // As far as the page lets it: to 80 px from the top, or to the page's end.
+ scrollIntoView: (o: ScrollIntoViewOptions) => {
+ scrolls.push(o);
+ const docTop = win.scrollY + at.top;
+ win.scrollY = Math.max(0, Math.min(docTop - 80, page.scrollHeight - win.innerHeight));
+ at.top = docTop - win.scrollY;
+ },
+ };
+ vi.stubGlobal("document", { body, documentElement: page });
+ return { keys: keys as unknown as Element, raw: keys, at, scrolls, banner, header, gpu, page };
+}
+
+let win: EventTarget & { scrollY: number; innerHeight: number };
+beforeEach(() => {
+ vi.useFakeTimers();
+ win = Object.assign(new EventTarget(), { scrollY: 0, innerHeight: 900 });
+ vi.stubGlobal("window", win);
+ vi.stubGlobal("ResizeObserver", FakeResizeObserver);
+});
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe("a section reached by its #id is held in view while the page settles", () => {
+ it("scrolls to it at once, and again each time something above it grows", () => {
+ const p = settingsPage();
+ keepInView(p.keys);
+ expect(p.scrolls).toEqual([{ block: "start" }]);
+ const ro = FakeResizeObserver.last!;
+ // Everything above it is watched: the sections before it, what is before the page around it, and the whole page.
+ expect(ro.observed).toEqual([p.gpu, p.header, p.banner, p.page]);
+ // Your GPU finds ComfyUI and grows by 565 px: the section is put back at the top.
+ p.at.top += 565;
+ ro.fire();
+ expect(p.scrolls).toHaveLength(2);
+ expect(p.at.top).toBe(80);
+ // A change that doesn't move it: no scroll.
+ ro.fire();
+ expect(p.scrolls).toHaveLength(2);
+ });
+
+ it("when the page ends too soon, scrolls the section up as soon as what is below it loads", () => {
+ // The menu's Add a key: Your keys starts at 960 px, and the page is only 1534 px tall so far.
+ const p = settingsPage(960, 1534);
+ keepInView(p.keys);
+ expect(win.scrollY).toBe(634);
+ expect(p.at.top).toBe(326);
+ const ro = FakeResizeObserver.last!;
+ // The cards below load and the page grows: the section goes up as far as the page lets it, then to the top.
+ p.page.scrollHeight = 1766;
+ ro.fire();
+ expect(p.scrolls).toHaveLength(2);
+ expect(p.at.top).toBe(94);
+ p.page.scrollHeight = 2400;
+ ro.fire();
+ expect(p.scrolls).toHaveLength(3);
+ expect(p.at.top).toBe(80);
+ // At the top, the page growing again moves nothing.
+ p.page.scrollHeight = 3000;
+ ro.fire();
+ expect(p.scrolls).toHaveLength(3);
+ });
+
+ it("lets go as soon as the reader scrolls, taps, clicks or types", () => {
+ expect(READER_EVENTS).toEqual(["wheel", "touchstart", "pointerdown", "keydown"]);
+ for (const t of READER_EVENTS) {
+ const p = settingsPage();
+ keepInView(p.keys);
+ const ro = FakeResizeObserver.last!;
+ win.dispatchEvent(new Event(t));
+ expect(ro.off, t).toBe(true);
+ p.at.top += 400;
+ ro.fire();
+ expect(p.scrolls, t).toHaveLength(1);
+ }
+ });
+
+ it("lets go after the hold, when the section leaves the page, or when asked", () => {
+ let p = settingsPage();
+ keepInView(p.keys);
+ vi.advanceTimersByTime(HOLD_MS - 1);
+ expect(FakeResizeObserver.last!.off).toBe(false);
+ vi.advanceTimersByTime(1);
+ expect(FakeResizeObserver.last!.off).toBe(true);
+
+ p = settingsPage();
+ keepInView(p.keys);
+ p.raw.isConnected = false;
+ p.at.top += 300;
+ FakeResizeObserver.last!.fire();
+ expect(FakeResizeObserver.last!.off).toBe(true);
+ expect(p.scrolls).toHaveLength(1);
+
+ p = settingsPage();
+ const stop = keepInView(p.keys);
+ stop();
+ expect(FakeResizeObserver.last!.off).toBe(true);
+ // Its listeners are gone: the reader's next tap finds nothing to end.
+ stop();
+ });
+
+ it("reads the id from the address", () => {
+ expect(hashId("#your-keys")).toBe("your-keys");
+ expect(hashId("your-gpu")).toBe("your-gpu");
+ expect(hashId("")).toBe("");
+ expect(hashId("#%E0%A4%A")).toBe("");
+ });
+});
+
+describe("the sections links point to", () => {
+ const src = (f: string) => fs.readFileSync(path.join(__dirname, "..", "src", f), "utf8");
+
+ it("hold themselves once they exist: Your GPU, Your keys and Account (an account's), and the owner's sections", () => {
+ expect(src("components/keys/your-keys.tsx")).toMatch(/useHashAnchor\("your-keys", shown\);\s+if \(!shown\) return null;/);
+ expect(src("components/gpu/account-gpu-section.tsx")).toMatch(/useHashAnchor\("your-gpu", shown\);\s+if \(!shown\) return null;/);
+ expect(src("components/owner-settings.tsx")).toContain('useHashAnchor("account", true);');
+ expect(src("components/settings-form.tsx")).toMatch(/document\.getElementById\(hashId\(window\.location\.hash\)\)[^]*keepInView\(el\)/);
+ });
+
+ it("the account menu's Add a key goes to Your keys", () => {
+ expect(src("components/nav/connected-accounts.tsx")).toContain('<IntentLink href="/settings#your-keys">');
+ });
+});
diff --git a/tests/key-info-ui.test.ts b/tests/key-info-ui.test.ts
index 131ddb9d..cf899c2b 100644
--- a/tests/key-info-ui.test.ts
+++ b/tests/key-info-ui.test.ts
@@ -100,12 +100,24 @@ describe("Settings: a saved key's account", () => {
expect(w).not.toMatch(NEVER);
});
- it("fal.ai without balance access: the billing link, and how to show the balance here", () => {
- const w = words(details([fal({ state: "link" })]));
+ it("fal.ai without balance access: the billing link, and how to see the balance here, from fal.ai's keys page", () => {
+ const html = details([fal({ state: "link" })]);
+ const w = words(html);
expect(w).toContain("fal.ai shows your balance on its billing page. See balance on fal.ai");
- expect(w).toContain("Show the balance here");
- expect(w).toContain("billing:usage:read");
+ // Folded under a name that says what it holds, with a chevron (not the browser's own marker).
+ expect(html).toMatch(/<details[^>]*><summary[^>]*list-none[^>]*>How to see your balance here<svg/);
+ expect(html).not.toMatch(/<details[^>]* open/);
+ expect(w.replaceAll(" .", ".")).toContain(
+ "Open your fal.ai keys page (opens in a new tab) and make a new key. " +
+ "For its permissions, choose your own list. Pick the ones in the API preset, then add billing:usage:read. " +
+ "Save the new key here in place of this one.",
+ );
+ // The way to fal.ai's keys page, in a new tab.
+ expect(html).toContain('href="https://fal.ai/dashboard/keys" target="_blank" rel="noreferrer"');
+ // Why it is safe to give that permission.
+ expect(w).toContain("That permission only reads your balance and what you spent. Fuobe uses it to show them here, and for nothing else.");
expect(w).not.toMatch(NEVER);
+ expect(w).not.toMatch(/Show the balance here|custom permission/);
});
it("an empty balance says to top up", () => {