Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Auto: a policy may give an account's picture order and the model menu's words

Adarshbea1ce15ae77
diff --git a/src/components/studio/model-picker.tsx b/src/components/studio/model-picker.tsx
index ac786b58..bbcce60b 100644
--- a/src/components/studio/model-picker.tsx
+++ b/src/components/studio/model-picker.tsx
@@ -101,6 +101,7 @@ export function ModelRow({
setup,
guest,
here,
+ mark,
}: {
m: ModelDef;
selected: boolean;
@@ -129,6 +130,8 @@ export function ModelRow({
* your GPU · 24 GB", "With your fal.ai key"; the owner's "Add to a worker") in place of the price.
*/
here?: { setup: OwnSetup; owner: boolean } | null;
+ /** The service's word for this open model in place of "Free" (src/lib/model-marks.ts). */
+ mark?: string;
}) {
return (
<>
@@ -187,7 +190,7 @@ export function ModelRow({
<span className="max-sm:hidden">{guest ? ownSetupLabel({ need: "key", provider: needs[0] }) : addKeyLabel(needs[0])}</span>
</span>
) : (
- <span className="shrink-0 text-right text-[11px] text-muted-foreground tabular-nums">{pickerPrice(m, today, edits)}</span>
+ <span className="shrink-0 text-right text-[11px] text-muted-foreground tabular-nums">{(m.engine === "open" && mark) || pickerPrice(m, today, edits)}</span>
)}
{/* Pointer only: inside an option it would be a nested control. Keyboard: Alt+S on the highlighted row (starKey). */}
<button
@@ -505,6 +508,7 @@ export function PickerList({
edits={editsClips}
setup={ownSetup?.(m)}
here={hereRow(m)}
+ mark={status?.viewer?.marks?.[m.id]}
/>
</CommandItem>
))}
diff --git a/src/lib/api.ts b/src/lib/api.ts
index c9a8534c..8ed7714e 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -1064,6 +1064,8 @@ export interface StatusInfo {
siteFallback?: SiteFallback;
/** The words a preset card shows when its run would go to this studio's GPUs ("Try free"), from the server. None: no words. */
cardText?: string;
+ /** The billing service's words for open models in the model menu, by id, in place of "Free" (src/lib/model-marks.ts). */
+ marks?: Record<string, string>;
/** What this studio's GPUs keep off, for a viewer with no GPU of its own: its pickers leave it out (src/lib/pool-rules.ts). */
pool?: PoolRules;
/** The billing service's words for the account's balance (src/server/billing.ts). */
diff --git a/src/lib/auto-image.ts b/src/lib/auto-image.ts
index 002bc0d9..35b546db 100644
--- a/src/lib/auto-image.ts
+++ b/src/lib/auto-image.ts
@@ -105,6 +105,19 @@ export function triggerOrder(text: string, lookup: (id: string) => AutoModelLike
return ids.length ? ids : [...DEFAULT_TRIGGER_MODELS];
}
+/**
+ * An account's own order for its plain and matched prompts on this install's GPUs, as the billing service's policy gives
+ * it (Policy.auto.image): the models Auto may list, in order, each once, at most AUTO_TRIGGER_MAX. Null when it lists
+ * none (the install's own orders then apply).
+ */
+export function ownAutoOrder(ids: unknown, lookup: (id: string) => AutoModelLike | undefined): string[] | null {
+ if (!Array.isArray(ids)) return null;
+ const out = [...new Set(ids.filter((id): id is string => typeof id === "string").map((id) => id.trim()))]
+ .filter((id) => autoT2iModel(id, lookup(id)))
+ .slice(0, AUTO_TRIGGER_MAX);
+ return out.length ? out : null;
+}
+
/**
* 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.
@@ -230,12 +243,14 @@ export interface AutoAsk {
* `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).
+ * and the next one makes the run when it fails (autoNext). `plain`: the order for a plain prompt (AUTO_T2I_MODELS when
+ * not given or empty; an account's own order on this install's GPUs, ownAutoOrder).
*/
export function autoCandidates(
ask: AutoAsk,
patterns: readonly { line: string; re: RegExp }[],
trigger: readonly string[] = DEFAULT_TRIGGER_MODELS,
+ plain: readonly string[] = AUTO_T2I_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" };
@@ -243,7 +258,7 @@ export function autoCandidates(
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: [...new Set(trigger.length ? trigger : DEFAULT_TRIGGER_MODELS)], why: "trigger", pattern };
- return { models: [...AUTO_T2I_MODELS], why: "plain" };
+ return { models: [...new Set(plain.length ? plain : AUTO_T2I_MODELS)], why: "plain" };
}
/** A size tier's place in order ("1K" < "1.5K" < "2K" < "4K"); NaN for a size that isn't a tier. */
diff --git a/src/lib/model-marks.ts b/src/lib/model-marks.ts
new file mode 100644
index 00000000..ac45ef32
--- /dev/null
+++ b/src/lib/model-marks.ts
@@ -0,0 +1,27 @@
+/**
+ * The short words a model menu shows on the right of an open model instead of "Free", by model id, when the billing
+ * service's policy gives them (Policy.marks) and the viewer's runs go to this install's GPUs. Fuobe has no such words of
+ * its own: with no service, or none sent, every open model shows "Free" as before.
+ */
+export type ModelMarks = Record<string, string>;
+
+/** The longest word kept (characters); a longer one is left out. */
+export const MARK_MAX = 12;
+/** The most models a policy may mark. */
+export const MARKS_MAX = 500;
+
+/** A policy's marks as kept: string ids and words only, control characters out, spaces folded. Null when none is left. */
+export function cleanMarks(raw: unknown): ModelMarks | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const out: ModelMarks = {};
+ let n = 0;
+ for (const [id, value] of Object.entries(raw as Record<string, unknown>)) {
+ if (n >= MARKS_MAX) break;
+ if (typeof value !== "string" || !id || id.length > 120) continue;
+ const s = value.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/\s+/g, " ").trim();
+ if (!s || s.length > MARK_MAX) continue;
+ out[id] = s;
+ n++;
+ }
+ return n ? out : null;
+}
diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.ts
index 129a7f97..a4e3e6fe 100644
--- a/src/server/account-gpu.ts
+++ b/src/server/account-gpu.ts
@@ -2,6 +2,7 @@ import "server-only";
import dns from "node:dns/promises";
import net from "node:net";
import { cleanCopy, type ServiceCopy } from "@/lib/service-copy";
+import { cleanMarks, type ModelMarks } from "@/lib/model-marks";
import { isCloudProvider, type CloudProvider } from "@/lib/your-keys";
import { accountEngineMode, accountKeyInfo, accountProviders, paidAllowed, usableProviders } from "./account-keys";
import { accountGpu, type Account, type AccountGpu } from "./auth";
@@ -372,6 +373,11 @@ export interface VisitorView {
* "Try free"; with no service, "Try free": those runs are free). Absent: the cards show none.
*/
cardText?: string;
+ /**
+ * The billing service's words for open models in the model menu, by id, in place of "Free" (src/lib/model-marks.ts).
+ * Only while the viewer's runs go to this install's GPUs.
+ */
+ marks?: ModelMarks;
/**
* What this install's GPUs keep off (the policy's model and app lists, and its kinds), for a visitor with no GPU of its
* own: its pickers leave those out instead of failing at Run. Absent: nothing is kept off, or it has a GPU of its own.
@@ -490,6 +496,11 @@ export async function visitorStatus(account: Account | null) {
if (rules) viewer.pool = rules;
if (account && p?.links?.length) viewer.links = p.links;
if (account && p?.notice) viewer.notice = p.notice;
+ // The service's words for open models in the menus, while this viewer's runs go to this install's GPUs (not a GPU
+ // of its own it runs on first).
+ const toSite = !gpu || viewer.runOn === "site" || (!viewer.runOn && p?.prefer === "pool");
+ const marks = p?.hosted && toSite ? cleanMarks(p.marks) : null;
+ if (marks) viewer.marks = marks;
// The service's display copy (wait and limit lines), for guests and accounts alike.
const copy = p?.hosted ? cleanCopy(p.copy) : null;
if (copy) viewer.copy = copy;
diff --git a/src/server/billing.ts b/src/server/billing.ts
index 28532734..4f58e477 100644
--- a/src/server/billing.ts
+++ b/src/server/billing.ts
@@ -216,6 +216,17 @@ export interface Policy {
* key left out: the app's own plain sentence. The latest answer's copy applies to every visitor's words.
*/
copy?: Record<string, string>;
+ /**
+ * Auto's picture models for this account's runs on this install's GPUs, in order: its plain and matched prompts start
+ * there (src/lib/auto-image.ts ownAutoOrder). Absent or empty: the install's own orders. Never applied to a run on the
+ * account's own GPU or key; lettering and edits keep their own orders.
+ */
+ auto?: { image?: string[] };
+ /**
+ * Short words a model menu shows on the right of an open model instead of "Free", by model id, while the viewer's runs
+ * go to this install's GPUs (src/lib/model-marks.ts; at most MARK_MAX characters each). Absent: "Free" as before.
+ */
+ marks?: Record<string, string>;
ttlS: number;
}
@@ -528,6 +539,18 @@ export function cachedPolicy(accountId: string | null): Policy | null | undefine
return hit && Date.now() - hit.at < hit.ttlMs ? hit.policy : undefined;
}
+/**
+ * The service's last answer for an account, however long ago it came (in memory, else kept across restarts), with no
+ * call: for what may lag an answer by a little, such as Auto's own order (a run on this install's GPUs reads the policy
+ * just before it is planned). No service: OPEN_POLICY. Null when the service never answered for it.
+ */
+export function lastPolicy(accountId: string): Policy | null {
+ if (!billingConfigured()) return OPEN_POLICY;
+ const hit = globalThis.__fuobeBillingPolicies?.get(accountId);
+ if (hit?.goodAt !== undefined && hit.policy) return hit.policy;
+ return savedPolicy(accountId);
+}
+
/** A free run's quote (no service set): Run keeps its own words. */
export const FREE_QUOTE: Quote = { allowed: true, amount: 0, priceVersion: "", text: "" };
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 58ce867d..dac075ad 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -38,7 +38,8 @@ 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, triggerOrder } from "@/lib/auto-image";
+import { AUTO_IMAGE, AUTO_LARGE_MODELS, autoCandidates, autoModelsFor, autoNext, autoPatterns, autoResolution, nextDeclinedFallback, ownAutoOrder, triggerOrder } from "@/lib/auto-image";
+import { lastPolicy } from "./billing";
import { h3Frames, h3Prompt, inH3Layout } from "@/lib/h3-prompt";
import { h3ReferenceTags, h3TalkPrompt } from "@/lib/h3-references";
import {
@@ -86,7 +87,7 @@ import { takesFilmLooks } from "@/lib/film-looks";
import { carriesLayout } from "@/lib/layout-prompt";
import { setResolver, watchGenerations, type LiveEvent } from "./live";
import { provider, PROVIDERS, RETIRED_PROVIDER_ERROR } from "./providers";
-import { comfyLoraFiles, comfyPlace, computerScope, onOwnGpu, onPoolWorkers, outputFetch, outsideOwnGpu, OWN_OUTPUT_LIMITS, ownGpu, ownLink, probeComfy, relayFile, troubleError, type OwnGpu } from "./providers/comfyui";
+import { accountOnInstall, comfyLoraFiles, comfyPlace, computerScope, onOwnGpu, onPoolWorkers, outputFetch, outsideOwnGpu, OWN_OUTPUT_LIMITS, ownGpu, ownLink, probeComfy, relayFile, troubleError, type OwnGpu } from "./providers/comfyui";
import { accountById, accountGpu, gpuLink, validToken, type AccountGpu } from "./auth";
import { accountEngineMode, accountKey, markKeyGood, paidAllowed, usableProviders } from "./account-keys";
import { addKeyMessage, CLOUD_KEY, CLOUD_PROVIDERS, isCloudProvider, keyRemovedMessage, type CloudProvider } from "@/lib/your-keys";
@@ -1485,6 +1486,18 @@ function autoTriggerNow(): string[] {
return triggerOrder(getSetting("autoTriggerModels"), getModel);
}
+/**
+ * Auto's orders for the current run: an account's run on this install's GPUs follows its own order for plain and
+ * matched prompts when the billing service's policy gives one (Policy.auto.image); the owner, a guest, a run on the
+ * account's own GPU or key, and an account the policy gives none for follow the install's (autoTriggerNow, then
+ * AUTO_T2I_MODELS). Lettering and edits keep their own orders.
+ */
+function autoOrdersNow(): { trigger: string[]; plain?: string[] } {
+ const account = accountOnInstall() ? tenantAccount() : undefined;
+ const own = account ? ownAutoOrder(lastPolicy(account)?.auto?.image, getModel) : null;
+ return own ? { trigger: own, plain: own } : { trigger: autoTriggerNow() };
+}
+
/**
* 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
@@ -1502,12 +1515,13 @@ function autoRouted(req: GenerationRequest): GenerationRequest {
const to = autoResolution(asked, getModel(model));
return to === asked ? r : { ...r, params: { ...r.params, resolution: to } };
};
+ const orders = autoOrdersNow();
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, autoTriggerNow()).includes(req.auto.model)) return sized({ ...req, modelId: req.auto.model, op }, req.auto.model);
+ if (autoModelsFor(op, orders.trigger).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(), autoTriggerNow());
+ const c = autoCandidates({ prompt: req.prompt, op: req.op, images }, autoPatternsNow(), orders.trigger, orders.plain);
const op: Operation = c.why === "edit" ? (req.op && req.op !== "t2i" ? req.op : "edit") : "t2i";
const runs = (id: string) => {
const m = getModel(id);
@@ -3380,7 +3394,11 @@ 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(), autoTriggerNow()).models, tried).filter((m) => !AUTO_LARGE_MODELS.has(m) || there(() => autoFitsHere(m, "t2i"))));
+ if (tried) {
+ // The orders where the run went (an account's own on this install's GPUs).
+ const orders = there(autoOrdersNow);
+ order.push(...autoNext(autoCandidates({ prompt: stored.prompt, op: "t2i" }, autoPatternsNow(), orders.trigger, orders.plain).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/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 1111e846..192e949f 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -287,6 +287,9 @@ const onInstallServer = <T,>(fn: () => T): T => poolScope.exit(() => serverScope
*/
export const onInstallComfy = <T,>(fn: () => T): T => outsideOwnGpu(() => (getSetting("comfyWhere") === "workers" ? serverScope.exit(() => poolScope.run(true, fn)) : onInstallServer(fn)));
+/** Is the current work an account's run on this install's GPUs (its workers, or its own ComfyUI server)? */
+export const accountOnInstall = (): boolean => !!tenantAccount() && !!(poolScope.getStore() || serverScope.getStore());
+
/**
* The install's own ComfyUI address is on this machine (loopback). Runs of accounts on this install's GPUs go straight
* to it only then: an address elsewhere would send accounts' files and prompts over a network to a ComfyUI nothing
@@ -1328,7 +1331,7 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,
return n;
},
sent,
- accountOnInstall: !!tenantAccount() && !!(poolScope.getStore() || serverScope.getStore()),
+ accountOnInstall: accountOnInstall(),
// (Asked only for the graph it is about, H3 Person Removal's review: no other run reads the settings for it.)
ownStudio: endpointTemplate === H3_REMOVAL_WORKFLOW && !ownGpu() && !computerScope() && !tenantAccount(),
});
diff --git a/tests/auto-image-pool.test.ts b/tests/auto-image-pool.test.ts
index 555e1f68..fd380744 100644
--- a/tests/auto-image-pool.test.ts
+++ b/tests/auto-image-pool.test.ts
@@ -295,3 +295,54 @@ describe("an account's free run of Auto on this install's GPUs", () => {
expect((await proxy(req("PUT"))).status).toBe(403);
});
});
+
+describe("an account's own Auto order and menu words from the billing service", () => {
+ const ZT = "oss-z-image-turbo";
+ const SCHNELL = "oss-flux1-schnell";
+ beforeEach(() => {
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+ billing.resetBillingCache();
+ });
+
+ it("plain and matched prompts start on the policy's order; lettering keeps its own; when one fails the next in that order makes it", async () => {
+ fake.policy = { ...FAKE_POLICY, auto: { image: [ZT, "not-a-model", SCHNELL, ZT] } };
+ const a = account();
+ accountId = a.id;
+ const plain = await post({ feature: "image", modelId: AUTO_IMAGE, prompt: "a koi pond at night" }, a.cookie, true);
+ expect(plain.status, JSON.stringify(plain.body)).toBe(200);
+ expect(plain.body).toMatchObject({ place: "pool", modelId: ZT });
+ const cat = await post({ feature: "image", modelId: AUTO_IMAGE, prompt: "a cat in an antique-gold paillette gown, her hair lifting in the wind" }, a.cookie, true);
+ expect(cat.body).toMatchObject({ place: "pool", modelId: ZT });
+ const sign = await post({ feature: "image", modelId: AUTO_IMAGE, prompt: 'a neon sign that says "OPEN"' }, a.cookie, true);
+ expect(sign.body).toMatchObject({ place: "pool", modelId: H3 });
+
+ failing = new Set([ZT]);
+ const shown = { amount: (plain.body.quote as { amount: number }).amount, priceVersion: (plain.body.quote as { priceVersion: string }).priceVersion };
+ const r = await post({ feature: "image", modelId: AUTO_IMAGE, prompt: "a koi pond at night", shown }, a.cookie);
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ const g = await settled(r.body.items![0].id);
+ expect(g.status, g.error ?? "").toBe("succeeded");
+ expect(sent.map((s) => s.model)).toEqual([ZT, SCHNELL]);
+ expect(g.request.auto).toEqual({ model: SCHNELL, why: "fallback" });
+ });
+
+ it("a policy with no order (or none Auto may list): the install's own order", async () => {
+ fake.policy = { ...FAKE_POLICY, auto: { image: ["not-a-model"] } };
+ const a = account();
+ accountId = a.id;
+ const plain = await post({ feature: "image", modelId: AUTO_IMAGE, prompt: "a koi pond at night" }, a.cookie, true);
+ expect(plain.body).toMatchObject({ place: "pool", modelId: H3 });
+ });
+
+ it("the menu words reach the viewer cleaned, only while its runs go to this install's GPUs", async () => {
+ fake.policy = { ...FAKE_POLICY, marks: { "oss-krea2-realism": "Pro", [H3]: "Included", "oss-qwen-image": "far too long a word", bad: 3 } };
+ const acct = auth.createAccount(`marks-${++n}@example.com`, "long enough");
+ const { visitorStatus } = await import("@/server/account-gpu");
+ const v = await visitorStatus(acct);
+ expect(v.viewer?.marks).toEqual({ "oss-krea2-realism": "Pro", [H3]: "Included" });
+ fake.policy = { ...FAKE_POLICY };
+ billing.resetBillingCache();
+ expect((await visitorStatus(acct)).viewer?.marks).toBeUndefined();
+ });
+});
diff --git a/tests/auto-image.test.ts b/tests/auto-image.test.ts
index 5a9172d1..0498017e 100644
--- a/tests/auto-image.test.ts
+++ b/tests/auto-image.test.ts
@@ -23,6 +23,7 @@ import {
triggerOrder,
matchedPattern,
nextDeclinedFallback,
+ ownAutoOrder,
} from "@/lib/auto-image";
import { EDIT_STUDIO, IMAGE_STUDIO, INPAINT_STUDIO } from "@/lib/studios";
import { withAutoPattern } from "@/components/add-auto-pattern";
@@ -321,3 +322,22 @@ describe("the order for prompts the patterns match", () => {
expect(autoTriggerModelsProblems(many.slice(0, AUTO_TRIGGER_MAX + 1).join(","), getModel)).toEqual([`Keep it to ${AUTO_TRIGGER_MAX} models`]);
});
});
+
+describe("an account's own order from the billing service (ownAutoOrder)", () => {
+ const t2i = { engine: "open", kind: "image", routes: [{ op: "t2i" }] };
+ const lookup = (id: string) => ({ a: t2i, b: t2i, c: { ...t2i, engine: "cloud" }, d: { ...t2i, routes: [{ op: "edit" }] } })[id as "a"];
+
+ it("keeps the models Auto may list, in order, each once; null when none is left or it isn't a list", () => {
+ expect(ownAutoOrder(["b", " a ", "c", "d", "b", 7, "zz"], lookup)).toEqual(["b", "a"]);
+ expect(ownAutoOrder(["c", "d"], lookup)).toBeNull();
+ expect(ownAutoOrder("a,b", lookup)).toBeNull();
+ expect(ownAutoOrder(undefined, lookup)).toBeNull();
+ });
+
+ it("autoCandidates: a plain prompt follows the given order, lettering and edits keep theirs", () => {
+ expect(autoCandidates({ prompt: "a koi pond" }, [], ["b"], ["a", "b"])).toEqual({ models: ["a", "b"], why: "plain" });
+ expect(autoCandidates({ prompt: "a koi pond" }, [], ["b"], [])).toEqual({ models: [...AUTO_T2I_MODELS], why: "plain" });
+ expect(autoCandidates({ prompt: 'a sign that says "OPEN"' }, [], ["b"], ["a"]).why).toBe("text");
+ expect(autoCandidates({ prompt: "x", images: 1 }, [], ["b"], ["a"]).why).toBe("edit");
+ });
+});
diff --git a/tests/model-marks.test.ts b/tests/model-marks.test.ts
new file mode 100644
index 00000000..5df9265a
--- /dev/null
+++ b/tests/model-marks.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vitest";
+import { cleanMarks, MARK_MAX, MARKS_MAX } from "@/lib/model-marks";
+
+/** The billing service's words for open models in the model menu, as the site keeps them. */
+describe("cleanMarks", () => {
+ it("keeps short words by model id, folded and trimmed", () => {
+ expect(cleanMarks({ a: " Pro ", b: "In\ncluded", c: "", d: 5, e: "x".repeat(MARK_MAX + 1) })).toEqual({ a: "Pro", b: "In cluded" });
+ });
+ it("null for nothing kept or not an object", () => {
+ expect(cleanMarks(null)).toBeNull();
+ expect(cleanMarks(["Pro"])).toBeNull();
+ expect(cleanMarks({ a: "" })).toBeNull();
+ });
+ it("at most MARKS_MAX models", () => {
+ const many = Object.fromEntries(Array.from({ length: MARKS_MAX + 20 }, (_, i) => [`m${i}`, "Pro"]));
+ expect(Object.keys(cleanMarks(many)!)).toHaveLength(MARKS_MAX);
+ });
+});