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
Runs: an owner's run asked for with an API token is an api run on every route
Adarshf525ff53e74f
diff --git a/docs/cli.md b/docs/cli.mdindex f67bd119..48012815 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -353,7 +353,8 @@ For script writers who'd rather call the API directly: `GET /api/models` (`kind``connected` and `runs`), `POST /api/generations` (with `?preview=1` to price; a model id Fuobe hasretired runs on the model that replaced it, and the answer gives that `modelId` with `notes` saying so;a script can say what made the run with `source` (`batch`, `drill`, `example` or `test`) and `sourceName` (its own-name, up to 80 characters); a run sent with an API token and no `source` reads as `api`, and the admin runs list tells+name, up to 80 characters); a run sent with an API token and no `source` reads as `api`, through any route that makes one (the studios'+and apps' routes too), and the admin runs list tellsall of them apart from `hands-on` runs made on the site),`GET /api/generations[/<id>]`,`POST /api/generations/<id>/cancel`, `POST /api/uploads` (multipart `file`), `GET /api/files/…`,diff --git a/src/server/api-caller.ts b/src/server/api-caller.tsnew file mode 100644index 00000000..62084c67--- /dev/null+++ b/src/server/api-caller.ts@@ -0,0 +1,42 @@+import "server-only";+import { AsyncLocalStorage } from "node:async_hooks";+import { workUnitAsyncStorage } from "next/dist/server/app-render/work-unit-async-storage.external";++/**+ * Was this request sent with the owner's API token (a script, the CLI, MCP, an agent), not from the signed-in browser?+ * Every route that makes a run (POST /api/generations, the studios, apps, Canvas, Chat's tools…) reads it in one place:+ * an owner's run made this way that says no source of its own is recorded as `source: "api"` (generations.ts+ * createGenerations). The generation runner and the other loops start when the server starts, outside any request, so+ * they never carry it.+ *+ * Two ways to know: auth.ts validToken marks the request it accepts a token for, for the rest of that request's work+ * (an async helper that checks the token after an await of its own marks only its own work), and the request Next is+ * handling carries its Authorization header (requestAuthorization), which generations.ts checks again.+ */++declare global {+ var __fuobeApiCaller: AsyncLocalStorage<boolean> | undefined;+}++// One store for the whole server process, however its modules are bundled.+const store = (globalThis.__fuobeApiCaller ??= new AsyncLocalStorage<boolean>());++/** Mark the request being handled as one sent with an API token (for the rest of its work). */+export const markApiCaller = (): void => store.enterWith(true);++/** Was the work in hand marked as part of a request sent with an API token? */+export const apiCaller = (): boolean => store.getStore() === true;++/** Run `fn` as a request of its own, which a token it accepts marks without touching the caller's (tests). */+export const asOwnRequest = <T,>(fn: () => T): T => store.run(false, fn);++/** The Authorization header of the request Next is handling now (null: none, or no request: a loop, a test). */+export function requestAuthorization(): string | null {+ try {+ const s = workUnitAsyncStorage.getStore();+ if (s?.type !== "request" || typeof s.headers?.get !== "function") return null;+ return s.headers.get("authorization");+ } catch {+ return null;+ }+}diff --git a/src/server/auth.ts b/src/server/auth.tsindex d4f805ec..09d18768 100644--- a/src/server/auth.ts+++ b/src/server/auth.ts@@ -18,6 +18,7 @@ import crypto from "node:crypto";import net from "node:net";import os from "node:os";import { LOCAL_SUFFIXES } from "@/lib/page-place";+import { markApiCaller } from "./api-caller";import { accountFrom, authStoreClosed, authStoreVersion, authWrite, sql, type AccountRow, type GpuRow, type KeyRow } from "./auth-store";export const SESSION_COOKIE = "fuobe_session";@@ -866,5 +867,7 @@ export function validToken(header: string | null): boolean {console.warn(`[fuobe] Couldn't note an API token's use: ${(e as Error).message}`);}}+ // The rest of this request's work was asked for with a token: an owner's run it makes says so (api-caller.ts).+ markApiCaller();return true;}diff --git a/src/server/generations.ts b/src/server/generations.tsindex ff8b8709..9ce00922 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -82,7 +82,7 @@ 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 { accountById, accountGpu, gpuLink, type AccountGpu } from "./auth";+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";import { cachedGpuState, GpuError, noteGpuState, testGpu } from "./account-gpu";@@ -115,6 +115,7 @@ import { cleanEngineText, ENGINE_WORDS, isEngineWords, storedErrorText, withoutFimport { CONNECT_GPU_MESSAGE, GUEST_RUN_MESSAGE, OWN_GPU_TOOL_MESSAGE } from "@/lib/guest-access";import { MODEL3D_SETUP, ownSetupLabel } from "@/lib/own-setup";import { outsideTenant, runAsTenant, tenant, tenantAccount } from "./tenant";+import { apiCaller, requestAuthorization } from "./api-caller";import { generationAccount } from "./account-library";import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "./account-files";import { prunePoolAdmissions } from "./pool-limits";@@ -1555,6 +1556,13 @@ export interface CreateOptions {const depIds = (v: string | null): string[] => (!v ? [] : v.startsWith("[") ? (JSON.parse(v) as string[]) : [v]);+/** Is the work in hand part of a request sent with the owner's API token (api-caller.ts)? */+function viaApiToken(): boolean {+ if (apiCaller()) return true;+ const header = requestAuthorization();+ return !!header && validToken(header);+}+/*** Public sign-up: inside an account's run (accountRun) every request it makes, and every step its chains queue, is* stamped as the account's own: on the open engine, or the engine it asked for while it may use paid models on its own@@ -1566,8 +1574,11 @@ function stampTenant(asked: GenerationRequest, opts: CreateOptions): GenerationRconst who = tenantAccount();if (!who) {if (ownGpu()) throw new Error("We can't find that run.");- // The owner's runs carry no place, hold or check of an account's run (run-stamp.ts).- return withRunStamp({}, () => stamped(asked));+ // The owner's runs carry no place, hold or check of an account's run (run-stamp.ts). One asked for with an API token+ // (any route: the studios, apps, Canvas, Chat's tools…) that says no source of its own is an "api" run: only a run+ // from the signed-in browser is hands-on (api-caller.ts).+ const sourced = !asked.source && viaApiToken() ? { ...asked, source: "api" as const } : asked;+ return withRunStamp({}, () => stamped(sourced));}if (asked.account && asked.account !== who) throw new Error("We can't find that run.");const deps = opts.dependsOn === undefined ? [] : Array.isArray(opts.dependsOn) ? opts.dependsOn : [opts.dependsOn];@@ -5306,6 +5317,9 @@ export function finishOutput(id: string, index: number, png: Buffer): Generation// ---------------------------------------------------------------------------// Results made in the browser (colour grading): stored as finished generations.+/** An owner's result recorded through an API token: an "api" run (createGenerations does the same for runs). */+const ownerApiSource = (): Pick<GenerationRequest, "source"> => (!tenantAccount() && viaApiToken() ? { source: "api" } : {});+/*** A live edit saved to the Library (the owner's): the kept master as the result, the steps that made it in* params.liveSteps, the joined step texts as the prompt. It ran on the owner's GPU already, so nothing is queued.@@ -5317,6 +5331,7 @@ export function recordLiveEdit(input: { master: string; original?: string; stepsconst prompt = input.steps.map((s) => s.text).filter(Boolean).join(" · ").slice(0, 2000) || "Live edit";const op: Generation["op"] = input.original ? "edit" : "t2i";const req: GenerationRequest = {+ ...ownerApiSource(),feature: "live-edit",modelId: model.id,op,@@ -5374,7 +5389,7 @@ export function recordLocalGeneration(input: {const now = Date.now();// Inside an account's work (the route's runAsTenant) the result is the account's own, as its runs are (stampTenant).const account = tenantAccount();- const req: GenerationRequest = { feature: input.feature, modelId: input.modelId, op: input.op, prompt: input.prompt, ...(input.title && { title: input.title }), inputs: input.inputs, params: input.params, ...(account && { account }) };+ const req: GenerationRequest = { feature: input.feature, modelId: input.modelId, op: input.op, prompt: input.prompt, ...(input.title && { title: input.title }), inputs: input.inputs, params: input.params, ...(account ? { account } : ownerApiSource()) };const row: Row = {id: nanoid(12),batch_id: null,diff --git a/tests/owner-hands-on.test.ts b/tests/owner-hands-on.test.tsindex 61893e18..42ae7ee4 100644--- a/tests/owner-hands-on.test.ts+++ b/tests/owner-hands-on.test.ts@@ -1,4 +1,5 @@import crypto from "node:crypto";+import { AsyncLocalStorage } from "node:async_hooks";import fs from "node:fs";import path from "node:path";import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";@@ -12,6 +13,8 @@ import { tempDir } from "./helpers/temp-dir";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));vi.setConfig({ testTimeout: 60_000 });+// Next's request scope, as its server sets it up (its stores read this global when they load).+(globalThis as { AsyncLocalStorage?: typeof AsyncLocalStorage }).AsyncLocalStorage ??= AsyncLocalStorage;const dir = tempDir("fuobe-owner-hands-on-");process.env.FUOBE_DATA_DIR = dir;@@ -24,7 +27,7 @@ globalThis.__fuobeTestDiskFree = 1e13;const auth = await import("@/server/auth");const { db } = await import("@/server/db");const { resetRates } = await import("@/server/rate");-const { setSetting } = await import("@/server/settings");+const { getSetting, setSetting } = await import("@/server/settings");const tasks = await import("@/server/computer/tasks");const pool = await import("@/server/computer/pool");const qc = await import("@/server/computer/queue-controls");@@ -282,3 +285,56 @@ describe("the Queue page", () => {expect(q[2]).not.toHaveProperty("handsOn");});});++describe("an owner's run asked for with an API token", () => {+ const gens = () => import("@/server/generations");+ const api = () => import("@/server/api-caller");+ const tenantMod = () => import("@/server/tenant");+ const ask = { feature: "image", modelId: "nano-banana-pro", prompt: "a fox" };++ it("is an api run on every route that makes one (one rule where runs are made); the browser's stays hands-on", async () => {+ const { createGenerations, getGeneration } = await gens();+ const { apiCaller, asOwnRequest } = await api();+ const { runAsTenant } = await tenantMod();+ const demo = getSetting("demoMode");+ setSetting("demoMode", "auto");+ const { token } = auth.createToken("script");+ // A request with the owner's token: what it makes, through any route, says so.+ const viaToken = asOwnRequest(() => {+ expect(auth.validToken(`Bearer ${token}`)).toBe(true);+ return createGenerations(ask)[0].id;+ });+ expect(getGeneration(viaToken)?.request.source).toBe("api");+ // The request Next is handling carries the token, whatever checked it where (an async helper after an await of its+ // own marks only its own work): the run says so too.+ const { workUnitAsyncStorage } = await import("next/dist/server/app-render/work-unit-async-storage.external");+ const checkLater = async () => {+ await null;+ auth.validToken(`Bearer ${token}`);+ };+ const viaRequest = await asOwnRequest(() =>+ workUnitAsyncStorage.run({ type: "request", headers: new Headers({ authorization: `Bearer ${token}` }) } as never, async () => {+ await checkLater();+ return createGenerations(ask)[0].id;+ }),+ );+ expect(getGeneration(viaRequest)?.request.source).toBe("api");+ // A script that names itself keeps its own source.+ const named = asOwnRequest(() => (auth.validToken(`Bearer ${token}`), createGenerations({ ...ask, source: "example" })[0].id));+ expect(getGeneration(named)?.request.source).toBe("example");+ // A token the studio doesn't know marks nothing.+ const unknown = asOwnRequest(() => (auth.validToken("Bearer fuobe_not-a-token"), createGenerations(ask)[0].id));+ expect(getGeneration(unknown)?.request.source).toBeUndefined();+ // The signed-in browser's run (no token) is hands-on, and the token's request never reaches this one.+ expect(apiCaller()).toBe(false);+ const byHand = createGenerations(ask)[0].id;+ expect(getGeneration(byHand)?.request.source).toBeUndefined();+ expect(pool.ownerRunClass(byHand)).toBe("free");+ expect(pool.ownerRunClass(viaToken)).toBe("owner");+ // An account's run never has a source.+ const acct = asOwnRequest(() => (auth.validToken(`Bearer ${token}`), runAsTenant({ kind: "account", id: alice }, () => createGenerations({ ...ask, engine: "open", modelId: "oss-z-image-turbo", op: "t2i" }).map((g) => g.id)[0])));+ expect(getGeneration(acct)?.request.account).toBe(alice);+ expect(getGeneration(acct)?.request.source).toBeUndefined();+ setSetting("demoMode", demo);+ });+});