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.

Workers: jobs carry checked 3D inputs, and the place gate counts every step's files

Adarshf4cb50de2578
diff --git a/bin/lib/worker/model-file.mjs b/bin/lib/worker/model-file.mjs
new file mode 100644
index 00000000..a02f7d52
--- /dev/null
+++ b/bin/lib/worker/model-file.mjs
@@ -0,0 +1,89 @@
+// 3D files a job sends to the worker's ComfyUI (a saved splat for Any Angle's angles, a GLB for Hi3D's refine), checked
+// by their bytes before anything reads them, as the studio checks them before it sends them (src/server/model-input.ts):
+// a splat is unpacked, its points counted to the byte, and written again as a fresh .spz; a GLB is a whole binary
+// glTF 2, and an account's has every buffer and picture inside it. A .ply comes only with the owner's own jobs.
+import zlib from "node:zlib";
+
+export const MODEL_MAX_BYTES = 300 * 2 ** 20;
+export const SPZ_MAX_POINTS = 2 ** 22;
+
+const SPZ_MAGIC = 0x5053474e;
+const GLB_MAGIC = 0x46546c67;
+const GLB_JSON = 0x4e4f534a;
+const SH_DIMS = [0, 3, 8, 15];
+
+/** The 3D format of a job's input, by its type or else its name; null for anything else. */
+export function modelFormat(input) {
+ const type = String(input?.contentType ?? "").split(";")[0].trim().toLowerCase();
+ const ext = /\.([a-z0-9]+)$/i.exec(String(input?.name ?? ""))?.[1]?.toLowerCase();
+ const byName = !type.startsWith("model/");
+ if (type === "model/x-spz" || (byName && ext === "spz")) return "spz";
+ if (type === "model/gltf-binary" || (byName && ext === "glb")) return "glb";
+ if (type === "model/ply" || (byName && ext === "ply")) return "ply";
+ return null;
+}
+
+/** A splat's points, unpacked and checked to the byte, or null. */
+export function spzPoints(data) {
+ if (!Buffer.isBuffer(data) || data.length < 18 || data.length > MODEL_MAX_BYTES || data[0] !== 0x1f || data[1] !== 0x8b || data[2] !== 8) return null;
+ try {
+ const head = zlib.gunzipSync(data.subarray(0, Math.min(data.length, 4096)), { finishFlush: zlib.constants.Z_SYNC_FLUSH, maxOutputLength: 1 << 20 });
+ if (head.length < 16 || head.readUInt32LE(0) !== SPZ_MAGIC) return null;
+ const version = head.readUInt32LE(4);
+ const points = head.readUInt32LE(8);
+ const sh = head[12];
+ if (version < 1 || version > 3 || points < 1 || points > SPZ_MAX_POINTS || sh > 3) return null;
+ const size = 16 + points * ((version === 1 ? 6 : 9) + 1 + 3 + 3 + (version >= 3 ? 4 : 3) + SH_DIMS[sh] * 3);
+ const raw = zlib.gunzipSync(data, { maxOutputLength: size });
+ return raw.length === size ? raw : null;
+ } catch {
+ return null;
+ }
+}
+
+const selfContained = (j) => {
+ const list = (v) => (v === undefined ? [] : Array.isArray(v) ? v : null);
+ const parts = [list(j.buffers), list(j.images)];
+ if (parts.some((x) => x === null)) return false;
+ return parts.flat().every((x) => x?.uri === undefined || (typeof x.uri === "string" && x.uri.startsWith("data:")));
+};
+
+/** A whole binary glTF 2 (its chunks end at its end, its JSON an object); an account's with nothing outside it. */
+export function isGlb(b, account) {
+ if (!Buffer.isBuffer(b) || b.length < 28 || b.length > MODEL_MAX_BYTES || b.readUInt32LE(0) !== GLB_MAGIC || b.readUInt32LE(4) !== 2 || b.readUInt32LE(8) !== b.length) return false;
+ if (b.readUInt32LE(16) !== GLB_JSON) return false;
+ let at = 12;
+ while (at < b.length) {
+ if (at + 8 > b.length) return false;
+ at += 8 + b.readUInt32LE(at);
+ }
+ if (at !== b.length) return false;
+ try {
+ const j = JSON.parse(b.subarray(20, 20 + b.readUInt32LE(12)).toString("utf8"));
+ return !!j && typeof j === "object" && !Array.isArray(j) && (!account || selfContained(j));
+ } catch {
+ return false;
+ }
+}
+
+/** A .ply's header: "ply", its format, and "end_header" within its first 64 KB. */
+export function isPly(b) {
+ if (!Buffer.isBuffer(b) || b.length > MODEL_MAX_BYTES) return false;
+ const head = b.subarray(0, 64 * 1024).toString("latin1");
+ const end = head.indexOf("end_header");
+ return /^ply\r?\n/.test(head) && end > 0 && /\nformat (ascii|binary_little_endian|binary_big_endian) 1\.0\r?\n/.test(head.slice(0, end));
+}
+
+/**
+ * A 3D input as its ComfyUI gets it: a splat made again, a GLB or the owner's .ply as it came once checked. Null when it
+ * isn't a real one, or isn't a kind this job's principal sends (`account`: an account's job ticket).
+ */
+export function modelAgain(format, data, account) {
+ if (format === "spz") {
+ const raw = spzPoints(data);
+ return raw ? zlib.gzipSync(raw) : null;
+ }
+ if (format === "glb") return isGlb(data, account) ? data : null;
+ if (format === "ply") return !account && isPly(data) ? data : null;
+ return null;
+}
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjs
index f29ed012..cffedcdb 100644
--- a/bin/lib/worker/run.mjs
+++ b/bin/lib/worker/run.mjs
@@ -35,6 +35,7 @@ import { freeLocal, localIdle, readCounters, readListeners, readLock, splitMemor
import { takeLock, workerLives } from "./lock.mjs";
import { finishers } from "./finish.mjs";
import { ffmpegVersion, fileSize, mediaKind, outputCap, reencode } from "./media.mjs";
+import { modelAgain, modelFormat } from "./model-file.mjs";
import { canCleanPictures, cleanPicture, isPicture } from "./picture.mjs";
import { previewShrinker } from "./preview.mjs";
import { withPlainResults } from "./results.mjs";
@@ -442,6 +443,14 @@ async function work(saved, deps, owner) {
data = Buffer.from(got);
fs.writeFileSync(kept, data, { mode: 0o600 });
}
+ // A 3D file (a finishing job's GLB is checked by its own script): real by its bytes, and a splat made again.
+ const model = t.finish ? null : modelFormat(input);
+ if (model) {
+ const again = modelAgain(model, data, !!t.ticket);
+ if (again) return arrayBuffer(again);
+ log(`Job ${t.id}: one of its 3D files isn't one it takes.`);
+ return "input-unreadable";
+ }
const kind = mediaKind(input, t.graph);
if (!kind) {
// The studio sends an account's pictures as they came: no EXIF, GPS or other metadata of them reaches its ComfyUI.
diff --git a/src/server/computer/finish.ts b/src/server/computer/finish.ts
index 99e70dba..89296eb4 100644
--- a/src/server/computer/finish.ts
+++ b/src/server/computer/finish.ts
@@ -7,6 +7,7 @@ import type { HistoryEntryLike, WantedFile } from "@/lib/relay";
import { accountTotalBytes, accountUsage, diskFloorBytes, diskFreeBytes, diskHasRoom } from "../account-files";
import { db } from "../db";
import { pictureWithoutMetadata } from "../media-clean";
+import { glbSelfContained } from "../model-input";
import { ACCOUNT_TURNTABLE, accountFinishProblem, FINISHED_3D_OPS, MODEL_FINISH_VERSION, modelToFinish, OWN_ORBIT, withTurntable } from "../model3d-finish";
import { getSetting } from "../settings";
import { absolutePath, deleteAsset, getAsset, readRef, saveFile, type Asset } from "../storage";
@@ -276,29 +277,7 @@ export function stopWorkerFinish(generationId: string): void {
for (const t of live) endTask(t.id, "canceled", { error: "Stopped" });
}
-/**
- * Is this a binary glTF 2 whose every buffer and picture is inside the file (no URI, or a data: URI)? This server
- * checks the worker's web GLB again before it keeps it: it reads only the header and the JSON chunk.
- */
-export function glbSelfContained(b: Buffer): boolean {
- if (b.length < 20 || b.readUInt32LE(0) !== 0x46546c67 || b.readUInt32LE(4) !== 2 || b.readUInt32LE(16) !== 0x4e4f534a) return false;
- const len = b.readUInt32LE(12);
- if (20 + len > b.length) return false;
- let j: { buffers?: unknown; images?: unknown };
- try {
- j = JSON.parse(b.subarray(20, 20 + len).toString("utf8"));
- } catch {
- return false;
- }
- if (!j || typeof j !== "object") return false;
- const list = (v: unknown) => (v === undefined ? [] : Array.isArray(v) ? v : null);
- const parts = [list(j.buffers), list(j.images)];
- if (parts.some((x) => x === null)) return false;
- return parts.flat().every((x) => {
- const uri = (x as { uri?: unknown } | null)?.uri;
- return uri === undefined || (typeof uri === "string" && uri.startsWith("data:"));
- });
-}
+export { glbSelfContained };
/** glbSelfContained for a file, reading only its header and its JSON chunk (at most 64 MB of it). */
export function glbFileSelfContained(file: string): boolean {
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 2aee9ea1..247c937e 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -145,7 +145,7 @@ import { accountSend } from "./account-send";
import { stamped, stampOf, withoutStamp, withRunStamp, type RunStamp } from "./run-stamp";
import { anyHeld, dropGone, dropHold, HELD, NOT_HELD } from "./pool-holds";
import { FILE_TROUBLE_WORDS, POOL_WORDS, RELAY_WORDS } from "@/lib/relay";
-import { heldLine, placeInLine, poolOnWorkers, poolRunsProvider, poolWaitMs, runOnPool } from "./hosted";
+import { heldLine, placeInLine, poolOnWorkers, poolRunsProvider, poolWaitMs, requestFileKinds, runOnPool, type FileKind } from "./hosted";
import { hostedRunsOn } from "./hosted-switch";
import { catalogVersion } from "./computer/catalog-version";
import { gettingReady, poolLane, queueOfGeneration, type LinePlace } from "./computer/pool";
@@ -1729,6 +1729,9 @@ export interface PlannedStep {
presetId: string | null;
waits: boolean;
loras?: string[];
+ /** The kinds of file a ComfyUI row reads: its own (`files`), and those its earlier steps hand it (`made`). */
+ files?: FileKind[];
+ made?: FileKind[];
}
const ROLLED_BACK = Symbol("rolled back");
@@ -1754,7 +1757,10 @@ export function plannedSteps(fn: () => unknown): PlannedStep[] {
return steps;
}
-/** A ComfyUI row with the LoRA files it loads, planned from its request as createGenerations planned it (else as it was). */
+/**
+ * A ComfyUI row with the LoRA files it loads, planned from its request as createGenerations planned it (else as it was),
+ * and the kinds of file it reads.
+ */
function withRowLoras(s: PlannedStep): PlannedStep {
if (s.provider !== "comfyui") return s;
const r = db().prepare("SELECT request_json, depends_on FROM generations WHERE id = ?").get(s.id) as { request_json: string; depends_on: string | null } | undefined;
@@ -1762,13 +1768,25 @@ function withRowLoras(s: PlannedStep): PlannedStep {
try {
const req = JSON.parse(r.request_json) as GenerationRequest;
const deps = !r.depends_on ? 0 : r.depends_on.startsWith("[") ? (JSON.parse(r.depends_on) as unknown[]).length : 1;
+ const made = chainFileKinds(req, deps);
+ const facts = { ...s, files: requestFileKinds(req), ...(made.length && { made }) };
const loras = runLoraFiles(previewChained(req, deps), req.params?.extra);
- return loras.length ? { ...s, loras } : s;
+ return loras.length ? { ...facts, loras } : facts;
} catch {
return s;
}
}
+/** The kinds of file a step's earlier steps hand it, by the slots they go to (words for its prompt are no file). */
+export function chainFileKinds(req: GenerationRequest, deps: number): FileKind[] {
+ const kinds = new Set<FileKind>();
+ for (const c of slotsFor(req, deps)) {
+ const k = SLOT_KIND[c.slot];
+ if (k !== "text") kinds.add(k);
+ }
+ return [...kinds];
+}
+
/** The rows of a run (by id) as steps. */
export function stepsOf(ids: string[]): PlannedStep[] {
const q = db().prepare("SELECT id, model_id, op, provider, kind, preset_id, depends_on FROM generations WHERE id = ?");
diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.ts
index 559de00e..9a214af8 100644
--- a/src/server/hosted-run.ts
+++ b/src/server/hosted-run.ts
@@ -44,7 +44,7 @@ import { loadIndex } from "./gpu/index-file";
import { attemptLimitMs, MAX_ATTEMPTS, poolLane } from "./computer/pool";
import { poolFinishes3d } from "./computer/finish";
import { holdTiming } from "./queue-settings";
-import { hostedDetails, hostedGuestWords, hostedWords, inputCounts, isOutputsWords, outputsWords, poolAllows, poolAllowsRun, poolAway, poolFitsSize, poolHasFiles, poolMostWords, poolOnWorkers, poolReady, poolRunsProvider, poolTakes, poolTicketsReady, poolUploads, POOL_LANE, queueFacts, runFacts, runOnPool, workflowPicks, type JobSize } from "./hosted";
+import { hostedDetails, hostedGuestWords, hostedWords, isOutputsWords, outputsWords, poolAllows, poolAllowsRun, poolAway, poolFitsSize, poolHasFiles, poolMostWords, poolOnWorkers, poolReady, poolRunsProvider, poolTakes, poolTakesKind, poolTicketsReady, POOL_LANE, queueFacts, requestFileKinds, runFacts, runOnPool, workflowPicks, type JobSize } from "./hosted";
import { withRunStamp } from "./run-stamp";
import { hostedRunsOn } from "./hosted-switch";
import { checkRun, moderationConfigured } from "./moderation";
@@ -399,7 +399,8 @@ export function gateDetail(gate: GateRefusal, place: Place): string | undefined
* model, app and kind lists (for the run's own model and every other model it makes a step with, such as a 2K take's
* finish), a worker allowed its lane, a card that can run it, LoRAs, the files it adds at run time (a look's, a motion's
* or a recipe's LoRAs: a worker allowed its lane must have verified each one), the kinds of file it sends, and every
- * later step of a chain (planned only once the cheaper checks pass), its run-time files too. `p` null: the billing service didn't answer, so only what needs
+ * later step of a chain (planned only once the cheaper checks pass), its run-time files and the files it reads too (and
+ * Any Angle's angles for its 3D view). `p` null: the billing service didn't answer, so only what needs
* no policy is checked. Passed, it gives the planned steps for the run's one price.
*
* First of all, every step's own setup (own-setup.ts): a model, mode or option that runs on a visitor's own GPU or key
@@ -428,11 +429,7 @@ export function poolGate(
// The files it adds at run time (a look's, a motion's or a recipe's LoRAs): a run whose worker would refuse it for a
// file it hasn't verified runs on the visitor's own GPU instead, said before Run (never dropped without a word).
if (!poolHasFiles(planned.route.endpoint, runLoraFiles(planned, req.params?.extra))) return { ok: false, reason: "files", setup: gpu };
- if (p) {
- const inputs = inputCounts(req);
- const takes = poolUploads(p);
- if ((inputs.image && !takes.image) || (inputs.video && !takes.video) || (inputs.audio && !takes.audio)) return { ok: false, reason: "inputs", setup: gpu };
- }
+ if (!requestFileKinds(req).every((k) => poolTakesKind(k, p))) return { ok: false, reason: "inputs", setup: gpu };
// A size bigger than every GPU here that runs it makes (their PCs' ceilings): said before Run as a label, never a run
// that fails once pressed (the run's own check stays the last guard: comfyui.ts POOL_TOO_BIG).
const size = sizeOf ? safeSize(sizeOf) : null;
@@ -451,6 +448,14 @@ export function poolGate(
if (s.provider === "comfyui" && !poolTakes(stepEndpoint(s))) return { ok: false, reason: "ownSetup", setup: needsGpu(stepEndpoint(s)) };
// A step that adds files at run time (a relit start frame's LoRA, a Mixed Media still's look) that no worker verified.
if (s.provider === "comfyui" && s.loras?.length && !poolHasFiles(stepEndpoint(s), s.loras)) return { ok: false, reason: "files", setup: needsGpu(stepEndpoint(s)) };
+ // A file it reads that these GPUs don't take: its own, or one an earlier step makes for it (a splat, a clip).
+ if (s.provider === "comfyui" && !((s.files ?? []).every((k) => poolTakesKind(k, p)) && (s.made ?? []).every((k) => poolTakesKind(k)))) return { ok: false, reason: "inputs", setup: needsGpu(stepEndpoint(s)) };
+ }
+ // Any Angle's 3D view is built here only where its angles (the runs that read it) run here too.
+ if (planned.model.id === ANY_ANGLE.buildModel) {
+ const shot = ownSetupHere(ANY_ANGLE.shotModel, "open");
+ if (shot) return { ok: false, reason: "ownSetup", setup: shot };
+ if ((p && !poolAllows(p, ANY_ANGLE.shotModel)) || !poolTakes(ANY_ANGLE.shotGraph)) return { ok: false, reason: "ownSetup", setup: needsGpu(ANY_ANGLE.shotGraph) };
}
const problem = steps && p ? stepsProblem(p, steps) : null;
if (problem) return { ok: false, reason: problem === hostedWords(placeFor(p)).rtxCard ? "rtxCard" : "notOffered", setup: gpu };
diff --git a/src/server/hosted.ts b/src/server/hosted.ts
index 49ba8bbb..1b824eb8 100644
--- a/src/server/hosted.ts
+++ b/src/server/hosted.ts
@@ -15,7 +15,8 @@ import { holdOf, NOT_HELD, type HoldReason } from "./pool-holds";
import { poolRunCounts } from "./pool-limits";
import { getWorkflow, installComfyLocal, onInstallComfy, workerFor, workersTake } from "./providers/comfyui";
import { getSetting, withCandidates } from "./settings";
-import { localHead, storedMedia } from "./storage";
+import { modelFormat, modelTaken } from "./model-input";
+import { contentTypeFor, localHead, storedMedia } from "./storage";
import { runAsTenant } from "./tenant";
/**
@@ -275,6 +276,42 @@ export function inputCounts(req: GenerationRequest): { image: number; video: num
return { image, video, audio };
}
+/** A kind of file a run sends to this install's GPUs. */
+export type FileKind = "image" | "video" | "audio" | "model3d" | "file";
+
+/** The kind of a stored file, data: URI or example a run names: a 3D file an account may send them, or another file. */
+export function refKind(ref: string): FileKind {
+ const type = ref.startsWith("data:") ? (/^data:([^;,]*)/.exec(ref)?.[1] ?? "") : contentTypeFor(ref.split(/[?#]/)[0], "");
+ const t = type.toLowerCase();
+ const model = modelFormat(t, ref.split(/[?#]/)[0]);
+ if (model) return modelTaken(model, true) ? "model3d" : "file";
+ if (t === "image/x-exr" || t === "image/aces") return "file";
+ return t.startsWith("image/") ? "image" : t.startsWith("video/") ? "video" : t.startsWith("audio/") ? "audio" : "file";
+}
+
+/** Every kind of file a request reads: its inputs and the files its params.extra names. */
+export function requestFileKinds(req: Pick<GenerationRequest, "inputs" | "params">): FileKind[] {
+ const out = new Set<FileKind>();
+ const c = inputCounts(req as GenerationRequest);
+ for (const k of ["image", "video", "audio"] as const) if (c[k]) out.add(k);
+ if (typeof req.inputs?.model3d === "string" && req.inputs.model3d) out.add(refKind(req.inputs.model3d));
+ for (const v of Object.values(req.params?.extra ?? {})) {
+ for (const x of typeof v === "string" ? [v] : Array.isArray(v) ? v : []) if (typeof x === "string" && /^(data:|\/api\/files\/)/.test(x)) out.add(refKind(x));
+ }
+ return [...out];
+}
+
+/**
+ * Do this install's GPUs take a kind of file: a picture, clip or sound as the policy's uploads and the workers allow (a
+ * file an earlier step made: as the workers allow, `p` left out), a 3D file always (checked by its bytes), and no other
+ * kind on the workers.
+ */
+export function poolTakesKind(kind: FileKind, p?: Pick<Policy, "uploads"> | null): boolean {
+ if (kind === "model3d") return true;
+ if (kind === "file") return !poolOnWorkers();
+ return p ? poolUploads(p)[kind] : poolTakesFiles(kind);
+}
+
/** The pool's one lane while this install's GPUs are its own ComfyUI server. */
export const POOL_LANE = "comfyui";
diff --git a/src/server/model-input.ts b/src/server/model-input.ts
new file mode 100644
index 00000000..78c71d27
--- /dev/null
+++ b/src/server/model-input.ts
@@ -0,0 +1,122 @@
+import zlib from "node:zlib";
+
+/**
+ * 3D files a job sends to a GPU worker (a saved splat for Any Angle's angles, a GLB for Hi3D's refine), checked by their
+ * bytes as the worker's results are (computer/http.ts outputType): a splat is a real .spz and is made again, a GLB is a
+ * whole binary glTF 2. An account sends a splat or a GLB whose every buffer and picture is inside the file; the owner's
+ * own jobs may also send a .ply. bin/lib/worker/model-file.mjs checks the same on the worker.
+ */
+export type ModelFormat = "spz" | "glb" | "ply";
+
+export const MODEL_INPUT_MAX_BYTES = 300 * 2 ** 20;
+/** The most points a splat sent to a worker holds (TripoSplat makes 262,144). */
+export const SPZ_MAX_POINTS = 2 ** 22;
+
+const SPZ_MAGIC = 0x5053474e;
+const GLB_MAGIC = 0x46546c67;
+const GLB_JSON = 0x4e4f534a;
+const SH_DIMS = [0, 3, 8, 15];
+
+/** The 3D format of a file, by its type or else its name; null for anything else. */
+export function modelFormat(contentType: string, name: string): ModelFormat | null {
+ const type = contentType.split(";")[0].trim().toLowerCase();
+ const ext = /\.([a-z0-9]+)$/i.exec(name)?.[1]?.toLowerCase();
+ if (type === "model/x-spz" || (!type.startsWith("model/") && ext === "spz")) return "spz";
+ if (type === "model/gltf-binary" || (!type.startsWith("model/") && ext === "glb")) return "glb";
+ if (type === "model/ply" || (!type.startsWith("model/") && ext === "ply")) return "ply";
+ return null;
+}
+
+/** May this principal send a file of this format to the workers? */
+export const modelTaken = (format: ModelFormat, account: boolean): boolean => format !== "ply" || !account;
+
+/**
+ * A splat's points, unpacked: gzip, the "NGSP" header (version 1 to 3, 1 to SPZ_MAX_POINTS points, SH degree 0 to 3), and
+ * exactly the bytes those points take, nothing after them. Null for anything else.
+ */
+export function spzPoints(data: Buffer): Buffer | null {
+ if (data.length < 18 || data.length > MODEL_INPUT_MAX_BYTES || data[0] !== 0x1f || data[1] !== 0x8b || data[2] !== 8) return null;
+ try {
+ const head = zlib.gunzipSync(data.subarray(0, Math.min(data.length, 4096)), { finishFlush: zlib.constants.Z_SYNC_FLUSH, maxOutputLength: 1 << 20 });
+ if (head.length < 16 || head.readUInt32LE(0) !== SPZ_MAGIC) return null;
+ const version = head.readUInt32LE(4);
+ const points = head.readUInt32LE(8);
+ const sh = head[12];
+ if (version < 1 || version > 3 || points < 1 || points > SPZ_MAX_POINTS || sh > 3) return null;
+ const each = (version === 1 ? 6 : 9) + 1 + 3 + 3 + (version >= 3 ? 4 : 3) + SH_DIMS[sh] * 3;
+ const size = 16 + points * each;
+ const raw = zlib.gunzipSync(data, { maxOutputLength: size });
+ return raw.length === size ? raw : null;
+ } catch {
+ return null;
+ }
+}
+
+/** A real splat made again: its checked points in a fresh gzip (no name, comment or anything after the stream). */
+export function splatAgain(data: Buffer): Buffer | null {
+ const raw = spzPoints(data);
+ return raw ? zlib.gzipSync(raw) : null;
+}
+
+/** Every buffer and picture of a GLB's JSON is inside the file (no URI, or a data: URI). */
+function selfContained(j: { buffers?: unknown; images?: unknown }): boolean {
+ const list = (v: unknown) => (v === undefined ? [] : Array.isArray(v) ? v : null);
+ const parts = [list(j.buffers), list(j.images)];
+ if (parts.some((x) => x === null)) return false;
+ return parts.flat().every((x) => {
+ const uri = (x as { uri?: unknown } | null)?.uri;
+ return uri === undefined || (typeof uri === "string" && uri.startsWith("data:"));
+ });
+}
+
+/** Is this a binary glTF 2 whose every buffer and picture is inside the file? Reads only the header and the JSON chunk. */
+export function glbSelfContained(b: Buffer): boolean {
+ if (b.length < 20 || b.readUInt32LE(0) !== GLB_MAGIC || b.readUInt32LE(4) !== 2 || b.readUInt32LE(16) !== GLB_JSON) return false;
+ const len = b.readUInt32LE(12);
+ if (20 + len > b.length) return false;
+ try {
+ const j = JSON.parse(b.subarray(20, 20 + len).toString("utf8"));
+ return !!j && typeof j === "object" && selfContained(j);
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * A whole binary glTF 2: its header's length is the file's, its first chunk is its JSON (an object), and its chunks end
+ * exactly at the file's end. `account`: its buffers and pictures are inside it too.
+ */
+export function isGlb(b: Buffer, account: boolean): boolean {
+ if (b.length < 28 || b.length > MODEL_INPUT_MAX_BYTES || b.readUInt32LE(0) !== GLB_MAGIC || b.readUInt32LE(4) !== 2 || b.readUInt32LE(8) !== b.length) return false;
+ if (b.readUInt32LE(16) !== GLB_JSON) return false;
+ let at = 12;
+ while (at < b.length) {
+ if (at + 8 > b.length) return false;
+ const len = b.readUInt32LE(at);
+ at += 8 + len;
+ }
+ if (at !== b.length) return false;
+ try {
+ const len = b.readUInt32LE(12);
+ const j = JSON.parse(b.subarray(20, 20 + len).toString("utf8"));
+ return !!j && typeof j === "object" && !Array.isArray(j) && (!account || selfContained(j));
+ } catch {
+ return false;
+ }
+}
+
+/** A .ply's header: "ply", its format, and "end_header" within its first 64 KB. */
+export function isPly(b: Buffer): boolean {
+ if (b.length > MODEL_INPUT_MAX_BYTES) return false;
+ const head = b.subarray(0, 64 * 1024).toString("latin1");
+ const end = head.indexOf("end_header");
+ return /^ply\r?\n/.test(head) && end > 0 && /\nformat (ascii|binary_little_endian|binary_big_endian) 1\.0\r?\n/.test(head.slice(0, end));
+}
+
+/** A 3D file for the workers, checked (and a splat made again); null when it isn't one they take from this principal. */
+export function modelForWorkers(format: ModelFormat, data: Buffer, account: boolean): Buffer | null {
+ if (!modelTaken(format, account) || data.length > MODEL_INPUT_MAX_BYTES) return null;
+ if (format === "spz") return splatAgain(data);
+ if (format === "glb") return isGlb(data, account) ? data : null;
+ return isPly(data) ? data : null;
+}
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index cbd170f8..f6a91010 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -32,6 +32,7 @@ import { ocrText, parseOcrFrame, parseOcrLines, type OcrFrame } from "@/lib/ocr"
import { getSetting, isCandidate, savedSetting } from "../settings";
import { decodePng } from "../png";
import { pictureWithoutMetadata } from "../media-clean";
+import { MODEL_INPUT_MAX_BYTES, modelForWorkers, modelFormat } from "../model-input";
import { probeAvi } from "../avi-probe";
import { probeWebm } from "../webm-probe";
import { adoptFile, contentTypeFor, readRef, saveFile, scratchDir } from "../storage";
@@ -227,7 +228,15 @@ export const workersTake = (kind: "image" | "video" | "audio"): boolean => poolM
* motion photo's clip): none of that ever leaves for a worker. A JPEG keeps its orientation. A kind of picture whose
* such parts this server can't blank that way (a GIF, an SVG, an animated WebP, say) is made again from its pixels here.
*/
-export async function forWorkers(data: Buffer, contentType: string, name: string, o: { onWorker?: boolean } = {}): Promise<{ data: Buffer; contentType: string; name: string }> {
+export async function forWorkers(data: Buffer, contentType: string, name: string, o: { onWorker?: boolean; account?: boolean } = {}): Promise<{ data: Buffer; contentType: string; name: string }> {
+ // A 3D file (a splat for Any Angle's angles, a GLB to refine): checked by its bytes as a worker's results are.
+ const format = modelFormat(contentType, name);
+ if (format) {
+ if (data.length > MODEL_INPUT_MAX_BYTES) throw new ProviderError("This 3D file is too big for the shared GPUs.");
+ const sent = modelForWorkers(format, data, o.account ?? !!o.onWorker);
+ if (!sent) throw new ProviderError("The shared GPUs don't take this kind of file.");
+ return { data: sent, contentType: format === "spz" ? "model/x-spz" : format === "glb" ? "model/gltf-binary" : "model/ply", name: name.replace(/\.[^.]*$/, "") + `.${format}` };
+ }
const kind = contentType.split("/")[0];
if (!poolMedia().has(kind)) throw new ProviderError(kind === "video" ? "The shared GPUs don't take clips yet." : kind === "audio" ? "The shared GPUs don't take sound yet." : "The shared GPUs don't take this kind of file.");
if (kind !== "image") return { data, contentType, name };
@@ -1591,7 +1600,7 @@ async function uploadTo(worker: ComfyWorker, data: Buffer, contentType: string,
const account = server ? tenantAccount() : undefined;
if (account) {
if (!installComfyLocal(worker)) throw new ProviderError(POOL_NOT_LOCAL);
- if (contentType.startsWith("image/")) ({ data, contentType, name } = await forWorkers(data, contentType, name));
+ if (contentType.startsWith("image/") || modelFormat(contentType, name)) ({ data, contentType, name } = await forWorkers(data, contentType, name, { account: true }));
}
const form = new FormData();
const ext = name.includes(".") ? name.split(".").pop() : contentType.split("/")[1];
diff --git a/tests/pool-limits.test.ts b/tests/pool-limits.test.ts
index fd00f763..eac607ad 100644
--- a/tests/pool-limits.test.ts
+++ b/tests/pool-limits.test.ts
@@ -764,8 +764,22 @@ describe("a run's price facts", () => {
expect(run.megapixels).toBeGreaterThan(0.9);
expect(run.megapixels).toBeLessThan(1.2);
expect(run.steps).toEqual([expect.objectContaining({ model: "oss-z-image-turbo", jobs: 1 })]);
- // A film of two shots: its two clips priced together with one hold; the join costs nothing.
- const film = await post({ feature: "video", modelId: "oss-wan22-14b-fast", prompt: "x", params: { aspectRatio: "16:9", shots: [{ prompt: "wide shot", duration: 3 }, { prompt: "close-up", duration: 3 }] }, ...SHOWN }, a.cookie);
+ // A film of two shots: its two clips priced together with one hold; the join costs nothing. (The join reads the
+ // clips, so the workers must take clips: until they do, the film is said before Run as the visitor's own GPU.)
+ const filmReq = { feature: "video", modelId: "oss-wan22-14b-fast", prompt: "x", params: { aspectRatio: "16:9", shots: [{ prompt: "wide shot", duration: 3 }, { prompt: "close-up", duration: 3 }] }, ...SHOWN };
+ const prior = process.env.FUOBE_POOL_MEDIA_INPUTS;
+ let film: Awaited<ReturnType<typeof post>>;
+ try {
+ process.env.FUOBE_POOL_MEDIA_INPUTS = "image";
+ const off = await post(filmReq, a.cookie);
+ expect(off.status, JSON.stringify(off.body)).toBe(403);
+ expect(off.body).toMatchObject({ error: "This file runs on your own GPU" });
+ process.env.FUOBE_POOL_MEDIA_INPUTS = "image,video";
+ film = await post(filmReq, a.cookie);
+ } finally {
+ if (prior === undefined) delete process.env.FUOBE_POOL_MEDIA_INPUTS;
+ else process.env.FUOBE_POOL_MEDIA_INPUTS = prior;
+ }
expect(film.status, JSON.stringify(film.body)).toBe(201);
const reserves = fake.calls_of("/v1/reserve");
const filmRun = (reserves.at(-1)!.body as { run: { steps?: { model: string; jobs: number }[] } }).run;
diff --git a/tests/worker-3d-inputs.test.ts b/tests/worker-3d-inputs.test.ts
new file mode 100644
index 00000000..c32c23da
--- /dev/null
+++ b/tests/worker-3d-inputs.test.ts
@@ -0,0 +1,297 @@
+import crypto from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+import zlib from "node:zlib";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import * as workerModel from "../bin/lib/worker/model-file.mjs";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * 3D files a job sends to the shared GPU workers: Any Angle's angles read the splat its 3D build made (and Hi3D's refine
+ * the GLB of the step before it). The studio checks each by its bytes and makes a splat again before a worker gets it,
+ * the worker checks it again before its ComfyUI reads it, and the place gate offers these GPUs only for a run whose
+ * every step's files they take, so nothing visible ends at a step they can't run.
+ */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 60_000 });
+
+const dir = tempDir("fuobe-worker-3d-inputs-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_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;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const realFetch = globalThis.fetch;
+globalThis.fetch = (async () => 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 tasks = await import("@/server/computer/tasks");
+const billing = await import("@/server/billing");
+const hosted = await import("@/server/hosted");
+const { poolQuote } = await import("@/server/hosted-run");
+const { forWorkers, loadManifest } = await import("@/server/providers/comfyui");
+const { loadIndex } = await import("@/server/gpu/index-file");
+const { allLanes } = await import("@/lib/lanes");
+const { catalogVersion } = await import("@/server/computer/catalog-version");
+const { chainFileKinds } = await import("@/server/generations");
+const { saveFile } = await import("@/server/storage");
+const { spzPoints } = await import("@/server/model-input");
+const { ANY_ANGLE, shotExtra } = await import("@/lib/catalog/any-angle");
+const { TINY_PNG } = await import("./helpers/fake-comfy-runner");
+
+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");
+
+/** TripoSplat's own splat as the open graph saves it (scripts/comfy/fixtures/test.spz: 64 points, version 2). */
+const SPLAT = fs.readFileSync(path.join(process.cwd(), "scripts/comfy/fixtures/test.spz"));
+const RAW = zlib.gunzipSync(SPLAT);
+
+/** The same points in a gzip that carries a file name and a comment. */
+function dressedSplat(): Buffer {
+ const g = zlib.gzipSync(RAW);
+ const head = Buffer.from(g.subarray(0, 10));
+ head[3] = 0x18;
+ return Buffer.concat([head, Buffer.from("C:\\Users\\someone\\secret.spz\0"), Buffer.from("a note\0"), g.subarray(10)]);
+}
+
+/** A binary glTF 2 with one buffer: inside the file, or at `uri`. */
+function glb(uri?: string, o: { tail?: Buffer } = {}): Buffer {
+ const json = Buffer.from(JSON.stringify({ asset: { version: "2.0" }, buffers: [{ byteLength: 4, ...(uri && { uri }) }] }).padEnd(64, " "));
+ const bin = Buffer.alloc(4);
+ const chunk = (type: number, data: Buffer) => {
+ const h = Buffer.alloc(8);
+ h.writeUInt32LE(data.length, 0);
+ h.writeUInt32LE(type, 4);
+ return Buffer.concat([h, data]);
+ };
+ const body = Buffer.concat([chunk(0x4e4f534a, json), chunk(0x004e4942, bin), o.tail ?? Buffer.alloc(0)]);
+ const head = Buffer.alloc(12);
+ head.write("glTF", 0, "latin1");
+ head.writeUInt32LE(2, 4);
+ head.writeUInt32LE(12 + body.length, 8);
+ return Buffer.concat([head, body]);
+}
+
+const PLY = Buffer.from("ply\nformat binary_little_endian 1.0\nelement vertex 1\nproperty float x\nend_header\n\0\0\0\0");
+
+describe("a splat for the shared GPUs (Any Angle's angles)", () => {
+ it("the owner's job sends its splat, made again: the same points in a fresh gzip", async () => {
+ const out = await forWorkers(dressedSplat(), "model/x-spz", "view.spz");
+ expect(out.contentType).toBe("model/x-spz");
+ expect(out.name).toBe("view.spz");
+ expect(zlib.gunzipSync(out.data).equals(RAW)).toBe(true);
+ // Nothing of the file it came in: no name, no comment.
+ expect(out.data[3]).toBe(0);
+ expect(out.data.includes(Buffer.from("secret"))).toBe(false);
+ // Bytes after the stream: not a splat.
+ await expect(forWorkers(Buffer.concat([SPLAT, Buffer.from("anything after it")]), "model/x-spz", "v.spz")).rejects.toThrow(/don't take/);
+ });
+
+ it("an account's run sends its splat the same way", async () => {
+ const out = await forWorkers(SPLAT, "model/x-spz", "fuobe_x.spz", { onWorker: true });
+ expect(spzPoints(out.data)?.equals(RAW)).toBe(true);
+ });
+
+ it("anything that only looks like one is refused: another gzip, too few or too many points' bytes, a page", async () => {
+ const short = zlib.gzipSync(RAW.subarray(0, RAW.length - 1));
+ const long = zlib.gzipSync(Buffer.concat([RAW, Buffer.alloc(1)]));
+ const other = zlib.gzipSync(Buffer.from("<html><script>alert(1)</script></html>"));
+ const many = Buffer.from(RAW);
+ many.writeUInt32LE(2 ** 30, 8);
+ for (const [what, data] of [["short", short], ["long", long], ["other", other], ["points", zlib.gzipSync(many)], ["page", Buffer.from("<html></html>")]] as const) {
+ await expect(forWorkers(data, "model/x-spz", "v.spz"), what).rejects.toThrow(/don't take this kind of file/);
+ await expect(forWorkers(data, "model/x-spz", "v.spz", { onWorker: true }), what).rejects.toThrow(/don't take this kind of file/);
+ }
+ });
+});
+
+describe("other 3D files for the shared GPUs", () => {
+ it("a GLB: whole, and an account's with nothing outside it; the owner's may point elsewhere as its results may", async () => {
+ expect((await forWorkers(glb(), "model/gltf-binary", "m.glb", { onWorker: true })).data.equals(glb())).toBe(true);
+ await expect(forWorkers(glb("../secret.bin"), "model/gltf-binary", "m.glb", { onWorker: true })).rejects.toThrow(/don't take/);
+ expect((await forWorkers(glb("../secret.bin"), "model/gltf-binary", "m.glb")).contentType).toBe("model/gltf-binary");
+ // More bytes after its last chunk, or a header that says another length: not a GLB, for anyone.
+ await expect(forWorkers(glb(undefined, { tail: Buffer.from("xyz") }), "model/gltf-binary", "m.glb")).rejects.toThrow(/don't take/);
+ const lying = glb();
+ lying.writeUInt32LE(lying.length + 4, 8);
+ await expect(forWorkers(lying, "model/gltf-binary", "m.glb")).rejects.toThrow(/don't take/);
+ });
+
+ it("a .ply only from the owner's own jobs, as with results", async () => {
+ expect((await forWorkers(PLY, "model/ply", "s.ply")).data.equals(PLY)).toBe(true);
+ await expect(forWorkers(PLY, "model/ply", "s.ply", { onWorker: true })).rejects.toThrow(/don't take/);
+ await expect(forWorkers(Buffer.from("not a ply"), "model/ply", "s.ply")).rejects.toThrow(/don't take/);
+ });
+
+ it("other kinds of file stay off the workers", async () => {
+ await expect(forWorkers(Buffer.from("{}"), "application/json", "a.json")).rejects.toThrow(/don't take this kind of file/);
+ await expect(forWorkers(Buffer.from("PK"), "application/zip", "a.zip")).rejects.toThrow(/don't take this kind of file/);
+ });
+});
+
+describe("the worker checks 3D files again before its ComfyUI reads them", () => {
+ it("knows them by type or name", () => {
+ expect(workerModel.modelFormat({ contentType: "model/x-spz", name: "fuobe_a.spz" })).toBe("spz");
+ expect(workerModel.modelFormat({ contentType: "", name: "fuobe_a.glb" })).toBe("glb");
+ expect(workerModel.modelFormat({ contentType: "image/png", name: "fuobe_a.png" })).toBeNull();
+ });
+
+ it("makes a splat again, and refuses one whose points don't add up", () => {
+ const again = workerModel.modelAgain("spz", dressedSplat(), true);
+ expect(zlib.gunzipSync(again!).equals(RAW)).toBe(true);
+ expect(again!.includes(Buffer.from("secret"))).toBe(false);
+ expect(workerModel.modelAgain("spz", zlib.gzipSync(RAW.subarray(0, 100)), true)).toBeNull();
+ expect(workerModel.modelAgain("spz", Buffer.from("plain text"), false)).toBeNull();
+ });
+
+ it("an account's GLB has nothing outside it, and its job never sends a .ply; the owner's may", () => {
+ expect(workerModel.modelAgain("glb", glb(), true)?.equals(glb())).toBe(true);
+ expect(workerModel.modelAgain("glb", glb("file:///etc/passwd"), true)).toBeNull();
+ expect(workerModel.modelAgain("glb", glb("file:///etc/passwd"), false)).not.toBeNull();
+ expect(workerModel.modelAgain("glb", glb(undefined, { tail: Buffer.from("x") }), false)).toBeNull();
+ expect(workerModel.modelAgain("ply", PLY, true)).toBeNull();
+ expect(workerModel.modelAgain("ply", PLY, false)?.equals(PLY)).toBe(true);
+ });
+});
+
+describe("the place gate and the files each step reads", () => {
+ let account: NonNullable<ReturnType<typeof auth.accountById>>;
+ let cookie = "";
+
+ beforeAll(() => {
+ auth.setPassword("install password");
+ const id = auth.createAccount("[email protected]", "long enough").id;
+ account = auth.accountById(id)!;
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(id).value}`;
+ });
+ afterAll(() => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestDiskFree = undefined;
+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE"]) delete process.env[k];
+ });
+ beforeEach(() => {
+ resetRates();
+ billing.resetBillingCache();
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ process.env.FUOBE_HOSTED_FREE = "1";
+ setSetting("comfyWhere", "workers");
+ setSetting("comfyUrl", "");
+ setSetting("engineMode", "open");
+ setSetting("demoMode", "off");
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+ });
+
+ /** A worker the owner resumed, allowed every lane, with every catalog file, running the given workflows (all unless said). */
+ function standInWorker(name: string, workflows?: string[]) {
+ const w = pool.addWorker(name);
+ const index = loadIndex();
+ const lanes = allLanes(index, sha);
+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l.lane, { delayMs: 0 }])), claimAfterMs: 0 });
+ db()
+ .prepare("UPDATE relay_workers SET facts_json = ?, catalog_version = ?, protocol = 3, seen_at = ?, paused_local = 0 WHERE id = ?")
+ .run(JSON.stringify({ vramBytes: 96 * 2 ** 30 }), catalogVersion(), Date.now(), w.id);
+ const own = Object.values(index.files).map((f) => ({ folder: f.folder, name: f.file, size: f.sizeBytes, sha256: f.sha256 ?? null }));
+ const packs = Object.keys(index.packs ?? {}).map((n) => ({ name: n, commit: null }));
+ const row = db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as import("@/server/computer/workers").WorkerRow;
+ pool.saveInventory(row, { files: own, nodePacks: packs, media: ["image", "video", "audio"] });
+ db()
+ .prepare("UPDATE relay_workers SET lanes_json = ? WHERE id = ?")
+ .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: workflows ?? loadManifest().workflows.map((x) => x.id) }), w.id);
+ return w;
+ }
+
+ const press = async (body: Record<string, unknown>) => {
+ const text = JSON.stringify(body);
+ const r = await generationsRoute.POST(
+ new Request(`http://${HOST}/api/generations`, { 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 Record<string, unknown> & { items?: { id: string }[]; error?: string } };
+ };
+
+ const mine = (data: Buffer, contentType: string, name: string) => saveFile({ data, contentType, name, source: "upload", accountId: account.id }).url;
+
+ const angle = (photo: string, splat: string) => ({
+ feature: ANY_ANGLE.feature,
+ modelId: ANY_ANGLE.shotModel,
+ op: "edit",
+ engine: "open",
+ prompt: "Left 30°",
+ inputs: { images: [photo] },
+ params: { seed: 46, extra: shotExtra({ yaw: 95, pitch: 10, distance: 2, fov: 33, target: [0, 0, 0] }, { width: 512, height: 512 }, splat) },
+ });
+
+ it("an account's angle goes in line for the workers with its splat made again (it used to fail at the upload)", async () => {
+ standInWorker("all");
+ const req = angle(mine(TINY_PNG, "image/png", "me.png"), mine(SPLAT, "model/x-spz", "view.spz"));
+ const q = await poolQuote(account, req as never, undefined);
+ expect(q?.quote.allowed, JSON.stringify(q?.quote)).toBe(true);
+ const r = await press(req);
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ const id = r.body.items![0].id;
+ let t: tasks.TaskRow | undefined;
+ for (let i = 0; i < 200 && !t; i++) {
+ await globalThis.__fuobeRunner?.tick();
+ t = db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ?").get(id) as tasks.TaskRow | undefined;
+ if (!t) await new Promise((res) => setTimeout(res, 20));
+ }
+ const row = db().prepare("SELECT status, error FROM generations WHERE id = ?").get(id) as { status: string; error: string | null };
+ expect(row.error ?? "").not.toMatch(/don't take/);
+ expect(t, "the angle's task").toBeDefined();
+ const inputs = tasks.inputsOf(t!.id);
+ const splat = inputs.find((i) => i.content_type === "model/x-spz");
+ expect(splat, JSON.stringify(inputs)).toBeDefined();
+ expect(spzPoints(fs.readFileSync(path.join(tasks.relayDir(), "in", splat!.name)))?.equals(RAW)).toBe(true);
+ });
+
+ it("a file the workers don't take, named in the run's settings, is said before Run as the visitor's own GPU", async () => {
+ standInWorker("all");
+ const req = angle(mine(TINY_PNG, "image/png", "me.png"), mine(Buffer.from("{}"), "application/json", "view.json"));
+ expect(hosted.requestFileKinds(req as never).sort()).toEqual(["file", "image"]);
+ const q = await poolQuote(account, req as never, undefined);
+ expect(q?.quote).toMatchObject({ allowed: false, text: "This file runs on your own GPU" });
+ });
+
+ it("a later step's files count too: a 3D model handed on is taken, a clip only where the workers take clips", () => {
+ expect(chainFileKinds({ chain: [{ slot: "model3d" }, { slot: "images" }] } as never, 2).sort()).toEqual(["image", "model3d"]);
+ expect(chainFileKinds({ chain: [{ slot: "prompt" }] } as never, 1)).toEqual([]);
+ expect(chainFileKinds({} as never, 1)).toEqual(["image"]);
+ expect(hosted.poolTakesKind("model3d")).toBe(true);
+ expect(hosted.poolTakesKind("file")).toBe(false);
+ const before = process.env.FUOBE_POOL_MEDIA_INPUTS;
+ try {
+ process.env.FUOBE_POOL_MEDIA_INPUTS = "image";
+ expect(hosted.poolTakesKind("video")).toBe(false);
+ process.env.FUOBE_POOL_MEDIA_INPUTS = "image,video";
+ expect(hosted.poolTakesKind("video")).toBe(true);
+ } finally {
+ if (before === undefined) delete process.env.FUOBE_POOL_MEDIA_INPUTS;
+ else process.env.FUOBE_POOL_MEDIA_INPUTS = before;
+ }
+ });
+
+ it("Any Angle's 3D view is offered on these GPUs only where its angles run too", async () => {
+ const build = { feature: ANY_ANGLE.stepFeature, modelId: ANY_ANGLE.buildModel, op: "splat", engine: "open", inputs: { images: [mine(TINY_PNG, "image/png", "p.png")] } };
+ standInWorker("no-angles", loadManifest().workflows.map((x) => x.id).filter((x) => x !== ANY_ANGLE.shotGraph));
+ expect(hosted.poolTakes(ANY_ANGLE.buildGraph)).toBe(true);
+ expect(hosted.poolTakes(ANY_ANGLE.shotGraph)).toBe(false);
+ const off = await poolQuote(account, build as never, undefined);
+ expect(off?.quote.allowed, JSON.stringify(off?.quote)).toBe(false);
+ standInWorker("all");
+ const on = await poolQuote(account, build as never, undefined);
+ expect(on?.quote.allowed, JSON.stringify(on?.quote)).toBe(true);
+ });
+});