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.

Tests: hosted runs on and off, the run and output checks, and a release when a run can't be made

Adarsh6526bac41aa3
diff --git a/tests/billing-release.test.ts b/tests/billing-release.test.ts
new file mode 100644
index 00000000..c01ec61a
--- /dev/null
+++ b/tests/billing-release.test.ts
@@ -0,0 +1,70 @@
+import fs from "node:fs";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { listenInRange, startFakeBilling, type FakeBilling } from "./helpers/fake-billing";
+import { startFakeComfy, type FakeComfy } from "./helpers/fake-comfy-runner";
+
+// A run whose rows can't be made after its price was set aside: the hold is released once (docs/billing-hook.md).
+vi.mock("@/server/generations", async (importOriginal) => {
+ const real = await importOriginal<typeof import("@/server/generations")>();
+ return {
+ ...real,
+ createGenerations: () => {
+ throw new Error("Something broke while the run was being made");
+ },
+ };
+});
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-billing-release-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+process.env.FUOBE_HOSTED_RUNS = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_MODERATION_URL;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const probe = http.createServer();
+const comfyPort = await listenInRange(probe);
+await new Promise<void>((r) => probe.close(() => r()));
+const comfy: FakeComfy = await startFakeComfy({ output: "image", delayMs: 0 }, comfyPort);
+process.env.COMFYUI_URL = comfy.url;
+
+const auth = await import("@/server/auth");
+const generationsRoute = await import("@/app/api/generations/route");
+
+let fake: FakeBilling;
+let cookie = "";
+beforeAll(async () => {
+ fake = await startFakeBilling();
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+ auth.setPassword("install password");
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(auth.createAccount("[email protected]", "long enough").id).value}`;
+});
+afterAll(async () => {
+ globalThis.__fuobeTestDiskFree = undefined;
+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];
+ await fake.close();
+ await comfy.close();
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+describe("a run that can't be made after its reserve", () => {
+ it("sends one release for its hold", async () => {
+ const text = JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox", shown: { amount: 7, priceVersion: "v7" } });
+ const r = await generationsRoute.POST(new Request("http://localhost:3000/api/generations", { method: "POST", headers: { cookie, host: "localhost:3000", "content-type": "application/json", "content-length": String(text.length) }, body: text }));
+ expect(r.status).toBe(422);
+ expect(fake.calls_of("/v1/reserve")).toHaveLength(1);
+ const end = Date.now() + 10_000;
+ while (!fake.calls_of("/v1/release").length && Date.now() < end) await new Promise((res) => setTimeout(res, 50));
+ const releases = fake.calls_of("/v1/release");
+ expect(releases).toHaveLength(1);
+ const hold = [...fake.holds.keys()][0];
+ expect(releases[0].body).toEqual({ holdId: hold, reason: "not-created" });
+ expect(fake.holds.get(hold)!.released).toBe(true);
+ });
+});
diff --git a/tests/hosted-runs.test.ts b/tests/hosted-runs.test.ts
new file mode 100644
index 00000000..bc469150
--- /dev/null
+++ b/tests/hosted-runs.test.ts
@@ -0,0 +1,149 @@
+import fs from "node:fs";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { listenInRange, startFakeBilling, type FakeBilling } from "./helpers/fake-billing";
+import { startFakeComfy, TINY_MP4, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";
+
+// Hosted runs (FUOBE_HOSTED_RUNS=1): off, everything is as before; on, an account with no GPU of its own may run in
+// the studios on this install's ComfyUI, and every other tool still needs its own GPU.
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-hosted-runs-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_HOSTED_RUNS;
+delete process.env.FUOBE_BILLING_URL;
+delete process.env.FUOBE_MODERATION_URL;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const probe = http.createServer();
+const comfyPort = await listenInRange(probe);
+await new Promise<void>((r) => probe.close(() => r()));
+const comfy: FakeComfy = await startFakeComfy({ output: "image", delayMs: 0 }, comfyPort);
+process.env.COMFYUI_URL = comfy.url;
+
+const auth = await import("@/server/auth");
+const generationsRoute = await import("@/app/api/generations/route");
+const uploadsRoute = await import("@/app/api/uploads/route");
+const { proxy } = await import("@/proxy");
+const { NextRequest } = await import("next/server");
+const { resetRates } = await import("@/server/rate");
+const billing = await import("@/server/billing");
+const { visitorStatus } = await import("@/server/account-gpu");
+const { poolAllows } = await import("@/server/hosted");
+
+let fake: FakeBilling;
+let a = "";
+let cookie = "";
+beforeAll(async () => {
+ fake = await startFakeBilling();
+ auth.setPassword("install password");
+ a = auth.createAccount("[email protected]", "long enough").id;
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;
+});
+afterAll(async () => {
+ globalThis.__fuobeTestDiskFree = undefined;
+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];
+ await fake.close();
+ await comfy.close();
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+beforeEach(() => {
+ resetRates();
+ billing.resetBillingCache();
+ delete process.env.FUOBE_HOSTED_RUNS;
+ delete process.env.FUOBE_BILLING_URL;
+ fake.policy = { hosted: true, pool: {}, uploads: { image: true, video: false, audio: false }, limits: { activeRuns: 7, waiting: 7, runsPerHour: 70, outputsPerRun: 2, maxMegapixels: 7, maxSeconds: 7, keepDays: 7, spaceBytes: 7 }, ttlS: 0 };
+});
+
+const headers = (extra: Record<string, string> = {}) => ({ cookie, host: "localhost:3000", ...extra });
+const viaProxy = (url: string, method = "POST") => proxy(new NextRequest(`http://localhost:3000${url}`, { method, headers: headers({ "content-type": "application/json" }), body: method === "POST" ? "{}" : undefined }));
+const post = (body: unknown) => {
+ const text = JSON.stringify(body);
+ return generationsRoute.POST(new Request("http://localhost:3000/api/generations", { method: "POST", headers: headers({ "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }), body: text }));
+};
+const upload = (bytes: Buffer, type: string, name: string) =>
+ uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: headers({ "content-type": type, "x-file-name": name, "content-length": String(bytes.length) }), body: bytes }));
+
+describe("hosted runs off (the default)", () => {
+ it("an account with no GPU or key: runs and uploads say Connect your GPU, and the status says nothing new", async () => {
+ const r = await viaProxy("/api/generations");
+ expect(r.status).toBe(403);
+ expect(((await r.json()) as { code: string }).code).toBe("connect-gpu");
+ expect((await upload(TINY_PNG, "image/png", "me.png")).status).toBe(403);
+ const s = await visitorStatus(auth.accountById(a)!);
+ expect(s.viewer.hosted).toBeUndefined();
+ expect(s.viewer.balance).toBeUndefined();
+ });
+});
+
+describe("hosted runs on", () => {
+ beforeEach(() => {
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ });
+
+ it("a studio run reaches the route; other tools still need the account's own GPU", async () => {
+ const r = await viaProxy("/api/generations");
+ expect(r.status).not.toBe(403);
+ const other = await viaProxy("/api/enhance");
+ expect(other.status).toBe(403);
+ expect(((await other.json()) as { code: string }).code).toBe("own-gpu-tool");
+ });
+
+ it("an account may add pictures for its runs here, not clips (the default policy)", async () => {
+ expect((await upload(TINY_PNG, "image/png", "me.png")).status).toBe(201);
+ const clip = await upload(TINY_MP4, "video/mp4", "me.mp4");
+ expect(clip.status).toBe(403);
+ expect(((await clip.json()) as { code: string }).code).toBe("connect-gpu");
+ });
+
+ it("the status says hosted runs are open", async () => {
+ const s = await visitorStatus(auth.accountById(a)!);
+ expect(s.viewer.hosted).toBe(true);
+ expect((await visitorStatus(null)).viewer.hosted).toBe(true);
+ });
+
+ it("refuses here what runs only on an account's own GPU: extra LoRAs, a model the policy leaves out", async () => {
+ const loras = await post({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox", loras: [{ file: "x.safetensors", url: "https://huggingface.co/x/x.safetensors" }] });
+ expect(loras.status).toBe(403);
+ expect(((await loras.json()) as { code: string }).code).toBe("not-offered");
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+ fake.policy = { ...fake.policy, pool: { deny: ["oss-z-image-turbo"] } };
+ const denied = await post({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" });
+ expect(denied.status).toBe(403);
+ expect(denied.headers.get("x-fuobe-billing")).toBe("not-offered");
+ });
+
+ it("an account the policy keeps off this install's GPUs gets today's answer", async () => {
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+ fake.policy = { ...fake.policy, hosted: false };
+ const r = await post({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" });
+ expect(r.status).toBe(403);
+ expect(((await r.json()) as { code: string }).code).toBe("connect-gpu");
+ expect((await visitorStatus(auth.accountById(a)!)).viewer.hosted).toBeUndefined();
+ });
+
+ it("the pool's allow and deny lists, for models and apps", () => {
+ expect(poolAllows({ pool: {} }, "m")).toBe(true);
+ expect(poolAllows({ pool: { allow: ["m"] } }, "m")).toBe(true);
+ expect(poolAllows({ pool: { allow: ["n"] } }, "m")).toBe(false);
+ expect(poolAllows({ pool: { deny: ["m"] } }, "m")).toBe(false);
+ expect(poolAllows({ pool: { apps: { deny: ["app-x"] } } }, "m", "app-x")).toBe(false);
+ expect(poolAllows({ pool: { apps: { allow: ["app-y"] } } }, "m", "app-x")).toBe(false);
+ });
+
+ it("an install whose ComfyUI is on the owner's computer doesn't offer hosted runs", async () => {
+ process.env.COMFYUI_WHERE = "computer";
+ try {
+ const { poolReady } = await import("@/server/hosted");
+ expect(poolReady()).toBe(false);
+ } finally {
+ delete process.env.COMFYUI_WHERE;
+ }
+ });
+});
diff --git a/tests/moderation-hook.test.ts b/tests/moderation-hook.test.ts
new file mode 100644
index 00000000..f841cba9
--- /dev/null
+++ b/tests/moderation-hook.test.ts
@@ -0,0 +1,209 @@
+import fs from "node:fs";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { listenInRange, startFakeBilling, startFakeModeration, type FakeBilling, type FakeModeration } from "./helpers/fake-billing";
+import { startFakeComfy, type FakeComfy } from "./helpers/fake-comfy-runner";
+
+// The moderation hook (docs/moderation-hook.md): the run check, the optional output check and reports, against
+// stand-in services. It ships off: with no address set nothing is checked.
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-moderation-hook-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_BILLING_URL;
+delete process.env.FUOBE_MODERATION_URL;
+process.env.FUOBE_HOSTED_RUNS = "1";
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const probe = http.createServer();
+const comfyPort = await listenInRange(probe);
+await new Promise<void>((r) => probe.close(() => r()));
+const comfy: FakeComfy = await startFakeComfy({ output: "image", delayMs: 0 }, comfyPort);
+process.env.COMFYUI_URL = comfy.url;
+
+const auth = await import("@/server/auth");
+const generationsRoute = await import("@/app/api/generations/route");
+const reportsRoute = await import("@/app/api/reports/route");
+const { proxy } = await import("@/proxy");
+const { NextRequest } = await import("next/server");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const billing = await import("@/server/billing");
+const outbox = await import("@/server/billing-outbox");
+const checks = await import("@/server/output-checks");
+const { getGeneration } = await import("@/server/generations");
+const { fileAccount, fileHeld } = await import("@/server/account-library");
+const { listReports } = await import("@/server/moderation");
+
+let mod: FakeModeration;
+let bill: FakeBilling;
+let a = "";
+let cookie = "";
+beforeAll(async () => {
+ mod = await startFakeModeration();
+ bill = await startFakeBilling();
+ auth.setPassword("install password");
+ a = auth.createAccount("[email protected]", "long enough").id;
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;
+});
+afterAll(async () => {
+ globalThis.__fuobeTestDiskFree = undefined;
+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_MODERATION_URL", "FUOBE_MODERATION_TOKEN", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];
+ await mod.close();
+ await bill.close();
+ await comfy.close();
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+beforeEach(() => {
+ resetRates();
+ billing.resetBillingCache();
+ mod.calls.length = 0;
+ mod.down = false;
+ mod.run = { allowed: true, checkOutputs: false };
+ mod.output = { decision: "show" };
+ bill.calls.length = 0;
+ process.env.FUOBE_MODERATION_URL = mod.url;
+ process.env.FUOBE_MODERATION_TOKEN = "test-moderation-token";
+ delete process.env.FUOBE_BILLING_URL;
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+});
+
+const post = (body: unknown) => {
+ const text = JSON.stringify(body);
+ return generationsRoute.POST(new Request("http://localhost:3000/api/generations", { method: "POST", headers: { cookie, host: "localhost:3000", "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }, body: text }));
+};
+const run = { feature: "image", modelId: "oss-z-image-turbo", prompt: "a quiet harbour" };
+const row = (id: string) => db().prepare("SELECT status, stage, error, outputs_json FROM generations WHERE id = ?").get(id) as { status: string; stage: string | null; error: string | null; outputs_json: string };
+
+async function until(fn: () => boolean, ms = 20_000): Promise<void> {
+ const end = Date.now() + ms;
+ while (!fn()) {
+ if (Date.now() > end) throw new Error("timed out waiting");
+ await new Promise((r) => setTimeout(r, 100));
+ }
+}
+
+async function started(body: unknown = run): Promise<string> {
+ const r = await post(body);
+ expect(r.status).toBe(201);
+ return ((await r.json()) as { items: { id: string }[] }).items[0].id;
+}
+
+describe("with no moderation service", () => {
+ it("checks nothing, and a report waits for the owner", async () => {
+ delete process.env.FUOBE_MODERATION_URL;
+ const id = await started();
+ await until(() => row(id).status === "succeeded");
+ expect(row(id).stage).toBeNull();
+ expect(mod.calls).toEqual([]);
+ const r = await reportsRoute.POST(new Request("http://localhost:3000/api/reports", { method: "POST", headers: { host: "localhost:3000", "content-type": "application/json" }, body: JSON.stringify({ target: { generationId: id }, category: "other", text: "looks wrong" }) }));
+ expect(r.status).toBe(201);
+ expect(mod.calls).toEqual([]);
+ const items = listReports();
+ expect(items.some((i) => i.target.generationId === id && i.category === "other")).toBe(true);
+ });
+});
+
+describe("the run check", () => {
+ it("a blocked run makes nothing and sets nothing aside", async () => {
+ process.env.FUOBE_BILLING_URL = bill.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+ mod.run = { allowed: false, code: "blocked", text: "This request can't be made here." };
+ const before = (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
+ const r = await post({ ...run, shown: { amount: 7, priceVersion: "v7" } });
+ expect(r.status).toBe(403);
+ expect(((await r.json()) as { error: string }).error).toBe("This request can't be made here.");
+ expect((db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n).toBe(before);
+ expect(bill.calls_of("/v1/reserve")).toEqual([]);
+ const sent = mod.calls_of("/v1/check-run")[0];
+ expect(sent.headers.authorization).toBe("Bearer test-moderation-token");
+ expect(sent.body).toMatchObject({ prompt: "a quiet harbour", account: { id: a }, consent: null });
+ });
+
+ it("no answer: the run is refused as paused", async () => {
+ mod.down = true;
+ const r = await post(run);
+ expect(r.status).toBe(503);
+ });
+});
+
+describe("the output check", () => {
+ it("checkOutputs false: no Checking stage and no output check; the result shows at once", async () => {
+ const id = await started();
+ await until(() => row(id).status === "succeeded");
+ expect(mod.calls_of("/v1/check-output")).toEqual([]);
+ });
+
+ it("an answer with no checkOutputs field: the outputs are held, never served, until the check says show", async () => {
+ mod.run = { allowed: true };
+ mod.output = { decision: "wait", retryAfterS: 3600 };
+ const id = await started();
+ await until(() => row(id).stage === "checking");
+ const g = getGeneration(id)!;
+ expect(g.stage).toBe("checking");
+ expect(g.outputs).toEqual([]);
+ const held = (JSON.parse(row(id).outputs_json) as { url: string }[])[0].url.replace(/^\/api\/files\//, "");
+ expect(fileHeld(held)).toBe(true);
+ expect(fileAccount(held)).not.toBe(a);
+ // The account's own request for the file is refused by the sign-in proxy.
+ const res = await proxy(new NextRequest(`http://localhost:3000/api/files/${held}`, { headers: { cookie, host: "localhost:3000" } }));
+ expect(res.status).toBe(403);
+ await until(() => mod.calls_of("/v1/check-output").length > 0);
+ const asked = mod.calls_of("/v1/check-output")[0];
+ expect(asked.headers["x-fuobe-generation"]).toBe(id);
+ expect(asked.headers["x-fuobe-kind"]).toBe("image");
+ expect(asked.bytes!.length).toBeGreaterThan(0);
+ // Show: served, and the row succeeds.
+ mod.output = { decision: "show" };
+ db().prepare("UPDATE output_checks SET next_at = 0 WHERE generation_id = ?").run(id);
+ await checks.sweepOutputChecks();
+ expect(row(id).status).toBe("succeeded");
+ expect(fileHeld(held)).toBe(false);
+ expect(fileAccount(held)).toBe(a);
+ });
+
+ it("hide: the file goes, the row fails, and its hold is refunded as hidden", async () => {
+ process.env.FUOBE_BILLING_URL = bill.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+ mod.run = { allowed: true, checkOutputs: true };
+ mod.output = { decision: "hide", text: "Removed by the checks. Not charged." };
+ const id = await started({ ...run, shown: { amount: 7, priceVersion: "v7" } });
+ await until(() => row(id).status === "failed");
+ expect(row(id).error).toBe("Removed by the checks. Not charged.");
+ expect(getGeneration(id)!.notCharged).toBe(true);
+ await outbox.sweepBilling();
+ const hold = [...bill.holds.entries()].find(([, h]) => h.reports.has(id));
+ expect(hold?.[1].reports.get(id)).toBe("hidden");
+ });
+
+ it("past the wait (a faked clock), the row fails and its files go", async () => {
+ mod.run = { allowed: true, checkOutputs: true };
+ mod.output = { decision: "wait", retryAfterS: 3600 };
+ const id = await started();
+ await until(() => row(id).stage === "checking");
+ const file = (JSON.parse(row(id).outputs_json) as { assetId: string }[])[0].assetId;
+ await checks.sweepOutputChecks(Date.now() + 25 * 3_600_000);
+ expect(row(id).status).toBe("failed");
+ expect(row(id).error).toBe(checks.UNCHECKED_WORDS);
+ expect(db().prepare("SELECT 1 FROM assets WHERE id = ?").get(file)).toBeUndefined();
+ });
+});
+
+describe("reports", () => {
+ it("go to the service when one is set", async () => {
+ const r = await reportsRoute.POST(new Request("http://localhost:3000/api/reports", { method: "POST", headers: { cookie, host: "localhost:3000", "content-type": "application/json" }, body: JSON.stringify({ target: { shareId: "abc123" }, category: "impersonation", text: "not me" }) }));
+ expect(r.status).toBe(201);
+ expect(((await r.json()) as { text: string }).text).toBe("Report received.");
+ expect(mod.calls_of("/v1/report")[0].body).toMatchObject({ target: { shareId: "abc123" }, category: "impersonation", reporter: { account: a, email: "[email protected]" } });
+ });
+
+ it("refuse a report with no target or no category", async () => {
+ const send = (body: unknown) => reportsRoute.POST(new Request("http://localhost:3000/api/reports", { method: "POST", headers: { host: "localhost:3000", "content-type": "application/json" }, body: JSON.stringify(body) }));
+ expect((await send({ category: "other" })).status).toBe(400);
+ expect((await send({ target: { generationId: "x" }, category: "nope" })).status).toBe(400);
+ });
+});