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
Run details: timeline, workers, cost, Auto's pick, declined cards and made values
Adarshcd8ccf788918
diff --git a/docs/public-signup.md b/docs/public-signup.mdindex 3d72309f..fcd6bcee 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -198,6 +198,15 @@ so it shows as **Same request again**; a change of model shows as the same wordscollapsed 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.+It also shows how long the run waited and ran: a timeline from the press to the end, with each worker that took+its job, gave it back or finished it (and its GPU), and the GPU time the worker measured. On this site's GPUs each+job shows its worker, GPU, lane, tries and times. It shows how the run was made: the model Auto picked and why, a run+Ideogram 4 declined (the asked model, the model that made it, and the picture it returned), the notices said on the+result, and each setting the model makes differently, asked and made side by side (the account's own pages show+the made value only). It shows where the run was made (the studio or tool, and whether a tool made it for one of the+account's projects), the job's id at its GPU or provider, its cost and whether it was charged, and each result's+check before it shows.+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>` withdiff --git a/src/components/run-details.tsx b/src/components/run-details.tsxindex 02af9a86..eec149cb 100644--- a/src/components/run-details.tsx+++ b/src/components/run-details.tsx@@ -8,20 +8,20 @@ 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 { DeclinedCards } from "@/components/studio/made-note";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 { elapsed, formatCost, 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";+import type { NearRun, RunDetails, RunInput, RunJob, RunMadeBy, RunMoney, RunTiming, WorkerEvent } from "@/server/run-details";-/** The address of a run's details page (the private admin panel links here too). */+/** The address of a run's details page. */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" };@@ -59,7 +59,17 @@ function shown(v: unknown): string {function BackToSettings() {const router = useRouter();useEffect(() => router.replace("/settings"), [router]);- return <GallerySkeleton cards={4} />;+ return <Loading />;+}++function Loading() {+ 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>+ );}/**@@ -80,16 +90,10 @@ export function RunDetailsView() {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} />;+ // One loading look for every wait, so the page the server draws matches the browser's first draw.+ if (viewer.isPending) return <Loading />;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.isPending) return <Loading />;if (q.isError)return (<div className="space-y-3">@@ -128,10 +132,16 @@ export function RunDetailsView() {<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>+ {" · "}+ {d.surface.label}+ {" · "}+ {d.model.name}</>}/>+ <Summary d={d} />+<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">@@ -143,10 +153,16 @@ export function RunDetailsView() {</div><div className="min-w-0 space-y-8">+ <Section title="Timeline">+ <Timeline t={d.timing} status={g.status} progress={d.progress} log={d.workerLog} />+ </Section>++ <MadeBy m={d.madeBy} model={d.model} cards={g.declinedCards} prompt={d.prompt} />+<Section title="What happened"><Facts><Fact label="Status">{STATUS_WORDS[g.status] ?? g.status}</Fact>- <Fact label="Started">{new Date(g.createdAt).toLocaleString()}</Fact>+ <Fact label="Pressed">{new Date(g.createdAt).toLocaleString()}</Fact>{g.completedAt && (<Fact label="Ended">{new Date(g.completedAt).toLocaleString()} ({elapsed(g.createdAt, g.completedAt)})@@ -196,6 +212,12 @@ export function RunDetailsView() {<Section title="Where it ran"><Facts>+ <Fact label="Made in">+ {d.surface.label}+ <span className="text-muted-foreground"> · {d.surface.standalone ? "on its own in a studio" : "by a tool, for one of its projects"}</span>+ {d.surface.skill && <span className="block text-muted-foreground">From the skill “{d.surface.skill}”</span>}+ {d.surface.step && <span className="block text-muted-foreground">Step: {d.surface.step}</span>}+ </Fact><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>}@@ -207,6 +229,11 @@ export function RunDetailsView() {</Fact>)}<Fact label="Reached the GPU or provider">{d.where.handedOver ? "Yes" : "No"}</Fact>+ {d.providerId && (+ <Fact label="Job id there">+ <code className="text-[12px] break-all">{d.providerId}</code>+ </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 && (@@ -217,6 +244,24 @@ export function RunDetailsView() {</Fact>)}</Facts>+ <Jobs jobs={d.jobs} />+ </Section>++ <Section title="Cost">+ <Money m={d.money} status={g.status} />+ {d.checks.length > 0 && (+ <Facts>+ <Fact label="Results checked first">+ {d.checks.map((c, i) => (+ <span key={i} className="block">+ Result {i + 1}: {CHECK_WORDS[c.state] ?? c.state}+ {c.decidedAt ? ` after ${dur(c.decidedAt - c.askedAt)}` : ""}+ {c.tries > 1 ? ` · ${c.tries} tries` : ""}+ </span>+ ))}+ </Fact>+ </Facts>+ )}</Section><Section title="Model and settings">@@ -224,6 +269,7 @@ export function RunDetailsView() {<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>}+ {d.model.ranOn && <span className="block text-muted-foreground">Made with {d.model.ranOn.name}</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>@@ -314,7 +360,7 @@ function Settings({ rows }: { rows: SettingRow[] }) {<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">Asked for</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>@@ -330,6 +376,12 @@ function Settings({ rows }: { rows: SettingRow[] }) {<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>}+ {r.made && (+ <span className="mt-0.5 block text-[11.5px] font-medium">+ Made at {r.made.value}+ <span className="text-muted-foreground"> · {r.made.reason}</span>+ </span>+ )}</td><td className="max-w-64 px-3 py-1.5 break-words text-muted-foreground">{r.hasDefault ? (@@ -483,3 +535,279 @@ function Near({ title, runs, current, empty, note }: { title: string; runs: Near</div>);}++const CHECK_WORDS: Record<string, string> = { waiting: "Waiting for its check", shown: "Passed", hidden: "Hidden by its check", unchecked: "Not checked in time" };+const HELD_WORDS: Record<string, string> = {+ mine: "behind its other runs",+ today: "the day's GPU time is used up",+ service: "waiting for the service to answer",+ hour: "an hourly limit",+ list: "the waiting list",+ credits: "no free runs left until they renew",+};+const EVENT_WORDS: Record<string, string> = {+ claimed: "Taken by a worker",+ finished: "Worker finished its job",+ requeued: "Worker gave it back: back in line",+ done: "Job done",+ failed: "Job failed",+ canceled: "Job canceled",+};+const JOB_STATE_WORDS: Record<string, string> = {+ waiting: "In line",+ sending: "Sending files",+ queued: "Queued on the GPU",+ running: "Running",+ collecting: "Collecting results",+ done: "Done",+ failed: "Failed",+ canceled: "Canceled",+};+const REPORT_WORDS: Record<string, string> = { settle: "Charge", refund: "Refund", release: "Release" };+const ENDED_WORDS: Record<string, string> = { succeeded: "Finished", failed: "Failed", canceled: "Canceled" };++/** A length of time in a few characters: "0.4s", "12s", "3m 05s", "1h 20m". */+function dur(ms: number): string {+ if (ms < 10_000) return `${(Math.max(0, ms) / 1000).toFixed(1)}s`;+ const s = Math.round(ms / 1000);+ if (s < 60) return `${s}s`;+ if (s < 3600) return `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, "0")}s`;+ return `${Math.floor(s / 3600)}h ${String(Math.floor((s % 3600) / 60)).padStart(2, "0")}m`;+}++const clock = (t: number) => new Date(t).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });++/** The few numbers the owner looks for first: how long it waited and ran, what it cost, and which worker made it. */+function Summary({ d }: { d: RunDetails }) {+ const t = d.timing;+ const job = [...d.jobs].reverse().find((j) => j.worker || j.device);+ const cost = d.money.charge ?? (d.money.costUsd != null ? formatCost(d.money.costUsd) : d.money.lineClass === "free" ? "Free" : null);+ const items: [string, string][] = [+ ...(t.waitedMs !== undefined ? [["Waited", dur(t.waitedMs)] as [string, string]] : []),+ ...(t.ranMs !== undefined ? [["Ran", dur(t.ranMs)] as [string, string]] : []),+ ...(t.gpuMs !== undefined ? [["GPU time", dur(t.gpuMs)] as [string, string]] : []),+ ...(t.totalMs !== undefined ? [["Total", dur(t.totalMs)] as [string, string]] : []),+ ...(cost ? [["Cost", cost] as [string, string]] : []),+ ...(job ? [["Made on", [job.worker, job.device].filter(Boolean).join(" · ")] as [string, string]] : []),+ ];+ if (!items.length) return null;+ return (+ <dl className="mb-8 grid grid-cols-2 gap-2 sm:flex sm:flex-wrap">+ {items.map(([label, value]) => (+ <div key={label} className="min-w-0 rounded-lg border px-3 py-2 sm:min-w-28">+ <dt className="text-[11.5px] text-muted-foreground">{label}</dt>+ <dd className="truncate text-[14px] font-medium tabular-nums" title={value}>+ {value}+ </dd>+ </div>+ ))}+ </dl>+ );+}++interface Step {+ at: number;+ words: string;+ more?: string;+ tone?: "bad" | "now";+}++/** Pressed, held, sent, started, each worker's take and give-back, and the end, in time order. */+function Timeline({ t, status, progress, log }: { t: RunTiming; status: string; progress: RunDetails["progress"]; log: WorkerEvent[] }) {+ const steps: Step[] = [{ at: t.pressedAt, words: "Run pressed" }];+ if (t.held) steps.push({ at: t.pressedAt, words: `Waiting to enter the line: ${HELD_WORDS[t.held.reason] ?? t.held.reason}`, more: t.held.startAt ? `May enter at ${clock(t.held.startAt)}` : undefined, tone: "now" });+ if (t.sentAt !== undefined) steps.push({ at: t.sentAt, words: "Sent to the GPU or provider", more: `${dur(t.sentAt - t.pressedAt)} after the press` });+ for (const e of log)+ steps.push({+ at: e.at,+ words: EVENT_WORDS[e.event] ?? e.event,+ more: [e.worker, e.device, e.lane && `lane ${e.lane}`, e.execMs != null && `GPU ${dur(e.execMs)}`].filter(Boolean).join(" · ") || undefined,+ tone: e.event === "requeued" || e.event === "failed" ? "bad" : undefined,+ });+ if (t.startedAt !== undefined) steps.push({ at: t.startedAt, words: "Work started", more: `waited ${dur(t.waitedMs ?? 0)}` });+ if (progress && (status === "running" || status === "queued")) {+ const s = progress.step;+ const bits = [+ progress.share != null && `${Math.round(progress.share * 100)}%`,+ s?.loading && "loading its model",+ s?.value !== undefined && s.max !== undefined && `step ${s.value} of ${s.max}`,+ s?.node && `node ${s.node}`,+ ].filter(Boolean);+ steps.push({ at: s?.at ?? Math.max(...steps.map((x) => x.at)), words: status === "running" ? "Working now" : "In line now", more: bits.join(" · ") || undefined, tone: "now" });+ }+ if (t.endedAt !== undefined) steps.push({ at: t.endedAt, words: ENDED_WORDS[status] ?? "Ended", more: t.ranMs !== undefined ? `ran ${dur(t.ranMs)}` : undefined, tone: status === "failed" ? "bad" : undefined });+ steps.sort((a, b) => a.at - b.at);+ return (+ <ol className="relative space-y-3 border-l pl-4 text-[13px]">+ {steps.map((s, i) => (+ <li key={i} className="relative">+ <span+ aria-hidden+ className={cn(+ "absolute top-1.5 -left-[1.3rem] size-2 rounded-full bg-muted-foreground/60",+ s.tone === "bad" && "bg-destructive",+ s.tone === "now" && "bg-foreground",+ )}+ />+ <p className="flex flex-wrap items-baseline gap-x-2">+ <span className={cn("font-medium", s.tone === "bad" && "text-destructive")}>{s.words}</span>+ <span className="text-[12px] text-muted-foreground tabular-nums" title={new Date(s.at).toLocaleString()}>+ {clock(s.at)}+ </span>+ </p>+ {s.more && <p className="text-[12px] break-words text-muted-foreground">{s.more}</p>}+ </li>+ ))}+ </ol>+ );+}++/** How it was made: Auto's pick and why, Ideogram 4's declines (with what it returned), notices, and values made differently. */+function MadeBy({ m, model, cards, prompt }: { m: RunMadeBy; model: RunDetails["model"]; cards?: AccountRun["declinedCards"]; prompt: string | null }) {+ if (!m.auto && !m.declined && !m.notices.length && !m.changes.length && !cards?.length) return null;+ return (+ <Section title="How it was made">+ <Facts>+ {m.auto && (+ <Fact label="Auto picked">+ {m.auto.name}+ <span className="block text-muted-foreground">{m.auto.words}</span>+ </Fact>+ )}+ {m.declined && (+ <Fact label="Ideogram 4 declined">+ {m.declined.words}+ {m.declined.askedModelName && m.declined.modelName && (+ <span className="block text-muted-foreground">+ Asked for {m.declined.askedModelName} · made with {m.declined.modelName}+ </span>+ )}+ {!m.declined.modelName && model.ranOn && <span className="block text-muted-foreground">Made with {model.ranOn.name}</span>}+ </Fact>+ )}+ {!!cards?.length && (+ <Fact label="What it returned">+ <DeclinedCards cards={cards} words={prompt ?? undefined} className="block break-words" />+ </Fact>+ )}+ {m.notices.map((n, i) => (+ <Fact key={i} label={i ? "" : "Said on the result"}>+ {n}+ </Fact>+ ))}+ {m.changes.length > 0 && (+ <Fact label="Made differently">+ {m.changes.map((c) => (+ <span key={c.setting} className="block">+ {c.label}: asked for {c.asked} · made at <span className="font-medium">{c.made}</span>+ <span className="text-muted-foreground"> ({c.reason})</span>+ </span>+ ))}+ <span className="mt-0.5 block text-[11.5px] text-muted-foreground">The account's pages show the made value only.</span>+ </Fact>+ )}+ </Facts>+ </Section>+ );+}++/** Each job on this site's GPUs or the account's computer: its worker and GPU, lane, tries and times. */+function Jobs({ jobs }: { jobs: RunJob[] }) {+ if (!jobs.length) return null;+ return (+ <div className="mt-4 space-y-2">+ <p className="text-[13px] text-muted-foreground">{jobs.length > 1 ? `Its ${jobs.length} jobs` : "Its job"}</p>+ <ul className="space-y-2">+ {jobs.map((j, i) => (+ <li key={i} className="rounded-lg border p-3 text-[12.5px]">+ <p className="flex flex-wrap items-baseline gap-x-2">+ <span className="font-medium">+ {jobs.length > 1 ? `Job ${i + 1}` : "Job"}+ {j.slot === "cpu" ? " (finishing, on a CPU)" : ""}+ </span>+ <span className={cn("text-muted-foreground", j.state === "failed" && "text-destructive")}>{JOB_STATE_WORDS[j.state] ?? j.state}</span>+ </p>+ <dl className="mt-1.5 grid grid-cols-[7rem_minmax(0,1fr)] gap-x-3 gap-y-0.5">+ {j.worker && <JobFact label="Worker">{j.worker}</JobFact>}+ {j.device && <JobFact label="GPU">{j.device}</JobFact>}+ {j.lane && <JobFact label="Lane">{j.lane}</JobFact>}+ {j.lineClass && <JobFact label="Line">{j.lineClass === "paid" ? "Paid" : j.lineClass === "free" ? "Free" : j.lineClass}</JobFact>}+ {j.workflowId && (+ <JobFact label="Graph">+ <code className="text-[11.5px]">{j.workflowId}</code>+ </JobFact>+ )}+ <JobFact label="Tries">+ {j.attempts ? `Sent to ComfyUI ${j.attempts}×` : "Not sent on this take"}+ {j.requeues ? ` · back in line ${j.requeues}×` : ""}+ {j.triedBy ? ` · ${j.triedBy} worker${j.triedBy > 1 ? "s" : ""} tried it` : ""}+ </JobFact>+ {(j.estMs !== undefined || j.execMs !== undefined) && (+ <JobFact label="GPU time">+ {j.execMs !== undefined ? dur(j.execMs) : "—"}+ {j.estMs !== undefined && <span className="text-muted-foreground"> (expected {dur(j.estMs)})</span>}+ </JobFact>+ )}+ <JobFact label="Times">+ <span className="tabular-nums">+ {[+ `made ${clock(j.createdAt)}`,+ j.claimedAt && `taken ${clock(j.claimedAt)}`,+ j.sentAt && `sent ${clock(j.sentAt)}`,+ j.startedAt && `started ${clock(j.startedAt)}`,+ j.finishedAt && `ended ${clock(j.finishedAt)}`,+ ]+ .filter(Boolean)+ .join(" · ")}+ </span>+ </JobFact>+ {j.down && (+ <JobFact label="GPU down">+ since {clock(j.down.at)}+ {j.down.why === "setting" ? " (its ComfyUI answers, without Fuobe's setting)" : ""}+ </JobFact>+ )}+ {j.note && <JobFact label="Note">{j.note}</JobFact>}+ {j.error && (+ <JobFact label="Error">+ <span className="break-words whitespace-pre-wrap text-destructive">{j.error}</span>+ </JobFact>+ )}+ </dl>+ </li>+ ))}+ </ul>+ </div>+ );+}++function JobFact({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <>+ <dt className="text-muted-foreground">{label}</dt>+ <dd className="min-w-0 break-words">{children}</dd>+ </>+ );+}++/** What it cost, its place in the line, and whether it was charged. */+function Money({ m, status }: { m: RunMoney; status: string }) {+ return (+ <Facts>+ <Fact label="Cost">{m.costUsd != null ? formatCost(m.costUsd) : "Not known"}</Fact>+ {m.charge && <Fact label="Charged">{m.charge}</Fact>}+ {m.lineClass && <Fact label="Line">{m.lineClass === "paid" ? "Paid run" : "Free run"}</Fact>}+ {m.light && <Fact label="Light work">Joins and trims only: free and not counted</Fact>}+ {(m.setAside || m.notCharged) && <Fact label="Set aside">{m.notCharged ? "Yes, and given back: nothing was charged" : status === "succeeded" ? "Yes, then charged" : "Yes"}</Fact>}+ {m.notBilled && <Fact label="Billed">No: it stopped before the provider took the job</Fact>}+ {m.waitMs !== undefined && <Fact label="Longest wait in line">{dur(m.waitMs)}</Fact>}+ {m.boostMs ? <Fact label="Head start in line">{dur(m.boostMs)}</Fact> : null}+ {m.report && (+ <Fact label={`${REPORT_WORDS[m.report.kind] ?? m.report.kind} report`}>+ {m.report.state === "sent" ? "Sent" : m.report.state === "gave-up" ? "Gave up" : "Waiting to send"}+ {m.report.tries > 1 ? ` · ${m.report.tries} tries` : ""}+ </Fact>+ )}+ </Facts>+ );+}diff --git a/src/lib/run-settings.ts b/src/lib/run-settings.tsindex 6c39ab86..b33e4deb 100644--- a/src/lib/run-settings.ts+++ b/src/lib/run-settings.ts@@ -33,6 +33,8 @@ export interface SettingRow {state: SettingState;/** The request carried it (false: left out, so its default applied). */sent: boolean;+ /** The model makes it differently: what it is made at, what was asked (in words), and why. */+ made?: { value: string; asked: string; reason: string };}/** What a run's defaults come from: its model, its preset (or app) and the preset's route on that model. */diff --git a/src/server/run-details.ts b/src/server/run-details.tsindex 90283425..bbc03cd2 100644--- a/src/server/run-details.ts+++ b/src/server/run-details.ts@@ -2,7 +2,10 @@ 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 { AUTO_IMAGE } from "@/lib/auto-image";+import type { AutoWhy, Engine, GenerationRequest, MediaKind } from "@/lib/catalog/types";+import { madeOfRun } from "@/lib/catalog/fitted";+import type { SettingChange } from "@/lib/catalog/made";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";@@ -105,7 +108,8 @@ export interface RunDetails {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 };+ /** The model the account chose (Auto, or the one it named), beside the composer's default; `ranOn`: the model that made it, when another. */+ model: { id: string; name: string; state: "default" | "changed" | "unknown"; default?: string; defaultName?: string; ranOn?: { id: string; name: string } };preset: { id: string; name: string; type: string } | null;studio: { title: string; feature: string } | null;prompt: string | null;@@ -120,9 +124,128 @@ export interface RunDetails {near: NearRun[];/** What was sent to the GPU or provider (the graph or the request), redacted; null when nothing was sent. */sent: unknown;+ /** When it was pressed, sent, started and ended, and how long it waited and ran. */+ timing: RunTiming;+ /** Its jobs on this site's GPUs or the account's computer, oldest first: each one's worker, times and tries. */+ jobs: RunJob[];+ /** The workers' log for this run, oldest first: who took each job, gave it back or finished it. */+ workerLog: WorkerEvent[];+ /** What it cost and whether it was charged. */+ money: RunMoney;+ /** How it was made: Auto's pick, a model that made it after another declined, and what changed while it ran. */+ madeBy: RunMadeBy;+ /** Where it was made: the studio or tool, and whether a tool made it for one of the account's projects. */+ surface: RunSurface;+ /** The job's id at the GPU or provider, when it reached one (addresses and credentials left out). */+ providerId: string | null;+ /** Its progress now (a run still going): the share done and the step the GPU is on. */+ progress: { share: number | null; step?: { value?: number; max?: number; node?: string; loading?: boolean; at?: number } } | null;+ /** Each result's check before it shows, when results are checked first. */+ checks: { state: string; askedAt: number; decidedAt: number | null; tries: number }[];+}++export interface RunTiming {+ /** Run was pressed (the row was made). */+ pressedAt: number;+ /** Still waiting to enter the line: why, and when it may (hosted runs). */+ held?: { reason: string; startAt: number | null; tries: number };+ /** Its job was handed to the GPU or provider. */+ sentAt?: number;+ /** The GPU or provider began working on it. */+ startedAt?: number;+ endedAt?: number;+ /** From the press to the start of work. */+ waitedMs?: number;+ /** From the start of work to the end. */+ ranMs?: number;+ /** The GPU's own measured time, as its worker said it. */+ gpuMs?: number;+ /** From the press to the end. */+ totalMs?: number;+}++export interface RunJob {+ state: string;+ /** "gpu", or "cpu" for a finishing job (joins, trims). */+ slot: "gpu" | "cpu";+ lane?: string;+ /** Its class in the line: paid, free or owner. */+ lineClass?: string;+ worker?: string;+ device?: string;+ workflowId?: string;+ attempts: number;+ /** Times a worker gave it back and it went back in line (a worker that stopped or crashed). */+ requeues: number;+ /** Workers that tried it before. */+ triedBy: number;+ estMs?: number;+ execMs?: number;+ createdAt: number;+ claimedAt?: number;+ sentAt?: number;+ startedAt?: number;+ finishedAt?: number;+ error?: string;+ note?: string;+ /** Its computer's ComfyUI didn't answer, since when (and why, when it said). */+ down?: { at: number; why?: string };+}++export interface WorkerEvent {+ at: number;+ event: string;+ worker?: string;+ lane?: string;+ execMs?: number;+ device?: string;+}++export interface RunMoney {+ costUsd: number | null;+ /** Its class in the line on this site's GPUs. */+ lineClass?: "paid" | "free";+ /** The words for what it cost on this site's GPUs ("7 units"). */+ charge?: string;+ /** An amount was set aside for it when it was pressed. */+ setAside: boolean;+ /** It failed or was stopped after an amount was set aside: nothing was charged. */+ notCharged: boolean;+ /** It failed or stopped before the paid provider took the job. */+ notBilled: boolean;+ /** Light work only (joins, trims): free and never counted. */+ light: boolean;+ /** How long it may wait in line, and its head start in line (ms). */+ waitMs?: number;+ boostMs?: number;+ /** Its charge, refund or release report and where it stands. */+ report?: { kind: string; state: "sent" | "waiting" | "gave-up"; tries: number };+}++export interface RunMadeBy {+ /** A run of Auto: the model it picked, and why. */+ auto?: { model: string; name: string; why: AutoWhy; words: string };+ /** Ideogram 4 declined it: where its retries stand, and the model that made it in its place. */+ declined?: { stage?: string; words: string; model?: string; modelName?: string; askedModel?: string; askedModelName?: string };+ /** What changed while it ran (an optional input left out, another model made it), said on the result. */+ notices: string[];+ /** Settings the model makes differently from what was asked (the account sees the made value only). */+ changes: SettingChange[];+}++export interface RunSurface {+ /** "Image", "Canvas", "Cinema Studio"… */+ label: string;+ /** Made on its own in a studio (true), or by a tool for one of the account's projects (false). Unknown on older runs. */+ standalone?: boolean;+ /** Made by a skill's recipe: the skill's name. */+ skill?: string;+ /** A step of a longer run: its label and place. */+ step?: string;}interface RawRow {+ request_json: string;message: string | null;error: string | null;external_id: string | null;@@ -261,28 +384,33 @@ function studioOf(feature: string): { title: string; feature: string; defaultMod* 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;+function modelChoice(run: AccountRun, chosen: string = run.modelId): RunDetails["model"] {+ const picked = modelPicked(run, chosen);+ return { ...picked, ...(chosen !== run.modelId && { ranOn: { id: run.modelId, name: run.modelName ?? run.modelId } }) };+}++function modelPicked(run: AccountRun, chosen: string): RunDetails["model"] {+ const name = chosen === run.modelId ? (run.modelName ?? run.modelId) : (getModel(chosen)?.name ?? chosen);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" };+ if (!first) return { id: chosen, name, state: "unknown" };const others = new Set(presetRoutes(preset, run.engine, has).map((r) => r.modelId));return {- id: run.modelId,+ id: chosen,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",+ state: first === chosen || (preset.type === "app" && others.has(chosen)) ? "default" : "changed",default: first,defaultName: getModel(first)?.name ?? first,};}const studio = studioOf(run.feature);- if (!studio) return { id: run.modelId, name, state: "unknown" };+ if (!studio) return { id: chosen, 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 };+ return { id: chosen, name, state: chosen === d || chosen === 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 {@@ -323,12 +451,260 @@ export function safeTrouble<T extends RunTrouble>(t: T, url?: string): T {};}+/** Tools and studios whose names aren't their feature's ("cinema-scene" is Cinema Studio's). */+const TOOL_NAMES: [RegExp, string][] = [+ [/^canvas$/, "Canvas"],+ [/^assist$/, "Assist"],+ [/^cinema(-|$)/, "Cinema Studio"],+ [/^storyboard(-|$)/, "Storyboard"],+ [/^content-factory$/, "Content Factory"],+ [/^faceless(-|$)/, "Faceless Studio"],+ [/^ad-multiplier$/, "Ad Multiplier"],+ [/^click-to-ad$/, "Click to Ad"],+ [/^(marketing|ads)$/, "Marketing Studio"],+ [/^photodump$/, "Photodump"],+ [/^genjutsu$/, "Genjutsu"],+ [/^moodboard$/, "Moodboards"],+ [/^layers$/, "Layers"],+ [/^explainer$/, "Explainer"],+ [/^influencer$/, "AI Influencer"],+];++const featureWords = (f: string) => f.charAt(0).toUpperCase() + f.slice(1).replaceAll("-", " ");++/** Where a run was made: its tool or studio, whether a tool made it for a project, and the skill or step it belongs to. */+export function surfaceOf(feature: string, stamp: GenerationRequest): RunSurface {+ const tool = TOOL_NAMES.find(([re]) => re.test(feature))?.[1];+ return {+ label: tool ?? studioOf(feature)?.title ?? featureWords(feature),+ standalone: stamp.standalone === true,+ ...(stamp.skill?.name && { skill: stamp.skill.name }),+ ...(stamp.step && { step: `${stamp.step.label} (${stamp.step.index + 1} of ${stamp.step.of})` }),+ };+}++/** Why Auto picked its model, in words. */+export const AUTO_WHY_WORDS: Record<AutoWhy, string> = {+ edit: "It had a picture to work from, so it went to the edit model",+ text: "Its words ask for lettering, so it went to Ideogram 4",+ trigger: "Its words match a pattern in Settings → Auto image model",+ plain: "A plain prompt: the usual first model",+ declined: "Ideogram 4 declined it, so this model made it instead",+};++const DECLINED_STAGE_WORDS: Record<string, string> = {+ retry: "Ideogram 4 declined it and was asked again with a new seed",+ fallback: "Ideogram 4 declined it twice, so another model made it",+};++/** How a run was made: Auto's pick, Ideogram 4's declines and the model after them, and the notices it carries. */+export function madeByOf(run: AccountRun, meta: Record<string, unknown>): RunMadeBy {+ const req = run.request;+ const pick = req.modelId === AUTO_IMAGE && req.auto ? req.auto : undefined;+ const d = obj(meta.declined);+ const was = obj(d.was);+ const stage = str(d.stage);+ const askedModel = str(was.model_id);+ const fallback = str(d.model);+ const declined =+ stage || run.declinedCards?.length+ ? {+ ...(stage && { stage }),+ words: (stage && DECLINED_STAGE_WORDS[stage]) || "Ideogram 4 returned its grey card for a picture",+ ...(fallback && { model: fallback, modelName: getModel(fallback)?.name ?? fallback }),+ ...(askedModel && { askedModel, askedModelName: getModel(askedModel)?.name ?? askedModel }),+ }+ : undefined;+ const skipped = req.chainSkipped?.slots.length ?? 0;+ const notices = [req.notice, skipped ? `Left out ${skipped} optional input${skipped > 1 ? "s" : ""} whose steps failed` : undefined]+ .map((n) => n?.trim())+ .filter((n): n is string => !!n);+ return {+ ...(pick && { auto: { model: pick.model, name: getModel(pick.model)?.name ?? pick.model, why: pick.why, words: AUTO_WHY_WORDS[pick.why] ?? pick.why } }),+ ...(declined && { declined }),+ notices,+ // Worked out here when the run doesn't carry it: the same rules the studios use before a run.+ changes: (run.made ?? madeOfRun(getModel(run.modelId), { op: run.op, provider: run.provider, request: run.request }))?.changes ?? [],+ };+}++interface TaskFacts {+ id: string;+ state: string;+ slot: string | null;+ lane: string | null;+ class: string | null;+ workflow_id: string | null;+ attempts: number;+ requeues: number | null;+ tried_json: string | null;+ est_ms: number | null;+ error: string | null;+ note: string | null;+ down_at: number | null;+ down_why: string | null;+ progress_json: string | null;+ created_at: number;+ claimed_at: number | null;+ sent_at: number | null;+ started_at: number | null;+ finished_at: number | null;+}++interface LogRow {+ at: number;+ event: string;+ task_id: string;+ worker_name: string | null;+ lane: string | null;+ exec_ms: number | null;+ device: string | null;+}++/** The columns a table has (empty: no such table), so an install from before a column reads what it has. */+function columnsOf(table: string): Set<string> {+ return new Set((db().prepare(`SELECT name FROM pragma_table_info(?)`).all(table) as { name: string }[]).map((c) => c.name));+}++/** A column when the table has it, else NULL under its name. */+const col = (have: Set<string>, name: string) => (have.has(name) ? name : `NULL AS ${name}`);++/** A run's jobs on this site's workers or the account's computer, and the workers' log of them, oldest first. */+function jobsOf(id: string, url?: string): { jobs: RunJob[]; log: WorkerEvent[]; tasks: TaskFacts[] } {+ const have = columnsOf("relay_tasks");+ if (!have.size) return { jobs: [], log: [], tasks: [] };+ const cols = ["slot", "lane", "class", "requeues", "tried_json", "est_ms", "progress_json"].map((c) => col(have, c)).join(", ");+ const tasks = db()+ .prepare(+ `SELECT id, state, workflow_id, attempts, error, note, down_at, down_why, created_at, claimed_at, sent_at, started_at, finished_at, ${cols}+ FROM relay_tasks WHERE generation_id = ? ORDER BY created_at, id`,+ )+ .all(id) as TaskFacts[];+ const log = columnsOf("worker_jobs").size+ ? (db().prepare("SELECT at, event, task_id, worker_name, lane, exec_ms, device FROM worker_jobs WHERE generation_id = ? ORDER BY id").all(id) as LogRow[])+ : [];+ const scrub = (t: string | null) => (t ? redactText(t, { url }) : undefined);+ const jobs = tasks.map((t): RunJob => {+ const mine = log.filter((l) => l.task_id === t.id);+ const finished = mine.filter((l) => l.event === "finished").at(-1);+ const taker = mine.filter((l) => l.event === "claimed").at(-1);+ const worker = finished?.worker_name ?? taker?.worker_name;+ const device = finished?.device ?? taker?.device;+ const tried = parse(t.tried_json);+ return {+ state: t.state,+ slot: t.slot === "cpu" ? "cpu" : "gpu",+ ...(t.lane && { lane: t.lane }),+ ...(t.class && { lineClass: t.class }),+ ...(worker && { worker }),+ ...(device && { device }),+ ...(t.workflow_id && { workflowId: t.workflow_id }),+ attempts: t.attempts,+ requeues: t.requeues ?? 0,+ triedBy: Array.isArray(tried) ? tried.length : 0,+ ...(t.est_ms != null && { estMs: t.est_ms }),+ ...(finished?.exec_ms != null && { execMs: finished.exec_ms }),+ createdAt: t.created_at,+ ...(t.claimed_at != null && { claimedAt: t.claimed_at }),+ ...(t.sent_at != null && { sentAt: t.sent_at }),+ ...(t.started_at != null && { startedAt: t.started_at }),+ ...(t.finished_at != null && { finishedAt: t.finished_at }),+ ...(t.error && { error: scrub(t.error) }),+ ...(t.note && { note: scrub(t.note) }),+ ...(t.down_at != null && { down: { at: t.down_at, ...(t.down_why && { why: t.down_why }) } }),+ };+ });+ return {+ jobs,+ tasks,+ log: log.map((l) => ({+ at: l.at,+ event: l.event,+ ...(l.worker_name && { worker: l.worker_name }),+ ...(l.lane && { lane: l.lane }),+ ...(l.exec_ms != null && { execMs: l.exec_ms }),+ ...(l.device && { device: l.device }),+ })),+ };+}++const earliest = (xs: (number | null | undefined)[]) => xs.filter((x): x is number => typeof x === "number").sort((a, b) => a - b)[0];++/** When the run was pressed, sent, started and ended, and the waits between. */+function timingOf(run: AccountRun, tasks: TaskFacts[], log: WorkerEvent[]): RunTiming {+ const times = columnsOf("generation_runs").size+ ? (db().prepare("SELECT submitted_at, started_at FROM generation_runs WHERE id = ?").get(run.id) as { submitted_at: number | null; started_at: number | null } | undefined)+ : undefined;+ const hold = columnsOf("pool_holds").size+ ? (db().prepare("SELECT reason, start_at, tries FROM pool_holds WHERE generation_id = ?").get(run.id) as { reason: string; start_at: number | null; tries: number } | undefined)+ : undefined;+ const sentAt = earliest([times?.submitted_at, ...tasks.map((t) => t.sent_at)]);+ const startedAt = earliest([times?.started_at, ...tasks.map((t) => t.started_at)]);+ const endedAt = run.completedAt ?? undefined;+ const gpuMs = log.filter((l) => l.event === "finished").reduce((n, l) => n + (l.execMs ?? 0), 0);+ return {+ pressedAt: run.createdAt,+ ...(hold && { held: { reason: hold.reason, startAt: hold.start_at, tries: hold.tries } }),+ ...(sentAt !== undefined && { sentAt }),+ ...(startedAt !== undefined && { startedAt, waitedMs: Math.max(0, startedAt - run.createdAt) }),+ ...(endedAt && { endedAt, totalMs: Math.max(0, endedAt - run.createdAt) }),+ ...(endedAt && startedAt !== undefined && { ranMs: Math.max(0, endedAt - startedAt) }),+ ...(gpuMs > 0 && { gpuMs }),+ };+}++/** What a run cost, whether an amount was set aside and charged, and where its report stands. */+function moneyOf(run: AccountRun, stamp: GenerationRequest): RunMoney {+ const report = columnsOf("billing_outbox").size+ ? (db().prepare("SELECT kind, done_at, gave_up, tries FROM billing_outbox WHERE key = ?").get(run.id) as { kind: string; done_at: number | null; gave_up: number; tries: number } | undefined)+ : undefined;+ return {+ costUsd: run.costUsd,+ ...((stamp.class === "paid" || stamp.class === "free") && { lineClass: stamp.class }),+ ...(stamp.charge && { charge: stamp.charge }),+ setAside: !!stamp.hold && !!stamp.charged,+ notCharged: !!run.notCharged,+ notBilled: !!run.notBilled,+ light: stamp.light === true,+ ...(typeof stamp.waitMs === "number" && { waitMs: stamp.waitMs }),+ ...(typeof stamp.boostMs === "number" && { boostMs: stamp.boostMs }),+ ...(report && { report: { kind: report.kind, state: report.gave_up ? "gave-up" : report.done_at ? "sent" : "waiting", tries: report.tries } }),+ };+}++/** Its results' checks before they show, oldest first. */+function checksOf(id: string): RunDetails["checks"] {+ if (!columnsOf("output_checks").size) return [];+ const rows = db().prepare("SELECT state, asked_at, decided_at, tries FROM output_checks WHERE generation_id = ? ORDER BY asked_at").all(id) as {+ state: string;+ asked_at: number;+ decided_at: number | null;+ tries: number;+ }[];+ return rows.map((c) => ({ state: c.state, askedAt: c.asked_at, decidedAt: c.decided_at, tries: c.tries }));+}++/** A run still going: the share done, and the step its GPU last said. */+function progressOf(run: AccountRun, tasks: TaskFacts[]): RunDetails["progress"] {+ if (run.status !== "queued" && run.status !== "running") return null;+ const live = [...tasks].reverse().find((t) => t.progress_json);+ const p = obj(parse(live?.progress_json));+ const step = {+ ...(num(p.value) !== undefined && { value: num(p.value) }),+ ...(num(p.max) !== undefined && { max: num(p.max) }),+ ...(str(p.node) && { node: str(p.node) }),+ ...(p.cold === true && { loading: true }),+ ...(num(p.at) !== undefined && { at: num(p.at) }),+ };+ return { share: run.progress, ...(Object.keys(step).length > 0 && { step }) };+}+/** 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;+ const raw = db().prepare("SELECT request_json, 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);@@ -342,6 +718,12 @@ export function runDetails(id: string, o: { emails?: boolean } = {}): RunDetailsconst 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 stored request with its stamp (place, class, charge): the run as read leaves the stamp out.+ const stamp = obj(parse(raw.request_json)) as unknown as GenerationRequest;+ const meta = obj(parse(raw.external_meta_json));+ const { jobs, log, tasks } = jobsOf(id, gpu.url);+ const madeBy = madeByOf(run, meta);+ const chosen = req.modelId === AUTO_IMAGE ? AUTO_IMAGE : (madeBy.declined?.askedModel ?? run.modelId);// 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@@ -369,20 +751,48 @@ export function runDetails(id: string, o: { emails?: boolean } = {}): RunDetailsfix: Object.keys(fixRest).length ? (redactValue(fixRest, { url: gpu.url }) as RunDetails["fix"]) : null,trouble,where: whereOf(run, raw, gpu),- model: modelChoice(run),+ model: modelChoice(run, chosen),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 }) }),- })),+ settings: withMade(+ 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 }) }),+ })),+ madeBy.changes,+ ),inputs: inputsOf(asked),batch,near,sent: redactValue(parse(raw.provider_input_json), { url: gpu.url }),+ timing: timingOf(run, tasks, log),+ jobs,+ workerLog: log,+ money: moneyOf(run, stamp),+ madeBy,+ surface: surfaceOf(run.feature, stamp),+ providerId: raw.external_id ? redactText(raw.external_id, { url: gpu.url }) : null,+ progress: progressOf(run, tasks),+ checks: checksOf(id),};}+/**+ * Each setting the model makes differently gets what it is made at, beside what was asked (the account sees the made+ * value only; the owner sees both). A change for a setting the request left out gets a row of its own.+ */+export function withMade(rows: SettingRow[], changes: SettingChange[]): SettingRow[] {+ const out = rows.map((r) => ({ ...r }));+ for (const c of changes) {+ const key = `params.${c.setting}`;+ const made = { value: c.made, asked: c.asked, reason: c.reason };+ const row = out.find((r) => r.key === key);+ if (row) row.made = made;+ else out.push({ key, label: c.label, hasDefault: false, state: "unknown", sent: false, made });+ }+ return out;+}+diff --git a/tests/run-details.test.ts b/tests/run-details.test.tsindex 14c8d576..498812d5 100644--- a/tests/run-details.test.ts+++ b/tests/run-details.test.ts@@ -168,11 +168,112 @@ describe("Run details: the owner's view of one account's run", () => {});it("says whether the model is the studio's default", async () => {+ // The Image studio opens on Auto on the open engine: a model named by hand is a change.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.model).toMatchObject({ id: "oss-qwen-image-21", state: "changed", default: "oss-auto-image" });+ expect(d.model.ranOn).toBeUndefined();expect(d.studio?.title).toBe("Image");});++ it("names Auto's pick and why, and the model that made it", async () => {+ const id = run(A, { status: "succeeded", request: { modelId: "oss-krea2-realism" } });+ db()+ .prepare("UPDATE generations SET request_json = json_set(request_json, '$.modelId', 'oss-auto-image', '$.auto', json(?)) WHERE id = ?")+ .run(JSON.stringify({ model: "oss-krea2-realism", why: "trigger" }), id);+ const d = (await (await get(id)).json()) as RunDetails;+ expect(d.model).toMatchObject({ id: "oss-auto-image", name: "Auto", state: "default", ranOn: { id: "oss-krea2-realism" } });+ expect(d.madeBy.auto).toMatchObject({ model: "oss-krea2-realism", why: "trigger" });+ expect(d.madeBy.auto?.words).toContain("Auto image model");+ });++ it("shows what Ideogram 4 declined and the model that made it in its place", async () => {+ const card = { url: "/api/files/held/card.png", spread: 3, grey: 0.97 };+ const id = run(A, {+ status: "succeeded",+ request: { notice: "Made with Qwen-Image 2.1 · Ideogram 4 declined this one" },+ meta: { jobIndex: 0, declined: { stage: "fallback", cards: [card], was: { model_id: "oss-ideogram-4", request_json: "{}" } } },+ });+ const d = (await (await get(id)).json()) as RunDetails;+ expect(d.run.declinedCards).toEqual([card]);+ expect(d.madeBy.declined).toMatchObject({ stage: "fallback", askedModel: "oss-ideogram-4" });+ expect(d.madeBy.notices).toEqual(["Made with Qwen-Image 2.1 · Ideogram 4 declined this one"]);+ expect(d.model).toMatchObject({ id: "oss-ideogram-4", ranOn: { id: "oss-qwen-image-21" } });+ });++ it("gives the timeline, its jobs and workers, and what it cost, without its hold or lease", async () => {+ const t0 = Date.now() - 120_000;+ const id = run(A, { status: "succeeded", at: t0, externalId: "task-1", request: { feature: "canvas" } });+ db()+ .prepare(+ "UPDATE generations SET completed_at = ?, cost_usd = 0.04, request_json = json_set(request_json, '$.place', 'pool', '$.class', 'paid', '$.hold', 'hold-secret-77', '$.charged', json('true'), '$.charge', '7 units') WHERE id = ?",+ )+ .run(t0 + 90_000, id);+ db().prepare("INSERT INTO generation_runs (id, submitted_at, started_at) VALUES (?, ?, ?)").run(id, t0 + 1_000, t0 + 30_000);+ db()+ .prepare(+ `INSERT INTO relay_tasks (id, principal, generation_id, state, prompt_id, lease_hash, lane, class, requeues, est_ms, created_at, updated_at, claimed_at, sent_at, started_at, finished_at)+ VALUES ('task-1', 'pool:pool', ?, 'done', 'p-1', 'lease-secret-99', 'image', 'paid', 1, 50000, ?, ?, ?, ?, ?, ?)`,+ )+ .run(id, t0 + 1_000, t0 + 90_000, t0 + 20_000, t0 + 25_000, t0 + 30_000, t0 + 88_000);+ const log = db().prepare(+ "INSERT INTO worker_jobs (at, event, worker_id, worker_name, task_id, generation_id, principal, lane, exec_ms, device) VALUES (?, ?, ?, ?, 'task-1', ?, 'pool:pool', 'image', ?, ?)",+ );+ log.run(t0 + 5_000, "claimed", "w1", "box-a", id, null, null);+ log.run(t0 + 10_000, "requeued", "w1", "box-a", id, null, null);+ log.run(t0 + 20_000, "claimed", "w2", "box-b", id, null, null);+ log.run(t0 + 88_000, "finished", "w2", "box-b", id, 55_000, "NVIDIA GeForce RTX 5090");+ db()+ .prepare("INSERT INTO billing_outbox (key, kind, hold_id, payload_json, tries, next_at, created_at, done_at) VALUES (?, 'settle', 'hold-secret-77', '{}', 1, 0, 0, 1)")+ .run(id);+ const text = await (await get(id)).text();+ for (const secret of ["hold-secret-77", "lease-secret-99"]) expect(text, secret).not.toContain(secret);+ const d = JSON.parse(text) as RunDetails;+ expect(d.timing).toMatchObject({ pressedAt: t0, sentAt: t0 + 1_000, startedAt: t0 + 30_000, endedAt: t0 + 90_000, waitedMs: 30_000, ranMs: 60_000, gpuMs: 55_000, totalMs: 90_000 });+ expect(d.jobs).toEqual([+ expect.objectContaining({ state: "done", slot: "gpu", lane: "image", lineClass: "paid", worker: "box-b", device: "NVIDIA GeForce RTX 5090", requeues: 1, estMs: 50_000, execMs: 55_000 }),+ ]);+ expect(d.workerLog.map((e) => [e.event, e.worker])).toEqual([+ ["claimed", "box-a"],+ ["requeued", "box-a"],+ ["claimed", "box-b"],+ ["finished", "box-b"],+ ]);+ expect(d.money).toMatchObject({ costUsd: 0.04, lineClass: "paid", charge: "7 units", setAside: true, notCharged: false, report: { kind: "settle", state: "sent", tries: 1 } });+ expect(d.surface).toMatchObject({ label: "Canvas", standalone: false });+ expect(d.providerId).toBe("task-1");+ expect(d.progress).toBeNull();+ });++ it("shows a value the model makes differently beside what was asked", async () => {+ const id = run(A, { status: "succeeded", request: { feature: "video", modelId: "minimax-h3-max-turbo", op: "t2v", params: { resolution: "2K" } } });+ db().prepare("UPDATE generations SET provider = 'fal', engine = 'cloud', kind = 'video' WHERE id = ?").run(id);+ const d = (await (await get(id)).json()) as RunDetails;+ expect(d.madeBy.changes).toEqual([expect.objectContaining({ setting: "resolution", asked: "2K", made: "1080p" })]);+ expect(d.settings.find((r) => r.key === "params.resolution")?.made).toMatchObject({ value: "1080p", asked: "2K" });+ });++ it("tells a run made on its own in a studio from one a tool made", async () => {+ const id = run(A, { request: { feature: "cinema-scene" } });+ expect(((await (await get(id)).json()) as RunDetails).surface).toMatchObject({ label: "Cinema Studio", standalone: false });+ const own = run(A);+ db().prepare("UPDATE generations SET request_json = json_set(request_json, '$.standalone', json('true')) WHERE id = ?").run(own);+ expect(((await (await get(own)).json()) as RunDetails).surface).toMatchObject({ label: "Image", standalone: true });+ });+});++describe("withMade: what a setting is made at, beside what was asked", () => {+ it("adds the made value to its row, and a row for a setting the request left out", async () => {+ const { withMade } = await import("@/server/run-details");+ const rows = withMade(+ [{ key: "params.resolution", label: "Resolution", value: "2K", hasDefault: true, default: "1080P", state: "changed", sent: true }],+ [+ { setting: "resolution", label: "Quality", asked: "2K", made: "1080p", reason: "the most this model makes", note: "" },+ { setting: "duration", label: "Duration", asked: "Its own", made: "6", reason: "its only length", note: "" },+ ],+ );+ expect(rows[0].made).toEqual({ value: "1080p", asked: "2K", reason: "the most this model makes" });+ expect(rows[1]).toMatchObject({ key: "params.duration", sent: false, made: { value: "6" } });+ });});describe("compareSettings: each setting beside the composer's default", () => {