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.

19.0 KB
Raw Blame
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 run of Auto on this install's GPUs: Auto picks its model there as anywhere (MiniMax H3 Image, then
 * Krea 2 Realism, or MOSS-Image for lettering), MiniMax H3 Image only where a worker allowed its lane has its files and
 * the VRAM it needs; when a model fails, the next one makes the same run on the same GPUs. One press of Run stays one
 * run: the hourly count, the runs at once and the billing hold count it once; the account reads which model made its
 * picture. The price before Run is the picked model's. (The owner's runs: tests/auto-image-runs.test.ts; a GPU the check
 * reads: tests/auto-image-gpu.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-auto-image-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 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 { AUTO_IMAGE } = await import("@/lib/auto-image");
const { autoLine } = await import("@/lib/auto-image");
const { encodePng } = await import("@/server/png");

const H3 = "oss-minimax-h3-image";
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 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(`auto-${++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, preview = false) => {
  const text = JSON.stringify(body);
  const r = await generationsRoute.POST(
    new Request(`http://${HOST}/api/generations${preview ? "?preview=1" : ""}`, { 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; modelId?: string; modelName?: string; place?: string; quote?: Record<string, unknown> } };
};

/**
 * A worker as the owner adds it, connected: the line is open for the account's runs. `vramGb`: its card (96 GB by
 * default); `without`: workflows whose files it doesn't hold.
 */
function standInWorker(o: { vramGb?: number; without?: string[] } = {}) {
  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 });
  const workflows = loadManifest()
    .workflows.map((x) => x.id)
    .filter((id) => !o.without?.includes(id));
  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 }), JSON.stringify({ vramBytes: (o.vramGb ?? 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 failing = new Set<string>();
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 = [];
  failing = new Set();
  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) => {
    if (failing.has(ctx.model.id)) return { state: "failed", error: "Out of memory on the GPU" };
    let pics = answers.get(ctx.externalId);
    if (!pics) answers.set(ctx.externalId, (pics = [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 run of Auto on this install's GPUs", () => {
  it("a plain prompt: MiniMax H3 Image, with no Ideogram 4 or FIBO 2 Dev job", async () => {
    const a = account();
    accountId = a.id;
    const r = await post({ feature: "image", modelId: AUTO_IMAGE, prompt: "a red fox in deep snow", params: { aspectRatio: "4:5" } }, 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(g.place).toBe("pool");
    expect(sent.map((s) => s.model)).toEqual([H3]);
    expect(g.request.auto).toEqual({ model: H3, why: "plain" });
    expect(autoLine(g)).toBe("Auto · made with MiniMax H3 Image");
  });

  it("MiniMax H3 Image fails: Krea 2 Realism makes it there at once, and it counts as one run", async () => {
    const a = account();
    accountId = a.id;
    failing = new Set([H3]);
    const r = await post({ feature: "image", modelId: AUTO_IMAGE, 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-krea2-realism");
    expect(g.request.modelId).toBe(AUTO_IMAGE);
    expect(g.request.auto).toEqual({ model: "oss-krea2-realism", why: "fallback" });
    expect(autoLine(g)).toBe("Auto · made with Krea 2 Realism · Auto's next model");
    expect(sent.map((s) => [s.model, s.id])).toEqual([
      [H3, id],
      ["oss-krea2-realism", id],
    ]);
    expect(sent[1].tile.status).toBe("running");
    expect(sent[1].tile.message).toBe("Making it with Krea 2 Realism");
    expect(sent[1].tile.queue).toBeUndefined();
    expect(sent.map((s) => s.going)).toEqual([1, 1]);
    expect(sent.map((s) => s.hourly)).toEqual([1, 1]);
    expect(admitted(a.id)).toBe(1);
    expect(rowsOf(a.id)).toBe(1);
  });

  it("lettering: MiniMax H3 Image first, then MOSS-Image when it fails, still one run", async () => {
    const a = account();
    accountId = a.id;
    failing = new Set([H3]);
    const r = await post({ feature: "image", modelId: AUTO_IMAGE, prompt: 'a sign that says "LIGHTHOUSE" at dusk' }, 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([H3, "oss-moss-image"]);
    expect(g.modelId).toBe("oss-moss-image");
    expect(g.request.auto).toEqual({ model: "oss-moss-image", why: "fallback" });
    expect(sent.map((s) => s.hourly)).toEqual([1, 1]);
    expect(admitted(a.id)).toBe(1);
    expect(rowsOf(a.id)).toBe(1);
  });

  it("all fail: each tried once, then the run fails once, as one run", async () => {
    const a = account();
    accountId = a.id;
    failing = new Set([H3, "oss-krea2-realism", "oss-moss-image"]);
    const r = await post({ feature: "image", modelId: AUTO_IMAGE, prompt: "a lighthouse at dusk" }, a.cookie);
    expect(r.status, JSON.stringify(r.body)).toBe(201);
    const g = await settled(r.body.items![0].id);
    expect(g.status).toBe("failed");
    expect(sent.map((s) => s.model)).toEqual([H3, "oss-krea2-realism", "oss-moss-image"]);
    expect(admitted(a.id)).toBe(1);
    expect(rowsOf(a.id)).toBe(1);
  });

  it("workers whose cards are too small for MiniMax H3 Image's lane: Krea 2 Realism, or MOSS-Image for lettering, priced as that", async () => {
    db().prepare("DELETE FROM relay_workers").run();
    standInWorker({ vramGb: 24 });
    const a = account();
    accountId = a.id;
    const price = await post({ feature: "image", modelId: AUTO_IMAGE, prompt: "a koi pond at night" }, a.cookie, true);
    expect(price.body).toMatchObject({ place: "pool", modelId: "oss-krea2-realism", quote: { allowed: true } });
    const words = await post({ feature: "image", modelId: AUTO_IMAGE, prompt: 'a sign that says "OPEN"' }, a.cookie, true);
    expect(words.body).toMatchObject({ place: "pool", modelId: "oss-moss-image" });
    // When Krea 2 Realism fails there, MOSS-Image makes it: MiniMax H3 Image is never sent to a card that can't take it.
    failing = new Set(["oss-krea2-realism"]);
    const r = await post({ feature: "image", modelId: AUTO_IMAGE, prompt: "a red fox in deep snow" }, 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(["oss-krea2-realism", "oss-moss-image"]);
  });

  it("workers without MiniMax H3 Image's files: the next model; one worker with them is enough", async () => {
    db().prepare("DELETE FROM relay_workers").run();
    standInWorker({ without: ["minimax-h3-image-t2i", "minimax-h3-image-edit"] });
    const a = account();
    accountId = a.id;
    const plain = { feature: "image", modelId: AUTO_IMAGE, prompt: "a koi pond at night" };
    expect((await post(plain, a.cookie, true)).body).toMatchObject({ place: "pool", modelId: "oss-krea2-realism" });
    standInWorker({ vramGb: 32 });
    expect((await post(plain, a.cookie, true)).body).toMatchObject({ place: "pool", modelId: H3, modelName: "MiniMax H3 Image" });
  });

  it("a prompt the patterns match goes to Krea 2 Realism, a plain one to MiniMax H3 Image; the price before Run is that model's", async () => {
    const a = account();
    accountId = a.id;
    const cat = { feature: "image", modelId: AUTO_IMAGE, prompt: "a cat in an antique-gold paillette gown, her hair lifting in the wind" };
    const price = await post(cat, a.cookie, true);
    expect(price.status, JSON.stringify(price.body)).toBe(200);
    expect(price.body).toMatchObject({ place: "pool", modelId: "oss-krea2-realism", modelName: "Krea 2 Realism", quote: { allowed: true } });
    const plain = await post({ ...cat, prompt: "a koi pond at night" }, a.cookie, true);
    expect(plain.body).toMatchObject({ place: "pool", modelId: H3, modelName: "MiniMax H3 Image", quote: { allowed: true } });
    const r = await post(cat, 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(["oss-krea2-realism"]);
    expect(g.request.auto).toEqual({ model: "oss-krea2-realism", why: "trigger" });
    expect(admitted(a.id)).toBe(1);
  });

  it("an account can't read or change Auto's patterns", async () => {
    const a = account();
    const { proxy } = await import("@/proxy");
    const { NextRequest } = await import("next/server");
    const req = (method: string) => new NextRequest(`http://${HOST}/api/settings`, { method, headers: { ...SITE_HEADERS, cookie: a.cookie, "content-type": "application/json" }, ...(method === "PUT" && { body: JSON.stringify({ autoImagePatterns: "koi" }) }) });
    expect((await proxy(req("GET"))).status).toBe(403);
    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();
  });

  it("the bar's link reaches guests and accounts cleaned, and the balance carries the browser's time zone", async () => {
    fake.policy = { ...FAKE_POLICY, navLink: { label: "Go Unlimited", url: "/pricing?from=nav" } } as typeof FAKE_POLICY;
    const acct = auth.createAccount(`navlink-${++n}@example.com`, "long enough");
    const { visitorStatus } = await import("@/server/account-gpu");
    expect((await visitorStatus(acct, "Asia/Kolkata")).viewer?.navLink).toEqual({ label: "Go Unlimited", url: "/pricing?from=nav" });
    expect((await visitorStatus(null)).viewer?.navLink).toEqual({ label: "Go Unlimited", url: "/pricing?from=nav" });
    expect(fake.calls_of("/v1/balance").at(-1)?.path).toBe(`/v1/balance?account=${encodeURIComponent(acct.id)}&tz=Asia%2FKolkata`);
    fake.policy = { ...FAKE_POLICY, navLink: { label: "Go", url: "https://example.com" } } as typeof FAKE_POLICY;
    billing.resetBillingCache();
    expect((await visitorStatus(acct)).viewer?.navLink).toBeUndefined();
  });
});