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
Ideogram 4: make a declined run again before it fails
Adarsh4590c67d9eb0
diff --git a/src/components/account-runs.tsx b/src/components/account-runs.tsxindex 3311b146..c26f4b72 100644--- a/src/components/account-runs.tsx+++ b/src/components/account-runs.tsx@@ -9,6 +9,7 @@ import { adminCall, OffBadge, runsHref, Stat, useAdminAccounts, useAdminAction,import { StatusCover } from "@/components/library/asset-card";import { PageHeader } from "@/components/page-shell";import { GallerySkeleton } from "@/components/skeletons";+import { DeclinedCards } from "@/components/studio/made-note";import { MediaThumb } from "@/components/studio/result-media";import { Button } from "@/components/ui/button";import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";@@ -422,7 +423,10 @@ function RunCard({);}-/** The prompt, two lines until "More" opens it whole, with a failed run's whole error. */+/**+ * The prompt, two lines until "More" opens it whole, with a failed run's whole error, what changed while it ran (its+ * notice), and what Ideogram 4 returned in place of a picture.+ */function RunWords({ g }: { g: AdminRun }) {const [open, setOpen] = useState(false);const prompt = g.request.prompt?.trim() || g.prompt?.trim();@@ -431,6 +435,8 @@ function RunWords({ g }: { g: AdminRun }) {<div className="text-[12px]">{prompt ? <p className={cn("break-words", open ? "whitespace-pre-wrap" : "line-clamp-2")}>{prompt}</p> : <p className="text-muted-foreground italic">No prompt</p>}{open && error && <p className="mt-1 break-words whitespace-pre-wrap text-destructive">{error}</p>}+ {g.request.notice && <p className="mt-1 break-words text-muted-foreground">{g.request.notice}</p>}+ {!!g.declinedCards?.length && <DeclinedCards cards={g.declinedCards} className="mt-1 block break-words text-muted-foreground" />}{((prompt?.length ?? 0) > 120 || error) && (<button type="button" className="text-muted-foreground underline-offset-2 hover:text-foreground hover:underline" aria-expanded={open} onClick={() => setOpen(!open)}>{open ? "Less" : "More"}diff --git a/src/components/library/asset-card.tsx b/src/components/library/asset-card.tsxindex bf960f16..58238edb 100644--- a/src/components/library/asset-card.tsx+++ b/src/components/library/asset-card.tsx@@ -297,6 +297,8 @@ export const AssetCard = memo(function AssetCard({{/* "Rendering", as the Status filter calls it: "In progress" is a review status. */}{!stack && g.status !== "succeeded" && ` · ${listStatus(g)}`}</p>+ {/* What changed while it ran ("Made with Qwen-Image 2.1 · Ideogram 4 declined this one"). */}+ {!stack && g.request.notice && <p className="truncate text-[12px] text-muted-foreground">{g.request.notice}</p>}{/* An account's own GPU or key: the way out, in the row (its thumbnail is too small for it). */}{!stack && !trashed && (g.status === "failed" ? g.trouble : g.status === "queued" ? g.waiting : undefined) && (<RunTroubleActions g={g} className="mt-1" actions={(g.status === "failed" ? g.trouble : g.waiting)!.actions} skip={["retry"]} max={1} compact context={g.status === "failed" ? "run" : "other"} />diff --git a/src/components/studio/made-note.tsx b/src/components/studio/made-note.tsxindex 9b0c9706..056b416c 100644--- a/src/components/studio/made-note.tsx+++ b/src/components/studio/made-note.tsx@@ -3,18 +3,47 @@ import type { Generation } from "@/lib/catalog/types";import { cn } from "@/lib/utils";/**- * Under a finished run (the feed card, the run details): each setting it was made at differently from what it asked, in- * one small muted line ("Quality: asked for 2K · made at 1080p (the most this model makes)"). Nothing when it made- * what it asked.+ * Under a run (the feed card, the run details): each setting it was made at differently from what it asked, in one small+ * muted line ("Quality: asked for 2K · made at 1080p (the most this model makes)"), what changed while it ran (its+ * notice: "Made with Qwen-Image 2.1 · Ideogram 4 declined this one"), and, for the owner's eyes only, what Ideogram 4+ * returned in place of a picture. Nothing when it made what it asked.*/-export function MadeNote({ g, className }: { g: Pick<Generation, "made">; className?: string }) {+export function MadeNote({ g, className }: { g: Pick<Generation, "made" | "declinedCards"> & { request: Pick<Generation["request"], "notice"> }; className?: string }) {const changes = g.made?.changes ?? [];- if (!changes.length) return null;+ const notice = g.request.notice?.trim();+ if (!changes.length && !notice && !g.declinedCards?.length) return null;return (<ul className={cn("space-y-0.5 text-[11.5px] leading-snug text-pretty text-muted-foreground", className)} aria-label="Made differently from what was asked">{changes.map((c) => (<li key={c.setting + c.label}>{changeLine(c)}</li>))}+ {notice && <li>{notice}</li>}+ {!!g.declinedCards?.length && (+ <li>+ <DeclinedCards cards={g.declinedCards} />+ </li>+ )}</ul>);}++/**+ * The owner's line on a run Ideogram 4 declined: a link to each picture it returned in place of one, with the two+ * measures that took it for the "blocked" card, so a false catch can be told from the card.+ */+export function DeclinedCards({ cards, className }: { cards: NonNullable<Generation["declinedCards"]>; className?: string }) {+ return (+ <span className={className}>+ Ideogram 4 declined: what it returned{" "}+ {cards.map((c, i) => (+ <span key={c.url + i}>+ {i > 0 && ", "}+ <a href={c.url} target="_blank" rel="noreferrer" className="underline underline-offset-2 hover:text-foreground">+ {cards.length > 1 ? `picture ${i + 1}` : "picture"}+ </a>{" "}+ (colour spread {c.spread}, {Math.round(c.grey * 100)}% grey)+ </span>+ ))}+ </span>+ );+}diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex 32bfcf9e..9e783aea 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -1579,6 +1579,19 @@ export interface Generation {* request whenever it is read, so older runs carry it too.*/made?: MadeSettings;+ /**+ * The owner's eyes only (their own runs, and Accounts' runs): what Ideogram 4 returned in place of a picture, the grey+ * "blocked" card (src/server/safety-card.ts), kept as a held file nobody else can open, with its measures (`spread`:+ * how far its colours spread; `grey`: the share of neutral mid-grey pixels), so a false catch can be told from the card.+ */+ declinedCards?: DeclinedCard[];+}++/** A picture Ideogram 4 returned that was taken for its "blocked" card (Generation.declinedCards). */+export interface DeclinedCard {+ url: string;+ spread: number;+ grey: number;}/** Why a ComfyUI run failed, when the GPU was missing something (generations.fix_json). */diff --git a/src/lib/ideogram-caption.ts b/src/lib/ideogram-caption.tsindex b76edb2a..655e9ace 100644--- a/src/lib/ideogram-caption.ts+++ b/src/lib/ideogram-caption.ts@@ -115,6 +115,18 @@ export function parseCaption(text: string): string | null {return c ? captionText(c) : null;}+/**+ * A caption's words as plain text, for a model that reads plain words (Qwen-Image 2.1 making a run Ideogram 4 declined):+ * its lead, its scene, then each element's words. Plain words come back as they are.+ */+export function captionWords(text: string): string {+ const c = readCaption(text);+ if (!c) return text;+ const cd = c.compositional_deconstruction;+ const parts = [c.high_level_description, cd.background, ...cd.elements.map((e) => (e.type === "text" && e.text ? `${e.desc} The text reads "${e.text}".` : e.desc))];+ return [...new Set(parts.map((p) => p?.trim()).filter((p): p is string => !!p))].join(" ");+}+/*** The caption when no LLM can write one: the words as the lead and as one element. No style block (a style is never* invented) and one element, since a caption without elements invites the safety card.diff --git a/src/server/account-admin.ts b/src/server/account-admin.tsindex a59014a7..d6dd7f30 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 { listGenerations, type ListOptions } from "./generations";+import { declinedCardsIn, listGenerations, type ListOptions } from "./generations";import { cursorFrom, HELPER_SQL, KINDS } from "./library";/**@@ -208,7 +208,7 @@ export function listAccountRuns(o: ListOptions, show: { content: boolean; emailsitems: 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) };+ const run: AccountRun = { ...g, outputs: withStates(g.outputs), account, ...detail(g), ...declinedCardsIn(g.id) };return show.content ? run : factsOnly(run);}),next: last && found.length === limit ? `${last.createdAt}:${last.id}` : null,diff --git a/src/server/generations.ts b/src/server/generations.tsindex 796f377a..9ae87bba 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -31,7 +31,7 @@ import { imageSize } from "@/lib/image-size";import { finishSteps, mosaicPixels, unionMasks } from "@/lib/soul-post";import { ANGLES_ORIGINAL, MOSAIC_SCALE } from "@/lib/catalog/open-tools";import { computeDimensions } from "@/lib/comfy";-import { captionFromWords, parseCaption } from "@/lib/ideogram-caption";+import { captionFromWords, captionWords, parseCaption } from "@/lib/ideogram-caption";import { h3Frames, h3Prompt, inH3Layout } from "@/lib/h3-prompt";import { h3ReferenceTags, h3TalkPrompt } from "@/lib/h3-references";import {@@ -39,6 +39,7 @@ import {LAST_FRAME_CHAIN,operationOutput,type ChainSlot,+ type DeclinedCard,type Engine,type Generation,type GenerationFix,@@ -62,7 +63,7 @@ import { qwen21Gpu } from "./qwen21-gpu";import { h3Gpu } from "./h3-gpu";import { H3_TIER_PARAM, H3_UNET_PARAM } from "@/lib/gpu/h3-tier";import { DETAILS_MAX_IMAGES, GPU_PARAM, QWEN21_SPEED, speedLora } from "@/lib/qwen21-speed";-import { BLOCKED_CARD_MESSAGE, looksBlocked } from "./safety-card";+import { BLOCKED_CARD_MESSAGE, blockedMeasures, DECLINED_FALLBACK_MODEL, DECLINED_NOTICE, DECLINED_WORDS } from "./safety-card";import { pollTrainings } from "./training";import { createEndFrameClip, createExtendChain, createKeyframeFilm, createMosaicRun, createRefinedModel, createRelitClip, createShotFilm, createStillTo3d, createVoiceFirst, joinClips } from "./chains";import { chainedRefine } from "@/lib/av/hi3d";@@ -219,6 +220,10 @@ export function toGeneration(r: Row): Generation {"SELECT (SELECT deleted_at FROM generation_trash WHERE generation_id = ?) AS deleted_at, (SELECT folder_id FROM folder_items WHERE generation_id = ?) AS folder_id",).get(r.id, r.id) as { deleted_at: number | null; folder_id: string | null });+ // An Ideogram 4 run that returned its "blocked" card (declinedAgain), made again in its place: Working, saying which try+ // it is on (never In line: nobody pressed Run again). One that waits for the account's own GPU to come back shows that.+ const meta = r.external_meta_json?.includes('"declined"') ? readMeta(r.external_meta_json) : undefined;+ const again = (r.status === "queued" || r.status === "running") && !(r.status === "queued" && !r.external_id && meta?.heal) ? declinedWords(meta ?? {}) : undefined;return {id: r.id,batchId: r.batch_id,@@ -229,10 +234,10 @@ export function toGeneration(r: Row): Generation {provider: r.provider,op: r.op,kind: r.kind,- status: r.status,+ status: again ? "running" : r.status,// In line on this install's GPUs (again, after an attempt): no progress.progress: (pool && r.status === "queued") || ready ? null : r.progress,- message: pool ? poolMessage(r, ready) : r.message,+ message: again ?? (pool ? poolMessage(r, ready) : r.message),prompt: r.prompt,request,// Held for the moderation service's check: nothing of it is shown until it passes.@@ -267,15 +272,29 @@ export function toGeneration(r: Row): Generation {// On this install's GPUs the output check is part of "Working": no word of its own....(checking && !pool && { stage: "checking" as const }),// Waiting in line on this install's GPUs: its place and the wait, about.- ...(stored.place === "pool" && (r.status === "queued" || r.status === "running") && !checking && poolQueue(r.id)),+ ...(stored.place === "pool" && (r.status === "queued" || r.status === "running") && !checking && !again && poolQueue(r.id)),// The owner's own job on the workers, waiting: its place in their line (in the list as after a refresh).- ...(stored.place !== "pool" && r.status === "queued" && r.provider === "comfyui" && workerQueue(r.id)),+ ...(stored.place !== "pool" && r.status === "queued" && r.provider === "comfyui" && !again && workerQueue(r.id)),// Working on this install's GPUs: the address of its latest preview picture, while there is one. None for a run// whose outputs the moderation service sees first (a preview would show what its check holds back)....(r.status === "running" && r.provider === "comfyui" && !checking && !stored.checkOutputs && livePreview(r.id)),+ // The owner's own run: what Ideogram 4 returned in place of a picture (an account's run shows it in Accounts' runs).+ ...(!stored.account && declinedCardsOf(meta)),};}+/** What Ideogram 4 returned in place of a picture, kept with the run for the owner (Generation.declinedCards). */+export function declinedCardsOf(meta: { declined?: unknown } | undefined): { declinedCards: DeclinedCard[] } | Record<string, never> {+ const cards = (meta?.declined as DeclinedMeta | undefined)?.cards;+ return Array.isArray(cards) && cards.length ? { declinedCards: cards } : {};+}++/** declinedCardsOf for a stored row (Accounts' runs). */+export function declinedCardsIn(id: string): { declinedCards: DeclinedCard[] } | Record<string, never> {+ const json = db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(id) as string | null | undefined;+ return json?.includes('"declined"') ? declinedCardsOf(readMeta(json)) : {};+}+/** The owner's job waiting for the workers: its place in their line, as the Generation field. */function workerQueue(id: string): { queue: LinePlace } | Record<string, never> {const q = queueOfGeneration(id);@@ -487,8 +506,25 @@ interface PendingMeta {sendingTask?: boolean;/** Who holds the run as the release before this one marked it (OLD_LEASE), and until when. */lease?: { by?: unknown; until?: unknown };+ /**+ * An Ideogram 4 run that returned only its "blocked" card (declinedAgain): which try it is on now (`stage`: made again+ * with a new seed, then with Qwen-Image 2.1), and the cards it returned (kept for the owner). Kept through every hand-over.+ */+ declined?: DeclinedMeta;+}++/** What an Ideogram 4 run that returned its "blocked" card keeps (PendingMeta.declined). */+interface DeclinedMeta {+ stage?: keyof typeof DECLINED_WORDS;+ cards?: DeclinedCard[];+ /** Made with Qwen-Image 2.1 now: the run as Ideogram 4's, put back when that fails too (declinedFails). */+ was?: DeclinedRun;}+/** The columns of a run that Qwen-Image 2.1 changes when it makes a run Ideogram 4 declined. */+type DeclinedRun = Pick<Row, "request_json" | "model_id" | "engine" | "op" | "kind" | "prompt" | "cost_usd">;+const declinedRun = (r: Row): DeclinedRun => ({ request_json: r.request_json, model_id: r.model_id, engine: r.engine, op: r.op, kind: r.kind, prompt: r.prompt, cost_usd: r.cost_usd });+/** A run's wait for its own GPU or key, kept with it (survives a restart). */interface HealState {since: number;@@ -806,7 +842,7 @@ export const ASSET_FREE: Record<string, string> = {"what a failed ComfyUI run was missing (model file names, node classes and packs), and what an account's GPU or key ran into: a cause, a details line and its buttons' links","gpu_snapshots.inventory_json": "what a GPU's ComfyUI has (class names, model file names and sizes), never a Fuobe file","gpu_snapshots.report_json": "readiness built from that inventory",- "generations.external_meta_json": "the provider's job handles",+ "generations.external_meta_json": "the provider's job handles, and the run's own held files (Ideogram 4's declined cards), which go with the run","billing_outbox.payload_json": "reports for the billing service: hold and run ids, counts and words, never a file","run_requests.ids_json": "the ids of the runs one press of Run made, never a file","run_requests.answer_json": "a copy of the answer one press of a tool's Run got, for a resend of it: its runs' own rows keep their files",@@ -2602,6 +2638,9 @@ async function pause(id: string, ms: number): Promise<boolean> {* account's own run, logged and noted for the owner (run-events.ts).*/function failRun(id: string, e: unknown, trouble: Diagnosis | undefined, account: string | undefined, facts?: RunFacts, own = !!facts): boolean {+ // Qwen-Image 2.1 making a run Ideogram 4 declined: it fails as the declined run.+ const declined = declinedFails(id, trouble?.words ?? String((e as Error | null)?.message ?? e));+ if (declined !== null) return declined;const fix = (e as { fix?: GenerationFix } | null)?.fix;const kept = keptFix(fix, trouble);// What the GPU was missing (a model, a node class) is kept, so the tile offers "Fix it", and its GPU check counts as stale.@@ -2890,7 +2929,7 @@ function resend(r: Row, account: string, words: string): boolean {// again meanwhile is left as it is.) It takes its turn to be sent in the same step: a run waiting to be sent again is// never sent by another app process too.const again = db().transaction((): boolean => {- const meta = JSON.stringify({ resent: true, jobIndex: index });+ const meta = JSON.stringify({ resent: true, jobIndex: index, ...(was.declined && { declined: was.declined }) });if (!updateLive(r.id, { external_id: null, external_meta_json: meta, status: "queued", progress: null, message: words }, " AND external_id = @__ext", { __ext: r.external_id })) return false;db().prepare("DELETE FROM generation_runs WHERE id = ?").run(r.id);noteSubmitTurn(r.id);@@ -2906,6 +2945,132 @@ function resend(r: Row, account: string, words: string): boolean {}}+/** The words an Ideogram 4 run made again after it declined shows while it works; undefined for any other run. */+function declinedWords(meta: PendingMeta | Record<string, unknown>): string | undefined {+ const stage = (meta as PendingMeta).declined?.stage;+ return stage && Object.hasOwn(DECLINED_WORDS, stage) ? DECLINED_WORDS[stage] : undefined;+}++/**+ * Files a run returned that are none of its results (Ideogram 4's "blocked" card): held, so no account and no link+ * serves them (only the owner opens them), never in a Library or the account's space, and deleted with the run (its+ * generation_id stays).+ */+function keepForOwner(assetIds: readonly string[]): void {+ const hold = db().prepare("UPDATE assets SET held = 1, account_id = NULL, source = 'derived' WHERE id = ?");+ for (const id of assetIds) hold.run(id);+}++/**+ * What Qwen-Image 2.1 is asked when it makes a run Ideogram 4 declined: the same words in plain text (a caption given as+ * the prompt becomes its words), the same pictures, aspect ratio, size and count, and Qwen-Image 2.1's own settings.+ */+function declinedFallback(stored: GenerationRequest): GenerationRequest {+ const p = stored.params ?? {};+ return {+ ...stored,+ modelId: DECLINED_FALLBACK_MODEL,+ op: stored.inputs?.images?.length ? "edit" : "t2i",+ ...(stored.prompt && { prompt: captionWords(stored.prompt) }),+ params: {+ ...(p.aspectRatio && { aspectRatio: p.aspectRatio }),+ ...(p.resolution && { resolution: p.resolution }),+ ...(p.numOutputs && { numOutputs: p.numOutputs }),+ },+ negativePrompt: undefined,+ };+}++/**+ * An Ideogram 4 run whose every picture was its "blocked" card is made again in its place: the same run (its id, its+ * place, its turn in the line, its billing hold), as the same job of its batch, through the same submit as every run+ * (this install's workers, the owner's ComfyUI, an account's own GPU). First Ideogram 4 once more, with the same caption+ * and a new seed (its refusals are often random); then Qwen-Image 2.1 (declinedFallback), and the run names the model+ * that made it (its model and its request's notice). Neither is a new press of Run: no limit counts it again, and no new+ * row or hold is made. The run's tile says which try it is on. False when both were made already, or a try can't go+ * where the run went: the run fails as before.+ */+function declinedAgain(r: Row, declined: DeclinedMeta): boolean {+ const next = !declined.stage ? "retry" : declined.stage === "retry" ? "fallback" : null;+ if (!next) return false;+ try {+ const stored = JSON.parse(r.request_json) as GenerationRequest;+ const account = stored.account;+ // Planned where the run went: this install's GPUs (its stamp: place, class, hold), the account's own, or the owner's.+ const planned = (req: GenerationRequest) =>+ account && stored.place === "pool"+ ? runOnPool(account, () => withRunStamp(stampOf(stored), () => prepare(req)))+ : account+ ? asAccount(account, () => prepare(req))+ : prepare(req);+ let asked = stored;+ let p: ReturnType<typeof prepare>;+ if (next === "retry") {+ p = planned(stored);+ // The caption it ran with (never written again), and a new seed.+ const caption = r.prompt ? parseCaption(r.prompt) : null;+ p = { ...p, plan: { ...p.plan, ...(caption && { prompt: caption }), params: { ...p.plan.params, seed: crypto.randomInt(0, 2 ** 31) } } };+ } else {+ asked = declinedFallback(stored);+ try {+ p = planned(asked);+ } catch {+ // A preset with no Qwen-Image 2.1 version: its words as they were planned, without the preset.+ const words = captionWords(planned(stored).plan.prompt);+ asked = { ...asked, presetId: undefined, presetOptions: undefined, signature: undefined, prompt: words };+ p = planned(asked);+ }+ }+ if (p.providerId !== r.provider) return false;+ const was = readMeta(r.external_meta_json);+ const index = jobIndexOf(r, was);+ const fields: Partial<Row> = {+ external_id: null,+ external_meta_json: JSON.stringify({ jobIndex: index, declined: { ...declined, stage: next, ...(next === "fallback" && { was: declinedRun(r) }) } }),+ // (Working, as it was: not a new run in line.)+ status: "running",+ progress: null,+ message: DECLINED_WORDS[next],+ ...(next === "fallback" && {+ model_id: p.plan.model.id,+ engine: p.plan.model.engine,+ op: p.plan.op,+ kind: outputKind(p.plan.op, p.plan.model),+ prompt: p.plan.prompt,+ cost_usd: p.cost,+ request_json: JSON.stringify({ ...asked, notice: [stored.notice, DECLINED_NOTICE].filter(Boolean).join(" · ") }),+ }),+ };+ // (Only while the run still goes and is still the job that declined: one another app process saved, ended or sent+ // again meanwhile is left as it is.) It takes its turn to be sent in the same step, and its finish turn goes.+ const again = db().transaction((): boolean => {+ if (!updateLive(r.id, fields, " AND external_id = @__ext", { __ext: r.external_id })) return false;+ db().prepare("DELETE FROM generation_runs WHERE id = ?").run(r.id);+ noteSubmitTurn(r.id);+ return true;+ })();+ if (!again) return true;+ submitting().add(r.id);+ void submit(r.id, p.route, p.providerId, p.plan, p.req, index);+ return true;+ } catch {+ return false;+ }+}++/**+ * Qwen-Image 2.1 couldn't make a run Ideogram 4 declined either: the run fails as Ideogram 4's (its model, request and+ * words put back, so Retry runs what was asked), saying what to try, whether its job failed or couldn't be sent. What+ * Qwen-Image 2.1 said goes to the log. Null: not such a run; else whether the run was failed here (it still went).+ */+function declinedFails(id: string, said: string, metaJson?: string | null): boolean | null {+ const json = metaJson !== undefined ? metaJson : (db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(id) as string | null | undefined);+ const was = readMeta(json).declined;+ if (was?.stage !== "fallback") return null;+ console.warn(`[generations] ${id}: Qwen-Image 2.1 after Ideogram 4 declined: ${said.slice(0, 500)}`);+ return updateLive(id, { ...(was.was ?? {}), status: "failed", error: BLOCKED_CARD_MESSAGE, completed_at: Date.now(), message: null });+}+/*** An account's poll that failed: a key that won't work (refused, no credit, no access) fails the run at once; a passing* problem (its GPU off, its provider busy) is asked again with a growing wait, the tile saying so. A run on its own GPU@@ -3331,10 +3496,17 @@ async function handOver(id: string, route: ModelRoute, providerId: ProviderId, pid,now,external_id: res.externalId,- meta: JSON.stringify({ ...(res.meta ?? {}), ...(sentTo && { sentTo: addressKey(sentTo) }), jobIndex: index, ...(before.resent && { resent: true }) }),+ meta: JSON.stringify({+ ...(res.meta ?? {}),+ ...(sentTo && { sentTo: addressKey(sentTo) }),+ jobIndex: index,+ ...(before.resent && { resent: true }),+ ...(before.declined && { declined: before.declined }),+ }),payload: res.payload ? JSON.stringify(res.payload).slice(0, 200_000) : null,- // A run sent again after its GPU lost it says so until its GPU reports on it.- message: before.resent || resentRuns().has(id) ? RESENT_WORDS : "Queued",+ // A run sent again after its GPU lost it says so until its GPU reports on it; an Ideogram 4 run made again after+ // it declined says that while it works.+ message: declinedWords(before) ?? (before.resent || resentRuns().has(id) ? RESENT_WORDS : "Queued"),}).changes;if (changed) recordSubmission(id, now);return changed > 0;@@ -3945,12 +4117,15 @@ async function pollOne(r: Row): Promise<void> {}if (startsNow) db().prepare("UPDATE generation_runs SET started_at = ? WHERE id = ?").run(Date.now(), r.id);// Back in line (a worker paused, went quiet or gave it back): no progress of the attempt before is kept.- updateLive(r.id, { status: res.state, progress: ownClocks && res.state === "queued" ? null : (res.progress ?? r.progress), message: res.message ?? null });+ // (An Ideogram 4 run made again after it declined says so while it works.)+ updateLive(r.id, { status: res.state, progress: ownClocks && res.state === "queued" ? null : (res.progress ?? r.progress), message: declinedWords(ctx.meta) ?? res.message ?? null });return;}if (res.state === "failed") {// Its GPU restarted and lost the job: an account's run is sent again once, as a computer's tab does.if (own && res.lost && resend(r, own, RESENT_WORDS)) return;+ // Qwen-Image 2.1 making a run Ideogram 4 declined: it fails as the declined run.+ if (declinedFails(r.id, res.error, r.external_meta_json) !== null) return;// An account's run: its own GPU's words (comfyui.ts), or its key's provider's read plainly; the provider's own words// go in the details line. The owner's runs keep the provider's words.const trouble =@@ -4067,16 +4242,27 @@ async function pollOne(r: Row): Promise<void> {}}}- // Ideogram 4's grey "blocked by safety filter" card is no picture (src/server/safety-card.ts): it is deleted, and a run- // left with nothing else fails, saying what to try.+ // Ideogram 4's grey "blocked by safety filter" card is no picture (src/server/safety-card.ts): it is left out of the+ // results and kept for the owner only (keepForOwner), with its measures. A run that got some real pictures keeps them.+ // A run whose every picture was the card is made again in its place (declinedAgain: a new seed, then Qwen-Image 2.1);+ // only when it can't be does it fail, saying what to try.if (model.options.promptFormat === "ideogram4") {- const cards = new Set<OutputFile>();+ const cards = new Map<OutputFile, DeclinedCard>();for (const o of outputs) {const png = o.kind === "image" && o.assetId ? await readRef(o.url).catch(() => null) : null;- if (png && looksBlocked(png.data)) cards.add(o);+ const m = png ? blockedMeasures(png.data) : null;+ if (m?.blocked) cards.set(o, { url: o.url, spread: m.spread, grey: m.grey });+ }+ const was = readMeta(r.external_meta_json).declined;+ const declined: DeclinedMeta = { ...was, cards: [...(was?.cards ?? []), ...cards.values()].slice(-8) };+ if (cards.size) {+ keepForOwner([...cards.keys()].map((o) => o.assetId!));+ db()+ .prepare(`UPDATE generations SET external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.declined', json(?)) WHERE id = ?`)+ .run(JSON.stringify(declined), r.id);}- for (const o of cards) deleteAsset(o.assetId!);if (cards.size && cards.size === outputs.length) {+ if (declinedAgain(r, declined)) return;updateLive(r.id, { status: "failed", error: BLOCKED_CARD_MESSAGE, completed_at: Date.now(), message: null });return;}diff --git a/src/server/safety-card.ts b/src/server/safety-card.tsindex 1ae9ac0b..5994b6f3 100644--- a/src/server/safety-card.ts+++ b/src/server/safety-card.ts@@ -43,11 +43,33 @@ function thumb(img: { width: number; height: number; data: Buffer }, w: number,/** Whether a PNG is the grey card. A picture that can't be read is not (it is kept, for a person to look at). */export function looksBlocked(png: Buffer): boolean {+ return blockedMeasures(png)?.blocked ?? false;+}++/**+ * An Ideogram 4 run whose every picture was the card is made again once with a new seed (its refusals are often+ * random), then with Qwen-Image 2.1, before it fails (src/server/generations.ts declinedAgain): the model of the second+ * try, the words each try shows while it works, and the line a run the second try made carries (its request's notice).+ */+export const DECLINED_FALLBACK_MODEL = "oss-qwen-image-21";+export const DECLINED_WORDS = {+ retry: "Ideogram 4 is trying again",+ fallback: "Making it with Qwen-Image 2.1",+} as const;+export const DECLINED_NOTICE = "Made with Qwen-Image 2.1 · Ideogram 4 declined this one";++/**+ * The card's measures of a picture, for the owner's note on a declined run: `spread`, how far its colours spread (the mean+ * RGB standard deviation on the 128×170 thumbnail: the card's is about 9, real photographs' 26 and up), and `grey`, the+ * share of its pixels that are neutral mid-grey (the card's is over 0.85). `blocked`: whether the two rules call it the+ * card. Null for a picture that can't be read.+ */+export function blockedMeasures(png: Buffer): { spread: number; grey: number; blocked: boolean } | null {let img: ReturnType<typeof decodePng>;try {img = decodePng(png);} catch {- return false;+ return null;}// Rule A's measures (luminance as PIL's "L" conversion).const a = thumb(img, 64, 64);@@ -83,5 +105,6 @@ export function looksBlocked(png: Buffer): boolean {if (Math.abs(r - g) < 8 && Math.abs(g - b) < 8 && r > 90 && r < 140) grey++;}const rgbStd = s.map((v, c) => Math.sqrt(Math.max(0, s2[c] / m - (v / m) ** 2))).reduce((x, y) => x + y) / 3;- return rgbStd < 20 && grey / m > 0.85 && spread < 6 && lumStd < 14 && lumMean > 95 && lumMean < 135;+ const blocked = rgbStd < 20 && grey / m > 0.85 && spread < 6 && lumStd < 14 && lumMean > 95 && lumMean < 135;+ return { spread: Math.round(rgbStd * 10) / 10, grey: Math.round((grey / m) * 1000) / 1000, blocked };}diff --git a/tests/ideogram-declined-pool.test.ts b/tests/ideogram-declined-pool.test.tsnew file mode 100644index 00000000..5b8a6f1d--- /dev/null+++ b/tests/ideogram-declined-pool.test.ts@@ -0,0 +1,222 @@+import crypto from "node:crypto";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import type { Generation } from "@/lib/catalog/types";+import { startFakeBilling, FAKE_POLICY, type FakeBilling } from "./helpers/fake-billing";+import { tempDir } from "./helpers/temp-dir";++/**+ * An account's free Ideogram 4 run on this install's GPUs that comes back as the grey "blocked" card is made again in its+ * place, on the same GPUs: once more with a new seed, then with Qwen-Image 2.1. One press of Run stays one run: the+ * hourly count, the runs at once and the billing hold count it once, and the billing service gets one report for it.+ * The cards are for the owner only (Accounts' runs), never the account's. (The rules themselves on the owner's runs:+ * tests/ideogram-declined.test.ts.)+ */++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+vi.setConfig({ testTimeout: 60_000 });++const dir = tempDir("fuobe-ideogram-declined-pool-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:7";+process.env.OLLAMA_URL = "http://127.0.0.1:7";+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_HOSTED_RUNS;+delete process.env.FUOBE_HOSTED_FREE;+delete process.env.FUOBE_BILLING_URL;+delete process.env.FUOBE_MODERATION_URL;+delete process.env.ANTHROPIC_API_KEY;+globalThis.__fuobeTestDiskFree = 1e13;++const realFetch = globalThis.fetch;+let allowed: string[] = [];+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input instanceof Request ? input.url : input);+ if (allowed.some((a) => url.startsWith(a))) return realFetch(input, init);+ return new Response("not reachable in this test", { status: 599 });+}) as typeof fetch;++const auth = await import("@/server/auth");+const generationsRoute = await import("@/app/api/generations/route");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { setSetting } = await import("@/server/settings");+const pool = await import("@/server/computer/pool");+const { catalogVersion } = await import("@/server/computer/catalog-version");+const billing = await import("@/server/billing");+const { queueReports } = await import("@/server/billing-outbox");+const limits = await import("@/server/pool-limits");+const { comfyProvider, loadManifest } = await import("@/server/providers/comfyui");+const { loadIndex } = await import("@/server/gpu/index-file");+const { allLanes } = await import("@/lib/lanes");+const { getGeneration } = await import("@/server/generations");+const { listAccountRuns } = await import("@/server/account-admin");+const { DECLINED_NOTICE, DECLINED_WORDS } = await import("@/server/safety-card");+const { encodePng } = await import("@/server/png");++const HOST = "localhost:3000";+const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");++const png = (w: number, h: number, at: (x: number, y: number) => [number, number, number]) => {+ const data = Buffer.alloc(w * h * 4);+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) data.set([...at(x, y), 255], (y * w + x) * 4);+ return encodePng({ width: w, height: h, data });+};+const card = png(640, 480, (x, y) => (y > 232 && y < 248 && x > 180 && x < 460 && x % 4 < 2 ? [58, 58, 57] : [120, 118, 116]));+const gradient = png(640, 480, (x, y) => [Math.round((x / 639) * 255), Math.round((y / 479) * 255), 128]);+const dataUri = (b: Buffer) => `data:image/png;base64,${b.toString("base64")}`;++let fake: FakeBilling;+let n = 0;++function account() {+ const a = auth.createAccount(`declined-${++n}@example.com`, "long enough");+ return { id: a.id, cookie: `${auth.SESSION_COOKIE}=${auth.createSession(a.id).value}` };+}++const post = async (body: Record<string, unknown>, cookie: string) => {+ const text = JSON.stringify(body);+ const r = await generationsRoute.POST(+ new Request(`http://${HOST}/api/generations`, { method: "POST", headers: { ...SITE_HEADERS, cookie, "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }, body: text }),+ );+ return { status: r.status, body: (await r.json()) as { items?: { id: string }[]; code?: string; error?: string } };+};++/** A worker as the owner adds it, connected: the line is open for the account's runs. */+function standInWorker() {+ const w = pool.addWorker(`stand-in-${++n}`);+ const lanes = allLanes(loadIndex(), sha);+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l.lane, { delayMs: 0 }])), claimAfterMs: 0 });+ db()+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ?, catalog_version = ?, protocol = 3 WHERE id = ?")+ .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), catalogVersion(), w.id);+ db().prepare("UPDATE relay_workers SET seen_at = ?, paused_local = 0 WHERE id = ?").run(Date.now(), w.id);+ return w;+}++const tick = () => globalThis.__fuobeRunner?.tick();+async function settled(id: string): Promise<Generation> {+ const end = Date.now() + 30_000;+ for (;;) {+ await tick();+ const g = getGeneration(id)!;+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;+ if (Date.now() > end) throw new Error(`${id} is still ${g.status}`);+ await new Promise((r) => setTimeout(r, 25));+ }+}++/** The jobs the GPUs were sent (the workers' side is stood in for: each job answers at its first look). */+let sent: { model: string; id: string; tile: Generation; going: number; hourly: number }[] = [];+let ideogram: Buffer[][] = [];+const submit = comfyProvider.submit;+const poll = comfyProvider.poll;+const answers = new Map<string, Buffer[]>();+let accountId = "";++const admitted = (id: string) => db().prepare("SELECT COUNT(*) FROM pool_admissions WHERE account = ?").pluck().get(id) as number;+const rowsOf = (id: string) => db().prepare("SELECT COUNT(*) FROM generations WHERE json_extract(request_json, '$.account') = ?").pluck().get(id) as number;++beforeAll(async () => {+ fake = await startFakeBilling();+ allowed = [fake.url];+ auth.setPassword("install password");+});+afterAll(async () => {+ globalThis.fetch = realFetch;+ globalThis.__fuobeTestDiskFree = undefined;+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];+ await fake.close();+});+beforeEach(() => {+ resetRates();+ billing.resetBillingCache();+ process.env.FUOBE_HOSTED_RUNS = "1";+ process.env.FUOBE_HOSTED_FREE = "1";+ delete process.env.FUOBE_BILLING_URL;+ delete process.env.FUOBE_BILLING_TOKEN;+ fake.policy = { ...FAKE_POLICY };+ setSetting("comfyWhere", "workers");+ setSetting("comfyUrl", "");+ setSetting("engineMode", "open");+ setSetting("demoMode", "off");+ setSetting("enhanceProvider", "none");+ db().prepare("DELETE FROM relay_workers").run();+ standInWorker();+ sent = [];+ ideogram = [];+ answers.clear();+ comfyProvider.submit = async (ctx) => {+ sent.push({ model: ctx.model.id, id: ctx.generationId, tile: getGeneration(ctx.generationId)!, going: limits.accountActiveRuns(accountId), hourly: admitted(accountId) });+ return { externalId: `job-${crypto.randomUUID()}`, meta: {} };+ };+ comfyProvider.poll = async (ctx) => {+ let pics = answers.get(ctx.externalId);+ if (!pics) answers.set(ctx.externalId, (pics = ctx.model.id === "oss-ideogram-4" ? (ideogram.shift() ?? [gradient]) : [gradient]));+ return { state: "succeeded", outputs: pics.map((p) => ({ url: dataUri(p), kind: "image" as const })) };+ };+});+afterEach(() => {+ comfyProvider.submit = submit;+ comfyProvider.poll = poll;+});++describe("an account's free Ideogram 4 run on this install's GPUs that comes back as the card", () => {+ it("is made again there, then by Qwen-Image 2.1, and counts as one run", async () => {+ const a = account();+ accountId = a.id;+ ideogram = [[card], [card]];+ const r = await post({ feature: "image", modelId: "oss-ideogram-4", prompt: "a red fox in deep snow", params: { aspectRatio: "4:5" } }, a.cookie);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ const id = r.body.items![0].id;+ const g = await settled(id);+ expect(g.status, g.error ?? "").toBe("succeeded");+ expect(g.place).toBe("pool");+ expect(g.modelId).toBe("oss-qwen-image-21");+ expect(g.request.notice).toBe(DECLINED_NOTICE);+ expect(g.outputs).toHaveLength(1);+ // Three jobs, all for the one run, on the same GPUs.+ expect(sent.map((s) => [s.model, s.id])).toEqual([+ ["oss-ideogram-4", id],+ ["oss-ideogram-4", id],+ ["oss-qwen-image-21", id],+ ]);+ // While it was made again, its tile said Working in plain words, and it was still one run going, let in once.+ expect(sent[1].tile.status).toBe("running");+ expect(sent[1].tile.message).toBe(DECLINED_WORDS.retry);+ expect(sent[1].tile.queue).toBeUndefined();+ expect(sent[2].tile.message).toBe(DECLINED_WORDS.fallback);+ expect(sent.map((s) => s.going)).toEqual([1, 1, 1]);+ expect(sent.map((s) => s.hourly)).toEqual([1, 1, 1]);+ expect(admitted(a.id)).toBe(1);+ expect(rowsOf(a.id)).toBe(1);+ // The account never sees what Ideogram 4 returned; the owner does, in Accounts' runs.+ expect(g.declinedCards).toBeUndefined();+ const listed = listAccountRuns({ account: a.id }).items.find((x) => x.id === id)!;+ expect(listed.declinedCards).toHaveLength(2);+ });++ it("with a billing service: one hold, and one report for the run", async () => {+ process.env.FUOBE_BILLING_URL = fake.url;+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";+ billing.resetBillingCache();+ const a = account();+ accountId = a.id;+ ideogram = [[card], [gradient]];+ const reserves = fake.calls_of("/v1/reserve").length;+ const r = await post({ feature: "image", modelId: "oss-ideogram-4", prompt: "a lighthouse at dusk", shown: { amount: 7, priceVersion: "v7" } }, a.cookie);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ const id = r.body.items![0].id;+ const g = await settled(id);+ expect(g.status, g.error ?? "").toBe("succeeded");+ expect(g.modelId).toBe("oss-ideogram-4");+ expect(sent.map((s) => s.model)).toEqual(["oss-ideogram-4", "oss-ideogram-4"]);+ expect(fake.calls_of("/v1/reserve").length - reserves).toBe(1);+ expect(admitted(a.id)).toBe(1);+ queueReports();+ const reports = db().prepare("SELECT kind FROM billing_outbox WHERE key = ?").pluck().all(id) as string[];+ expect(reports).toEqual(["settle"]);+ expect(db().prepare("SELECT COUNT(*) FROM billing_outbox WHERE hold_id = (SELECT json_extract(request_json, '$.hold') FROM generations WHERE id = ?)").pluck().get(id)).toBe(1);+ });+});diff --git a/tests/ideogram-declined.test.ts b/tests/ideogram-declined.test.tsnew file mode 100644index 00000000..a94f72a6--- /dev/null+++ b/tests/ideogram-declined.test.ts@@ -0,0 +1,192 @@+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { renderToStaticMarkup } from "react-dom/server";+import type { GenInput, Generation } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";++// An Ideogram 4 run whose every picture is its grey "blocked" card is made again in its place: once more with a new seed,+// then with Qwen-Image 2.1, and only then does it fail. A run with some real pictures keeps them, as before. The cards are+// kept for the owner only. (Runs on this install's GPUs, and their limits: tests/ideogram-declined-pool.test.ts.)+vi.setConfig({ testTimeout: 60_000 });+const dir = tempDir("fuobe-ideogram-declined-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9"; // nothing listens here: runs fall back to the demo+process.env.OLLAMA_URL = "http://127.0.0.1:9";+delete process.env.ANTHROPIC_API_KEY;++const { setSetting } = await import("@/server/settings");+const { createGenerations, getGeneration } = await import("@/server/generations");+const { mockProvider } = await import("@/server/providers/mock");+const { BLOCKED_CARD_MESSAGE, DECLINED_NOTICE, DECLINED_WORDS, blockedMeasures } = await import("@/server/safety-card");+const { encodePng } = await import("@/server/png");+const { getAsset, listAssets } = await import("@/server/storage");+const { db } = await import("@/server/db");+const { fileAccount, HELD_FILE } = await import("@/server/account-library");+const { captionFromWords } = await import("@/lib/ideogram-caption");+const { MadeNote } = await import("@/components/studio/made-note");++/** A picture drawn pixel by pixel, as a PNG. */+const png = (w: number, h: number, at: (x: number, y: number) => [number, number, number]) => {+ const data = Buffer.alloc(w * h * 4);+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) data.set([...at(x, y), 255], (y * w + x) * 4);+ return encodePng({ width: w, height: h, data });+};+// The card: flat, slightly warm mid-grey, one line of dark type across the middle.+const card = png(640, 480, (x, y) => (y > 232 && y < 248 && x > 180 && x < 460 && x % 4 < 2 ? [58, 58, 57] : [120, 118, 116]));+const gradient = png(640, 480, (x, y) => [Math.round((x / 639) * 255), Math.round((y / 479) * 255), 128]);+const dataUri = (b: Buffer) => `data:image/png;base64,${b.toString("base64")}`;++/** Ideogram 4's answer to each job it is sent, in order (its pictures); Qwen-Image 2.1 makes its own, or fails. */+let ideogram: Buffer[][] = [];+let qwenFails = false;+/** Each job handed to the provider: which model, what it got, and how the run read at that moment. */+let handed: { model: string; input: GenInput; run: Generation }[] = [];+const submit = mockProvider.submit;+const poll = mockProvider.poll;+const answers = new Map<string, Buffer[]>();++beforeAll(() => setSetting("demoMode", "auto"));+beforeEach(() => {+ setSetting("enhanceProvider", "none");+ ideogram = [];+ qwenFails = false;+ handed = [];+ answers.clear();+ mockProvider.submit = async (ctx) => {+ handed.push({ model: ctx.model.id, input: ctx.input, run: getGeneration(ctx.generationId)! });+ return submit(ctx);+ };+ mockProvider.poll = async (ctx) => {+ if (ctx.model.id === "oss-ideogram-4") {+ let pics = answers.get(ctx.externalId);+ if (!pics) answers.set(ctx.externalId, (pics = ideogram.shift() ?? [gradient]));+ return { state: "succeeded", outputs: pics.map((p) => ({ url: dataUri(p), kind: "image" as const })) };+ }+ if (ctx.model.id === "oss-qwen-image-21" && qwenFails) return { state: "failed", error: "Out of memory on the GPU" };+ return poll(ctx);+ };+});+afterEach(() => {+ mockProvider.submit = submit;+ mockProvider.poll = poll;+});++const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));+async function settled(id: string, ms = 30_000): Promise<Generation> {+ const end = Date.now() + ms;+ for (;;) {+ const g = getGeneration(id)!;+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;+ if (Date.now() > end) throw new Error(`${id} is still ${g.status}`);+ await sleep(50);+ }+}+async function run(params: Record<string, unknown> = {}) {+ const made = createGenerations({ feature: "image", modelId: "oss-ideogram-4", prompt: "a red fox in deep snow", params });+ expect(made).toHaveLength(1);+ return settled(made[0].id);+}+/** The run's files, as stored. */+const filesOf = (id: string) => db().prepare("SELECT id FROM assets WHERE generation_id = ?").pluck().all(id) as string[];+const rowsLike = (id: string) => (db().prepare("SELECT COUNT(*) FROM generations WHERE created_at >= (SELECT created_at FROM generations WHERE id = ?)").pluck().get(id) as number);++describe("Ideogram 4 that declines a run", () => {+ it("measures the card apart from real pictures", () => {+ expect(blockedMeasures(card)).toMatchObject({ blocked: true });+ expect(blockedMeasures(card)!.spread).toBeLessThan(20);+ expect(blockedMeasures(card)!.grey).toBeGreaterThan(0.85);+ expect(blockedMeasures(gradient)).toMatchObject({ blocked: false });+ expect(blockedMeasures(Buffer.from("not a picture"))).toBeNull();+ });++ it("runs once more with a new seed, as the same run, and keeps what it made then", async () => {+ ideogram = [[card], [gradient]];+ const g = await run({ seed: 41 });+ expect(g.status, g.error ?? "").toBe("succeeded");+ expect(g.modelId).toBe("oss-ideogram-4");+ expect(g.outputs).toHaveLength(1);+ expect(g.request.notice).toBeUndefined();+ // Two jobs of the one run: the same caption, a new seed; the second said what it was doing while it worked.+ const jobs = handed.filter((h) => h.model === "oss-ideogram-4");+ expect(jobs).toHaveLength(2);+ expect(jobs[1].input.prompt).toBe(jobs[0].input.prompt);+ expect(jobs[0].input.prompt).toBe(captionFromWords("a red fox in deep snow"));+ expect(jobs[0].input.seed).toBe(41);+ expect(jobs[1].input.seed).not.toBe(41);+ expect(jobs[1].run.status).toBe("running");+ expect(jobs[1].run.message).toBe(DECLINED_WORDS.retry);+ expect(rowsLike(g.id)).toBe(1);+ // The card stays with the run for the owner: held (no account and no link serves it), out of every file list.+ expect(g.declinedCards).toHaveLength(1);+ const kept = filesOf(g.id).map((id) => getAsset(id)!).find((a) => a.url === g.declinedCards![0].url)!;+ expect(kept.source).toBe("derived");+ expect(fileAccount(kept.relPath)).toBe(HELD_FILE);+ expect(listAssets({ limit: 1000 }).some((a) => a.id === kept.id)).toBe(false);+ expect(g.outputs.some((o) => o.url === kept.url)).toBe(false);+ });++ it("declined again: Qwen-Image 2.1 makes it, from the same words, in the same shape, and the run says so", async () => {+ ideogram = [[card], [card]];+ const g = await run({ aspectRatio: "16:9", resolution: "1.5K", extra: { preset: "Turbo" } });+ expect(g.status, g.error ?? "").toBe("succeeded");+ expect(g.modelId).toBe("oss-qwen-image-21");+ expect(g.modelName).toBe("Qwen-Image 2.1");+ expect(g.request.notice).toBe(DECLINED_NOTICE);+ expect(g.outputs).toHaveLength(1);+ expect(rowsLike(g.id)).toBe(1);+ const qwen = handed.filter((h) => h.model === "oss-qwen-image-21");+ expect(qwen).toHaveLength(1);+ // Plain words (never the caption), the shape and size asked, none of Ideogram 4's own settings.+ expect(qwen[0].input.prompt).toBe("a red fox in deep snow");+ expect(qwen[0].input.aspectRatio).toBe("16:9");+ expect(qwen[0].input.resolution).toBe("1.5K");+ expect(qwen[0].input.extra?.preset).toBeUndefined();+ expect(qwen[0].run.message).toBe(DECLINED_WORDS.fallback);+ expect(qwen[0].run.status).toBe("running");+ // Both cards are the owner's to look at.+ expect(g.declinedCards).toHaveLength(2);+ // The tile's one plain line, and the owner's line with what Ideogram 4 returned.+ const html = renderToStaticMarkup(MadeNote({ g })!);+ expect(html).toContain("Made with Qwen-Image 2.1 · Ideogram 4 declined this one");+ expect(html).toContain("Ideogram 4 declined: what it returned");+ // Someone else's eyes (an account's own run never carries the cards): only the plain line.+ const theirs = renderToStaticMarkup(MadeNote({ g: { ...g, declinedCards: undefined } })!);+ expect(theirs).toContain(DECLINED_NOTICE);+ expect(theirs).not.toContain("what it returned");+ });++ it("when Qwen-Image 2.1 can't make it either, the run fails as Ideogram 4's, in the words it always had", async () => {+ ideogram = [[card], [card]];+ qwenFails = true;+ const g = await run();+ expect(g.status).toBe("failed");+ expect(g.error).toBe(BLOCKED_CARD_MESSAGE);+ expect(g.outputs).toEqual([]);+ // Put back as it was asked, so Retry runs Ideogram 4 again.+ expect(g.modelId).toBe("oss-ideogram-4");+ expect(g.request.modelId).toBe("oss-ideogram-4");+ expect(g.request.notice).toBeUndefined();+ expect(handed.map((h) => h.model)).toEqual(["oss-ideogram-4", "oss-ideogram-4", "oss-qwen-image-21"]);+ expect(rowsLike(g.id)).toBe(1);+ // No result kept; the two cards stay for the owner, and go with the run.+ expect(g.declinedCards).toHaveLength(2);+ expect(listAssets({ source: "generation", limit: 1000 }).filter((a) => a.generationId === g.id)).toEqual([]);+ });++ it("some real pictures and some cards: the real ones are kept and nothing runs again", async () => {+ ideogram = [[card, gradient]];+ const g = await run();+ expect(g.status, g.error ?? "").toBe("succeeded");+ expect(g.modelId).toBe("oss-ideogram-4");+ expect(g.outputs).toHaveLength(1);+ expect(g.request.notice).toBeUndefined();+ expect(handed.map((h) => h.model)).toEqual(["oss-ideogram-4"]);+ expect(g.declinedCards).toHaveLength(1);+ });++ it("a run with no card is left as it was", async () => {+ const g = await run();+ expect(g.status).toBe("succeeded");+ expect(g.declinedCards).toBeUndefined();+ expect(handed).toHaveLength(1);+ });+});diff --git a/tests/open-ideogram-4.test.ts b/tests/open-ideogram-4.test.tsindex d8af1ff6..addc5805 100644--- a/tests/open-ideogram-4.test.ts+++ b/tests/open-ideogram-4.test.ts@@ -421,12 +421,14 @@ describe("Ideogram 4's grey safety card", () => {}}- it("fails the run with what to try, and keeps no file of it", async () => {+ it("never keeps the card as a result: the run is made again in its place (tests/ideogram-declined.test.ts)", async () => {const g = await answered(card);- expect(g.status).toBe("failed");- expect(g.error).toBe("Ideogram 4 declined this one. Run it again, or try Qwen-Image 2.1 or Krea 2 Realism.");- expect(g.outputs).toEqual([]);- expect(listAssets({ source: "generation", limit: 1000 }).filter((a) => a.generationId === g.id)).toEqual([]);+ expect(g.status, g.error ?? "").toBe("succeeded");+ expect(g.modelId).toBe("oss-qwen-image-21");+ expect(g.outputs).toHaveLength(1);+ // The card is no result of the run (only the owner's held copy is kept with it).+ expect(listAssets({ source: "generation", limit: 1000 }).filter((a) => a.generationId === g.id)).toHaveLength(1);+ expect(g.declinedCards?.length).toBe(2);});it("keeps a real picture", async () => {