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
Auto: the model order for prompts the list matches is a setting
Adarshc2d94d951561
diff --git a/src/components/add-auto-pattern.tsx b/src/components/add-auto-pattern.tsxindex 98e09a5a..b1107df1 100644--- a/src/components/add-auto-pattern.tsx+++ b/src/components/add-auto-pattern.tsx@@ -20,7 +20,7 @@ export function withAutoPattern(saved: string, line: string): string | null {/*** The owner's "Add a pattern" on a run Ideogram 4 declined: a word, phrase or pattern (the words selected on the page, to- * start with) goes on Auto's list in Settings, so Auto starts such prompts on Krea 2 Realism and their run details name+ * start with) goes on Auto's list in Settings, so Auto starts such prompts on the models set for them and their run details name* the line. Owner only: the settings it changes are the owner's (an account gets a 403).*/export function AddAutoPattern({ className }: { className?: string }) {@@ -41,7 +41,7 @@ export function AddAutoPattern({ className }: { className?: string }) {const res = await fetch("/api/settings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ autoImagePatterns: next }) });const body = (await res.json().catch(() => ({}))) as { error?: string };if (!res.ok || body.error) throw new Error(body.error ?? "Couldn't save the pattern");- toast.success("Added: Auto sends prompts like this to Krea 2 Realism");+ toast.success("Added: Auto sends prompts like this to the models set for the list");setLine(null);} catch (e) {toast.error((e as Error).message);diff --git a/src/components/auto-patterns-setting.tsx b/src/components/auto-patterns-setting.tsxindex 2f71e3e2..91f39bc0 100644--- a/src/components/auto-patterns-setting.tsx+++ b/src/components/auto-patterns-setting.tsx@@ -1,13 +1,16 @@"use client";+import { useQuery } from "@tanstack/react-query";+import { ArrowDown, ArrowUp, X } from "lucide-react";import { useState } from "react";import { Button } from "@/components/ui/button";import { Label } from "@/components/ui/label";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import type { PublicSetting } from "@/components/connect-field";-import { autoPatternsProblems, DEFAULT_AUTO_PATTERNS } from "@/lib/auto-image";+import { AUTO_IMAGE, AUTO_TRIGGER_MAX, autoPatternsProblems, DEFAULT_AUTO_PATTERNS, DEFAULT_TRIGGER_MODELS, triggerModelIds } from "@/lib/auto-image";/**- * Settings → Auto image model: the prompts Auto starts on Krea 2 Realism (as it does every plain prompt), whose run+ * Settings → Auto image model: the prompts Auto starts on the models set for them (AutoTriggerModelsSetting), whose run* details name the line they matched, one per line. The owner's only, as every setting is. Saving checks each line;* Reset puts the built-in list back.*/@@ -25,7 +28,7 @@ export function AutoPatternsSetting({ setting, onSave, saving }: { setting: Publreturn (<div className="space-y-2"><Label htmlFor="setting-auto-patterns" className="text-[13px] font-medium">- Prompts that go to Krea 2 Realism+ Prompts that go to the models below</Label><textareaid="setting-auto-patterns"@@ -57,3 +60,94 @@ export function AutoPatternsSetting({ setting, onSave, saving }: { setting: Publ</div>);}++/** The open text-to-image models switched on here (GET /api/models), Auto itself left out. */+function useT2iModels() {+ return useQuery({+ queryKey: ["models", "auto-trigger"],+ queryFn: async () => {+ const body = (await (await fetch("/api/models?kind=image&engine=open&op=t2i")).json()) as { items?: { id: string; name: string; hidden?: boolean }[] };+ return (body.items ?? []).filter((m) => m.id !== AUTO_IMAGE && !m.hidden);+ },+ staleTime: 60_000,+ });+}++/**+ * Settings → Auto image model: the models for prompts the list above matches, in order (autoTriggerModels). Auto plans+ * the first that is switched on and fits the GPU; when one fails, the next makes the run. Saved as model ids separated by+ * commas; Reset puts the built-in order back.+ */+export function AutoTriggerModelsSetting({ setting, onSave, saving }: { setting: PublicSetting | undefined; onSave: (value: string) => void; saving: boolean }) {+ const savedText = setting?.isSet ? setting.value : "";+ const saved = savedText.trim() ? triggerModelIds(savedText) : [...DEFAULT_TRIGGER_MODELS];+ const [list, setList] = useState<string[]>(saved);+ // A save changes what is saved: the list follows it.+ const [shown, setShown] = useState(saved.join(","));+ if (shown !== saved.join(",")) {+ setShown(saved.join(","));+ setList(saved);+ }+ const models = useT2iModels();+ const on = models.data ?? [];+ const nameOf = (id: string) => on.find((m) => m.id === id)?.name;+ const addable = on.filter((m) => !list.includes(m.id));+ const move = (i: number, by: -1 | 1) =>+ setList((l) => {+ const next = [...l];+ [next[i], next[i + by]] = [next[i + by], next[i]];+ return next;+ });+ const changed = list.join(",") !== saved.join(",");+ return (+ <div className="space-y-2">+ <Label id="setting-auto-trigger-models" className="text-[13px] font-medium">+ Models for these prompts, in order+ </Label>+ <ol aria-labelledby="setting-auto-trigger-models" className="divide-y rounded-xl border bg-background">+ {list.map((id, i) => (+ <li key={id} data-trigger-model={id} className="flex items-center gap-2 px-3 py-2 text-[13px]">+ <span className="w-5 shrink-0 text-right tabular-nums text-muted-foreground">{i + 1}</span>+ <span className="min-w-0 flex-1 truncate">+ {nameOf(id) ?? id}+ {models.isSuccess && !nameOf(id) && <span className="ml-2 text-[12px] text-muted-foreground">Switched off: skipped</span>}+ </span>+ <Button size="icon-sm" variant="ghost" aria-label={`Move ${nameOf(id) ?? id} up`} disabled={i === 0} onClick={() => move(i, -1)}>+ <ArrowUp />+ </Button>+ <Button size="icon-sm" variant="ghost" aria-label={`Move ${nameOf(id) ?? id} down`} disabled={i === list.length - 1} onClick={() => move(i, 1)}>+ <ArrowDown />+ </Button>+ <Button size="icon-sm" variant="ghost" aria-label={`Remove ${nameOf(id) ?? id}`} disabled={list.length === 1} onClick={() => setList((l) => l.filter((m) => m !== id))}>+ <X />+ </Button>+ </li>+ ))}+ </ol>+ <Select value="" onValueChange={(id) => setList((l) => (l.includes(id) ? l : [...l, id]))} disabled={!addable.length || list.length >= AUTO_TRIGGER_MAX}>+ <SelectTrigger aria-label="Add a model" className="w-full sm:w-auto sm:min-w-56">+ <SelectValue placeholder="Add a model" />+ </SelectTrigger>+ <SelectContent>+ {addable.map((m) => (+ <SelectItem key={m.id} value={m.id}>+ {m.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <p className="text-[12px] leading-relaxed text-muted-foreground">+ Auto starts on the first model that is switched on and fits the GPU. When one can’t make the run, the next one makes it, each at most+ once. Up to {AUTO_TRIGGER_MAX} models.+ </p>+ <div className="flex gap-2">+ <Button size="sm" disabled={!changed || !list.length || saving} onClick={() => onSave(list.join(","))}>+ Save+ </Button>+ <Button size="sm" variant="outline" disabled={saving || !setting?.isSet} onClick={() => onSave("")}>+ Reset to default+ </Button>+ </div>+ </div>+ );+}diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsxindex cc9ad17d..5cb5ec36 100644--- a/src/components/settings-form.tsx+++ b/src/components/settings-form.tsx@@ -30,7 +30,7 @@ import { ConnectorSettings } from "@/components/assist/connectors-settings";import { NotificationSettings } from "@/components/notification-settings";import { SecuritySettings } from "@/components/security-settings";import { radioKeys, radioTab } from "@/components/studio/radio-keys";-import { AutoPatternsSetting } from "@/components/auto-patterns-setting";+import { AutoPatternsSetting, AutoTriggerModelsSetting } from "@/components/auto-patterns-setting";import { UploadSwitchesSettings } from "@/components/upload-switches-settings";function Section({@@ -802,10 +802,11 @@ export function SettingsForm({ prices }: { prices?: string }) {<Sectionid="auto-image"title="Auto image model"- description="Auto is the Image studio's first pick on the open engine: MiniMax H3 Image first for every picture, then Krea 2 Realism, or MOSS-Image for lettering, posters and logos; Qwen-Image 2.1 for edits. MiniMax H3 Image runs where the GPU has about 32 GB and its files; elsewhere Auto starts on the next model. When a model is switched off, can't run or fails, the next one makes the same run, at no extra charge. Prompts that match the lines below start on Krea 2 Realism instead, and their run details name the line."+ description="Auto is the Image studio's first pick on the open engine: MiniMax H3 Image first for every picture, then Krea 2 Realism, or MOSS-Image for lettering, posters and logos; Qwen-Image 2.1 for edits. MiniMax H3 Image runs where the GPU has about 32 GB and its files; elsewhere Auto starts on the next model. When a model is switched off, can't run or fails, the next one makes the same run, at no extra charge. Prompts that match the lines below go to the models set for them below, in order, and their run details name the line."inactive={mode === "cloud" ? "Not used in Paid APIs only mode" : undefined}><AutoPatternsSetting setting={get("autoImagePatterns")} saving={save.isPending} onSave={set("autoImagePatterns")} />+ <AutoTriggerModelsSetting setting={get("autoTriggerModels")} saving={save.isPending} onSave={set("autoTriggerModels")} /></Section><Sectiondiff --git a/src/components/studio/made-note.tsx b/src/components/studio/made-note.tsxindex 09e8c2e0..c8b14c27 100644--- a/src/components/studio/made-note.tsx+++ b/src/components/studio/made-note.tsx@@ -34,8 +34,8 @@ export function MadeNote({ g, className }: { g: NoteRun; className?: string }) {/*** 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; the words it declined- * (`words`, where the view doesn't show them already); and "Add a pattern", which sends such words to Krea 2 Realism- * next time Auto picks (Settings → Auto image model).+ * (`words`, where the view doesn't show them already); and "Add a pattern", which sends such words to the models set for+ * the list next time Auto picks (Settings → Auto image model).*/export function DeclinedCards({ cards, words, className }: { cards: NonNullable<Generation["declinedCards"]>; words?: string; className?: string }) {const said = words?.trim();diff --git a/src/lib/auto-image.ts b/src/lib/auto-image.tsindex d3e94bf5..002bc0d9 100644--- a/src/lib/auto-image.ts+++ b/src/lib/auto-image.ts@@ -17,13 +17,13 @@ export const AUTO_NAME = "Auto";* run goes to can't take it, Auto starts on the next model.*/export const AUTO_LEAD_MODEL = "oss-minimax-h3-image";-/** Next for a plain prompt, and first for a prompt the setting's patterns match: natural skin, light and faces. */+/** Next for a plain prompt, and first in the built-in order for prompts the patterns match: natural skin, light and faces. */export const AUTO_PHOTO_MODEL = "oss-krea2-realism";/** Next for lettering (posters, logos, signs, words in quotes): MOSS-Image follows the words and draws them in place. */export const AUTO_TEXT_MODEL = "oss-moss-image";/*** Auto's text-to-image models, in order for a plain prompt (lettering takes MOSS-Image before Krea 2 Realism; a prompt the- * patterns match starts on Krea 2 Realism). When one is switched off or can't run here, the run is planned on the next;+ * patterns match follows the order for matched prompts, DEFAULT_TRIGGER_MODELS or the saved one). When one is switched off or can't run here, the run is planned on the next;* when it fails, the next makes the same run (src/server/generations.ts autoFails), each model at most once.*/export const AUTO_T2I_MODELS = [AUTO_LEAD_MODEL, AUTO_PHOTO_MODEL, AUTO_TEXT_MODEL] as const;@@ -48,10 +48,71 @@ export const AUTO_EDIT_MODELS: Readonly<Partial<Record<Operation, readonly strinoutpaint: ["oss-qwen-image-21"],};-/** The models Auto may plan an operation on: text to image on AUTO_T2I_MODELS, the others on AUTO_EDIT_MODELS. */-export const autoModelsFor = (op: Operation): readonly string[] => (op === "t2i" ? AUTO_T2I_MODELS : (AUTO_EDIT_MODELS[op] ?? []));+/**+ * The built-in order for a prompt the setting's patterns match. Settings → Auto image model can save another+ * (autoTriggerModels, key auto.triggerModels: model ids, comma-separated); an empty value means this one.+ */+export const DEFAULT_TRIGGER_MODELS: readonly string[] = [AUTO_PHOTO_MODEL, AUTO_LEAD_MODEL, AUTO_TEXT_MODEL];+/** How many models the order may list. */+export const AUTO_TRIGGER_MAX = 10;++/** The fields of a catalog model the order's checks read. */+export interface AutoModelLike {+ engine: string;+ kind: string;+ hidden?: boolean;+ routes: readonly { op: string }[];+}++/** A model the order may list: an open-engine image model in the catalog that makes text to image (never Auto itself). */+export const autoT2iModel = (id: string, m: AutoModelLike | undefined): boolean =>+ !!m && id !== AUTO_IMAGE && m.engine === "open" && m.kind === "image" && !m.hidden && m.routes.some((r) => r.op === "t2i");++/** The setting's value as model ids, in order (comma-separated; blanks left out). */+export const triggerModelIds = (text: string): string[] =>+ text+ .split(",")+ .map((s) => s.trim())+ .filter(Boolean);++/**+ * Why the order can't be saved, one line per problem (empty: it can): 1 to AUTO_TRIGGER_MAX models, each one the catalog+ * knows that makes text to image on the open engine, none twice. An empty value is the built-in order.+ */+export function autoTriggerModelsProblems(text: string, lookup: (id: string) => AutoModelLike | undefined): string[] {+ if (!text.trim()) return [];+ const ids = triggerModelIds(text);+ const problems: string[] = [];+ if (!ids.length) problems.push("List at least one model");+ if (ids.length > AUTO_TRIGGER_MAX) problems.push(`Keep it to ${AUTO_TRIGGER_MAX} models`);+ const seen = new Set<string>();+ for (const id of ids) {+ const m = lookup(id);+ if (!m) problems.push(`${id.slice(0, 80)} isn't a model this install has`);+ else if (!autoT2iModel(id, m)) problems.push(`${id} doesn't make pictures from words on the open engine`);+ if (seen.has(id)) problems.push(`${id.slice(0, 80)} is listed twice`);+ seen.add(id);+ }+ return [...new Set(problems)];+}++/**+ * The saved order as Auto uses it: the models it may list, in order, each once. The built-in order when the value is+ * empty or lists none it may (a model the catalog no longer has is left out).+ */+export function triggerOrder(text: string, lookup: (id: string) => AutoModelLike | undefined): string[] {+ const ids = [...new Set(triggerModelIds(text))].filter((id) => autoT2iModel(id, lookup(id))).slice(0, AUTO_TRIGGER_MAX);+ return ids.length ? ids : [...DEFAULT_TRIGGER_MODELS];+}++/**+ * The models Auto may plan an operation on: text to image on AUTO_T2I_MODELS and the order for matched prompts (`trigger`,+ * DEFAULT_TRIGGER_MODELS when not given), the others on AUTO_EDIT_MODELS.+ */+export const autoModelsFor = (op: Operation, trigger: readonly string[] = DEFAULT_TRIGGER_MODELS): readonly string[] =>+ op === "t2i" ? [...new Set([...AUTO_T2I_MODELS, ...trigger])] : (AUTO_EDIT_MODELS[op] ?? []);-/** Every model Auto may plan a run on. */+/** Every model Auto may plan a run on with the built-in order for matched prompts. */export const AUTO_MODELS: ReadonlySet<string> = new Set([...AUTO_T2I_MODELS, ...Object.values(AUTO_EDIT_MODELS).flat()]);/**@@ -63,8 +124,9 @@ const TEXT_WORDS =const QUOTED = /["“”«»][^"“”«»\n]{2,80}["“”«»]/;/**- * The setting's list (Settings → Auto image model): prompts Auto starts on Krea 2 Realism (then MiniMax H3 Image, then- * MOSS-Image), and whose run details name the line they matched. Lettering still follows its own order. One per line: a word or phrase matches as a whole word (a space or a hyphen matches either), any other line is a regular+ * The setting's list (Settings → Auto image model): prompts Auto starts on the order for matched prompts+ * (DEFAULT_TRIGGER_MODELS, or the saved one), and whose run details name the line they matched. Lettering still follows+ * its own order. One per line: a word or phrase matches as a whole word (a space or a hyphen matches either), any other line is a regular* expression, and a line that starts with "#" is a note; case never matters.*/export const DEFAULT_AUTO_PATTERNS: readonly string[] = [@@ -165,18 +227,22 @@ export interface AutoAsk {/*** The models Auto would plan a run on, best first, and why: a picture to work from → the studio's edit model for its* operation; lettering → MiniMax H3 Image, then MOSS-Image, then Krea 2 Realism; a prompt the setting's patterns match →- * Krea 2 Realism, then MiniMax H3 Image, then MOSS-Image; anything else → MiniMax H3 Image, then Krea 2 Realism, then- * MOSS-Image. The same for the owner, an account and a guest. The server plans the first one that is switched on, runs- * the operation and fits the GPUs the run goes to (src/server/generations.ts autoRouted), and the next one makes the run- * when it fails (autoNext).+ * `trigger` in its order (the saved order; DEFAULT_TRIGGER_MODELS when not given or empty); anything else → MiniMax H3+ * Image, then Krea 2 Realism, then MOSS-Image. The same for the owner, an account and a guest. The server plans the first+ * one that is switched on, runs the operation and fits the GPUs the run goes to (src/server/generations.ts autoRouted),+ * and the next one makes the run when it fails (autoNext).*/-export function autoCandidates(ask: AutoAsk, patterns: readonly { line: string; re: RegExp }[]): { models: string[]; why: AutoWhy; pattern?: string } {+export function autoCandidates(+ ask: AutoAsk,+ patterns: readonly { line: string; re: RegExp }[],+ trigger: readonly string[] = DEFAULT_TRIGGER_MODELS,+): { models: string[]; why: AutoWhy; pattern?: string } {const op = ask.op && ask.op !== "t2i" ? ask.op : (ask.images ?? 0) > 0 ? "edit" : "t2i";if (op !== "t2i") return { models: [...(AUTO_EDIT_MODELS[op] ?? [])], why: "edit" };const words = ask.prompt ?? "";if (asksForText(words)) return { models: [AUTO_LEAD_MODEL, AUTO_TEXT_MODEL, AUTO_PHOTO_MODEL], why: "text" };const pattern = matchedPattern(words, patterns);- if (pattern) return { models: [AUTO_PHOTO_MODEL, AUTO_LEAD_MODEL, AUTO_TEXT_MODEL], why: "trigger", pattern };+ if (pattern) return { models: [...new Set(trigger.length ? trigger : DEFAULT_TRIGGER_MODELS)], why: "trigger", pattern };return { models: [...AUTO_T2I_MODELS], why: "plain" };}diff --git a/src/server/generations.ts b/src/server/generations.tsindex be781b7e..1cdbcae8 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -38,7 +38,7 @@ 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, captionWords, parseCaption } from "@/lib/ideogram-caption";-import { AUTO_IMAGE, AUTO_LARGE_MODELS, autoCandidates, autoModelsFor, autoNext, autoPatterns, autoResolution, nextDeclinedFallback } from "@/lib/auto-image";+import { AUTO_IMAGE, AUTO_LARGE_MODELS, autoCandidates, autoModelsFor, autoNext, autoPatterns, autoResolution, nextDeclinedFallback, triggerOrder } from "@/lib/auto-image";import { h3Frames, h3Prompt, inH3Layout } from "@/lib/h3-prompt";import { h3ReferenceTags, h3TalkPrompt } from "@/lib/h3-references";import {@@ -1464,6 +1464,11 @@ function autoPatternsNow(): ReturnType<typeof autoPatterns> {return autoPatternCache.patterns;}+/** Auto's order for prompts the patterns match, as saved in Settings (the built-in order when none is). */+function autoTriggerNow(): string[] {+ return triggerOrder(getSetting("autoTriggerModels"), getModel);+}+/*** A run of Auto (src/lib/auto-image.ts) as the model it picks runs it: the pick it carries (a run planned again: a resend,* a run that waited to enter the line, Auto's next model after the one before failed) while it is one of Auto's models@@ -1484,9 +1489,9 @@ function autoRouted(req: GenerationRequest): GenerationRequest {if (req.auto) {const m = getModel(req.auto.model);const op = (req.op && m?.routes.some((r) => r.op === req.op) ? req.op : undefined) ?? (images ? "edit" : "t2i");- if (autoModelsFor(op).includes(req.auto.model)) return sized({ ...req, modelId: req.auto.model, op }, req.auto.model);+ if (autoModelsFor(op, autoTriggerNow()).includes(req.auto.model)) return sized({ ...req, modelId: req.auto.model, op }, req.auto.model);}- const c = autoCandidates({ prompt: req.prompt, op: req.op, images }, autoPatternsNow());+ const c = autoCandidates({ prompt: req.prompt, op: req.op, images }, autoPatternsNow(), autoTriggerNow());const op: Operation = c.why === "edit" ? (req.op && req.op !== "t2i" ? req.op : "edit") : "t2i";const runs = (id: string) => {const m = getModel(id);@@ -3333,7 +3338,8 @@ function declinedFallback(stored: GenerationRequest, modelId: string): Generatio* 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), never* by a model that tried it before. A run of Auto goes to Auto's models left in its order (src/lib/auto-image.ts: MiniMax H3- * Image where the GPUs can take it, Krea 2 Realism and MOSS-Image, never Ideogram 4), each at most once, and keeps Auto,+ * Image where the GPUs can take it, Krea 2 Realism and MOSS-Image, or the saved order for prompts the patterns match;+ * never Ideogram 4), each at most once, and keeps Auto,* its pick saying why (`why: "fallback"`, or "declined" after Ideogram 4 declined an older run); Ideogram 4 picked by name goes to DECLINED_FALLBACKS in order and* names the model that made it (its model and its request's notice). Each next model is the first switched on that goes* where the run went, and only when the one before fails (declinedFails).@@ -3358,7 +3364,7 @@ function declinedAgain(r: Row, declined: DeclinedMeta, later = false): boolean {const tried = auto ? [...new Set([...(declined.tried ?? []), r.model_id])] : undefined;const order: string[] = [];// (A model whose lane needs a large GPU only where the GPUs the run went to can take it: src/server/auto-gpu.ts.)- if (tried) order.push(...autoNext(autoCandidates({ prompt: stored.prompt, op: "t2i" }, autoPatternsNow()).models, tried).filter((m) => !AUTO_LARGE_MODELS.has(m) || there(() => autoFitsHere(m, "t2i"))));+ if (tried) order.push(...autoNext(autoCandidates({ prompt: stored.prompt, op: "t2i" }, autoPatternsNow(), autoTriggerNow()).models, tried).filter((m) => !AUTO_LARGE_MODELS.has(m) || there(() => autoFitsHere(m, "t2i"))));else for (let m = nextDeclinedFallback(declined.model); m; m = nextDeclinedFallback(m)) order.push(m);const why = declined.cause === "failed" ? "fallback" : "declined";for (const m of order) {diff --git a/src/server/run-details.ts b/src/server/run-details.tsindex 5d54148a..d8efea12 100644--- a/src/server/run-details.ts+++ b/src/server/run-details.ts@@ -506,7 +506,7 @@ export function surfaceOf(feature: string, stamp: GenerationRequest): RunSurfaceexport 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 MiniMax H3 Image first",- trigger: "Its words match a pattern in Settings → Auto image model, so it went to Krea 2 Realism first",+ trigger: "Its words match a pattern in Settings → Auto image model, so it went to the models set for those prompts, in order",plain: "A plain prompt, so it went to MiniMax H3 Image first",fallback: "The model before it couldn't make it, so Auto's next model made it",declined: "Ideogram 4 declined it, so this model made it instead",diff --git a/src/server/settings.ts b/src/server/settings.tsindex 003188b7..353278ff 100644--- a/src/server/settings.ts+++ b/src/server/settings.ts@@ -1,7 +1,8 @@import "server-only";import { AsyncLocalStorage } from "node:async_hooks";import { PLACE_NAME_MAX } from "@/lib/place-name";-import { autoPatternsProblems, DEFAULT_AUTO_PATTERNS } from "@/lib/auto-image";+import { autoPatternsProblems, autoTriggerModelsProblems, DEFAULT_AUTO_PATTERNS } from "@/lib/auto-image";+import { getModel } from "@/lib/catalog";import { db } from "./db";/**@@ -137,10 +138,16 @@ export const SETTINGS = {/** Tokens of context the local model gets (Ollama's num_ctx; LM Studio loads models with it). 0 = the server's own setting. */llmContext: { key: "llm.context", env: "FUOBE_LLM_CONTEXT", default: "16384" },/**- * Settings → Auto image model: prompts Auto starts on Krea 2 Realism (a plain prompt starts on MiniMax H3 Image), one pattern per- * line, whose run details name the line they matched (src/lib/auto-image.ts). Empty: the built-in list.+ * Settings → Auto image model: prompts Auto starts on the order for matched prompts (autoTriggerModels; a plain prompt+ * starts on MiniMax H3 Image), one pattern per line, whose run details name the line they matched+ * (src/lib/auto-image.ts). Empty: the built-in list.*/autoImagePatterns: { key: "auto.imagePatterns", default: DEFAULT_AUTO_PATTERNS.join("\n") },+ /**+ * Settings → Auto image model: the models for prompts the list matches, in order, as model ids separated by commas+ * (src/lib/auto-image.ts triggerOrder). Empty: the built-in order (DEFAULT_TRIGGER_MODELS).+ */+ autoTriggerModels: { key: "auto.triggerModels" },/*** Settings → Failed runs: what a person reads when a run of theirs on this install's GPUs fails. "full": the plain* sentence, and under it the cleaned technical reason (ComfyUI's own, src/lib/comfy-reason.ts: no folders, addresses,@@ -256,6 +263,11 @@ export function validateSetting(name: SettingName, value: string, from: "api" |const problems = autoPatternsProblems(value);if (problems.length) throw new Error(`Auto's patterns: ${problems.join("; ")}`);}+ // Auto's order for matched prompts: 1 to 10 open text-to-image models the catalog has, none twice.+ if (name === "autoTriggerModels" && value !== "") {+ const problems = autoTriggerModelsProblems(value, getModel);+ if (problems.length) throw new Error(`Auto's models for matched prompts: ${problems.join("; ")}`);+ }if (name === "smartPlan" && value !== "" && value !== "auto" && !/^[a-z0-9-]{2,32}\|[\w.:/@+-]{1,200}$/.test(value)) {throw new Error("smartPlan must be auto, or a provider and model as provider|model");}diff --git a/tests/auto-image-runs.test.ts b/tests/auto-image-runs.test.tsindex ccfa04ed..ffe5ee8b 100644--- a/tests/auto-image-runs.test.ts+++ b/tests/auto-image-runs.test.ts@@ -50,6 +50,7 @@ beforeAll(() => setSetting("demoMode", "auto"));beforeEach(() => {setSetting("enhanceProvider", "none");setSetting("autoImagePatterns", "");+ setSetting("autoTriggerModels", "");changeAccess([{ kind: "reset" }]);ideogram = [];failing = new Set();@@ -296,6 +297,55 @@ describe("Ideogram 4 picked by name, when it declines", () => {});});+describe("the saved order for prompts the patterns match", () => {+ const ORDER = "oss-z-image-turbo,oss-qwen-image-21,oss-fibo2-dev";++ it("a matched prompt starts on the saved order's first model; plain words, lettering and edits keep theirs", async () => {+ setSetting("autoTriggerModels", ORDER);+ const g = await run(CAT);+ expect(g.status, g.error ?? "").toBe("succeeded");+ expect(handed.map((h) => h.model)).toEqual(["oss-z-image-turbo"]);+ expect(g.request.auto).toEqual({ model: "oss-z-image-turbo", why: "trigger" });+ expect(previewGeneration({ feature: "image", modelId: AUTO_IMAGE, prompt: "a koi pond at night" }).model.id).toBe(H3);+ expect(previewGeneration({ feature: "image", modelId: AUTO_IMAGE, prompt: 'a poster that says "OPEN"' }).model.id).toBe(H3);+ expect(previewGeneration({ feature: "image", modelId: AUTO_IMAGE, prompt: CAT, inputs: { images: [dataUri(gradient)] } }).model.id).toBe("oss-qwen-image-21");+ // A run planned again keeps a pick from the saved order.+ expect(previewGeneration({ feature: "image", modelId: AUTO_IMAGE, prompt: CAT, auto: { model: "oss-fibo2-dev", why: "fallback" } }).model.id).toBe("oss-fibo2-dev");+ });++ it("a model switched off is passed over", () => {+ setSetting("autoTriggerModels", ORDER);+ changeAccess([{ kind: "model", id: "oss-z-image-turbo", on: false }]);+ expect(previewGeneration({ feature: "image", modelId: AUTO_IMAGE, prompt: CAT }).model.id).toBe("oss-qwen-image-21");+ });++ it("when a model fails, the next in the saved order makes the same run, each at most once", async () => {+ setSetting("autoTriggerModels", ORDER);+ failing = new Set(["oss-z-image-turbo", "oss-qwen-image-21"]);+ const g = await run(CAT);+ expect(g.status, g.error ?? "").toBe("succeeded");+ expect(handed.map((h) => h.model)).toEqual(["oss-z-image-turbo", "oss-qwen-image-21", "oss-fibo2-dev"]);+ expect(g.request.auto).toEqual({ model: "oss-fibo2-dev", why: "fallback" });+ expect(rowsSince(g.id)).toBe(1);++ handed = [];+ failing = new Set(["oss-z-image-turbo", "oss-qwen-image-21", "oss-fibo2-dev"]);+ const f = await run(CAT);+ expect(f.status).toBe("failed");+ expect(handed.map((h) => h.model)).toEqual(["oss-z-image-turbo", "oss-qwen-image-21", "oss-fibo2-dev"]);+ });++ it("is checked on save, and empty is the built-in order", () => {+ expect(getSetting("autoTriggerModels")).toBe("");+ expect(() => validateSetting("autoTriggerModels", "oss-krea2-realism,nope", "api")).toThrow(/nope isn't a model this install has/);+ expect(() => setSetting("autoTriggerModels", "oss-krea2-realism,oss-krea2-realism")).toThrow(/listed twice/);+ expect(() => setSetting("autoTriggerModels", "oss-minimax-h3-image,oss-krea2-realism,oss-qwen-image-21,oss-z-image-turbo,oss-fibo2-dev,oss-moss-image")).not.toThrow();+ expect(previewGeneration({ feature: "image", modelId: AUTO_IMAGE, prompt: CAT }).model.id).toBe(H3);+ setSetting("autoTriggerModels", "");+ expect(previewGeneration({ feature: "image", modelId: AUTO_IMAGE, prompt: CAT }).model.id).toBe("oss-krea2-realism");+ });+});+describe("the setting", () => {it("is checked on save: a line that can't be read, or that matches every prompt, is refused", () => {expect(() => validateSetting("autoImagePatterns", "bikini\n(oops", "api")).toThrow(/Line 2 isn't a pattern/);diff --git a/tests/auto-image.test.ts b/tests/auto-image.test.tsindex e36c5a3a..5a9172d1 100644--- a/tests/auto-image.test.ts+++ b/tests/auto-image.test.ts@@ -8,6 +8,7 @@ import {AUTO_LARGE_MODELS,AUTO_MODELS,AUTO_T2I_MODELS,+ AUTO_TRIGGER_MAX,autoCandidates,autoLine,autoModelsFor,@@ -15,8 +16,11 @@ import {autoPatterns,autoPatternsProblems,autoResolution,+ autoTriggerModelsProblems,DECLINED_FALLBACKS,DEFAULT_AUTO_PATTERNS,+ DEFAULT_TRIGGER_MODELS,+ triggerOrder,matchedPattern,nextDeclinedFallback,} from "@/lib/auto-image";@@ -262,3 +266,58 @@ describe("the line under a run of Auto", () => {expect(owners).toContain("Add a pattern");});});++describe("the order for prompts the patterns match", () => {+ const MATCHED = "a cat in an antique-gold paillette gown";+ const OPEN_T2I = ["oss-krea2-realism", "oss-qwen-image-21", "oss-z-image-turbo", "oss-fibo2-dev", "oss-moss-image", H3];++ it("defaults to Krea 2 Realism, then MiniMax H3 Image, then MOSS-Image", () => {+ expect(DEFAULT_TRIGGER_MODELS).toEqual(KREA_FIRST);+ expect(pick(MATCHED)).toMatchObject({ models: KREA_FIRST, why: "trigger" });+ expect(triggerOrder("", getModel)).toEqual(KREA_FIRST);+ expect(triggerOrder(" ", getModel)).toEqual(KREA_FIRST);+ });++ it("a saved order replaces it for matched prompts only; plain, lettering and edits keep theirs", () => {+ const order = triggerOrder("oss-z-image-turbo, oss-qwen-image-21,oss-fibo2-dev", getModel);+ expect(order).toEqual(["oss-z-image-turbo", "oss-qwen-image-21", "oss-fibo2-dev"]);+ expect(autoCandidates({ prompt: MATCHED }, defaults, order)).toMatchObject({ models: order, why: "trigger" });+ expect(autoCandidates({ prompt: "a koi pond at night" }, defaults, order)).toMatchObject({ models: PLAIN, why: "plain" });+ expect(autoCandidates({ prompt: 'a poster that says "OPEN"' }, defaults, order)).toMatchObject({ models: LETTERING, why: "text" });+ expect(autoCandidates({ prompt: MATCHED, images: 1 }, defaults, order)).toMatchObject({ models: ["oss-qwen-image-21", "oss-fibo2-dev"], why: "edit" });+ // The models Auto may plan for text to image take the saved ones in too, so a run planned again keeps its pick.+ expect(autoModelsFor("t2i", order)).toEqual([...PLAIN, "oss-z-image-turbo", "oss-qwen-image-21", "oss-fibo2-dev"]);+ expect(autoModelsFor("edit", order)).toEqual(["oss-qwen-image-21", "oss-fibo2-dev"]);+ });++ it("after a model fails, the next in the saved order makes the run, each at most once", () => {+ const order = ["oss-z-image-turbo", "oss-qwen-image-21", H3];+ expect(autoNext(order, ["oss-z-image-turbo"])).toEqual(["oss-qwen-image-21", H3]);+ expect(autoNext(order, ["oss-z-image-turbo", "oss-qwen-image-21"])).toEqual([H3]);+ expect(autoNext(order, order)).toEqual([]);+ });++ it("leaves out what Auto may not list when reading a saved value; none left is the built-in order", () => {+ expect(triggerOrder("oss-z-image-turbo,gone-model,oss-z-image-turbo,oss-moss-image", getModel)).toEqual(["oss-z-image-turbo", "oss-moss-image"]);+ expect(triggerOrder("gone-model", getModel)).toEqual(KREA_FIRST);+ });++ it("is checked on save: known open text-to-image models, none twice, 1 to 10", () => {+ for (const id of OPEN_T2I) expect(autoTriggerModelsProblems(id, getModel), id).toEqual([]);+ expect(autoTriggerModelsProblems(OPEN_T2I.join(","), getModel)).toEqual([]);+ expect(autoTriggerModelsProblems("", getModel)).toEqual([]);+ expect(autoTriggerModelsProblems(" , ", getModel)).toEqual(["List at least one model"]);+ expect(autoTriggerModelsProblems("oss-krea2-realism,no-such-model", getModel)).toEqual(["no-such-model isn't a model this install has"]);+ expect(autoTriggerModelsProblems("oss-krea2-realism,oss-krea2-realism", getModel)).toEqual(["oss-krea2-realism is listed twice"]);+ expect(autoTriggerModelsProblems(AUTO_IMAGE, getModel)[0]).toMatch(/doesn't make pictures from words on the open engine/);+ // A cloud model, and a model that doesn't make pictures from words.+ const cloud = MODELS.find((m) => m.engine === "cloud" && m.kind === "image" && m.routes.some((r) => r.op === "t2i"))!;+ expect(autoTriggerModelsProblems(cloud.id, getModel)[0]).toMatch(/doesn't make pictures from words/);+ const video = MODELS.find((m) => m.engine === "open" && m.kind === "video")!;+ expect(autoTriggerModelsProblems(video.id, getModel)[0]).toMatch(/doesn't make pictures from words/);+ const many = MODELS.filter((m) => m.engine === "open" && m.kind === "image" && !m.hidden && m.id !== AUTO_IMAGE && m.routes.some((r) => r.op === "t2i")).map((m) => m.id);+ expect(many.length).toBeGreaterThan(AUTO_TRIGGER_MAX);+ expect(autoTriggerModelsProblems(many.slice(0, AUTO_TRIGGER_MAX).join(","), getModel)).toEqual([]);+ expect(autoTriggerModelsProblems(many.slice(0, AUTO_TRIGGER_MAX + 1).join(","), getModel)).toEqual([`Keep it to ${AUTO_TRIGGER_MAX} models`]);+ });+});