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' runs: a Run details page for each account's run
Adarsh7f936cea499f
diff --git a/docs/public-signup.md b/docs/public-signup.mdindex 025273fe..3d72309f 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -184,12 +184,28 @@ it ran. The owner can delete a run with its files, which gives the account its sswitch 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.+**Run details** (`/settings/runs/<run id>`: a run's name or **Run details** in its menu) shows everything about+one account's run. It shows what the account saw: its studio tile and its Library card, made by the same components+the account's pages use, with the same words, details line and buttons (nothing on it can be pressed). It shows what+went wrong: the stored error, the cause, the buttons the account was given, the files missing on its GPU, and the+note kept when it failed (stage, code, the GPU's or provider's own words). It shows where the run went: its own GPU+(a RunPod pod, a tunnel, a LAN or web address, its own computer), its own key, or this site's GPUs, and the graph.+It shows the model, the app, preset or studio, the prompt and negative prompt, and each setting beside the default+the composer would have started with (marked Default, Changed or Unknown default; a default that isn't known is+never guessed). It shows the input files (an upload that was cleared after 14 days says Removed), the other runs of+its batch, and the account's runs from 2 hours before to 6 hours after it. A Retry is the same request sent again,+so it shows as **Same request again**; a change of model shows as the same words and files on another model. A+collapsed section shows what was sent to the GPU or provider. Links show by their kind only, and keys, tokens,+cookies and passwords are left out.+The API, for the owner only (guests get 401, accounts 403): `GET /api/admin/accounts` (each accountwith `runs`, `runsDay`, `runsWeek`, `running`, `failedWeek`, `lastRunAt`, `bytes` and `capBytes`,and `totals`; `?format=csv` for the file), `PATCH /api/admin/accounts/<id>` with`{ "disabled": true | false }`, `DELETE /api/admin/accounts/<id>`, `GET /api/admin/generations`(`?account=<id>`, `status=finished|running|failed`, `kind=image|video|audio|model3d|text`,-`before=<createdAt>:<id>` from the last page's `next`, `limit` up to 100) and+`before=<createdAt>:<id>` from the last page's `next`, `limit` up to 100),+`GET /api/admin/generations/<id>` (Run details for an account's run; 404 for the owner's own run; an admin token+needs `runs:read` and `outputs:view`, and `accounts:read` for the email) and`DELETE /api/admin/generations/<id>` (an account's run only).An account can delete itself: `DELETE /api/auth/me` with `{ "password" }`. When an account isdiff --git a/src/app/(studio)/settings/runs/[id]/loading.tsx b/src/app/(studio)/settings/runs/[id]/loading.tsxnew file mode 100644index 00000000..5384692b--- /dev/null+++ b/src/app/(studio)/settings/runs/[id]/loading.tsx@@ -0,0 +1,5 @@+import { GalleryPageSkeleton } from "@/components/skeletons";++export default function Loading() {+ return <GalleryPageSkeleton title="Run details" />;+}diff --git a/src/app/(studio)/settings/runs/[id]/page.tsx b/src/app/(studio)/settings/runs/[id]/page.tsxnew file mode 100644index 00000000..e81f3a17--- /dev/null+++ b/src/app/(studio)/settings/runs/[id]/page.tsx@@ -0,0 +1,26 @@+import { ArrowLeft } from "lucide-react";+import type { Metadata } from "next";+import Link from "next/link";+import { Suspense } from "react";+import { PageShell } from "@/components/page-shell";+import { RunDetailsView } from "@/components/run-details";+import { GallerySkeleton } from "@/components/skeletons";++export const metadata: Metadata = { title: "Run details" };++/**+ * Settings → Accounts' runs → one run (the owner only): what the account asked for, saw and did. The run's id is read+ * in the browser (its data comes from the owner-only API), as Accounts' runs reads its filters.+ */+export default function Page() {+ return (+ <PageShell>+ <Link href="/settings/runs" className="mb-3 inline-flex items-center gap-1.5 rounded-md text-[13px] text-muted-foreground hover:text-foreground">+ <ArrowLeft className="size-3.5" /> Accounts' runs+ </Link>+ <Suspense fallback={<GallerySkeleton cards={4} />}>+ <RunDetailsView />+ </Suspense>+ </PageShell>+ );+}diff --git a/src/app/api/admin/generations/[id]/route.ts b/src/app/api/admin/generations/[id]/route.tsindex d109a01b..db07f5ed 100644--- a/src/app/api/admin/generations/[id]/route.ts+++ b/src/app/api/admin/generations/[id]/route.ts@@ -1,9 +1,31 @@+import { connection } from "next/server";import { generationAccount } from "@/server/account-library";-import { adminAccess, audit } from "@/server/admin-tokens";+import { actorHas, adminAccess, audit, auditContentRead, lacksScope } from "@/server/admin-tokens";import { deleteForever } from "@/server/library";+import { runDetails } from "@/server/run-details";const NO_STORE = { "Cache-Control": "no-store" };+/**+ * One account's run in full, for the owner's Run details (owner only, or an admin token with runs:read and+ * outputs:view): what it asked for (each setting beside its default), its files, where it ran, what came back and what+ * the account was shown, and its batch and the account's runs around it. Keys, tokens and a GPU's address never are+ * part of it (src/server/run-details.ts). The account's email needs accounts:read. The owner's own runs aren't here+ * (404): they are in the Library. Each read is in the admin log with the account as its target.+ */+export async function GET(request: Request, ctx: RouteContext<"/api/admin/generations/[id]">) {+ await connection();+ const access = adminAccess(request, "runs:read", "You can't open this.");+ if (access instanceof Response) return access;+ const denied = lacksScope(access.actor, "outputs:view", request);+ if (denied) return denied;+ const { id } = await ctx.params;+ const details = runDetails(id, { emails: actorHas(access.actor, "accounts:read") });+ if (!details) return Response.json({ error: "No such run" }, { status: 404, headers: NO_STORE });+ auditContentRead(access.actor, "runs.content", [details.run.account.id], { run: id });+ return Response.json(details, { headers: NO_STORE });+}+/*** Delete an account's run for good (owner only, or an admin token with runs:delete), as the account's own delete does:* a run still going is canceled first, and its files go unless another run still uses them, so the account's spacediff --git a/src/components/account-runs.tsx b/src/components/account-runs.tsxindex 4bd7ee9a..b1e47092 100644--- a/src/components/account-runs.tsx+++ b/src/components/account-runs.tsx@@ -1,13 +1,14 @@"use client";import { keepPreviousData, useInfiniteQuery } from "@tanstack/react-query";-import { ExternalLink, Filter, Loader2, MoreHorizontal, Trash2, UserCheck, UserX } from "lucide-react";+import { ExternalLink, FileSearch, Filter, Loader2, MoreHorizontal, Trash2, UserCheck, UserX } from "lucide-react";import Link from "next/link";import { useRouter, useSearchParams } from "next/navigation";import { useEffect, useRef, useState } from "react";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 { runDetailsHref } from "@/components/run-details";import { GallerySkeleton } from "@/components/skeletons";import { DeclinedCards } from "@/components/studio/made-note";import { autoLine } from "@/lib/auto-image";@@ -369,6 +370,11 @@ function RunCard({</Button></DropdownMenuTrigger><DropdownMenuContent align="end">+ <DropdownMenuItem asChild>+ <Link href={runDetailsHref(g.id)}>+ <FileSearch /> Run details+ </Link>+ </DropdownMenuItem>{files.map((f) => (<DropdownMenuItem key={f.index} asChild><a href={f.url} target="_blank" rel="noreferrer">@@ -406,7 +412,11 @@ function RunCard({{row?.disabled && <OffBadge />}</div>)}- <p className="truncate text-[13px] font-medium">{g.presetName ?? featureName(g.feature)}</p>+ <p className="truncate text-[13px] font-medium">+ <Link href={runDetailsHref(g.id)} className="underline-offset-2 hover:underline" title="Run details">+ {g.presetName ?? featureName(g.feature)}+ </Link>+ </p><p className="truncate text-[12px] text-muted-foreground">{g.modelName ?? g.modelId} · {OPERATION_LABELS[g.op] ?? g.op}</p>diff --git a/src/components/run-details.tsx b/src/components/run-details.tsxnew file mode 100644index 00000000..02af9a86--- /dev/null+++ b/src/components/run-details.tsx@@ -0,0 +1,485 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { ExternalLink, FileX2, Link2 } from "lucide-react";+import Link from "next/link";+import { useParams, useRouter } from "next/navigation";+import { useEffect } from "react";+import { adminCall, runsHref } from "@/components/accounts-admin";+import { StatusCover } from "@/components/library/asset-card";+import { PageHeader } from "@/components/page-shell";+import { GallerySkeleton } from "@/components/skeletons";+import { FailedTile, tileRatio } from "@/components/studio/feed";+import { MediaThumb } from "@/components/studio/result-media";+import { Button } from "@/components/ui/button";+import { Skeleton } from "@/components/ui/skeleton";+import { useViewer } from "@/lib/api";+import { OPERATION_LABELS, type Generation } from "@/lib/catalog/types";+import { elapsed, timeAgo } from "@/lib/format";+import type { SettingRow, SettingState } from "@/lib/run-settings";+import { cn } from "@/lib/utils";+import type { AccountRun } from "@/server/account-admin";+import type { NearRun, RunDetails, RunInput } from "@/server/run-details";++/** The address of a run's details page (the private admin panel links here too). */+export const runDetailsHref = (id: string) => `/settings/runs/${encodeURIComponent(id)}`;++const STATUS_WORDS: Record<string, string> = { succeeded: "Finished", queued: "Queued", running: "Running", failed: "Failed", canceled: "Canceled" };+const STATE_WORDS: Record<SettingState, string> = { default: "Default", changed: "Changed", unknown: "Unknown default", input: "Its input" };+const STATE_STYLE: Record<SettingState, string> = {+ default: "bg-muted text-muted-foreground",+ changed: "bg-highlight text-highlight-foreground",+ unknown: "border border-dashed text-muted-foreground",+ input: "bg-secondary text-secondary-foreground",+};+const FROM_WORDS: Record<string, string> = { composer: "composer", model: "model", preset: "preset", app: "app", control: "model option", option: "app option" };+const HOST_WORDS: Record<string, string> = {+ runpod: "RunPod pod",+ tunnel: "Tunnel (Cloudflare, ngrok…)",+ lan: "LAN address",+ web: "Web address",+ computer: "ComfyUI on its own computer",+ connect: "Paired with a code (Fuobe Connect)",+ none: "No GPU set",+};+const MATCH_WORDS: Record<NearRun["match"], string> = { same: "Same request again", "other-model": "Same words and files, other model or settings", other: "Another run" };++const featureName = (f: string) => f.charAt(0).toUpperCase() + f.slice(1).replaceAll("-", " ");++/** A value in a few words: lists and objects as compact JSON, a boolean as On/Off. */+function shown(v: unknown): string {+ if (v === undefined) return "—";+ if (typeof v === "boolean") return v ? "On" : "Off";+ if (typeof v === "string" || typeof v === "number") return String(v);+ const s = JSON.stringify(v);+ return s.length > 300 ? `${s.slice(0, 299)}…` : s;+}++/** Anyone but the owner goes back to Settings: this page is the owner's. */+function BackToSettings() {+ const router = useRouter();+ useEffect(() => router.replace("/settings"), [router]);+ return <GallerySkeleton cards={4} />;+}++/**+ * Settings → Accounts' runs → a run (the owner only): everything about one account's run. What the account was shown+ * (its feed tile and Library card, the same components, inert here), what went wrong and where it ran, the model and+ * each setting beside its default, the prompt, its input files, its batch and the account's runs around it (a Retry+ * is the same request sent again), and what was sent to the GPU or provider. Nothing here is a key, a token or a GPU's+ * address (the server leaves them out).+ */+export function RunDetailsView() {+ const id = useParams<{ id: string }>().id ?? "";+ const viewer = useViewer();+ const owner = !!viewer.data?.owner;+ const q = useQuery({+ queryKey: ["admin-run", id],+ enabled: owner,+ queryFn: () => adminCall<RunDetails>(`/api/admin/generations/${encodeURIComponent(id)}`),+ refetchInterval: (s) => (s.state.data && (s.state.data.run.status === "queued" || s.state.data.run.status === "running") ? 10_000 : false),+ });++ if (viewer.isPending) return <GallerySkeleton cards={4} />;+ if (!owner) return <BackToSettings />;+ if (q.isPending)+ return (+ <div className="space-y-4" aria-busy="true" aria-label="Loading">+ <Skeleton className="h-10 w-72 max-w-full" />+ <Skeleton className="h-4 w-52 max-w-full" />+ <Skeleton className="h-56 w-full max-w-md rounded-xl" />+ </div>+ );+ if (q.isError)+ return (+ <div className="space-y-3">+ <PageHeader title="Run details" />+ <p className="text-[13px] text-destructive">Couldn't load this run. {q.error.message}</p>+ <div className="flex gap-2">+ <Button size="sm" variant="secondary" onClick={() => void q.refetch()}>+ Try again+ </Button>+ <Button size="sm" variant="ghost" asChild>+ <Link href="/settings/runs">Accounts' runs</Link>+ </Button>+ </div>+ </div>+ );++ const d = q.data;+ const g = d.run;+ const email = g.account.email;+ return (+ <>+ <PageHeader+ title={d.preset?.name ?? g.presetName ?? d.studio?.title ?? featureName(g.feature)}+ description={+ <>+ {email ? (+ <Link href={runsHref({ account: g.account.id })} className="underline-offset-2 hover:underline">+ {email}+ </Link>+ ) : email === null ? (+ "Deleted account"+ ) : (+ "An account"+ )}+ {" · "}+ <span className={cn(g.status === "failed" && "text-destructive")}>{STATUS_WORDS[g.status] ?? g.status}</span>+ {" · "}+ <span title={new Date(g.createdAt).toLocaleString()}>{timeAgo(g.createdAt)}</span>+ </>+ }+ />++ <div className="grid gap-8 lg:grid-cols-[minmax(0,22rem)_minmax(0,1fr)]">+ <div className="space-y-8">+ <Section title="What the account saw">+ <Seen g={g} />+ </Section>+ <Section title="Its input files">+ <Inputs inputs={d.inputs} />+ </Section>+ </div>++ <div className="min-w-0 space-y-8">+ <Section title="What happened">+ <Facts>+ <Fact label="Status">{STATUS_WORDS[g.status] ?? g.status}</Fact>+ <Fact label="Started">{new Date(g.createdAt).toLocaleString()}</Fact>+ {g.completedAt && (+ <Fact label="Ended">+ {new Date(g.completedAt).toLocaleString()} ({elapsed(g.createdAt, g.completedAt)})+ </Fact>+ )}+ <Fact label="Last change">{new Date(g.updatedAt).toLocaleString()}</Fact>+ {d.stored.message && <Fact label="Status words">{d.stored.message}</Fact>}+ {d.stored.error && (+ <Fact label="Error (stored)">+ <span className="whitespace-pre-wrap text-destructive">{d.stored.error}</span>+ </Fact>+ )}+ {g.error && g.error !== d.stored.error && <Fact label="Error (as the account read it)">{g.error}</Fact>}+ {d.trouble && (+ <>+ <Fact label="Cause">+ <code className="text-[12px]">{d.trouble.cause}</code>+ </Fact>+ {d.trouble.details && <Fact label="Details line">{d.trouble.details}</Fact>}+ </>+ )}+ {(g.status === "failed" || g.status === "canceled") && (+ <Fact label="Buttons it was given">+ {[...(g.trouble?.actions.filter((a) => a.kind !== "retry").map((a) => a.label) ?? []), ...(g.status === "failed" && g.fix ? ["Fix it"] : []), "Retry"].join(" · ")}+ {(g.trouble?.actions.length ?? 0) > 2 && <span className="block text-[12px] text-muted-foreground">A tile shows two or three of them: its tiles under What the account saw show which.</span>}+ </Fact>+ )}+ {d.fix?.items?.length ? (+ <Fact label="Missing on its GPU">+ <ul className="space-y-0.5">+ {d.fix.items.map((it, i) => (+ <li key={i} className="font-mono text-[12px] break-all">+ {[it.folder, it.file, it.class, it.pack].filter(Boolean).join(" · ")}+ </li>+ ))}+ </ul>+ </Fact>+ ) : null}+ {d.where.note && (+ <Fact label="Noted when it failed">+ {[d.where.note.stage && `stage ${d.where.note.stage}`, d.where.note.code && `code ${d.where.note.code}`, d.where.note.cause && `cause ${d.where.note.cause}`].filter(Boolean).join(" · ") || "—"}+ {d.where.note.said && <span className="mt-1 block font-mono text-[11.5px] break-all whitespace-pre-wrap text-muted-foreground">{d.where.note.said}</span>}+ </Fact>+ )}+ </Facts>+ </Section>++ <Section title="Where it ran">+ <Facts>+ <Fact label="Place">{d.where.label}</Fact>+ {d.where.hostKind && <Fact label="GPU reached through">{HOST_WORDS[d.where.hostKind] ?? d.where.hostKind}</Fact>}+ {d.where.hostKindNow && <Fact label="Its GPU setting now">{HOST_WORDS[d.where.hostKindNow] ?? d.where.hostKindNow}</Fact>}+ <Fact label="Engine">{d.where.engine === "open" ? "Open source" : "Cloud"}</Fact>+ <Fact label="Provider">{d.where.provider}</Fact>+ {d.where.workflowId && (+ <Fact label="Graph">+ <code className="text-[12px]">{d.where.workflowId}</code>+ </Fact>+ )}+ <Fact label="Reached the GPU or provider">{d.where.handedOver ? "Yes" : "No"}</Fact>+ {d.where.workers && <Fact label="Workers">Ran through this site's workers</Fact>}+ {d.where.resent && <Fact label="Resent">Sent again once after its GPU lost it</Fact>}+ {d.where.wait && (+ <Fact label="Waited for its GPU or key">+ {d.where.wait.tries} {d.where.wait.tries === 1 ? "try" : "tries"}+ {d.where.wait.until ? `, until ${new Date(d.where.wait.until).toLocaleTimeString()}` : ""}+ {d.where.wait.words && <span className="block text-muted-foreground">{d.where.wait.words}</span>}+ </Fact>+ )}+ </Facts>+ </Section>++ <Section title="Model and settings">+ <Facts>+ <Fact label="Model">+ {d.model.name} <StateChip state={d.model.state} />+ {d.model.state === "changed" && d.model.defaultName && <span className="text-muted-foreground"> (default {d.model.defaultName})</span>}+ </Fact>+ {d.preset && (+ <Fact label={d.preset.type === "app" ? "App" : d.preset.type === "unknown" ? "Preset" : d.preset.type === "motion" ? "Camera motion" : "Effect"}>{d.preset.name}</Fact>+ )}+ {d.studio && <Fact label="Studio">{d.studio.title}</Fact>}+ <Fact label="Operation">{OPERATION_LABELS[g.op] ?? g.op}</Fact>+ {d.asked && <Fact label="Request">Made in steps; settings are those it was asked with</Fact>}+ </Facts>+ <Words label="Prompt" text={d.prompt} />+ {d.negativePrompt && <Words label="Negative prompt" text={d.negativePrompt} />}+ <Settings rows={d.settings} />+ </Section>++ <Section title="Its batch and retries">+ <Near title={d.batch.length > 1 ? `Its batch (${d.batch.length} runs)` : "Its batch"} runs={d.batch} current={g.id} empty="It wasn't part of a batch." />+ <Near+ title="The account's runs around it (2 hours before to 6 hours after)"+ runs={d.near}+ current={g.id}+ empty="No other runs then."+ note="A Retry, or Run pressed again with nothing changed, sends the same request again: both show as Same request again."+ />+ </Section>++ <Section title="What was sent">+ {d.sent == null ? (+ <p className="text-[13px] text-muted-foreground">Nothing was sent to a GPU or provider.</p>+ ) : (+ <details className="rounded-lg border">+ <summary className="cursor-pointer px-3 py-2 text-[13px]">The graph or request as sent (links shown by their kind, keys left out)</summary>+ <pre className="max-h-[32rem] overflow-auto border-t p-3 text-[11px] leading-snug">{JSON.stringify(d.sent, null, 2)}</pre>+ </details>+ )}+ </Section>+ </div>+ </div>+ </>+ );+}++function Section({ title, children }: { title: string; children: React.ReactNode }) {+ return (+ <section className="min-w-0 space-y-3">+ <h2 className="text-[15px] font-medium">{title}</h2>+ {children}+ </section>+ );+}++function Facts({ children }: { children: React.ReactNode }) {+ return <dl className="grid grid-cols-1 gap-x-4 gap-y-1.5 text-[13px] sm:grid-cols-[11rem_minmax(0,1fr)]">{children}</dl>;+}++function Fact({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <>+ <dt className="text-muted-foreground">{label}</dt>+ <dd className="min-w-0 break-words">{children}</dd>+ </>+ );+}++function StateChip({ state }: { state: SettingState }) {+ return <span className={cn("ml-1 inline-flex rounded-full px-1.5 py-px text-[11px] font-medium whitespace-nowrap", STATE_STYLE[state])}>{STATE_WORDS[state]}</span>;+}++function Words({ label, text }: { label: string; text: string | null }) {+ return (+ <div className="mt-3 text-[13px]">+ <p className="text-muted-foreground">{label}</p>+ {text?.trim() ? <p className="mt-0.5 rounded-lg bg-muted/60 p-2.5 break-words whitespace-pre-wrap">{text}</p> : <p className="mt-0.5 text-muted-foreground italic">None</p>}+ </div>+ );+}++/** Each setting: what the run used, its default and where that comes from, and whether the account changed it. */+function Settings({ rows }: { rows: SettingRow[] }) {+ if (!rows.length) return <p className="mt-3 text-[13px] text-muted-foreground">No settings.</p>;+ const changed = rows.filter((r) => r.state === "changed").length;+ return (+ <div className="mt-4">+ <p className="mb-2 text-[13px] text-muted-foreground">+ {changed ? `${changed} changed from the default` : "Nothing changed from the defaults"}+ {rows.some((r) => r.state === "unknown") ? "; some defaults aren't known here." : "."}+ </p>+ <div className="overflow-x-auto rounded-lg border">+ <table className="w-full text-left text-[12.5px]">+ <thead className="bg-muted/50 text-muted-foreground">+ <tr>+ <th className="px-3 py-1.5 font-normal">Setting</th>+ <th className="px-3 py-1.5 font-normal">Used</th>+ <th className="px-3 py-1.5 font-normal">Default</th>+ <th className="px-3 py-1.5 font-normal">+ <span className="sr-only">State</span>+ </th>+ </tr>+ </thead>+ <tbody>+ {rows.map((r) => (+ <tr key={r.key} className="border-t align-top">+ <td className="px-3 py-1.5" title={r.key}>+ {r.label}+ </td>+ <td className="max-w-64 px-3 py-1.5 break-words">+ {r.sent ? (r.valueLabel ?? shown(r.value)) : <span className="text-muted-foreground">not sent</span>}+ {r.valueLabel && r.sent && <span className="text-muted-foreground"> ({shown(r.value)})</span>}+ </td>+ <td className="max-w-64 px-3 py-1.5 break-words text-muted-foreground">+ {r.hasDefault ? (+ <>+ {r.defaultLabel ?? (r.default === undefined ? "none" : shown(r.default))}+ {r.from && <span className="text-[11px]"> · {FROM_WORDS[r.from] ?? r.from}</span>}+ </>+ ) : (+ "—"+ )}+ </td>+ <td className="px-3 py-1.5 text-right">+ <StateChip state={r.state} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ );+}++/** Its files: each opens full size (the owner's view of the account's file); a removed upload says so. */+function Inputs({ inputs }: { inputs: RunInput[] }) {+ if (!inputs.length) return <p className="text-[13px] text-muted-foreground">No files.</p>;+ return (+ <ul className="grid grid-cols-3 gap-2">+ {inputs.map((f, i) => (+ <li key={i} className="min-w-0">+ <div className="aspect-square overflow-hidden rounded-lg border bg-muted">+ {f.url && f.kind === "image" ? (+ <a href={f.url} target="_blank" rel="noreferrer" aria-label={`Open ${f.slot}`} className="block size-full">+ {/* eslint-disable-next-line @next/next/no-img-element -- the account's own stored file, as the files route serves it */}+ <img src={f.url} alt="" loading="lazy" className="size-full object-cover" />+ </a>+ ) : f.url && f.kind === "video" ? (+ <video src={f.url} preload="metadata" muted controls className="size-full object-cover" />+ ) : f.url ? (+ <a href={f.url} target="_blank" rel="noreferrer" className="grid size-full place-items-center text-[12px] text-muted-foreground hover:text-foreground">+ <span className="inline-flex items-center gap-1">+ <ExternalLink className="size-3.5" /> Open+ </span>+ </a>+ ) : (+ <div className="grid size-full place-items-center p-2 text-center text-[11.5px] text-muted-foreground">+ {f.state === "removed" ? (+ <span className="inline-flex flex-col items-center gap-1">+ <FileX2 className="size-4" /> Removed+ </span>+ ) : f.state === "link" ? (+ <span className="inline-flex flex-col items-center gap-1">+ <Link2 className="size-4" /> {f.words ?? "A link"}+ </span>+ ) : (+ "Sent inline"+ )}+ </div>+ )}+ </div>+ <p className="mt-1 truncate text-[12px]">{f.slot}</p>+ {f.state === "example" && <p className="text-[11px] text-muted-foreground">Example file</p>}+ {f.state === "removed" && <p className="text-[11px] text-muted-foreground">Uploads clear after 14 days</p>}+ </li>+ ))}+ </ul>+ );+}++/**+ * What the account was shown for this run: its studio feed's tile and its Library card, made by the same components+ * its own pages use (inert: nothing here runs anything). A finished run shows its results.+ */+function Seen({ g }: { g: AccountRun }) {+ const run = g as unknown as Generation;+ if (g.status === "succeeded") {+ const outs = g.outputs.filter((o) => o.state === "shown");+ return (+ <div className="space-y-2">+ <div className="grid grid-cols-2 gap-2">+ {g.outputs.map((o, i) => (+ <div key={i} className="aspect-square overflow-hidden rounded-lg border bg-muted">+ {o.state === "shown" ? (+ <MediaThumb output={o} g={run} />+ ) : (+ <div className="grid size-full place-items-center text-[12px] text-muted-foreground">{o.state === "held" ? "Held for its check" : "Removed"}</div>+ )}+ </div>+ ))}+ </div>+ <p className="text-[12px] text-muted-foreground">+ {outs.length === g.outputs.length ? `Its result${g.outputs.length > 1 ? "s" : ""}, as it saw ${g.outputs.length > 1 ? "them" : "it"}.` : "Some results weren't shown to it."}+ </p>+ </div>+ );+ }+ return (+ <div className="space-y-4">+ <div>+ <p className="mb-1.5 text-[12px] text-muted-foreground">In its studio</p>+ <div inert className="h-56 max-w-full">+ {g.status === "failed" || g.status === "canceled" ? (+ <FailedTile g={run} ratio={tileRatio(run)} onRetry={() => {}} />+ ) : (+ <div className="aspect-square h-full overflow-hidden rounded-xl">+ <StatusCover g={run} actionable />+ </div>+ )}+ </div>+ </div>+ <div>+ <p className="mb-1.5 text-[12px] text-muted-foreground">In its Library</p>+ <div inert className="@container aspect-square w-56 overflow-hidden rounded-xl bg-muted">+ <StatusCover g={run} actionable />+ </div>+ </div>+ <p className="text-[12px] text-muted-foreground">The same words and buttons the account's pages show. Nothing here can be pressed.</p>+ </div>+ );+}++function Near({ title, runs, current, empty, note }: { title: string; runs: NearRun[]; current: string; empty: string; note?: string }) {+ return (+ <div className="space-y-1.5">+ <p className="text-[13px] text-muted-foreground">{title}</p>+ {!runs.length ? (+ <p className="text-[13px] text-muted-foreground italic">{empty}</p>+ ) : (+ <ul className="divide-y rounded-lg border text-[12.5px]">+ {runs.map((r) => (+ <li key={r.id} className={cn("flex flex-wrap items-baseline gap-x-2 gap-y-0.5 px-3 py-1.5", r.id === current && "bg-muted/50")}>+ {r.id === current ? (+ <span className="font-medium">This run</span>+ ) : (+ <Link href={runDetailsHref(r.id)} className="font-medium underline-offset-2 hover:underline">+ {r.presetName ?? r.modelName ?? r.modelId}+ </Link>+ )}+ <span className={cn("text-muted-foreground", r.status === "failed" && "text-destructive")}>{STATUS_WORDS[r.status] ?? r.status}</span>+ <span className="text-muted-foreground" title={new Date(r.createdAt).toLocaleString()}>+ {new Date(r.createdAt).toLocaleTimeString()}+ </span>+ {r.step && <span className="text-muted-foreground">{r.step}</span>}+ {r.id !== current && <span className="text-[11px] text-muted-foreground">· {MATCH_WORDS[r.match]}</span>}+ {r.error && <span className="w-full truncate text-[12px] text-muted-foreground">{r.error}</span>}+ </li>+ ))}+ </ul>+ )}+ {note && <p className="text-[11.5px] text-muted-foreground">{note}</p>}+ </div>+ );+}diff --git a/src/lib/run-settings.ts b/src/lib/run-settings.tsnew file mode 100644index 00000000..6c39ab86--- /dev/null+++ b/src/lib/run-settings.ts@@ -0,0 +1,320 @@+import type { GenerationRequest, GenParams, ModelDef, Preset, PresetRoute } from "./catalog/types";+import { routeParams } from "./composer";+import { gpuHostOf, withoutAddress, withoutSecrets } from "./diagnose";++/**+ * The owner's Run details (Settings → Accounts' runs → a run): each of a run's settings beside the value the composer+ * would have started it with, so the owner sees what the account changed. Also the helpers that keep secrets out of+ * what the page shows (keys, tokens, a GPU's address).+ */++/**+ * `default`: what the composer starts with (sent or not); `changed`: the account picked another value; `unknown`: no+ * default is known for it here; `input`: the account's own content (shots, lines of dialogue, points), not a setting.+ */+export type SettingState = "default" | "changed" | "unknown" | "input";++/** Where a default comes from: the composer itself, the model's defaults, the preset's or app's route, a model control, an app option. */+export type DefaultSource = "composer" | "model" | "preset" | "app" | "control" | "option";++export interface SettingRow {+ /** "params.duration", "params.extra.quality", "presetOptions.angle", "presetStrength", "mix", "loras", "prefer". */+ key: string;+ label: string;+ /** What the run asked for (undefined: not sent, so the default applied). */+ value?: unknown;+ /** The value's words where it has them (an app option's choice label). */+ valueLabel?: string;+ /** The default, when known (`hasDefault`). */+ default?: unknown;+ defaultLabel?: string;+ hasDefault: boolean;+ from?: DefaultSource;+ state: SettingState;+ /** The request carried it (false: left out, so its default applied). */+ sent: boolean;+}++/** What a run's defaults come from: its model, its preset (or app) and the preset's route on that model. */+export interface DefaultsContext {+ model?: Pick<ModelDef, "defaults" | "options">;+ preset?: Pick<Preset, "type" | "options">;+ /** The preset's route on the run's model and engine (presetRoutes), when it has one. */+ route?: Pick<PresetRoute, "params">;+}++const LABELS: Record<string, string> = {+ aspectRatio: "Aspect ratio",+ resolution: "Resolution",+ duration: "Length (s)",+ numOutputs: "How many",+ seed: "Seed",+ generateAudio: "Sound",+ enhancePrompt: "Enhance prompt",+ voice: "Voice",+ voiceDescription: "Voice description",+ voiceTranscript: "Voice transcript",+ targetFps: "Frame rate",+ format: "Format",+ targetLanguage: "Language",+ sourceLanguage: "Source language",+ shots: "Shots",+ dialogue: "Dialogue",+ clipSeconds: "Clip length (s)",+ multiShot: "Multi-shot",+ draft: "Draft",+ fps: "FPS",+ palette: "Palette",+ styleId: "Style",+ numLayers: "Layers",+ points: "Points",+ keyframeTimes: "Keyframe times",+ startTime: "Start (s)",+ endTime: "End (s)",+ quality: "Quality",+};++/** The composer's own starting values, under every model's (src/components/studio/composer.tsx, settings-panel.tsx). */+const COMPOSER: GenParams = { numOutputs: 1, enhancePrompt: false };++/** Settings whose composer start is "none" (a seed is random until the person sets one). */+const NONE_BY_DEFAULT = new Set(["seed"]);++/** The account's own content, not a setting with a default (its shots, lines, points, the file's own size). */+const CONTENT = new Set([+ "shots",+ "dialogue",+ "points",+ "keyframeTimes",+ "elements",+ "palette",+ "voiceTranscript",+ "voiceDescription",+ "sourceSize",+ "sourceFps",+ "draftId",+ "drawnRefs",+ "startTime",+ "endTime",+ "zoomFrom",+ "zoomTo",+ "panFrom",+ "panTo",+]);++/** A camelCase key as words ("targetFps" → "Target fps"), for a key with no label of its own. */+export function settingLabel(key: string): string {+ if (LABELS[key]) return LABELS[key];+ const words = key+ .replace(/[_-]+/g, " ")+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")+ .toLowerCase()+ .trim();+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : key;+}++/** Two settings are the same value: primitives by their words (a control's 3 and "3"), the rest by their JSON. */+export function sameValue(a: unknown, b: unknown): boolean {+ if (a === b) return true;+ if (a === undefined || b === undefined || a === null || b === null) return false;+ const prim = (v: unknown) => typeof v === "string" || typeof v === "number" || typeof v === "boolean";+ if (prim(a) && prim(b)) return String(a) === String(b);+ return stableJson(a) === stableJson(b);+}++/** JSON with object keys in order, so two equal values give the same text. */+export function stableJson(v: unknown): string {+ if (Array.isArray(v)) return `[${v.map(stableJson).join(",")}]`;+ if (v && typeof v === "object") {+ const o = v as Record<string, unknown>;+ return `{${Object.keys(o)+ .filter((k) => o[k] !== undefined)+ .sort()+ .map((k) => `${JSON.stringify(k)}:${stableJson(o[k])}`)+ .join(",")}}`;+ }+ return JSON.stringify(v) ?? "null";+}++/** A stored file's address, an example input or an inline file: input content, not a setting. */+const isFileRef = (v: unknown) => typeof v === "string" && /^(\/api\/files\/|\/examples\/|\/samples\/|data:|https?:\/\/)/i.test(v.trim());++type Known = { v: unknown; from: DefaultSource };++function row(key: string, label: string, value: unknown, d: Known | undefined, o: { content?: boolean; valueLabel?: string; defaultLabel?: string } = {}): SettingRow {+ const sent = value !== undefined;+ const base = { key, label, ...(sent && { value }), ...(o.valueLabel && { valueLabel: o.valueLabel }), sent };+ if (o.content) return { ...base, hasDefault: false, state: "input" };+ if (!d) return { ...base, hasDefault: false, state: "unknown" };+ const known = { hasDefault: true, ...(d.v !== undefined && { default: d.v }), ...(o.defaultLabel && { defaultLabel: o.defaultLabel }), from: d.from };+ if (!sent) return { ...base, ...known, state: "default" };+ return { ...base, ...known, state: sameValue(value, d.v) ? "default" : "changed" };+}++/**+ * Each setting of a run beside the value the composer would have started it with, in this order: the composer's own+ * (how many, Enhance prompt), the model's defaults, the preset's or app's route on that model (an app's route as it is,+ * a camera motion's plain settings and its Quality: routeParams), the model's controls and sliders (params.extra), the+ * app's options (each its `default`, else its first choice), the preset's strength (1), a Mix, LoRAs and a provider+ * preference (none). A setting with no known default says so (`unknown`), never a guess. A run made from a request that+ * expanded into steps is compared as it was asked (`asked`).+ */+export function compareSettings(req: GenerationRequest, ctx: DefaultsContext = {}): SettingRow[] {+ const r = req.asked ?? req;+ const params = (r.params ?? {}) as Record<string, unknown>;+ const extra = (params.extra ?? {}) as Record<string, unknown>;+ const fromRoute: DefaultSource = ctx.preset?.type === "app" ? "app" : "preset";+ const route = ctx.route && ctx.preset ? (routeParams(ctx.route, ctx.preset.type) as Record<string, unknown>) : {};++ const plain = new Map<string, Known>();+ for (const [k, v] of Object.entries(COMPOSER)) plain.set(k, { v, from: "composer" });+ for (const k of NONE_BY_DEFAULT) plain.set(k, { v: undefined, from: "composer" });+ for (const [k, v] of Object.entries(ctx.model?.defaults ?? {})) if (v !== undefined) plain.set(k, { v, from: "model" });+ for (const [k, v] of Object.entries(route)) if (k !== "extra" && v !== undefined) plain.set(k, { v, from: fromRoute });++ const extras = new Map<string, Known>();+ const labels = new Map<string, string>();+ for (const c of ctx.model?.options?.controls ?? []) {+ labels.set(c.param, c.label);+ // A control left on its "auto" (no default) runs the model's own choice: unset is its default.+ extras.set(c.param, { v: c.default, from: "control" });+ }+ for (const s of ctx.model?.options?.sliders ?? []) {+ labels.set(s.param, s.label);+ extras.set(s.param, { v: s.default, from: "control" });+ }+ for (const [k, v] of Object.entries((route.extra ?? {}) as Record<string, unknown>)) if (v !== undefined) extras.set(k, { v, from: fromRoute });++ const rows: SettingRow[] = [];+ const plainKeys = [...new Set([...Object.keys(params).filter((k) => k !== "extra" && params[k] !== undefined), ...[...plain.entries()].filter(([, d]) => d.v !== undefined).map(([k]) => k)])];+ for (const k of plainKeys) rows.push(row(`params.${k}`, settingLabel(k), params[k], plain.get(k), { content: CONTENT.has(k) }));++ const extraKeys = [...new Set([...Object.keys(extra).filter((k) => extra[k] !== undefined), ...[...extras.entries()].filter(([, d]) => d.v !== undefined).map(([k]) => k)])];+ for (const k of extraKeys) {+ const v = extra[k];+ rows.push(row(`params.extra.${k}`, labels.get(k) ?? settingLabel(k), v, extras.get(k), { content: isFileRef(v) || (Array.isArray(v) && v.some(isFileRef)) }));+ }++ const options = ctx.preset?.options ?? [];+ const picked = r.presetOptions ?? {};+ for (const o of options) {+ const d = o.default ?? o.choices[0]?.value;+ const name = (v: unknown) => o.choices.find((c) => c.value === v)?.label;+ rows.push(+ row(`presetOptions.${o.key}`, o.label, picked[o.key], d === undefined ? undefined : { v: d, from: "option" }, {+ valueLabel: picked[o.key] !== undefined ? name(picked[o.key]) : undefined,+ defaultLabel: name(d),+ }),+ );+ }+ for (const [k, v] of Object.entries(picked)) if (!options.some((o) => o.key === k)) rows.push(row(`presetOptions.${k}`, settingLabel(k), v, undefined));++ if (r.presetStrength !== undefined || (ctx.preset && ctx.preset.type !== "app")) {+ rows.push(row("presetStrength", "Strength", r.presetStrength, ctx.preset && ctx.preset.type !== "app" ? { v: 1, from: "composer" } : undefined));+ }+ if (r.mix) rows.push(row("mix", "Mix", r.mix, { v: undefined, from: "composer" }));+ if (r.loras?.length) rows.push(row("loras", "LoRAs", r.loras.map((l) => `${l.file}${l.strength !== undefined ? ` × ${l.strength}` : ""}`), { v: undefined, from: "composer" }));+ if (r.prefer) rows.push(row("prefer", "Ran on its key at", r.prefer, { v: undefined, from: "composer" }));+ return rows;+}++/** The parts of a request that make it the same run again (a Retry sends the request back as it was). */+export function runFingerprint(req: GenerationRequest): string {+ const r = req.asked ?? req;+ return stableJson({+ feature: r.feature,+ presetId: r.presetId,+ modelId: r.modelId,+ op: r.op,+ prompt: r.prompt?.trim(),+ negativePrompt: r.negativePrompt?.trim(),+ inputs: r.inputs,+ params: r.params,+ presetOptions: r.presetOptions,+ presetStrength: r.presetStrength,+ mix: r.mix,+ loras: r.loras?.map((l) => [l.file, l.strength]),+ engine: r.engine,+ });+}++/** The same words and files with any model or settings (Pick another model, then Run). */+function contentFingerprint(req: GenerationRequest): string {+ const r = req.asked ?? req;+ return stableJson({ feature: r.feature, presetId: r.presetId, prompt: r.prompt?.trim(), inputs: r.inputs });+}++/**+ * How another of the account's runs relates to this one: `same` (the same request again: Retry, or Run pressed again+ * with nothing changed; they can't be told apart), `other-model` (the same words, files and app on another model or+ * other settings: Pick another model, or a setting changed) or `other`.+ */+export type RunMatch = "same" | "other-model" | "other";++export function runMatch(a: GenerationRequest, b: GenerationRequest): RunMatch {+ if (runFingerprint(a) === runFingerprint(b)) return "same";+ return contentFingerprint(a) === contentFingerprint(b) ? "other-model" : "other";+}++// ---------------------------------------------------------------------------+// Keeping secrets out++/** Where a link points, by kind only: a RunPod pod, a tunnel, a LAN address, or another web address. */+export type LinkKind = "runpod" | "tunnel" | "lan" | "web";++const PRIVATE_HOST = /^(localhost|127\.\d+\.\d+\.\d+|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(1[6-9]|2\d|3[01])\.\d+\.\d+|169\.254\.\d+\.\d+|\[?(::1|f[cd][0-9a-f]{2}:[^\]]*|fe80:[^\]]*)\]?|[^.]+|.+\.(local|lan|home|internal))$/i;++export function linkKind(url: string): LinkKind {+ const k = gpuHostOf(url).kind;+ if (k !== "web") return k;+ try {+ return PRIVATE_HOST.test(new URL(url).hostname) ? "lan" : "web";+ } catch {+ return "web";+ }+}++export const LINK_WORDS: Record<LinkKind, string> = { runpod: "a RunPod address", tunnel: "a tunnel address", lan: "a LAN address", web: "a web address" };++/** A key that holds a credential (api_key, hfToken, Authorization, cookie, password…): its value is never shown. */+export const SECRET_KEY = /(api.?key|access.?key|secret|token|passw(or)?d|authorization|^auth$|cookie|session|signature|^sig$|credential|bearer|^key$|private.?key)/i;++const URL_IN_TEXT = /\b(?:https?|wss?):\/\/[^\s"'<>\]\)}]+/gi;++/**+ * A text as the page may show it: every link said by its kind ("[a RunPod address]"), any IP address and port taken out,+ * an address the caller names taken out, and credentials a text echoes (Bearer …, api_key=…) masked.+ */+export function redactText(text: string, o: { url?: string } = {}): string {+ const t = String(text).replace(URL_IN_TEXT, (u) => `[${LINK_WORDS[linkKind(u)]}]`);+ return withoutSecrets(withoutAddress(t, o.url));+}++/** The longest text the page shows of one value. */+const MAX_TEXT = 4000;++/**+ * A stored JSON value (what was sent to the GPU or provider, the job's handles) as the page may show it: credentials'+ * values masked by their key, links said by their kind, inline files (data:) by their type and size, long texts cut.+ * At most `depth` levels, 300 keys and 200 items a level.+ */+export function redactValue(v: unknown, o: { url?: string; depth?: number } = {}): unknown {+ const depth = o.depth ?? 12;+ if (typeof v === "string") {+ const data = /^data:([^;,]+)?[;,]/i.exec(v);+ if (data) return `[inline ${data[1] ?? "file"}, ${Math.round((v.length * 3) / 4 / 1024)} KB]`;+ const t = redactText(v, o);+ return t.length > MAX_TEXT ? `${t.slice(0, MAX_TEXT)}… [${t.length - MAX_TEXT} more characters]` : t;+ }+ if (v === null || typeof v !== "object") return v;+ if (depth <= 0) return "[…]";+ if (Array.isArray(v)) {+ const items = v.slice(0, 200).map((x) => redactValue(x, { ...o, depth: depth - 1 }));+ return v.length > 200 ? [...items, `[${v.length - 200} more]`] : items;+ }+ const out: Record<string, unknown> = {};+ const entries = Object.entries(v as Record<string, unknown>);+ for (const [k, x] of entries.slice(0, 300)) out[k] = SECRET_KEY.test(k) && ((typeof x === "string" && x !== "") || (x !== null && typeof x === "object")) ? "••••" : redactValue(x, { ...o, depth: depth - 1 });+ if (entries.length > 300) out["…"] = `${entries.length - 300} more keys`;+ return out;+}diff --git a/src/server/account-admin.ts b/src/server/account-admin.tsindex d6dd7f30..d08b30a3 100644--- a/src/server/account-admin.ts+++ b/src/server/account-admin.ts@@ -4,7 +4,7 @@ import type { Generation, OutputFile } from "@/lib/catalog/types";import { accountsMaxBytes, accountTotalBytes } from "./account-files";import { listAccounts, type AccountInfo } from "./auth";import { db } from "./db";-import { declinedCardsIn, listGenerations, type ListOptions } from "./generations";+import { declinedCardsIn, getGeneration, listGenerations, type ListOptions } from "./generations";import { cursorFrom, HELPER_SQL, KINDS } from "./library";/**@@ -198,19 +198,32 @@ export function listAccountRuns(o: ListOptions, show: { content: boolean; emails// The WHERE already leaves the owner's runs out; this keeps them out whatever a caller passes.const found = listGenerations(opts).filter((g) => g.request.account);const last = found.at(-1);- const raw = db().prepare("SELECT error FROM generations WHERE id = ?");- const detail = (g: Generation) => {- if (g.place !== "pool" || !g.error) return {};- const e = (raw.get(g.id) as { error: string | null } | undefined)?.error;- return e && e !== g.error ? { detail: e } : {};- };return {items: found.map((g) => {- const id = g.request.account!;- const account: AccountOfRun = show.emails ? { id, email: emails.get(id) ?? null } : { id, emailHidden: true };- const run: AccountRun = { ...g, outputs: withStates(g.outputs), account, ...detail(g), ...declinedCardsIn(g.id) };+ const run = asAccountRun(g, emails, show.emails);return show.content ? run : factsOnly(run);}),next: last && found.length === limit ? `${last.createdAt}:${last.id}` : null,};}++/** An account's run (`g.request.account` set) as the owner sees it: whose, each result's state, and a hosted run's technical reason. */+function asAccountRun(g: Generation, emails: Map<string, string>, showEmails: boolean): AccountRun {+ const id = g.request.account!;+ const account: AccountOfRun = showEmails ? { id, email: emails.get(id) ?? null } : { id, emailHidden: true };+ return { ...g, outputs: withStates(g.outputs), account, ...poolDetail(g), ...declinedCardsIn(g.id) };+}++/** A failed run on this install's GPUs: the stored reason, when it isn't the plain sentence the account reads. */+function poolDetail(g: Generation): { detail?: string } {+ if (g.place !== "pool" || !g.error) return {};+ const e = (db().prepare("SELECT error FROM generations WHERE id = ?").get(g.id) as { error: string | null } | undefined)?.error;+ return e && e !== g.error ? { detail: e } : {};+}++/** One account's run as the list gives it (null: no such run, or it is the owner's own). */+export function accountRunById(id: string, showEmails = true): AccountRun | null {+ const g = getGeneration(id, { includeDeleted: true });+ if (!g?.request.account) return null;+ return asAccountRun(g, new Map(listAccounts().map((a) => [a.id, a.email])), showEmails);+}diff --git a/src/server/run-details.ts b/src/server/run-details.tsnew file mode 100644index 00000000..90283425--- /dev/null+++ b/src/server/run-details.ts@@ -0,0 +1,388 @@+import "server-only";+import fs from "node:fs";+import { getModel, getPreset } from "@/lib/catalog";+import { presetRoutes } from "@/lib/catalog/preset-recipe-routes";+import type { Engine, GenerationRequest, MediaKind } from "@/lib/catalog/types";+import type { RunTrouble } from "@/lib/diagnose";+import { compareSettings, LINK_WORDS, SECRET_KEY, linkKind, redactText, redactValue, runMatch, type LinkKind, type RunMatch, type SettingRow } from "@/lib/run-settings";+import * as STUDIOS from "@/lib/studios";+import { viewerDefaults } from "@/lib/composer";+import { accountRunById, type AccountRun } from "./account-admin";+import { fileAccount } from "./account-library";+import { accountGpu } from "./auth";+import { db } from "./db";+import { exampleRel } from "./example-files";+import { listGenerations } from "./generations";+import type { OwnRunNote } from "./run-events";+import { absolutePath, contentTypeFor, filesRel } from "./storage";++/**+ * The owner's Run details (GET /api/admin/generations/<id>, Settings → Accounts' runs → a run): everything about one+ * account's run in one answer. What it asked for (each setting beside its default), its files, where it ran, what came+ * back, what the account was shown, and the account's other runs of the same batch and around it (a Retry is the same+ * request sent again). Never a key, a token, a GPU's address, a cookie or a password: links are said by their kind, and+ * what was sent and the job's handles go through redactValue.+ */++/** Where a run ran, by kind: the account's own GPU, its own key, this install's GPUs, or (an older run) not known. */+export type RunPlaceKind = "own-gpu" | "own-key" | "site-gpus" | "unknown";++/** How the account's GPU is reached: a RunPod pod, a tunnel, a LAN or web address, the ComfyUI on its computer, or Fuobe Connect. */+export type GpuHostKind = LinkKind | "computer" | "connect";++export const HOST_WORDS: Record<GpuHostKind, string> = {+ runpod: "RunPod pod",+ tunnel: "Tunnel (Cloudflare, ngrok…)",+ lan: "LAN address",+ web: "Web address",+ computer: "ComfyUI on its own computer",+ connect: "Paired with a code (Fuobe Connect)",+};++export interface RunWhere {+ kind: RunPlaceKind;+ /** In words: "Its own GPU", "Its own fal.ai key", "This site's GPUs". */+ label: string;+ provider: string;+ engine: Engine;+ /** Where the job went, as the failure's note recorded it (its kind only). */+ hostKind?: GpuHostKind;+ /** How the account's GPU is set up now (Settings → Your GPU), by kind: it may have changed since the run. */+ hostKindNow?: GpuHostKind | "none";+ /** The ComfyUI graph it ran (its id in the library). */+ workflowId?: string;+ /** The job reached the GPU or provider (it has a job id there). */+ handedOver: boolean;+ /** Which job of its batch it is. */+ jobIndex?: number;+ /** Sent again once, after its GPU lost it. */+ resent?: boolean;+ /** Ran through this install's workers (hosted runs). */+ workers?: boolean;+ /** Waited for its GPU or key to come back: tries so far, since when, until when (a run still waiting). */+ wait?: { tries: number; since?: number; until?: number; words?: string };+ /** The failure as the server noted it for the owner (src/server/run-events.ts): the step, an answer's status or network code, the GPU's or provider's own words. */+ note?: { at: number; cause?: string; stage?: string; code?: string; said?: string };+}++export interface RunInput {+ /** "Image 1", "End frame", "Clip", "Voice"…, or the setting's name for a file in params.extra. */+ slot: string;+ kind: MediaKind | "file";+ /**+ * `kept`: the stored file is there (`url` opens it, for the owner only); `removed`: gone (uploads clear after 14 days,+ * or it was deleted); `example`: one of Fuobe's published example inputs; `inline`: a file sent inside the request;+ * `link`: a web link (said by its kind only).+ */+ state: "kept" | "removed" | "example" | "inline" | "link";+ url?: string;+ /** For a link: where it points, in words. */+ words?: string;+}++/** Another run of the same batch, or one of the account's runs near this one, and how it relates to it. */+export interface NearRun {+ id: string;+ status: string;+ createdAt: number;+ modelId: string;+ modelName?: string;+ presetName?: string | null;+ feature: string;+ /** Its error as the account read it (a failed run). */+ error?: string | null;+ match: RunMatch;+ /** Its job index in the batch. */+ step?: string;+}++export interface RunDetails {+ /** The run as the account's own feed has it (its words, trouble, buttons), with whose it is and each result's state. */+ run: AccountRun;+ /** The stored status words and error (the account may have read a plainer sentence: a hosted run's), without addresses or credentials. */+ stored: { message: string | null; error: string | null };+ /** What a failed run's GPU was missing, and what its GPU or key ran into (stored even where the account wasn't shown it). */+ fix: { code?: string; workflowId?: string; items?: { folder?: string; file?: string; class?: string; pack?: string }[] } | null;+ trouble: RunTrouble | null;+ where: RunWhere;+ model: { id: string; name: string; state: "default" | "changed" | "unknown"; default?: string; defaultName?: string };+ preset: { id: string; name: string; type: string } | null;+ studio: { title: string; feature: string } | null;+ prompt: string | null;+ negativePrompt: string | null;+ /** Made by a request that became several steps: the settings are those it was asked with. */+ asked: boolean;+ settings: SettingRow[];+ inputs: RunInput[];+ /** The other runs of its batch, in order (this one included, `match` "same" for itself). */+ batch: NearRun[];+ /** The account's other runs from 2 hours before to 6 hours after it, oldest first (helper steps left out). */+ near: NearRun[];+ /** What was sent to the GPU or provider (the graph or the request), redacted; null when nothing was sent. */+ sent: unknown;+}++interface RawRow {+ message: string | null;+ error: string | null;+ external_id: string | null;+ external_meta_json: string | null;+ provider_input_json: string | null;+ fix_json: string | null;+}++const parse = (json: string | null | undefined): unknown => {+ if (!json) return null;+ try {+ return JSON.parse(json) as unknown;+ } catch {+ return null;+ }+};+const obj = (v: unknown): Record<string, unknown> => (v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {});+const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);+const str = (v: unknown) => (typeof v === "string" && v ? v : undefined);++const HOST_KINDS = new Set<GpuHostKind>(["runpod", "tunnel", "lan", "web", "computer", "connect"]);++/** The account's GPU now (Settings → Your GPU), by kind; its address is never part of the answer. */+function gpuNow(account: string): { kind: GpuHostKind | "none"; url?: string } {+ const gpu = accountGpu(account);+ if (!gpu) return { kind: "none" };+ if (gpu.mode === "computer") return { kind: "computer" };+ return { kind: linkKind(gpu.url), url: gpu.url };+}++function whereOf(run: AccountRun, raw: RawRow, gpu: ReturnType<typeof gpuNow>): RunWhere {+ const meta = obj(parse(raw.external_meta_json));+ const note = obj(meta.ownRun) as Partial<OwnRunNote>;+ const heal = obj(meta.heal);+ const pool = run.place === "pool";+ const own = !pool && run.provider === "comfyui";+ const key = !pool && (run.provider === "fal" || run.provider === "replicate");+ const kind: RunPlaceKind = pool ? "site-gpus" : own ? "own-gpu" : key ? "own-key" : "unknown";+ const label = pool ? "This site's GPUs" : own ? "Its own GPU" : key ? `Its own ${run.provider === "fal" ? "fal.ai key" : "Replicate token"}` : run.provider;+ const hostKind = typeof note.hostKind === "string" && HOST_KINDS.has(note.hostKind as GpuHostKind) ? (note.hostKind as GpuHostKind) : undefined;+ const said = str(note.said);+ return {+ kind,+ label,+ provider: run.provider,+ engine: run.engine,+ ...(hostKind && own && { hostKind }),+ ...(own && { hostKindNow: gpu.kind }),+ ...(str(meta.workflowId) && { workflowId: str(meta.workflowId) }),+ handedOver: !!raw.external_id,+ ...(num(meta.jobIndex) !== undefined && { jobIndex: num(meta.jobIndex) }),+ ...(meta.resent === true && { resent: true }),+ ...(meta.workers === true && { workers: true }),+ ...(num(heal.tries) !== undefined && {+ wait: {+ tries: num(heal.tries)!,+ ...(num(heal.since) !== undefined && { since: num(heal.since) }),+ ...(num(heal.deadline) !== undefined && { until: num(heal.deadline) }),+ ...(str(heal.words) && { words: redactText(str(heal.words)!, { url: gpu.url }) }),+ },+ }),+ ...(typeof note.at === "number" && {+ note: {+ at: note.at,+ ...(str(note.cause) && { cause: str(note.cause) }),+ ...(str(note.stage) && { stage: str(note.stage) }),+ ...(str(note.code) && { code: str(note.code) }),+ ...(said && { said: redactText(said, { url: gpu.url }) }),+ },+ }),+ };+}++/** What each input slot is called on the page. */+const SLOT_WORDS: Record<string, string> = {+ images: "Image",+ endImage: "End frame",+ mask: "Mask",+ sketch: "Sketch",+ video: "Clip",+ videos: "Clip",+ audio: "Sound",+ audio2: "Second sound",+ audios: "Sound",+ voiceAudio: "Voice",+ voiceAudio2: "Second voice",+ model3d: "3D model",+};++const kindOfType = (type: string): RunInput["kind"] =>+ type.startsWith("image/") ? "image" : type.startsWith("video/") ? "video" : type.startsWith("audio/") ? "audio" : /gltf|glb/.test(type) ? "model3d" : "file";++/** One file a run named, as the owner may open it: a stored file that is still there, else what it was. */+export function inputOf(slot: string, ref: string): RunInput {+ const r = ref.trim();+ if (r.startsWith("data:")) return { slot, kind: kindOfType(/^data:([^;,]+)/.exec(r)?.[1] ?? ""), state: "inline" };+ if (/^(https?|wss?):\/\//i.test(r)) return { slot, kind: "file", state: "link", words: LINK_WORDS[linkKind(r)] };+ if (exampleRel(r)) return { slot, kind: kindOfType(contentTypeFor(r)), state: "example", url: r };+ const rel = r.startsWith("/api/files/") ? filesRel(r) : null;+ if (rel === null) return { slot, kind: "file", state: "removed" };+ const kind = kindOfType(contentTypeFor(rel));+ let there = false;+ try {+ there = fileAccount(rel) !== undefined && fs.statSync(absolutePath(rel)).isFile();+ } catch {+ there = false;+ }+ return there ? { slot, kind, state: "kept", url: r } : { slot, kind, state: "removed" };+}++/** Every file a request names: its inputs (in slot order), then any file a setting in params.extra names. */+export function inputsOf(req: GenerationRequest): RunInput[] {+ const out: RunInput[] = [];+ for (const [slot, v] of Object.entries(req.inputs ?? {})) {+ const words = SLOT_WORDS[slot] ?? slot;+ if (Array.isArray(v)) v.forEach((ref, i) => typeof ref === "string" && out.push(inputOf(v.length > 1 ? `${words} ${i + 1}` : words, ref)));+ else if (typeof v === "string") out.push(inputOf(words, v));+ }+ for (const [k, v] of Object.entries(req.params?.extra ?? {})) {+ const refs = (Array.isArray(v) ? v : [v]).filter((x): x is string => typeof x === "string" && /^(\/api\/files\/|data:)/.test(x));+ refs.forEach((ref, i) => out.push(inputOf(refs.length > 1 ? `${k} ${i + 1}` : k, ref)));+ }+ return out;+}++/** The studio a feature belongs to (its config), for its default model. */+function studioOf(feature: string): { title: string; feature: string; defaultModels: { cloud: string; open: string }; uncaptioned?: Partial<{ cloud: string; open: string }> } | undefined {+ for (const v of Object.values(STUDIOS)) {+ const c = v as { feature?: unknown; title?: unknown; defaultModels?: { cloud: string; open: string }; uncaptioned?: Partial<{ cloud: string; open: string }> };+ if (c && typeof c === "object" && c.feature === feature && typeof c.title === "string" && c.defaultModels) return c as never;+ }+ return undefined;+}++/**+ * The model the composer would have opened on for this run: an app's or a camera motion's first route on its engine,+ * else its studio's default (or the stand-in it names where the server writes no caption). Unknown otherwise.+ */+function modelChoice(run: AccountRun): RunDetails["model"] {+ const name = run.modelName ?? run.modelId;+ const preset = run.presetId ? getPreset(run.presetId) : undefined;+ const has = (id: string) => !!getModel(id);+ if (preset) {+ const first = presetRoutes(preset, run.engine, has)[0]?.modelId;+ if (!first) return { id: run.modelId, name, state: "unknown" };+ const others = new Set(presetRoutes(preset, run.engine, has).map((r) => r.modelId));+ return {+ id: run.modelId,+ name,+ // An app's other routes are its own models too (the composer offers only those).+ state: first === run.modelId || (preset.type === "app" && others.has(run.modelId)) ? "default" : "changed",+ default: first,+ defaultName: getModel(first)?.name ?? first,+ };+ }+ const studio = studioOf(run.feature);+ if (!studio) return { id: run.modelId, name, state: "unknown" };+ const d = studio.defaultModels[run.engine];+ const stand = viewerDefaults(studio.defaultModels, studio.uncaptioned, false)[run.engine];+ return { id: run.modelId, name, state: run.modelId === d || run.modelId === stand ? "default" : "changed", default: stand, defaultName: getModel(stand)?.name ?? stand };+}++function nearOf(g: { id: string; status: string; createdAt: number; modelId: string; modelName?: string; presetName?: string | null; feature: string; error: string | null; request: GenerationRequest }, req: GenerationRequest): NearRun {+ return {+ id: g.id,+ status: g.status,+ createdAt: g.createdAt,+ modelId: g.modelId,+ ...(g.modelName && { modelName: g.modelName }),+ presetName: g.presetName ?? null,+ feature: g.feature,+ ...(g.status === "failed" && { error: g.error ? redactText(g.error) : null }),+ match: runMatch(req, g.request),+ ...(g.request.step && { step: `${g.request.step.label} (${g.request.step.index + 1} of ${g.request.step.of})` }),+ };+}++const HOUR = 3_600_000;++/** A link a button opens, without its query or fragment (a console page's pod id, a signed download's token). Settings links stay. */+export function safeTarget(target: string): string {+ if (!/^https?:\/\//i.test(target)) return target;+ try {+ const u = new URL(target);+ const kind = linkKind(target);+ return kind === "web" ? `${u.origin}${u.pathname}` : `[${LINK_WORDS[kind]}]`;+ } catch {+ return "";+ }+}++/** A trouble as the page shows it: its details line without an address or a credential, its buttons' links without a query. */+export function safeTrouble<T extends RunTrouble>(t: T, url?: string): T {+ return {+ ...t,+ ...(t.details && { details: redactText(t.details, { url }) }),+ actions: t.actions.map((a) => ({ ...a, ...(a.target && { target: safeTarget(a.target) }) })),+ };+}++/** The owner's view of one account's run, or null: no such run, or it is the owner's own (the Library has those). */+export function runDetails(id: string, o: { emails?: boolean } = {}): RunDetails | null {+ const run = accountRunById(id, o.emails ?? true);+ if (!run) return null;+ const account = run.account.id;+ const raw = db().prepare("SELECT message, error, external_id, external_meta_json, provider_input_json, fix_json FROM generations WHERE id = ?").get(id) as RawRow | undefined;+ if (!raw) return null;+ const gpu = gpuNow(account);+ const scrub = (t: string | null) => (t ? redactText(t, { url: gpu.url }) : t);+ const req = run.request;+ const asked = req.asked ?? req;+ const preset = run.presetId ? getPreset(run.presetId) : undefined;+ const has = (m: string) => !!getModel(m);+ const route = preset ? presetRoutes(preset, run.engine, has).find((r) => r.modelId === run.modelId) : undefined;+ const fixRaw = obj(parse(raw.fix_json));+ const { trouble: troubleRaw, ...fixRest } = fixRaw;+ const t = obj(troubleRaw);+ const trouble: RunTrouble | null = typeof t.cause === "string" && Array.isArray(t.actions) ? safeTrouble(t as unknown as RunTrouble, gpu.url) : null;+ const studio = preset ? null : studioOf(run.feature);++ // The same batch, in the order its jobs were made; and the account's runs around this one (a Retry is a new run).+ const batch = run.batchId+ ? listGenerations({ batchId: run.batchId, account, steps: true, limit: 200 })+ .sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id))+ .map((g) => nearOf(g, req))+ : [];+ const inBatch = new Set(batch.map((b) => b.id));+ const near = listGenerations({ account, since: run.createdAt - 2 * HOUR, until: run.createdAt + 6 * HOUR, limit: 60 })+ .filter((g) => g.id !== run.id && !inBatch.has(g.id))+ .sort((a, b) => a.createdAt - b.createdAt)+ .map((g) => nearOf(g, req));++ return {+ run: {+ ...run,+ request: redactValue(run.request, { url: gpu.url }) as GenerationRequest,+ error: scrub(run.error),+ message: scrub(run.message),+ ...(run.detail && { detail: scrub(run.detail) ?? undefined }),+ ...(run.trouble && { trouble: safeTrouble(run.trouble, gpu.url) }),+ ...(run.waiting && { waiting: safeTrouble(run.waiting, gpu.url) }),+ },+ stored: { message: scrub(raw.message), error: scrub(raw.error) },+ fix: Object.keys(fixRest).length ? (redactValue(fixRest, { url: gpu.url }) as RunDetails["fix"]) : null,+ trouble,+ where: whereOf(run, raw, gpu),+ model: modelChoice(run),+ preset: preset ? { id: preset.id, name: preset.name, type: preset.type } : run.presetId ? { id: run.presetId, name: run.presetName ?? run.presetId, type: "unknown" } : null,+ studio: studio ? { title: studio.title, feature: studio.feature } : null,+ prompt: asked.prompt ?? run.prompt ?? null,+ negativePrompt: asked.negativePrompt ?? null,+ asked: !!req.asked,+ settings: compareSettings(req, { model: getModel(run.modelId), preset, route }).map((s) => ({+ ...s,+ ...(s.value !== undefined && { value: SECRET_KEY.test(s.key.split(".").pop() ?? "") ? "••••" : redactValue(s.value, { url: gpu.url }) }),+ })),+ inputs: inputsOf(asked),+ batch,+ near,+ sent: redactValue(parse(raw.provider_input_json), { url: gpu.url }),+ };+}+diff --git a/tests/record-pages.test.ts b/tests/record-pages.test.tsindex 39b73168..b2a22ea0 100644--- a/tests/record-pages.test.ts+++ b/tests/record-pages.test.ts@@ -57,7 +57,9 @@ describe("record pages (real 404s)", () => {// share tokens: the proxy checks those itself. A visitor's Canvas boards aren't records either: a ready board is the// catalog's (/canvas/try), a draft lives in the browser (/canvas/draft) and an account's board is checked by its API// (/canvas/saved).- const catalog = /^\/(apps|audio|video-tools|upscale|s|canvas\/(start|try|draft|saved))\/\[|\/start\/\[id\]$/;+ // An owner-only page that reads its id through an owner-only API (Run details: /api/admin/generations/<id> answers+ // 404 itself) isn't a record page either: a 404 from the proxy would tell anyone whether that run exists.+ const catalog = /^\/(apps|audio|video-tools|upscale|s|canvas\/(start|try|draft|saved))\/\[|\/start\/\[id\]$|^\/settings\/runs\/\[id\]$/;for (const route of routes) {if (!route.includes("[")) {expect(recordForPath(route), route).toBeNull();diff --git a/tests/run-details.test.ts b/tests/run-details.test.tsnew file mode 100644index 00000000..14c8d576--- /dev/null+++ b/tests/run-details.test.ts@@ -0,0 +1,243 @@+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import type { GenerationRequest } from "@/lib/catalog/types";+import type { RunDetails } from "@/server/run-details";+import { TINY_PNG } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";++// Route handlers are called directly, outside a Next request: connection() has nothing to wait for.+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++const dir = tempDir("fuobe-run-details-");+process.env.FUOBE_DATA_DIR = dir;+process.env.FUOBE_PUBLIC_SIGNUP = "1";+process.env.COMFYUI_URL = "http://127.0.0.1:9";+delete process.env.FUOBE_PASSWORD;+const auth = await import("@/server/auth");+const { db } = await import("@/server/db");+const admin = await import("@/server/admin-tokens");+const { saveFile, absolutePath, filesRel } = await import("@/server/storage");+const { runAsTenant } = await import("@/server/tenant");+const { proxy } = await import("@/proxy");+const runRoute = await import("@/app/api/admin/generations/[id]/route");+const { compareSettings, redactText, redactValue, runMatch, linkKind } = await import("@/lib/run-settings");+const fs = await import("node:fs");+afterAll(() => {+ delete process.env.FUOBE_PUBLIC_SIGNUP;+});++const A = auth.createAccount("[email protected]", "long enough").id;+const POD = "https://abc123xyz-8188.proxy.runpod.net";+const GPU_TOKEN = "gpu-secret-token-123456";++let seq = 0;+/** A run as the runner stores it: `account`'s (or the owner's), with the stored columns given. */+function run(+ account: string | undefined,+ o: {+ status?: string;+ batch?: string;+ at?: number;+ request?: Partial<GenerationRequest>;+ error?: string;+ message?: string;+ externalId?: string;+ meta?: unknown;+ payload?: unknown;+ fix?: unknown;+ } = {},+): string {+ const id = `rd-${String(++seq).padStart(4, "0")}`;+ const at = o.at ?? Date.now();+ const request = { feature: "image", modelId: "oss-qwen-image-21", op: "t2i", prompt: "a fox", engine: "open", ...o.request, ...(account && { account }) };+ db()+ .prepare(+ `INSERT INTO generations (id, batch_id, feature, model_id, engine, provider, op, kind, status, message, request_json, provider_input_json, external_id, external_meta_json, outputs_json, error, fix_json, created_at, updated_at)+ VALUES (?, ?, ?, ?, 'open', 'comfyui', ?, 'image', ?, ?, ?, ?, ?, ?, '[]', ?, ?, ?, ?)`,+ )+ .run(+ id,+ o.batch ?? null,+ request.feature,+ request.modelId,+ request.op,+ o.status ?? "failed",+ o.message ?? null,+ JSON.stringify(request),+ o.payload === undefined ? null : JSON.stringify(o.payload),+ o.externalId ?? null,+ o.meta === undefined ? null : JSON.stringify(o.meta),+ o.error ?? null,+ o.fix === undefined ? null : JSON.stringify(o.fix),+ at,+ at,+ );+ return id;+}++const cookies = {} as Record<"owner" | "a", string>;+beforeAll(() => {+ auth.setPassword("install password");+ cookies.owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;+ cookies.a = `${auth.SESSION_COOKIE}=${auth.createSession(A).value}`;+ auth.setAccountGpu(A, { url: POD, token: GPU_TOKEN });+});++const viaProxy = (url: string, cookie?: string) => proxy(new NextRequest(`http://localhost:3000${url}`, { headers: cookie ? { cookie } : {} }));+const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";+const direct = (url: string, headers: Record<string, string> = {}) => new Request(`http://localhost:3000${url}`, { headers });+const ctx = (id: string) => ({ params: Promise.resolve({ id }) }) as never;+const get = (id: string, headers: Record<string, string> = { cookie: cookies.owner }) => runRoute.GET(direct(`/api/admin/generations/${id}`, headers), ctx(id));++describe("Run details: the owner's view of one account's run", () => {+ it("is the owner's only: guests 401, accounts 403, the owner 200", async () => {+ const id = run(A);+ expect(viaProxy(`/api/admin/generations/${id}`).status).toBe(401);+ expect(viaProxy(`/api/admin/generations/${id}`, cookies.a).status).toBe(403);+ expect(passed(viaProxy(`/api/admin/generations/${id}`, cookies.owner))).toBe(true);+ // The route checks again itself.+ expect((await get(id, { cookie: cookies.a })).status).toBe(403);+ expect((await get(id, {})).status).toBe(403);+ const res = await get(id);+ expect(res.status).toBe(200);+ expect(res.headers.get("cache-control")).toBe("no-store");+ });++ it("answers 404 for a run that doesn't exist and for the owner's own run", async () => {+ expect((await get("nope")).status).toBe(404);+ expect((await get(run(undefined))).status).toBe(404);+ });++ it("needs outputs:view as well as runs:read for an admin token, and accounts:read for the email", async () => {+ const id = run(A);+ const factsOnly = admin.createAdminToken({ name: "facts", scopes: ["runs:read"], expiresInDays: null }).token;+ expect((await get(id, { authorization: `Bearer ${factsOnly}` })).status).toBe(403);+ const content = admin.createAdminToken({ name: "content", scopes: ["runs:read", "outputs:view"], expiresInDays: null }).token;+ const res = await get(id, { authorization: `Bearer ${content}` });+ expect(res.status).toBe(200);+ const d = (await res.json()) as RunDetails;+ expect(d.run.account).toEqual({ id: A, emailHidden: true });+ const owner = (await (await get(id)).json()) as RunDetails;+ expect(owner.run.account.email).toBe("[email protected]");+ });++ it("never carries a key, a token or a GPU's address", async () => {+ const id = run(A, {+ error: `ComfyUI at ${POD}/prompt answered 500 (Authorization: Bearer ${GPU_TOKEN})`,+ externalId: "job-1",+ request: { loras: [{ file: "x.safetensors", url: `https://civitai.com/api/download/1?token=${GPU_TOKEN}` }], params: { extra: { api_key: "sk-live-abcdef123456" } } },+ payload: { "3": { class_type: "LoadImage", inputs: { image: `${POD}/view?file=a.png` } }, api_key: "sk-live-abcdef123456", headers: { cookie: "fuobe_session=abc.def" } },+ meta: { workflowId: "qwen-image", jobIndex: 0, sentTo: "0123456789abcdef", lease: { by: "runner-xyz" }, ownRun: { at: Date.now(), stage: "submit", code: "500", hostKind: "runpod", said: `upstream ${POD} failed` } },+ fix: { trouble: { cause: "gpu-error", details: `500 from ${POD}`, actions: [{ kind: "start-gpu", label: "Start your pod", target: "https://console.runpod.io/pods?id=abc123xyz" }] } },+ });+ const res = await get(id);+ const text = await res.text();+ for (const secret of ["abc123xyz", "proxy.runpod.net", GPU_TOKEN, "sk-live-abcdef123456", "fuobe_session=abc", "runner-xyz", "install password"]) expect(text, secret).not.toContain(secret);+ const d = JSON.parse(text) as RunDetails;+ expect(d.where).toMatchObject({ kind: "own-gpu", hostKind: "runpod", hostKindNow: "runpod", workflowId: "qwen-image", handedOver: true, jobIndex: 0 });+ expect(d.where.note).toMatchObject({ stage: "submit", code: "500" });+ expect(d.trouble?.actions[0]).toMatchObject({ kind: "start-gpu", label: "Start your pod", target: "https://console.runpod.io/pods" });+ expect(d.stored.error).toContain("[a RunPod address]");+ expect(JSON.stringify(d.sent)).toContain("LoadImage");+ });++ it("shows its input files to the owner, and a removed upload as removed", async () => {+ const kept = runAsTenant({ kind: "account", id: A }, () => saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", name: "kept.png" }).url);+ const gone = runAsTenant({ kind: "account", id: A }, () => saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", name: "gone.png" }).url);+ fs.rmSync(absolutePath(filesRel(gone)!));+ const id = run(A, { request: { op: "edit", inputs: { images: [kept, gone] } } });+ const d = (await (await get(id)).json()) as RunDetails;+ expect(d.inputs).toEqual([+ { slot: "Image 1", kind: "image", state: "kept", url: kept },+ { slot: "Image 2", kind: "image", state: "removed" },+ ]);+ });++ it("lists its batch and the account's runs around it, marking the same request sent again (Retry)", async () => {+ const t = Date.now() - 60_000;+ const first = run(A, { batch: "b-1", at: t, request: { prompt: "a red fox" } });+ const second = run(A, { batch: "b-1", at: t + 1, request: { prompt: "a red fox" } });+ const retried = run(A, { at: t + 30_000, request: { prompt: "a red fox" } });+ const otherModel = run(A, { at: t + 40_000, request: { prompt: "a red fox", modelId: "oss-ideogram-4" } });+ const d = (await (await get(first)).json()) as RunDetails;+ expect(d.batch.map((b) => b.id)).toEqual([first, second]);+ const near = new Map(d.near.map((r) => [r.id, r.match]));+ expect(near.get(retried)).toBe("same");+ expect(near.get(otherModel)).toBe("other-model");+ expect(near.has(second)).toBe(false);+ });++ it("says whether the model is the studio's default", async () => {+ const d = (await (await get(run(A))).json()) as RunDetails;+ // The Image studio opens on Qwen-Image 2.1 on the open engine where the server writes no caption.+ expect(d.model).toMatchObject({ id: "oss-qwen-image-21", state: "default" });+ expect(d.studio?.title).toBe("Image");+ });+});++describe("compareSettings: each setting beside the composer's default", () => {+ const model = {+ defaults: { aspectRatio: "1:1", resolution: "1K" },+ options: { controls: [{ param: "quality", label: "Quality", values: ["fast", "best"], default: "fast" }], sliders: [{ param: "cfg", label: "CFG", min: 1, max: 10, step: 0.5, default: 4 }] },+ } as never;+ const req = (params: Record<string, unknown>, more: Partial<GenerationRequest> = {}): GenerationRequest => ({ feature: "image", modelId: "m", params, ...more }) as GenerationRequest;+ const byKey = (rows: ReturnType<typeof compareSettings>) => Object.fromEntries(rows.map((r) => [r.key, r]));++ it("marks defaults (sent or not), changes and unknown defaults", () => {+ const rows = byKey(compareSettings(req({ aspectRatio: "16:9", numOutputs: 1, guidance: 7, extra: { quality: "best", cfg: 4 } }), { model }));+ expect(rows["params.aspectRatio"]).toMatchObject({ state: "changed", value: "16:9", default: "1:1", from: "model" });+ expect(rows["params.resolution"]).toMatchObject({ state: "default", sent: false, default: "1K" });+ expect(rows["params.numOutputs"]).toMatchObject({ state: "default", sent: true, from: "composer" });+ expect(rows["params.enhancePrompt"]).toMatchObject({ state: "default", sent: false, default: false });+ expect(rows["params.guidance"]).toMatchObject({ state: "unknown", hasDefault: false });+ expect(rows["params.extra.quality"]).toMatchObject({ state: "changed", label: "Quality", default: "fast", from: "control" });+ expect(rows["params.extra.cfg"]).toMatchObject({ state: "default", sent: true });+ });++ it("counts a set seed as a change and the account's shots as its input", () => {+ const rows = byKey(compareSettings(req({ seed: 42, shots: [{ prompt: "a", duration: 3 }] }), { model }));+ expect(rows["params.seed"].state).toBe("changed");+ expect(rows["params.shots"].state).toBe("input");+ });++ it("takes an app's route and options as the defaults, and an unknown model's settings as unknown", () => {+ const preset = { type: "app", options: [{ key: "angle", label: "Angle", choices: [{ value: "front", label: "Front", prompt: "" }, { value: "side", label: "Side", prompt: "" }] }] } as never;+ const route = { params: { duration: 5, extra: { strength: 0.8 } } } as never;+ const rows = byKey(compareSettings(req({ duration: 5, extra: { strength: 0.6 } }, { presetOptions: { angle: "side" } }), { model, preset, route }));+ expect(rows["params.duration"]).toMatchObject({ state: "default", from: "app" });+ expect(rows["params.extra.strength"]).toMatchObject({ state: "changed", default: 0.8, from: "app" });+ expect(rows["presetOptions.angle"]).toMatchObject({ state: "changed", valueLabel: "Side", defaultLabel: "Front" });+ const bare = byKey(compareSettings(req({ aspectRatio: "16:9" })));+ expect(bare["params.aspectRatio"].state).toBe("unknown");+ });++ it("compares a request that became steps as it was asked", () => {+ const asked = req({ aspectRatio: "1:1" });+ const rows = byKey(compareSettings({ ...req({ aspectRatio: "9:16" }), asked }, { model }));+ expect(rows["params.aspectRatio"].state).toBe("default");+ });+});++describe("keeping secrets out", () => {+ it("says links by their kind and masks credentials", () => {+ expect(linkKind("https://abc-8188.proxy.runpod.net/x")).toBe("runpod");+ expect(linkKind("https://foo.trycloudflare.com")).toBe("tunnel");+ expect(linkKind("http://192.168.1.20:8188")).toBe("lan");+ expect(linkKind("https://gpu.example.com")).toBe("web");+ expect(redactText("failed at http://10.0.0.5:8188/prompt with Bearer abcdefghijk")).toBe("failed at [a LAN address] with Bearer ••••");+ expect(redactValue({ apiKey: "k-123456", hf_token: "hf_abc", max_tokens: 50, image: "data:image/png;base64,AAAA", nested: { password: "pw" } })).toEqual({+ apiKey: "••••",+ hf_token: "••••",+ max_tokens: 50,+ image: "[inline image/png, 0 KB]",+ nested: { password: "••••" },+ });+ });++ it("tells the same request from another model's", () => {+ const a = { feature: "image", modelId: "m", prompt: "x", params: { seed: 1 } } as GenerationRequest;+ expect(runMatch(a, { ...a })).toBe("same");+ expect(runMatch(a, { ...a, modelId: "n" })).toBe("other-model");+ expect(runMatch(a, { ...a, prompt: "y" })).toBe("other");+ });+});