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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Accounts: fixes from the review of the owner's view of accounts' runs
Adarsh106426774b0d
diff --git a/docs/public-signup.md b/docs/public-signup.mdindex d100c8f9..c66f9545 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -73,24 +73,31 @@ An account is signed in, but it sees the owner's studio as a guest does:owner can see them, open their files and delete them ([Managing accounts](#managing-accounts));the sign-up form says so. An account's delete is for good (it has no Trash), so its space comesback at once. The live-updates stream isn't sent to accounts: their studios poll instead.-- **Its own uploads are its own.** Only the account that uploaded a file can open it or use it in a- run. See [Uploads](#uploads).+- **Its own uploads are its own.** Only the account that uploaded a file can use it in a run, and+ no other account can open it. The studio's owner can open it too: a clip made from an uploaded+ picture shows that picture as its poster in the owner's view of accounts' runs. The sign-up form+ says the owner sees what an account uploads and makes. See [Uploads](#uploads).## Managing accounts-The owner sees everyone who signed up in **Settings → Accounts**: email, when the account was-created, its last log-in, whether its own GPU is connected, its runs (all time, in the last 7 days,-running now, failed in the last 7 days), when it last ran, and the space its files take against its-limit (1 GB in its first 7 days, then 3 GB). A line above the list gives the runs of every account-in the last 24 hours and 7 days, the runs going now, and the space all accounts' files take against-their share of the disk. The owner can switch an account off (it is signed out at once and can't-log in) or delete it, and export the list as CSV.+The owner sees everyone who signed up in **Settings → Accounts**, the last section of Settings (the+**Accounts** chip at the top of Settings and the link under Public sign-up lead there): email,+whether its own GPU is connected, its runs (all time, in the last 7 days, running now, failed in the+last 7 days), when it last ran, and the space its files take against its limit (1 GB in its first 7+days, then 3 GB). On wide screens the list also shows when the account was created and its last+log-in (the CSV always has them). Running now counts as the run limit does: a batch or a chain+going is one run. A line above the list gives the runs of every account in the last 24 hours and 7+days, the runs going now, and the space all accounts' files take against their share of the disk.+The owner can switch an account off (it is signed out at once and can't log in) or delete it, and+export the list as CSV.**Accounts' runs** (`/settings/runs`, from the list) shows what accounts made, newest first: oneaccount's or every account's, each labelled with its email, filtered by account, status (finished,-running, failed) and kind. Each run shows its result (a clip plays on hover or a tap), the app,-preset or studio and the model, the prompt, its status with the error of a failed run, and when it-ran. The owner can delete a run with its files, which gives the account its space back at once, or+running, failed) and kind. The filters are in the address (`?account=<id>&status=failed&kind=video`),+so a reload or a shared link keeps them. Each run shows its result (a clip plays on hover, a tap, or+Enter; the count on a run with several files steps through them, and its menu opens each one), the+app, preset or studio and the model, the prompt, its status with the error of a failed run, and when+it ran. The owner can delete a run with its files, which gives the account its space back at once, orswitch the account off from there. The owner's own runs are never listed there, and accounts' runsnever appear in the owner's Library, its counts or the live feed.diff --git a/src/components/account-runs.tsx b/src/components/account-runs.tsxindex fcd996ff..48b94214 100644--- a/src/components/account-runs.tsx+++ b/src/components/account-runs.tsx@@ -5,7 +5,7 @@ import { ExternalLink, Filter, Loader2, MoreHorizontal, Trash2, UserCheck, UserXimport Link from "next/link";import { useRouter, useSearchParams } from "next/navigation";import { useRef, useState } from "react";-import { adminCall, OffBadge, Stat, useAdminAccounts, useAdminAction, type AccountRow } from "@/components/accounts-admin";+import { adminCall, OffBadge, runsHref, Stat, useAdminAccounts, useAdminAction, type AccountRow } from "@/components/accounts-admin";import { StatusCover } from "@/components/library/asset-card";import { PageHeader } from "@/components/page-shell";import { GallerySkeleton } from "@/components/skeletons";@@ -15,8 +15,9 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparaimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Skeleton } from "@/components/ui/skeleton";import { useViewer } from "@/lib/api";-import { OPERATION_LABELS, type Generation, type MediaKind } from "@/lib/catalog/types";+import { OPERATION_LABELS, type Generation, type MediaKind, type OutputFile } from "@/lib/catalog/types";import { storageSize, timeAgo } from "@/lib/format";+import { editOnlyFormat, modelPreview, shownOutputs } from "@/lib/output-actions";import { cn } from "@/lib/utils";/** An account's run as GET /api/admin/generations lists it, with whose it is (null email: the account was deleted). */@@ -42,7 +43,26 @@ const STATUS_LABELS: Record<Generation["status"], string> = { succeeded: "Finishconst PAGE = 30;const featureName = (f: string) => f.charAt(0).toUpperCase() + f.slice(1).replaceAll("-", " ");-const runsHref = (id?: string) => (id ? `/settings/runs?account=${encodeURIComponent(id)}` : "/settings/runs");++/** The filters in the page's address (?status=failed&kind=video), so a reload, Back or a shared link keeps them. */+export function runFilters(sp: Pick<URLSearchParams, "get">): { status: Status; kind: Kind } {+ return {+ status: STATUSES.find(([v]) => v === sp.get("status"))?.[0] ?? "all",+ kind: KINDS.find(([v]) => v === sp.get("kind"))?.[0] ?? "all",+ };+}++/** A run's files, one "Open file" each: what its tile can show (a 3D model's turntable is the model's preview, not a file of its own). */+export function runFiles(g: Pick<Generation, "kind" | "outputs">): { index: number; url: string; label: string }[] {+ const shown = shownOutputs(g);+ return shown.map((index, n) => ({ index, url: g.outputs[index].url, label: shown.length > 1 ? `Open file ${n + 1} of ${shown.length}` : "Open file" }));+}++/** Whether a tile plays a clip (a video the browser plays, or a 3D model's turntable): its box then plays and pauses on a tap or a key. */+export function playsClip(g: Pick<Generation, "outputs" | "op" | "request">, out?: OutputFile): boolean {+ if (out?.kind === "video") return !editOnlyFormat(g, out);+ return out?.kind === "model3d" && !!modelPreview(g, out).video;+}/*** Settings → Accounts' runs (the owner only): what accounts made on their own GPUs, newest first, one account's or every@@ -53,9 +73,9 @@ export function AccountRunsView() {const viewer = useViewer();const owner = !!viewer.data?.owner;const router = useRouter();- const account = useSearchParams().get("account") ?? "";- const [status, setStatus] = useState<Status>("all");- const [kind, setKind] = useState<Kind>("all");+ const sp = useSearchParams();+ const account = sp.get("account") ?? "";+ const { status, kind } = runFilters(sp);const accounts = useAdminAccounts(owner);const act = useAdminAction();const rows = accounts.data?.items;@@ -82,6 +102,12 @@ export function AccountRunsView() {if (viewer.isPending) return <GallerySkeleton cards={8} />;if (!owner) return <PageHeader title="Accounts' runs" description="Only the studio's owner sees accounts' runs." />;+ // Another account is another page (Back returns to this one); a filter changes this one.+ const show = (to: { account?: string; status?: Status; kind?: Kind }) => {+ const href = runsHref({ account, status, kind, ...to });+ if ("account" in to) router.push(href, { scroll: false });+ else router.replace(href, { scroll: false });+ };const switchAccount = (a: Pick<AccountRow, "id" | "email" | "disabled">) => {if (!a.disabled && !window.confirm(`Switch ${a.email} off? They're signed out at once and can't log in until you switch them on again.`)) return;void act(() => adminCall(`/api/admin/accounts/${a.id}`, "PATCH", { disabled: !a.disabled }), a.disabled ? "Switched on" : "Switched off");@@ -92,6 +118,8 @@ export function AccountRunsView() {};const items = runs.data?.pages.flatMap((p) => p.items) ?? [];const filtered = status !== "all" || kind !== "all";+ // Whose runs: the account's row, else the email its runs carry (while the accounts load, or when they couldn't).+ const email = me?.email ?? items.find((g) => g.account.id === account)?.account.email ?? undefined;return (<>@@ -99,8 +127,26 @@ export function AccountRunsView() {<PageHeader title="Accounts' runs" description="What people who signed up made on their own GPUs, newest first. Your own runs are in your Library." />) : gone ? (<PageHeader title="Deleted account" description="This account no longer exists. Runs it left behind are listed until the next clean-up." />+ ) : email ? (+ <PageHeader title={email} description="This account's runs, newest first." />+ ) : accounts.isPending || runs.isPending ? (+ <div className="pb-6" aria-busy="true" aria-label="Loading">+ <Skeleton className="h-10 w-72 max-w-full" />+ <Skeleton className="mt-2 h-4 w-52 max-w-full" />+ </div>) : (- <PageHeader title={me?.email ?? "Accounts' runs"} description="This account's runs, newest first." />+ <PageHeader title="Accounts' runs" description="This account's runs, newest first." />+ )}++ {accounts.isError && !rows && (+ <div className="mb-4 flex flex-wrap items-center gap-3">+ <p className="text-[13px] text-destructive">+ Couldn't load {account ? "the account" : "the accounts"}. {accounts.error.message}+ </p>+ <Button size="sm" variant="secondary" disabled={accounts.isFetching} onClick={() => void accounts.refetch()}>+ Try again+ </Button>+ </div>)}{me && (@@ -126,7 +172,7 @@ export function AccountRunsView() {)}<div className="mb-4 grid grid-cols-2 gap-2 sm:flex sm:flex-wrap sm:items-center">- <Select value={account || "all"} onValueChange={(id) => router.replace(runsHref(id === "all" ? undefined : id), { scroll: false })}>+ <Select value={account || "all"} onValueChange={(id) => show({ account: id === "all" ? undefined : id })}><SelectTrigger className="col-span-2 w-full sm:col-span-1 sm:w-auto sm:max-w-80 sm:min-w-44" aria-label="Account"><SelectValue /></SelectTrigger>@@ -138,10 +184,10 @@ export function AccountRunsView() {{a.disabled ? " (off)" : ""}</SelectItem>))}- {gone && <SelectItem value={account}>Deleted account</SelectItem>}+ {account && !me && <SelectItem value={account}>{gone ? "Deleted account" : (email ?? "This account")}</SelectItem>}</SelectContent></Select>- <Select value={status} onValueChange={(v) => setStatus(v as Status)}>+ <Select value={status} onValueChange={(v) => show({ status: v as Status })}><SelectTrigger className="w-full sm:w-auto sm:min-w-44" aria-label="Status"><SelectValue /></SelectTrigger>@@ -153,7 +199,7 @@ export function AccountRunsView() {))}</SelectContent></Select>- <Select value={kind} onValueChange={(v) => setKind(v as Kind)}>+ <Select value={kind} onValueChange={(v) => show({ kind: v as Kind })}><SelectTrigger className="w-full sm:w-auto sm:min-w-44" aria-label="Kind"><SelectValue /></SelectTrigger>@@ -190,15 +236,7 @@ export function AccountRunsView() {{filtered ? (<><p>No runs match these filters.</p>- <Button- size="sm"- variant="secondary"- className="mt-3"- onClick={() => {- setStatus("all");- setKind("all");- }}- >+ <Button size="sm" variant="secondary" className="mt-3" onClick={() => show({ status: "all", kind: "all" })}>Clear filters</Button></>@@ -211,7 +249,15 @@ export function AccountRunsView() {) : (<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">{items.map((g) => (- <RunCard key={g.id} g={g} one={!!account} row={rows?.find((a) => a.id === g.account.id)} onSwitch={switchAccount} onDelete={deleteRun} />+ <RunCard+ key={g.id}+ g={g}+ one={!!account}+ href={runsHref({ account: g.account.id, status, kind })}+ row={rows?.find((a) => a.id === g.account.id)}+ onSwitch={switchAccount}+ onDelete={deleteRun}+ />))}</div>)}@@ -234,38 +280,77 @@ export function AccountRunsView() {}/**- * One run: its result (a picture opens full size, a clip plays on hover or a tap, sound has its player), what made it,- * the prompt, its status and when. `one`: the page shows one account, so the email is left out; `row`: the account's- * row (its off state), absent when the account is gone.+ * One run: its result (a picture opens full size, a clip plays on hover, a tap or Enter, sound has its player; the+ * count steps through a run's files), what made it, the prompt, its status and when. `one`: the page shows one account,+ * so the email is left out; `href`: this account's runs, with the filters; `row`: the account's row (its off state),+ * absent when the account is gone.*/-function RunCard({ g, one, row, onSwitch, onDelete }: { g: AdminRun; one: boolean; row?: AccountRow; onSwitch: (a: AccountRow) => void; onDelete: (g: AdminRun) => void }) {- const out = g.status === "succeeded" ? g.outputs[0] : undefined;+function RunCard({+ g,+ one,+ href,+ row,+ onSwitch,+ onDelete,+}: {+ g: AdminRun;+ one: boolean;+ href: string;+ row?: AccountRow;+ onSwitch: (a: AccountRow) => void;+ onDelete: (g: AdminRun) => void;+}) {+ const files = runFiles(g);+ const [at, setAt] = useState(0);+ const n = files.length ? at % files.length : 0;+ const out = g.status === "succeeded" && files.length ? g.outputs[files[n].index] : undefined;+ const clip = playsClip(g, out);// Whether the clip was paused when the press began: a tap's emulated hover starts it just before the click.const paused = useRef(true);+ const toggle = (v: HTMLVideoElement | null, wasPaused: boolean) => {+ if (!v) return;+ if (wasPaused) void v.play().catch(() => {});+ else v.pause();+ };return (<div className="min-w-0">- <div- className="relative aspect-square overflow-hidden rounded-xl border bg-muted"- onPointerDown={(e) => {- paused.current = e.currentTarget.querySelector("video")?.paused ?? true;- }}- onClick={(e) => {- const v = e.currentTarget.querySelector("video");- if (!v) return;- if (paused.current) void v.play().catch(() => {});- else v.pause();- }}- >- {!out ? (- <StatusCover g={g} />- ) : out.kind === "image" ? (- <a href={out.url} target="_blank" rel="noreferrer" aria-label="Open the picture" className="block size-full">- <MediaThumb output={out} g={g} />- </a>- ) : (- <MediaThumb output={out} g={g} />+ <div className="relative">+ <div+ className={cn("aspect-square overflow-hidden rounded-xl border bg-muted", clip && "outline-none focus-visible:ring-2 focus-visible:ring-ring")}+ role={clip ? "button" : undefined}+ tabIndex={clip ? 0 : undefined}+ aria-label={clip ? "Play or pause the clip" : undefined}+ onPointerDown={(e) => {+ paused.current = e.currentTarget.querySelector("video")?.paused ?? true;+ }}+ onClick={(e) => toggle(e.currentTarget.querySelector("video"), paused.current)}+ onKeyDown={(e) => {+ if (!clip || e.target !== e.currentTarget || (e.key !== "Enter" && e.key !== " ")) return;+ e.preventDefault();+ const v = e.currentTarget.querySelector("video");+ toggle(v, v?.paused ?? true);+ }}+ >+ {!out ? (+ <StatusCover g={g} />+ ) : out.kind === "image" ? (+ <a href={out.url} target="_blank" rel="noreferrer" aria-label="Open the picture" className="block size-full">+ <MediaThumb key={out.url} output={out} g={g} />+ </a>+ ) : (+ <MediaThumb key={out.url} output={out} g={g} />+ )}+ </div>+ {out && files.length > 1 && (+ <button+ type="button"+ className="absolute right-2 bottom-2 rounded-md bg-black/60 px-1.5 py-0.5 text-[11px] text-white tabular-nums hover:bg-black/75"+ aria-label={`File ${n + 1} of ${files.length}: show the next`}+ onClick={() => setAt(n + 1)}+ >+ {n + 1}/{files.length}+ </button>)}- {g.outputs.length > 1 && <span className="absolute right-2 bottom-2 rounded-md bg-black/60 px-1.5 py-0.5 text-[11px] text-white">{g.outputs.length}</span>}</div><div className="relative mt-2 min-w-0 space-y-0.5 pr-8"><DropdownMenu>@@ -275,16 +360,16 @@ function RunCard({ g, one, row, onSwitch, onDelete }: { g: AdminRun; one: boolea</Button></DropdownMenuTrigger><DropdownMenuContent align="end">- {g.outputs[0] && (- <DropdownMenuItem asChild>- <a href={g.outputs[0].url} target="_blank" rel="noreferrer">- <ExternalLink /> Open file+ {files.map((f) => (+ <DropdownMenuItem key={f.index} asChild>+ <a href={f.url} target="_blank" rel="noreferrer">+ <ExternalLink /> {f.label}</a></DropdownMenuItem>- )}+ ))}{!one && (<DropdownMenuItem asChild>- <Link href={runsHref(g.account.id)}>+ <Link href={href}><Filter /> Only this account</Link></DropdownMenuItem>@@ -303,7 +388,7 @@ function RunCard({ g, one, row, onSwitch, onDelete }: { g: AdminRun; one: boolea{!one && (<div className="flex min-w-0 items-center gap-1.5 text-[12px] font-medium">{g.account.email ? (- <Link href={runsHref(g.account.id)} className="truncate underline-offset-2 hover:underline">+ <Link href={href} className="truncate underline-offset-2 hover:underline">{g.account.email}</Link>) : (diff --git a/src/components/accounts-admin.tsx b/src/components/accounts-admin.tsxindex 58c07fdc..8fa03b81 100644--- a/src/components/accounts-admin.tsx+++ b/src/components/accounts-admin.tsx@@ -3,6 +3,7 @@import { useQuery, useQueryClient } from "@tanstack/react-query";import { Download, Images, Loader2, Trash2, UserX, UserCheck } from "lucide-react";import Link from "next/link";+import { useEffect } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";import { useViewer } from "@/lib/api";@@ -88,13 +89,61 @@ export function OffBadge({ className }: { className?: string }) {return <span className={cn("rounded-sm bg-muted px-1 py-0.5 text-[10px] font-normal text-muted-foreground", className)}>off</span>;}-const runsHref = (id: string) => `/settings/runs?account=${encodeURIComponent(id)}`;+/** The runs page for one account (else every account's), with its status and kind filters ("all" and unset are left out). */+export function runsHref({ account, status, kind }: { account?: string; status?: string; kind?: string } = {}): string {+ const q = new URLSearchParams();+ if (account) q.set("account", account);+ if (status && status !== "all") q.set("status", status);+ if (kind && kind !== "all") q.set("kind", kind);+ const s = q.toString();+ return s ? `/settings/runs?${s}` : "/settings/runs";+}++/** Settings' strip (the owner, once someone has signed up): how many, and the way down to Accounts, the last section. */+export function AccountsChip() {+ const owner = useViewer().data?.owner;+ const q = useAdminAccounts(!!owner);+ if (!q.data?.total) return null;+ return (+ <a href="#accounts" className="inline-flex h-7 shrink-0 items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] whitespace-nowrap transition-colors hover:bg-accent">+ <span className="text-muted-foreground">Accounts</span>+ <span className="font-medium">{q.data.total}</span>+ {q.data.totals.running > 0 && <span className="text-muted-foreground">· {q.data.totals.running} running</span>}+ </a>+ );+}++const OWNER_MOVES = ["wheel", "touchstart", "keydown", "pointerdown"] as const;++/**+ * /settings#accounts (the runs page's "← Settings", a bookmark) arrives before this list and the sections+ * above it have loaded, so the browser finds no anchor, or one that moves down as they grow: go to it once the list is+ * here, and stay on it while the page above grows, until the owner scrolls or 10 seconds pass.+ */+function useAccountsAnchor(ready: boolean) {+ useEffect(() => {+ if (!ready || window.location.hash !== "#accounts") return;+ const go = () => document.getElementById("accounts")?.scrollIntoView({ block: "start" });+ const ro = new ResizeObserver(go);+ const stop = () => {+ ro.disconnect();+ clearTimeout(timer);+ for (const e of OWNER_MOVES) window.removeEventListener(e, stop);+ };+ const timer = setTimeout(stop, 10_000);+ go();+ ro.observe(document.body);+ for (const e of OWNER_MOVES) window.addEventListener(e, stop, { passive: true });+ return stop;+ }, [ready]);+}/** Settings → Accounts (the owner only): who signed up (public sign-up), what each made and the space it takes, with switch-off, delete and a CSV export. */export function AccountsAdmin() {const owner = useViewer().data?.owner;const q = useAdminAccounts(!!owner);const act = useAdminAction();+ useAccountsAnchor(!!q.data);if (!owner || (!q.data && !q.isError)) return null;const total = q.data?.total ?? 0;return (@@ -155,26 +204,27 @@ export function AccountsAdmin() {<th className="px-3 py-2 font-medium">Last run</th><th className="px-3 py-2 font-medium">Space</th><th className="px-3 py-2 font-medium">GPU</th>- <th className="px-3 py-2 font-medium max-sm:hidden">Created</th>- <th className="px-3 py-2 font-medium max-sm:hidden">Last login</th>- <th className="px-3 py-2" />+ <th className="px-3 py-2 font-medium max-2xl:hidden">Created</th>+ <th className="px-3 py-2 font-medium max-2xl:hidden">Last login</th>+ {/* The actions stay in view when the table is wider than its box (a long email, a phone); what's under them fades out. */}+ <th className="sticky right-0 bg-background bg-linear-to-r from-muted/50 to-muted/50 px-3 py-2" /></tr></thead><tbody className="divide-y">{q.data.items.map((a) => (<tr key={a.id} className={a.disabled ? "text-muted-foreground" : undefined}>- <td className="max-w-56 truncate px-3 py-2 font-medium">+ <td className="max-w-40 truncate px-3 py-2 font-medium 2xl:max-w-56" title={a.email}>{a.email}{a.disabled && <OffBadge className="ml-1.5" />}</td><td className="px-3 py-2">- <Link href={runsHref(a.id)} className="font-medium tabular-nums underline-offset-2 hover:underline">+ <Link href={runsHref({ account: a.id })} className="font-medium tabular-nums underline-offset-2 hover:underline">{a.runs}</Link>- <div className="text-[11px] whitespace-nowrap text-muted-foreground">- {a.runsWeek} in 7 days- {a.failedWeek > 0 && <span className="text-destructive"> · {a.failedWeek} failed</span>}- {a.running > 0 && ` · ${a.running} running`}+ <div className="text-[11px] text-muted-foreground">+ <span className="whitespace-nowrap">{a.runsWeek} in 7 days</span>+ {a.failedWeek > 0 && <span className="whitespace-nowrap text-destructive"> · {a.failedWeek} failed</span>}+ {a.running > 0 && <span className="whitespace-nowrap"> · {a.running} running</span>}</div></td><td className="px-3 py-2 whitespace-nowrap">{a.lastRunAt ? timeAgo(a.lastRunAt) : "—"}</td>@@ -182,11 +232,11 @@ export function AccountsAdmin() {{storageSize(a.bytes)} of {storageSize(a.capBytes)}</td><td className="px-3 py-2">{a.gpu ? "Connected" : "—"}</td>- <td className="px-3 py-2 whitespace-nowrap max-sm:hidden">{timeAgo(a.createdAt)}</td>- <td className="px-3 py-2 whitespace-nowrap max-sm:hidden">{a.lastLoginAt ? timeAgo(a.lastLoginAt) : "—"}</td>- <td className="px-2 py-1 text-right whitespace-nowrap">+ <td className="px-3 py-2 whitespace-nowrap max-2xl:hidden">{timeAgo(a.createdAt)}</td>+ <td className="px-3 py-2 whitespace-nowrap max-2xl:hidden">{a.lastLoginAt ? timeAgo(a.lastLoginAt) : "—"}</td>+ <td className="sticky right-0 bg-background px-2 py-1 text-right whitespace-nowrap before:pointer-events-none before:absolute before:inset-y-0 before:right-full before:w-4 before:bg-linear-to-l before:from-background"><Button asChild size="icon" variant="ghost" className="size-7 text-muted-foreground">- <Link href={runsHref(a.id)} aria-label={`Runs by ${a.email}`} title="Runs">+ <Link href={runsHref({ account: a.id })} aria-label={`Runs by ${a.email}`} title="Runs"><Images className="size-3.5" /></Link></Button>diff --git a/src/components/gpu/account-gpu-section.tsx b/src/components/gpu/account-gpu-section.tsxindex 3acfbab3..18cb3fb3 100644--- a/src/components/gpu/account-gpu-section.tsx+++ b/src/components/gpu/account-gpu-section.tsx@@ -16,7 +16,7 @@ export function AccountGpuSection() {Your GPU</h2><p className="mt-1 text-[13px] text-muted-foreground">- Signed in as {account.email}. Connect your own ComfyUI to run open-source models. The studio's owner can see what you make here.+ Signed in as {account.email}. Connect your own ComfyUI to run open-source models. The studio's owner can see what you upload and make here.</p><Buttonsize="sm"diff --git a/src/components/login-form.tsx b/src/components/login-form.tsxindex bb61942b..b323345e 100644--- a/src/components/login-form.tsx+++ b/src/components/login-form.tsx@@ -102,7 +102,7 @@ export function LoginForm() {<Button type="submit" className="mt-4 h-11 w-full" disabled={!password || (mode !== "owner" && !email) || (mode === "signup" && password.length < 8) || busy}>{busy && <Loader2 className="animate-spin" />} {copy.button}</Button>- {mode === "signup" && <p className="mt-3 text-center text-[12px] text-muted-foreground">The studio's owner can see what you make here.</p>}+ {mode === "signup" && <p className="mt-3 text-center text-[12px] text-muted-foreground">The studio's owner can see what you upload and make here.</p>}{open && (<div className="mt-4 space-y-1.5 text-center text-[13px] text-muted-foreground">{mode === "signup" ? (diff --git a/src/components/security-settings.tsx b/src/components/security-settings.tsxindex bf58db40..ba5967c6 100644--- a/src/components/security-settings.tsx+++ b/src/components/security-settings.tsx@@ -301,7 +301,11 @@ function PublicSignup() {Guests can browse every page read-only (not your library), and anyone can sign up with an email and a password. Accounts never use your cloud keys or GPU, andcan't change settings, keys or tokens.{p.fromEnv !== null && " Set by FUOBE_PUBLIC_SIGNUP on the server."}- {p.active && !(p.fromEnv ?? p.setting) && " On for this address (fuobe.com)."}+ {p.active && !(p.fromEnv ?? p.setting) && " On for this address (fuobe.com)."}{" "}+ <a href="#accounts" className="text-brand-text underline underline-offset-2">+ See who signed up and what they make+ </a>+ .</p></div>);diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsxindex 5c269a7b..a96f60a2 100644--- a/src/components/settings-form.tsx+++ b/src/components/settings-form.tsx@@ -10,6 +10,7 @@ import { Button } from "@/components/ui/button";import { Label } from "@/components/ui/label";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Skeleton } from "@/components/ui/skeleton";+import { AccountsChip } from "@/components/accounts-admin";import { ConnectField, useSettings, type PublicSetting } from "@/components/connect-field";import { GetStarted } from "@/components/get-started";import { LoraSettings } from "@/components/lora-settings";@@ -152,7 +153,7 @@ function ChoiceField({/*** What's connected, at a glance and always in view: one chip per connection (green when it works,- * each a link to its field) and the engine mode. Also opens the setup guide again.+ * each a link to its field), the engine mode and, once someone has signed up, the accounts. Also opens the setup guide again.*/function StatusStrip({ status, onGuide, guideOpen }: { status?: StatusInfo; onGuide: () => void; guideOpen: boolean }) {return (@@ -178,6 +179,7 @@ function StatusStrip({ status, onGuide, guideOpen }: { status?: StatusInfo; onGu<span className="text-muted-foreground">Engine</span><span className="font-medium">{ENGINE_MODE_LABEL[status.engineMode]}</span></a>+ <AccountsChip />{!guideOpen && (<button type="button" onClick={onGuide} className="inline-flex h-7 shrink-0 items-center gap-1 rounded-full px-2.5 text-[12px] font-medium whitespace-nowrap text-brand-text hover:bg-brand-faint">Setup guidediff --git a/src/server/account-admin.ts b/src/server/account-admin.tsindex 1025b05e..ca690d18 100644--- a/src/server/account-admin.ts+++ b/src/server/account-admin.ts@@ -20,7 +20,7 @@ export interface AccountStats {runs: number;runsDay: number;runsWeek: number;- /** Queued or running now. */+ /** Runs going now (queued or running), as the account's run limit counts them: a batch or a chain is one run. */running: number;/** Failed in the last 7 days (a run the account canceled isn't counted). */failedWeek: number;@@ -42,18 +42,21 @@ export interface AccountTotals {export type AccountListing = AccountInfo & AccountStats;-/** Every account's runs in one pass over generations_account (a range search: only accounts' entries). */-export const STATS_SQL = `SELECT json_extract(g.request_json, '$.account') AS account, COUNT(*) AS runs,- SUM(g.created_at >= @day) AS runsDay, SUM(g.created_at >= @week) AS runsWeek,- SUM(g.status IN ('queued', 'running')) AS running, SUM(g.status = 'failed' AND g.created_at >= @week) AS failedWeek,- MAX(g.created_at) AS lastRunAt- FROM generations g WHERE json_extract(g.request_json, '$.account') > '' AND NOT ${HELPER_SQL}- GROUP BY json_extract(g.request_json, '$.account')`;+/**+ * Every account's runs in one pass over generations_account (a range search: only accounts' entries). Helper steps+ * count only in `running`, which counts as POST /api/generations does (activeRuns): one per batch or chain.+ */+export const STATS_SQL = `SELECT account, SUM(NOT step) AS runs, SUM(NOT step AND created_at >= @day) AS runsDay,+ SUM(NOT step AND created_at >= @week) AS runsWeek, COUNT(DISTINCT CASE WHEN status IN ('queued', 'running') THEN COALESCE(batch_id, id) END) AS running,+ SUM(NOT step AND status = 'failed' AND created_at >= @week) AS failedWeek, MAX(CASE WHEN NOT step THEN created_at END) AS lastRunAt+ FROM (SELECT json_extract(g.request_json, '$.account') AS account, ${HELPER_SQL} AS step, g.id, g.batch_id, g.status, g.created_at+ FROM generations g WHERE json_extract(g.request_json, '$.account') > '')+ GROUP BY account`;/** What each account's files weigh (what accountUsage counts), over assets_account. */export const SPACE_SQL = "SELECT account_id AS account, SUM(size) AS bytes FROM assets WHERE account_id > '' GROUP BY account_id";-type StatsRow = { account: string; runs: number; runsDay: number; runsWeek: number; running: number; failedWeek: number; lastRunAt: number };+type StatsRow = { account: string; runs: number; runsDay: number; runsWeek: number; running: number; failedWeek: number; lastRunAt: number | null };/** Each account with its numbers, and the totals over every account's runs and files on this server. */export function accountsWithStats(items: AccountInfo[] = listAccounts(), now = Date.now()): { items: AccountListing[]; totals: AccountTotals } {@@ -73,7 +76,7 @@ export function accountsWithStats(items: AccountInfo[] = listAccounts(), now = DrunsWeek: Number(r?.runsWeek ?? 0),running: Number(r?.running ?? 0),failedWeek: Number(r?.failedWeek ?? 0),- lastRunAt: r ? Number(r.lastRunAt) : null,+ lastRunAt: r?.lastRunAt != null ? Number(r.lastRunAt) : null,bytes: bytesOf.get(a.id) ?? 0,capBytes: accountTotalBytes(a.id, a.createdAt),};diff --git a/src/server/generations.ts b/src/server/generations.tsindex b39a31c6..a5eb69fb 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -113,7 +113,8 @@ interface Row {/** Trash and folder columns, joined onto every library read. */const LIBRARY_COLUMNS = "g.*, t.deleted_at AS deleted_at, fi.folder_id AS folder_id";-const LIBRARY_JOIN = "generations g LEFT JOIN generation_trash t ON t.generation_id = g.id LEFT JOIN folder_items fi ON fi.generation_id = g.id";+const LIBRARY_JOINS = "LEFT JOIN generation_trash t ON t.generation_id = g.id LEFT JOIN folder_items fi ON fi.generation_id = g.id";+const LIBRARY_JOIN = `generations g ${LIBRARY_JOINS}`;export function toGeneration(r: Row): Generation {const request = JSON.parse(r.request_json) as GenerationRequest;@@ -297,10 +298,18 @@ export function listGenerations(o: ListOptions = {}): Generation[] {const q = o.q?.trim();// The user's own words (request.prompt) and what the model got (prompt, with suffixes and templates).if (q) add("(g.prompt LIKE ? OR json_extract(g.request_json, '$.prompt') LIKE ?)", `%${q}%`, `%${q}%`);- const sql = `SELECT ${LIBRARY_COLUMNS} FROM ${LIBRARY_JOIN} WHERE ${where.join(" AND ")} ORDER BY ${col} DESC, g.id DESC LIMIT ?`;+ // Every account's runs: from the accounts' entries in generations_account, then sorted (they go after 30 days, so they+ // stay few). Left to its own plan, SQLite walks every run newest first (or every run of a status), the owner's too,+ // until the page is full: the whole table when accounts' runs are few or none match. Without the index (db.ts goes+ // on when it can't make it), the plain plan.+ const from = !o.account && o.accounts && accountIndexed() ? `generations g INDEXED BY generations_account ${LIBRARY_JOINS}` : LIBRARY_JOIN;+ const sql = `SELECT ${LIBRARY_COLUMNS} FROM ${from} WHERE ${where.join(" AND ")} ORDER BY ${col} DESC, g.id DESC LIMIT ?`;return (db().prepare(sql).all(...args, Math.max(1, Math.min(o.limit ?? 60, 200))) as Row[]).map(toGeneration);}+/** Whether the runs-by-account index exists (db.ts makes it outside the migrations, and goes on without it on a failure). */+const accountIndexed = () => !!db().prepare("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'generations_account'").get();+export function setFavorite(id: string, favorite: boolean): void {update(id, { favorite: favorite ? 1 : 0 });}diff --git a/tests/account-runs-admin.test.ts b/tests/account-runs-admin.test.tsindex 1a2d9488..2daec27c 100644--- a/tests/account-runs-admin.test.ts+++ b/tests/account-runs-admin.test.ts@@ -5,6 +5,7 @@ import path from "node:path";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";import type { AccountListing, AccountRun, AccountTotals } from "@/server/account-admin";+import type { ListOptions } from "@/server/generations";import { TINY_PNG } from "./helpers/fake-comfy-runner";// Route handlers are called directly, outside a Next request: connection() has nothing to wait for.@@ -44,16 +45,27 @@ const HOUR = 3_600_000;const DAY = 24 * HOUR;let seq = 0;-/** A run as the runner stores it: `account`'s (or the owner's), made `ago` ms before now (or `at`). */-function run(account?: string, o: { status?: string; kind?: string; feature?: string; ago?: number; at?: number; error?: string } = {}): string {+/** A run as the runner stores it: `account`'s (or the owner's), made `ago` ms before now (or `at`), in `batch` when given. */+function run(account?: string, o: { status?: string; kind?: string; feature?: string; ago?: number; at?: number; error?: string; batch?: string } = {}): string {const id = `run-${String(++seq).padStart(4, "0")}`;const at = o.at ?? Date.now() - (o.ago ?? 0);const feature = o.feature ?? "image";db().prepare(- "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, error, created_at, updated_at) VALUES (?, ?, 'm', 'open', 'comfyui', ?, ?, ?, ?, '[]', ?, ?, ?)",+ "INSERT INTO generations (id, batch_id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, error, created_at, updated_at) VALUES (?, ?, ?, 'm', 'open', 'comfyui', ?, ?, ?, ?, '[]', ?, ?, ?)",)- .run(id, feature, o.kind === "video" ? "t2v" : "t2i", o.kind ?? "image", o.status ?? "succeeded", JSON.stringify({ feature, modelId: "m", prompt: "a fox", ...(account && { account }) }), o.error ?? null, at, at);+ .run(+ id,+ o.batch ?? null,+ feature,+ o.kind === "video" ? "t2v" : "t2i",+ o.kind ?? "image",+ o.status ?? "succeeded",+ JSON.stringify({ feature, modelId: "m", prompt: "a fox", ...(account && { account }) }),+ o.error ?? null,+ at,+ at,+ );return id;}@@ -187,11 +199,21 @@ describe("Settings → Accounts: what accounts make", () => {it("reads its numbers and lists through the indexes", () => {expect(plan(admin.STATS_SQL, { day: 0, week: 0 })).toMatch(/SEARCH g USING INDEX generations_account/);expect(plan(admin.SPACE_SQL)).toMatch(/USING INDEX assets_account/);- // One account's: a search of its entries. Every account's: newest first along generations_created until the page is- // full (the limit is bound, so SQLite plans for any size), or a search of the accounts' entries when it reckons that cheaper.+ // One account's: a search of its entries. Every account's: a search of the accounts' entries too, whatever the+ // filters. Along generations_created or generations_status it would read the owner's runs as well, until the page+ // is full: all of them when accounts' runs are few, or none match (3D: accounts can't make it).expect(listPlan(() => admin.listAccountRuns({ account: A, before: Date.now(), beforeId: "x" }))).toMatch(/SEARCH g USING INDEX generations_account/);- expect(listPlan(() => admin.listAccountRuns({ accounts: true }))).toMatch(/^(SEARCH|SCAN) g USING INDEX generations_(account|created)\b/);- expect(listPlan(() => admin.listAccountRuns({ accounts: true, statuses: ["failed"] }))).toMatch(/^SEARCH g USING INDEX generations_(status|account)\b/);+ const filters: ListOptions[] = [{}, { statuses: ["succeeded"] }, { statuses: ["queued", "running"] }, { kind: "model3d" }, { statuses: ["failed"], kind: "audio" }, { before: Date.now(), beforeId: "x" }];+ for (const o of filters) expect(listPlan(() => admin.listAccountRuns({ accounts: true, ...o })), JSON.stringify(o)).toMatch(/^SEARCH g USING INDEX generations_account\b/);+ // db.ts goes on without the index when it can't make it: the list still answers, the slow way.+ const every = admin.listAccountRuns({ accounts: true, limit: 100 }).items.map((g) => g.id);+ db().exec("DROP INDEX generations_account");+ try {+ expect(admin.listAccountRuns({ accounts: true, limit: 100 }).items.map((g) => g.id)).toEqual(every);+ } finally {+ db().exec("CREATE INDEX IF NOT EXISTS generations_account ON generations(json_extract(request_json, '$.account'), created_at DESC)");+ }+ expect(every.length).toBeGreaterThan(0);});it("pages newest first, and no run is skipped or repeated", async () => {@@ -348,4 +370,27 @@ describe("Settings → Accounts: what accounts make", () => {expect(storageSize(1.25 * 2 ** 30)).toBe("1.3 GB");expect(storageSize(3 * 2 ** 30)).toBe("3 GB");});++ // Synchronous: the runner (started above) can't fail these queued runs before they are counted.+ it("counts a batch or a chain going as one run, as the account's run limit does", () => {+ const D = auth.createAccount("[email protected]", "long enough").id;+ const E = auth.createAccount("[email protected]", "long enough").id;+ // Four pictures in one batch; a film whose four shots (chain steps) and join share a batch; a chain whose only job+ // going is a step; and a run of its own.+ for (let i = 0; i < 4; i++) run(D, { status: i ? "queued" : "running", batch: "pictures", ago: 10 * 60_000 });+ for (let i = 0; i < 4; i++) run(D, { feature: "video-step", kind: "video", status: i ? "queued" : "running", batch: "film", ago: 5 * 60_000 });+ const join = run(D, { feature: "video", kind: "video", status: "queued", batch: "film", ago: 5 * 60_000 });+ run(D, { feature: "upscale-step", status: "running", batch: "chain" });+ run(D, { status: "failed", error: "Out of memory", ago: HOUR });+ // Only a helper step: no run to show, and no last run.+ run(E, { feature: "upscale-step", ago: HOUR });++ const going = (db().prepare("SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') = ?").get(D) as { n: number }).n;+ const { items } = admin.accountsWithStats();+ const of = (id: string) => items.find((a) => a.id === id)!;+ expect(going).toBe(3);+ expect(of(D)).toMatchObject({ runs: 6, runsDay: 6, runsWeek: 6, running: going, failedWeek: 1 });+ expect(of(D).lastRunAt).toBe(gens.getGeneration(join)!.createdAt);+ expect(of(E)).toMatchObject({ runs: 0, running: 0, lastRunAt: null });+ });});diff --git a/tests/account-runs-page.test.ts b/tests/account-runs-page.test.tsnew file mode 100644index 00000000..36421aee--- /dev/null+++ b/tests/account-runs-page.test.ts@@ -0,0 +1,86 @@+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { playsClip, runFiles, runFilters } from "@/components/account-runs";+import { runsHref } from "@/components/accounts-admin";+import type { Generation, OutputFile } from "@/lib/catalog/types";++const src = (f: string) => fs.readFileSync(path.join(__dirname, "..", f), "utf8");++/** A run's fields the tiles read: `outputs` of `kind`, made by `op`. */+function made(kind: Generation["kind"], outputs: Partial<OutputFile>[], op = "t2i", params: Record<string, unknown> = {}) {+ return {+ kind,+ op,+ request: { feature: "image", modelId: "m", params },+ outputs: outputs.map((o, i) => ({ url: `/api/files/outputs/2026-10-31/f${i}.png`, kind: "image", ...o }) as OutputFile),+ } as Pick<Generation, "kind" | "op" | "request" | "outputs">;+}++describe("Settings → Accounts' runs: the page", () => {+ it("keeps the account, status and kind in the address", () => {+ expect(runsHref()).toBe("/settings/runs");+ expect(runsHref({ account: "a1" })).toBe("/settings/runs?account=a1");+ expect(runsHref({ account: "a1", status: "failed", kind: "video" })).toBe("/settings/runs?account=a1&status=failed&kind=video");+ expect(runsHref({ status: "all", kind: "all" })).toBe("/settings/runs");+ expect(runsHref({ account: "a b&c" })).toBe("/settings/runs?account=a+b%26c");+ expect(runFilters(new URLSearchParams("status=failed&kind=model3d"))).toEqual({ status: "failed", kind: "model3d" });+ expect(runFilters(new URLSearchParams("status=sideways&kind=hologram"))).toEqual({ status: "all", kind: "all" });+ expect(runFilters(new URLSearchParams())).toEqual({ status: "all", kind: "all" });+ const back = new URL(runsHref({ account: "a1", status: "running", kind: "audio" }), "http://localhost").searchParams;+ expect(runFilters(back)).toEqual({ status: "running", kind: "audio" });+ // Another account is a new page (Back returns to the one before); a filter changes this one.+ const page = src("src/components/account-runs.tsx");+ expect(page).toMatch(/if \("account" in to\) router\.push\(href/);+ });++ it("opens every file a run shows, and leaves a 3D model's turntable out of the count", () => {+ expect(runFiles(made("image", [{}, {}]))).toEqual([+ { index: 0, url: "/api/files/outputs/2026-10-31/f0.png", label: "Open file 1 of 2" },+ { index: 1, url: "/api/files/outputs/2026-10-31/f1.png", label: "Open file 2 of 2" },+ ]);+ expect(runFiles(made("image", [{}])).map((f) => f.label)).toEqual(["Open file"]);+ const model = made("model3d", [{ url: "/api/files/outputs/m.glb", kind: "model3d" }, { url: "/api/files/outputs/t.mp4", kind: "video" }], "image-to-3d");+ expect(runFiles(model)).toEqual([{ index: 0, url: "/api/files/outputs/m.glb", label: "Open file" }]);+ expect(runFiles(made("image", []))).toEqual([]);+ });++ it("plays a clip from the keyboard as well as with a tap", () => {+ const clip = made("video", [{ url: "/api/files/outputs/c.mp4", kind: "video" }], "t2v");+ expect(playsClip(clip, clip.outputs[0])).toBe(true);+ const prores = made("video", [{ url: "/api/files/outputs/c.mov", kind: "video" }], "export-video", { format: "prores_422_hq" });+ expect(playsClip(prores, prores.outputs[0])).toBe(false);+ const model = made("model3d", [{ url: "/api/files/outputs/m.glb", kind: "model3d" }, { url: "/api/files/outputs/t.mp4", kind: "video" }], "image-to-3d");+ expect(playsClip(model, model.outputs[0])).toBe(true);+ const bare = made("model3d", [{ url: "/api/files/outputs/m.glb", kind: "model3d" }], "image-to-3d");+ expect(playsClip(bare, bare.outputs[0])).toBe(false);+ expect(playsClip(made("image", [{}]), made("image", [{}]).outputs[0])).toBe(false);+ expect(playsClip(clip, undefined)).toBe(false);+ // The clip's box is a button that takes focus, and Enter or Space plays or pauses it.+ const page = src("src/components/account-runs.tsx");+ expect(page).toMatch(/role=\{clip \? "button" : undefined\}\s+tabIndex=\{clip \? 0 : undefined\}/);+ expect(page).toMatch(/e\.key !== "Enter" && e\.key !== " "/);+ });++ it("keeps Settings → Accounts in reach: its row actions in view, and ways down to it", () => {+ const admin = src("src/components/accounts-admin.tsx");+ // The actions cell sticks to the table's right edge; Created and Last login wait for wide screens.+ expect(admin).toMatch(/<th className="sticky right-0 bg-background /);+ expect(admin).toMatch(/<td className="sticky right-0 bg-background /);+ expect(admin.match(/max-2xl:hidden/g)).toHaveLength(4);+ // /settings#accounts lands on the section once its list is here.+ expect(admin).toMatch(/useAccountsAnchor\(!!q\.data\)/);+ // The strip at the top of Settings and the Public sign-up switch lead to it.+ expect(src("src/components/settings-form.tsx")).toMatch(/<AccountsChip \/>/);+ expect(src("src/components/security-settings.tsx")).toMatch(/<a href="#accounts"/);+ });++ it("tells people who sign up that the owner sees their uploads too", () => {+ for (const f of ["src/components/login-form.tsx", "src/components/gpu/account-gpu-section.tsx"]) {+ expect(src(f), f).toContain("The studio's owner can see what you upload and make here.");+ }+ const doc = src("docs/public-signup.md");+ expect(doc).not.toMatch(/Only the account that uploaded a file can open it/);+ expect(doc).toMatch(/The studio's owner can open it too/);+ });+});