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
Job tickets: typed tickets, the catalog version and the composer in the worker
Adarshfba4972454cc
diff --git a/bin/lib/worker/composer-files.mjs b/bin/lib/worker/composer-files.mjsnew file mode 100644index 00000000..2c6b5dc0--- /dev/null+++ b/bin/lib/worker/composer-files.mjs@@ -0,0 +1,69 @@+// The graph composer the worker builds in (docs/gpu-workers.md, "Job tickets"): the files of src/lib/ticket-compose.ts+// and everything it imports, and the catalog version, one SHA-256 over those files and the catalog's workflows. The+// studio computes the same version from its own copy (src/server/computer/catalog-version.ts), so a worker composes+// a ticket only from the catalog the ticket was made for.+import crypto from "node:crypto";+import fs from "node:fs";+import path from "node:path";++/** Where the composer starts: the worker's side of job tickets, and everything it imports. */+export const COMPOSER_ROOTS = ["src/lib/ticket-compose.ts"];++/** The file built for a composer file, inside dist/compose/ ("src/lib/comfy.ts" → "lib/comfy.mjs"; JSON → ".json.mjs"). */+export const builtName = (rel) => rel.replace(/^src\//, "").replace(/\.tsx?$/, ".mjs").replace(/\.json$/, ".json.mjs");++/** Every module a source names: imports, re-exports and import() with a fixed name. Type-only ones are left out. */+export function specifiers(src) {+ const out = new Set();+ for (const m of src.matchAll(/(?:^|[\n;])\s*(import|export)\s+(type\s+)?(?:[\w*{}\s,$]+?\s+from\s+)?["']([^"'\n]+)["']/g)) if (!m[2]) out.add(m[3]);+ for (const m of src.matchAll(/\bimport\(\s*["']([^"'\n]+)["']\s*\)/g)) out.add(m[1]);+ return [...out];+}++/** A module name as a repo file ("@/lib/x" → src/lib/x.ts), "node:" for Node's own, or null for a package. */+export function resolveSpec(root, fromRel, spec) {+ if (spec.startsWith("node:")) return "node:";+ let base;+ if (spec.startsWith("@/")) base = path.join(root, "src", spec.slice(2));+ else if (spec.startsWith(".")) base = path.resolve(root, path.dirname(fromRel), spec);+ else return null;+ for (const f of [`${base}.ts`, `${base}.tsx`, path.join(base, "index.ts"), base]) {+ if (fs.existsSync(f) && fs.statSync(f).isFile()) return path.relative(root, f).split(path.sep).join("/");+ }+ throw new Error(`${fromRel} imports ${spec}, which isn't there`);+}++/** The composer's files, repo-relative and sorted. Throws when one imports a package (the worker installs none). */+export function composerFiles(root) {+ const seen = new Set();+ const walk = (rel) => {+ if (seen.has(rel)) return;+ seen.add(rel);+ if (rel.endsWith(".json")) return;+ const src = fs.readFileSync(path.join(root, rel), "utf8");+ for (const spec of specifiers(src)) {+ const r = resolveSpec(root, rel, spec);+ if (r === "node:") continue;+ if (r === null) throw new Error(`${rel} imports the package ${spec}: the composer may import only its own files and Node's`);+ walk(r);+ }+ };+ for (const r of COMPOSER_ROOTS) walk(r);+ return [...seen].sort();+}++/** A text file's SHA-256 with its line ends made plain (a Windows checkout's CRLF counts as LF). */+const textSha = (file) => crypto.createHash("sha256").update(fs.readFileSync(file, "utf8").replace(/\r\n/g, "\n")).digest("hex");++/**+ * The catalog version: one SHA-256 over each composer file's name and content, and each .json of the catalog's folder+ * (workflows/comfyui), with line ends made plain.+ */+export function catalogVersion(root, catalogDir = path.join(root, "workflows/comfyui")) {+ const entries = composerFiles(root).map((rel) => [rel, path.join(root, rel)]);+ for (const f of fs.readdirSync(catalogDir).filter((x) => x.endsWith(".json"))) entries.push([`workflows/comfyui/${f}`, path.join(catalogDir, f)]);+ entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));+ const all = crypto.createHash("sha256");+ for (const [name, file] of entries) all.update(`${name}\u0000${textSha(file)}\n`);+ return all.digest("hex");+}diff --git a/bin/lib/worker/stamp.mjs b/bin/lib/worker/stamp.mjsindex 330a2e3b..073f303d 100644--- a/bin/lib/worker/stamp.mjs+++ b/bin/lib/worker/stamp.mjs@@ -5,12 +5,13 @@import crypto from "node:crypto";import fs from "node:fs";import path from "node:path";+import { composerFiles } from "./composer-files.mjs";/** The file the build writes the stamp into, in dist/. */export const STAMP_FILE = "build-stamp.json";/** The code that turns the catalog into the worker's parts. */-const BUILD_CODE = ["scripts/build-worker.mjs", "scripts/lib/worker-build.mjs", "scripts/lib/worker-catalog.mjs", "scripts/lib/catalog-checks.mjs", "bin/lib/worker/rules.mjs", "bin/lib/worker/stamp.mjs"];+const BUILD_CODE = ["scripts/build-worker.mjs", "scripts/lib/worker-build.mjs", "scripts/lib/worker-catalog.mjs", "scripts/lib/catalog-checks.mjs", "bin/lib/worker/rules.mjs", "bin/lib/worker/stamp.mjs", "bin/lib/worker/composer-files.mjs"];/** Every source file of the studio's graph builders and job runner (src/lib and src/server, .ts and .tsx). */export function builderSources(root) {@@ -18,13 +19,23 @@ export function builderSources(root) {return [...walk(path.join(root, "src/lib")), ...walk(path.join(root, "src/server"))];}+/** The composer's files outside src/lib and src/server (it imports a few), or none in a checkout without the composer. */+function composerExtras(root) {+ try {+ return composerFiles(root).filter((f) => !f.startsWith("src/lib/") && !f.startsWith("src/server/"));+ } catch {+ return [];+ }+}+/*** Every file the parts are built from, as [its name in the stamp, its path]: the studio's sources (the job runner, and- * the graph builders the node allowlist reads), the build's own code, and every .json of the catalog's folder.+ * the graph builders the node allowlist reads), the composer's other files, the build's own code, and every .json of+ * the catalog's folder.*/export function stampFiles(root, catalogDir = path.join(root, "workflows/comfyui")) {const rel = (f) => path.relative(root, f).split(path.sep).join("/");- const files = [...builderSources(root).map((f) => [rel(f), f]), ...BUILD_CODE.map((f) => [f, path.join(root, f)])];+ const files = [...builderSources(root).map((f) => [rel(f), f]), ...composerExtras(root).map((f) => [f, path.join(root, f)]), ...BUILD_CODE.map((f) => [f, path.join(root, f)])];for (const f of fs.readdirSync(catalogDir).filter((x) => x.endsWith(".json"))) files.push([`workflows/comfyui/${f}`, path.join(catalogDir, f)]);return files.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));}diff --git a/bin/lib/worker/tickets.mjs b/bin/lib/worker/tickets.mjsnew file mode 100644index 00000000..f7302c62--- /dev/null+++ b/bin/lib/worker/tickets.mjs@@ -0,0 +1,135 @@+// Job tickets on the worker (docs/gpu-workers.md, "Job tickets"): an account's run comes as a ticket, not a graph. The+// worker composes the graph itself, with the studio's own composer built into its dist (compose/) and its own copy of+// the catalog (workflows/comfyui in its checkout), for the catalog version its build was made from. Its PC's ceiling+// (worker.json `ceiling`) is the most it ever runs; the PC's own facts (its GPU's memory, its RAM, the model files and+// packs its ComfyUI has) make the choices that depend on the PC.+import crypto from "node:crypto";+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";++const here = path.dirname(fileURLToPath(import.meta.url));++/** The catalog version this worker's build composes for (dist/catalog-version.json), or null when it isn't built. */+export function builtCatalogVersion(dist = path.join(here, "dist")) {+ try {+ const v = JSON.parse(fs.readFileSync(path.join(dist, "catalog-version.json"), "utf8")).version;+ return typeof v === "string" && /^[0-9a-f]{64}$/.test(v) ? v : null;+ } catch {+ return null;+ }+}++/**+ * The catalog as the composer reads it, from a checkout's workflows/comfyui: manifest.json and each workflow's file+ * (read again for each job, so the composer never shares a graph between two jobs).+ */+export function workerCatalog(dir) {+ const manifest = JSON.parse(fs.readFileSync(path.join(dir, "manifest.json"), "utf8"));+ const byId = new Map((manifest.workflows ?? []).map((w) => [w.id, w]));+ return {+ has: (id) => byId.has(id),+ get: (id) => {+ const m = byId.get(id);+ if (!m) throw new Error(`The catalog has no workflow ${id}`);+ return { manifest: m, workflow: JSON.parse(fs.readFileSync(path.join(dir, path.basename(String(m.file))), "utf8")) };+ },+ };+}++const LANE = /^([0-9a-f]{12}|small)$/;+const WORKFLOW = /^[a-z0-9][a-z0-9._-]{0,95}(\{n\}[a-z0-9._-]{0,32})?$/i;+const sha = (s) => crypto.createHash("sha256").update(s).digest("hex");++/**+ * A ceiling as worker.json keeps it (src/lib/job-ticket.ts cleanCeiling says the same): the lanes and workflows its PC+ * may ever run (absent: all), and the largest picture in megapixels, the longest clip in seconds and the most results+ * per run (absent: no limit of its own). Null when it sets nothing.+ */+export function ceilingOf(raw) {+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;+ const ids = (v, re) => (Array.isArray(v) ? [...new Set(v.filter((x) => typeof x === "string" && re.test(x)))].sort() : undefined);+ const cap = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.min(v, 1e6) : undefined);+ const c = {};+ const lanes = ids(raw.lanes, LANE);+ const workflows = ids(raw.workflows, WORKFLOW);+ if (lanes) c.lanes = lanes;+ if (workflows) c.workflows = workflows;+ for (const k of ["maxMegapixels", "maxSeconds", "maxOutputs"]) {+ const v = cap(raw[k]);+ if (v !== undefined) c[k] = k === "maxOutputs" ? Math.floor(v) : v;+ }+ return Object.keys(c).length ? c : null;+}++/**+ * A ceiling from setup's answers: `work` is "all" (or empty) or lane and workflow names separated by commas or spaces;+ * the three sizes are numbers (0 or empty: no limit). `known(id)` says whether the catalog has a workflow. Returns+ * { ceiling } (null: no ceiling), or { error } in words.+ *+ * @param {{ work?: string, megapixels?: string, seconds?: string, outputs?: string }} a+ * @param {(id: string) => boolean} [known]+ */+export function ceilingFrom(a, known = () => true) {+ const raw = {};+ const work = String(a.work ?? "").trim();+ if (work && work.toLowerCase() !== "all") {+ const names = work.split(/[\s,;]+/).filter(Boolean);+ const lanes = names.filter((n) => LANE.test(n));+ const workflows = names.filter((n) => !LANE.test(n));+ const bad = workflows.find((n) => !WORKFLOW.test(n) || !known(n));+ if (bad) return { error: `${bad} isn't a lane or a workflow of the studio's catalog.` };+ if (lanes.length) raw.lanes = lanes;+ if (workflows.length) raw.workflows = workflows;+ }+ for (const [k, v] of [["maxMegapixels", a.megapixels], ["maxSeconds", a.seconds], ["maxOutputs", a.outputs]]) {+ const text = String(v ?? "").trim();+ if (!text) continue;+ const n = Number(text);+ if (!Number.isFinite(n) || n < 0) return { error: `${text} isn't a number of 0 or more.` };+ if (n > 0) raw[k] = n;+ }+ return { ceiling: ceilingOf(raw) };+}++/** A ceiling in words for the PC's owner ("all workflows, pictures up to 4 MP, clips up to 10 s, 4 results a run"). */+export function ceilingWords(c) {+ if (!c) return "everything the studio asks, at any size";+ const work = c.lanes || c.workflows ? [...(c.lanes ?? []).map((l) => `lane ${l}`), ...(c.workflows ?? [])].join(", ") : "all workflows";+ const sizes = [c.maxMegapixels && `pictures up to ${c.maxMegapixels} MP`, c.maxSeconds && `clips up to ${c.maxSeconds} s`, c.maxOutputs && `${c.maxOutputs} result${c.maxOutputs === 1 ? "" : "s"} a run`].filter(Boolean);+ return [work, ...sizes].join(", ");+}++/** Each workflow's lane, from the requirements index (the studio's lanes: src/lib/lanes.ts allLanes). */+export function laneMap(index, allLanes) {+ const by = new Map();+ for (const l of allLanes(index, sha)) for (const id of l.workflows) by.set(id, l.lane);+ return (id) => by.get(id) ?? "small";+}++/**+ * Is a graph job inside the ceiling (the owner's own jobs come as graphs): by its lane or workflow. A ticket's sizes are+ * checked by the composer.+ */+export function graphInside(c, t) {+ if (!c || (c.lanes === undefined && c.workflows === undefined)) return true;+ return (!!t.lane && !!c.lanes?.includes(t.lane)) || (!!t.workflowId && !!c.workflows?.includes(t.workflowId));+}++/**+ * Its own ComfyUI's answers for the choices that depend on the PC (src/lib/ticket-compose.ts workerFactsFrom), read+ * through `own` (its ComfyUI only). An answer it can't read stays unknown.+ */+export async function readPcAnswers(own, base) {+ const get = async (p) => {+ try {+ const r = await own(`${base}${p}`, { cache: "no-store" });+ if (r.status === 404) return null;+ return r.ok ? await r.json() : undefined;+ } catch {+ return undefined;+ }+ };+ const [stats, dbs, reuse, idol] = await Promise.all([get("/system_stats"), get("/models/dbs"), get("/models/reuse"), get("/object_info/IdolPruneSplat")]);+ return { stats, dbs: dbs ?? undefined, reuse, idol };+}diff --git a/scripts/build-worker.mjs b/scripts/build-worker.mjsindex c5251b0a..31b01ca7 100644--- a/scripts/build-worker.mjs+++ b/scripts/build-worker.mjs@@ -27,7 +27,13 @@ function main(argv) {fs.mkdirSync(out, { recursive: true });// The stamp goes first and comes back last, so parts left half written never pass for a whole build.fs.rmSync(path.join(out, STAMP_FILE), { force: true });- for (const [name, text] of Object.entries(files)) if (name !== STAMP_FILE) fs.writeFileSync(path.join(out, name), text);+ // The composer's folder is made again whole: a file it no longer has never stays.+ fs.rmSync(path.join(out, "compose"), { recursive: true, force: true });+ for (const [name, text] of Object.entries(files)) {+ if (name === STAMP_FILE) continue;+ fs.mkdirSync(path.dirname(path.join(out, name)), { recursive: true });+ fs.writeFileSync(path.join(out, name), text);+ }fs.writeFileSync(path.join(out, STAMP_FILE), files[STAMP_FILE]);console.log(`${summary} -> ${path.relative(ROOT, out) || out}`);}diff --git a/scripts/lib/worker-build.mjs b/scripts/lib/worker-build.mjsindex d4bdca3e..82b37887 100644--- a/scripts/lib/worker-build.mjs+++ b/scripts/lib/worker-build.mjs@@ -9,12 +9,16 @@// into it;// - file-pins.json: the SHA-256 of every model file the catalog names. A worker reports a file only when its own// hash matches;+// - compose/: the graph composer (src/lib/ticket-compose.ts and every file it imports: bin/lib/worker/composer-files.mjs),+// transpiled the same way, so the worker composes a job ticket's graph with the studio's own code;+// - catalog-version.json: the catalog version those files and the catalog give. A worker takes a ticket only for it;// - build-stamp.json: one SHA-256 over every file the parts are built from (bin/lib/worker/stamp.mjs). A worker// starts only when its checkout gives the same stamp.import fs from "node:fs";import path from "node:path";import { fileURLToPath } from "node:url";import ts from "typescript";+import { builtName, catalogVersion, composerFiles, resolveSpec } from "../../bin/lib/worker/composer-files.mjs";import { buildStamp, STAMP_FILE } from "../../bin/lib/worker/stamp.mjs";import { unruledPathInputs } from "./catalog-checks.mjs";import { allowedNodeList, filePins, inputRules, missingRules, readCatalog } from "./worker-catalog.mjs";@@ -36,14 +40,53 @@ export function workerParts(catalog, root = ROOT) {return { nodes, rules, pins: filePins(catalog) };}-/** Each built file's text: the transpiled modules, the three catalog files and the stamp. Nothing is written. */+const TRANSPILE = { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022, verbatimModuleSyntax: false, isolatedModules: true };++/**+ * The graph composer as plain .mjs files under compose/ (src/lib/x.ts → compose/lib/x.mjs; a .json it imports →+ * compose/….json.mjs, with the data as its default export), each import pointed at the built file. Node's own modules+ * stay; a package is refused (composer-files.mjs).+ */+export function composerParts(root = ROOT) {+ const files = {};+ for (const rel of composerFiles(root)) {+ const out = `compose/${builtName(rel)}`;+ const src = fs.readFileSync(path.join(root, rel), "utf8");+ const head = `// Built from ${rel} by scripts/build-worker.mjs. Don't edit.\n`;+ if (rel.endsWith(".json")) {+ files[out] = `${head}const data = ${JSON.stringify(JSON.parse(src))};\nexport default data;\n`;+ continue;+ }+ const { outputText } = ts.transpileModule(src, { compilerOptions: TRANSPILE, fileName: path.basename(rel) });+ // Each module name the transpiled file imports (TypeScript finds them: imports, re-exports, import()), from the last.+ const named = ts.preProcessFile(outputText, true, true).importedFiles.sort((a, b) => b.pos - a.pos);+ let js = outputText;+ for (const f of named) {+ const r = resolveSpec(root, rel, f.fileName);+ if (r === "node:") continue;+ if (r === null) throw new Error(`${rel} imports the package ${f.fileName}: the composer may import only its own files and Node's`);+ let to = path.posix.relative(path.posix.dirname(out), `compose/${builtName(r)}`);+ if (!to.startsWith(".")) to = `./${to}`;+ const at = js.indexOf(f.fileName, f.pos);+ if (at < 0 || at > f.end) throw new Error(`Couldn't place the import of ${f.fileName} in ${rel}`);+ js = js.slice(0, at) + to + js.slice(at + f.fileName.length);+ }+ files[out] = head + js;+ }+ return files;+}++/**+ * Each built file's text: the transpiled modules, the composer, the three catalog files, the catalog version and the+ * stamp. Nothing is written.+ */export function workerFiles({ root = ROOT, catalogDir } = {}) {const catalog = readCatalog(root, catalogDir);const { nodes, rules, pins } = workerParts(catalog, root);const files = {};for (const name of SOURCES) {const src = fs.readFileSync(path.join(root, "src/lib", `${name}.ts`), "utf8");- const { outputText } = ts.transpileModule(src, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022, verbatimModuleSyntax: false, isolatedModules: true }, fileName: `${name}.ts` });+ const { outputText } = ts.transpileModule(src, { compilerOptions: TRANSPILE, fileName: `${name}.ts` });const js = outputText.replace(/from "\.\/([\w-]+)"/g, (m, dep) => {if (!SOURCES.includes(dep)) throw new Error(`${name}.ts imports ./${dep}, which the worker build doesn't include`);return `from "./${dep}.mjs"`;@@ -55,7 +98,10 @@ export function workerFiles({ root = ROOT, catalogDir } = {}) {files["allowed-nodes.json"] = json({ nodes });files["input-rules.json"] = json(rules);files["file-pins.json"] = json({ files: pins });+ const composer = composerParts(root);+ Object.assign(files, composer);+ files["catalog-version.json"] = json({ version: catalogVersion(root, catalogDir) });files[STAMP_FILE] = json({ stamp: buildStamp(root, catalogDir) });const ruled = Object.values(rules.inputs).reduce((n, r) => n + Object.keys(r).length, 0);- return { files, summary: `worker: ${SOURCES.length} modules, ${nodes.length} allowed node types, ${ruled} input rules, ${Object.keys(pins).length} file hashes` };+ return { files, summary: `worker: ${SOURCES.length} modules, ${Object.keys(composer).length} composer files, ${nodes.length} allowed node types, ${ruled} input rules, ${Object.keys(pins).length} file hashes` };}diff --git a/src/lib/comfy-compose.ts b/src/lib/comfy-compose.tsindex 9626b1da..03f91d78 100644--- a/src/lib/comfy-compose.ts+++ b/src/lib/comfy-compose.ts@@ -175,6 +175,8 @@ export interface ComposedPrompt {workflow: ComfyWorkflow;meta: Record<string, unknown>;size: ComposedSize;+ /** The params.extra keys it dropped: an account's file input this run didn't send (a job ticket leaves them out too). */+ dropped: string[];}/**@@ -1126,8 +1128,13 @@ export async function composeWorkflow(endpointTemplate: string, input: GenInput,}// An account's run on this install's GPUs never names a file there itself: a file input in params.extra is one this// run sent (a media ref, uploaded above), else it is dropped (it could name another run's file in the same folder).+ const dropped: string[] = [];if (ctx.accountOnInstall) {- for (const k of mediaKeys(manifest, workflow)) if (k in extra && !sentHere.has(k)) delete extra[k];+ for (const k of mediaKeys(manifest, workflow)) {+ if (!(k in extra) || sentHere.has(k)) continue;+ delete extra[k];+ dropped.push(k);+ }}// Idol 3D: "It's a photo" is the clean graph's "real" crop (the core graph's photo switch), then the pack's pruning.if (manifest.id === IDOL_WORKFLOWS.core || manifest.id === IDOL_WORKFLOWS.clean || manifest.id === IDOL_VIEWS_WORKFLOW) {@@ -1369,6 +1376,7 @@ export async function composeWorkflow(endpointTemplate: string, input: GenInput,manifest,workflow: wf,size: jobSize(values, input, ctx.media),+ dropped,// The seed the graph drew with (one Fuobe picked when none was asked): its pictures keep it, so Edit layout redraws the same one.meta: {workflowId: manifest.id,diff --git a/src/lib/job-ticket.ts b/src/lib/job-ticket.tsnew file mode 100644index 00000000..6fd92e9c--- /dev/null+++ b/src/lib/job-ticket.ts@@ -0,0 +1,430 @@+/**+ * Job tickets (docs/gpu-workers.md, "Job tickets"): what a worker gets for a run of an account on this install's GPUs in+ * place of a graph. A ticket names a catalog workflow, the catalog version it was made for, the run's typed settings, its+ * input files (slot, name, kind, SHA-256 and header facts), how many results it makes and how big it is. The worker+ * composes the graph itself from its own copy of the catalog (src/lib/comfy-compose.ts, built into the worker), so a+ * server can never hand it a graph of its own making. The owner's own jobs and a person's own GPU keep full graphs.+ *+ * Both sides check a ticket the same way (ticketProblem): the studio when it makes one, the worker before it composes.+ * Settings are typed: enums, ranges and lists; a person's words go only to the prompt fields, and no text names a path.+ * Files are named only through their slots.+ *+ * The PC's ceiling (worker.json `ceiling`, set at `fuobe worker setup`): the most a worker may ever run. The studio and+ * its panel only narrow inside it, and a worker never claims a job outside it (ceilingProblem).+ *+ * Pure: the server, the worker program and the tests share it.+ */+import { INPUT_NAME } from "./relay";++export const TICKET_VERSION = 1;++/** The kinds of file a ticket's input may be. */+export const TICKET_INPUT_KINDS = ["image", "video", "audio", "model3d", "file"] as const;+export type TicketInputKind = (typeof TICKET_INPUT_KINDS)[number];++/** What the studio read from an input's header (the composer sizes clips and checks times by it). */+export interface TicketFacts {+ container?: string;+ duration?: number;+ videoDuration?: number;+ width?: number;+ height?: number;+ fps?: number;+ frames?: number;+ hasVideo?: boolean;+ hasAudio?: boolean;+ channels?: number;+}++/**+ * One input file. `slot` says where it goes: images.<i>, endImage, mask, video, videos.<i>, audio, audio2, voiceAudio,+ * voiceAudio2, audios.<i>, model3d, extra.<key> (a setting that names a file), or made.<i> (a file the composer makes+ * itself, such as a fade curve or a palette swatch: the worker makes it again and never reads the studio's copy).+ */+export interface TicketInput {+ slot: string;+ name: string;+ kind: TicketInputKind;+ sha256: string;+ facts?: TicketFacts;+}++/** How big a job is: the largest picture (megapixels), the longest clip (seconds) and the results asked for. */+export interface TicketSize {+ megapixels: number;+ seconds: number;+ outputs: number;+}++export interface JobTicket {+ v: typeof TICKET_VERSION;+ /** The catalog workflow (or its template, such as video-concat-{n}) the run asked for. */+ workflowId: string;+ /** The catalog version it was made for (catalogVersion: the worker's build has its own). */+ catalogVersion: string;+ /** The operation (t2i, i2v, trim…): the composer shapes the graph by it. */+ op: string;+ /** The run's settings, typed (TICKET_SETTINGS). No file names: those are the inputs. */+ settings: Record<string, unknown>;+ inputs: TicketInput[];+ /** How many results the job makes, and of what kind. */+ outputs: { count: number; kind: string };+ size: TicketSize;+ /** The route puts the run's one LoRA in the graph's own LoRA slot (comfy-compose.ts ComposeContext.loraSlot). */+ loraSlot?: boolean;+ /** Set at the claim: how long the job may run, and go without progress. */+ runLimitMs?: number;+ stallMs?: number;+}++/** Why a ticket can't be used: an older or newer catalog ("update-worker"), or settings outside their rules. */+export type TicketRefusal = { reason: "update-worker" | "bad-ticket"; detail: string };++// ---------------------------------------------------------------------------+// Words and paths++const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;+/** File names a setting may never carry (models, media, code and data files). */+const FILE_EXT = /\.(safetensors|gguf|ckpt|pt|pt2|pth|bin|sft|onnx|pkl|pickle|engine|png|jpe?g|webp|gif|bmp|tiff?|exr|mp4|mov|m4v|webm|mkv|avi|wav|mp3|flac|m4a|ogg|opus|aac|glb|gltf|ply|obj|fbx|splat|json|ya?ml|toml|py|pyc|sh|bat|cmd|ps1|exe|dll|so|txt|csv|srt|vtt|zip|tar|gz|7z|npz|npy)$/i;+/** A drive, a share, a home or a file address inside text, or a ".." step. */+const PATH_IN_TEXT = /(^|[\s"'(=,;[{])([A-Za-z]:[\\/]|\\\\[^\s\\]|~[\\/]|file:)|(^|[\\/\s"'(])\.\.[\\/]|[\\/]\.\.($|[\s"')])/i;+/** A path as a whole value: rooted, a drive, a share, a home folder, or a ".." step. */+const PATH_SHAPE = /^([\\/]|[A-Za-z]:|~|\\\\)|(^|[\\/])\.\.([\\/]|$)/;++/**+ * A person's words (prompts, lyrics, captions): any text, but never a path. A value with no space that has the shape of+ * a path, and text that holds a drive, a share, a home folder, a file address or a ".." step, are refused.+ */+export function textProblem(s: unknown, max = 20_000): string | null {+ if (typeof s !== "string") return "not text";+ if (s.length > max) return "too long";+ if (CONTROL.test(s)) return "a control character";+ if (!/\s/.test(s.trim()) && PATH_SHAPE.test(s.trim())) return "a path";+ if (PATH_IN_TEXT.test(s)) return "a path";+ return null;+}++/**+ * A setting written as words (a quality, a language, a colour, a choice): textProblem's rules, and no slash or backslash+ * in a value without spaces, no file name, no address, no encoded or variable part.+ */+export function wordProblem(s: unknown, max = 4000): string | null {+ const p = textProblem(s, max);+ if (p) return p;+ const v = (s as string).trim();+ if (!/\s/.test(v) && /[\\/]/.test(v)) return "a path";+ if (!/\s/.test(v) && FILE_EXT.test(v)) return "a file name";+ if (/:\/\/|%[0-9a-f]{2}|%[A-Za-z_][\w]*%|\$\{|\$[A-Z_]{2,}/i.test(v)) return "an address or a variable";+ return null;+}++// ---------------------------------------------------------------------------+// Settings++type Check = (v: unknown) => string | null;++const finite = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);+const num =+ (min: number, max: number, int = false): Check =>+ (v) =>+ !finite(v) ? "not a number" : v < min || v > max ? `outside ${min}-${max}` : int && !Number.isInteger(v) ? "not a whole number" : null;+const bool: Check = (v) => (typeof v === "boolean" ? null : "not true or false");+const oneOf =+ (...values: readonly string[]): Check =>+ (v) =>+ typeof v === "string" && values.includes(v) ? null : `not one of ${values.join(", ")}`;+const token =+ (re = /^[\w .:+#()%-]{0,80}$/): Check =>+ (v) =>+ typeof v !== "string" ? "not text" : !re.test(v) ? "not an allowed value" : wordProblem(v);+const text =+ (max = 20_000): Check =>+ (v) =>+ textProblem(v, max);+const either =+ (...checks: Check[]): Check =>+ (v) => {+ const problems = checks.map((c) => c(v));+ return problems.includes(null) ? null : problems[0];+ };+const list =+ (item: Check, max: number): Check =>+ (v) => {+ if (!Array.isArray(v)) return "not a list";+ if (v.length > max) return `more than ${max}`;+ for (const [i, x] of v.entries()) {+ const p = item(x);+ if (p) return `[${i}] ${p}`;+ }+ return null;+ };+const shape =+ (fields: Record<string, Check>, required: string[] = []): Check =>+ (v) => {+ if (!v || typeof v !== "object" || Array.isArray(v)) return "not a group of settings";+ for (const k of required) if (!(k in v)) return `${k} missing`;+ for (const [k, x] of Object.entries(v)) {+ if (x === undefined) continue;+ const c = fields[k];+ if (!c) return `${k} isn't a known setting`;+ const p = c(x);+ if (p) return `${k} ${p}`;+ }+ return null;+ };++const KEY = /^[A-Za-z_][\w-]{0,63}$/;+/** The longest words one setting in params.extra may hold (a window review's controls are the longest). */+const EXTRA_TEXT_MAX = 131_072;++/**+ * Any other setting (params.extra and what it holds): numbers, true or false, lists and groups of them, and words+ * (wordProblem). At most 8 deep, 1024 items in a list and 128 keys in a group.+ */+export function plainProblem(v: unknown, depth = 0): string | null {+ if (v === null || typeof v === "boolean") return null;+ if (typeof v === "number") return Number.isFinite(v) && Math.abs(v) <= 1e12 ? null : "a number out of range";+ if (typeof v === "string") return wordProblem(v, EXTRA_TEXT_MAX);+ if (depth >= 8) return "too deep";+ if (Array.isArray(v)) {+ if (v.length > 1024) return "a list too long";+ for (const [i, x] of v.entries()) {+ const p = plainProblem(x, depth + 1);+ if (p) return `[${i}] ${p}`;+ }+ return null;+ }+ if (typeof v === "object") {+ const entries = Object.entries(v as Record<string, unknown>);+ if (entries.length > 128) return "too many keys";+ for (const [k, x] of entries) {+ if (!KEY.test(k)) return "a key that isn't a plain name";+ const p = plainProblem(x, depth + 1);+ if (p) return `${k} ${p}`;+ }+ return null;+ }+ return "not a setting";+}++const point = shape({ x: num(-1e5, 1e5), y: num(-1e5, 1e5), label: oneOf("positive", "negative") }, ["x", "y"]);+const cameraKey = shape({ t: num(0, 1), azimuth: num(-1e5, 1e5), elevation: num(-360, 360), distance: num(0, 100), truck: num(-100, 100), pedestal: num(-100, 100), roll: num(-360, 360), fov: num(0, 360) }, ["t"]);+/** A LoRA by its file name in the loras folder (subfolders allowed, never a path out), and how it's mixed. */+const LORA_FILE = /^(?!.*(^|\/)\.\.?(\/|$))[\w .()+-]+(\/[\w .()+-]+)*\.safetensors$/;+const lora = shape(+ {+ file: (v) => (typeof v === "string" && LORA_FILE.test(v) && v.length <= 256 ? null : "not a LoRA file name"),+ strength: num(-10, 10),+ trigger: text(400),+ target: oneOf("high", "low", "both"),+ },+ ["file"],+);++/**+ * The settings a ticket may carry, by their GenInput name (src/lib/catalog/types.ts), each with its rule. A person's+ * words go only in prompt, negativePrompt, voiceDescription, voiceTranscript, dialogue and shots (and their words inside+ * params.extra); everything else is a number, a choice or a list of them.+ */+export const TICKET_SETTINGS: Record<string, Check> = {+ prompt: text(),+ negativePrompt: text(4000),+ aspectRatio: token(/^(auto|\d{1,3}:\d{1,3})$/),+ resolution: token(/^[\w.]{1,16}$/),+ duration: num(0, 3600),+ numOutputs: num(1, 16, true),+ seed: num(0, Number.MAX_SAFE_INTEGER, true),+ generateAudio: bool,+ enhancePrompt: bool,+ voice: token(),+ voiceDescription: text(2000),+ voiceTranscript: text(4000),+ dialogue: list(shape({ text: text(4000), voice: oneOf("A", "B") }, ["text"]), 200),+ targetLanguage: token(),+ sourceLanguage: token(),+ shots: list(shape({ prompt: text(4000), duration: num(0, 600) }), 64),+ elements: list(shape({ images: list(num(0, 64, true), 16), video: num(0, 64, true) }), 16),+ clipSeconds: num(0, 600),+ drawnRefs: num(0, 64, true),+ multiShot: oneOf("auto"),+ draft: bool,+ draftId: token(/^[\w-]{1,64}$/),+ startTime: num(0, 86_400),+ endTime: num(0, 86_400),+ fps: num(0, 1000),+ palette: list(token(/^#?[0-9A-Za-z]{1,16}$/), 64),+ styleId: token(/^[\w.:-]{1,80}$/),+ numLayers: num(1, 64, true),+ points: list(point, 256),+ keyframeTimes: list(num(0, 86_400), 64),+ format: token(/^[\w-]{1,32}$/),+ zoomFrom: num(0, 100),+ zoomTo: num(0, 100),+ panFrom: shape({ x: num(-10, 10), y: num(-10, 10) }, ["x", "y"]),+ panTo: shape({ x: num(-10, 10), y: num(-10, 10) }, ["x", "y"]),+ position: shape({ x: num(-10, 10), y: num(-10, 10) }, ["x", "y"]),+ easing: oneOf("linear", "ease-in-out"),+ crossfade: num(0, 600),+ sourceDuration: num(0, 86_400),+ sourceFps: num(0, 1000),+ sourceSize: shape({ width: num(0, 65_536), height: num(0, 65_536) }, ["width", "height"]),+ frameInterval: num(0, 10_000),+ targetFps: num(0, 1000),+ slowdown: num(0, 64),+ colormap: token(/^[\w-]{1,32}$/),+ sideBySide: bool,+ matteOutput: oneOf("cutout", "matte", "foreground"),+ scale: num(0, 64),+ animation: either(token(), num(-1e6, 1e6)),+ cameraPath: list(cameraKey, 256),+ loras: list(lora, 16),+ extra: (v) => (v && typeof v === "object" && !Array.isArray(v) ? plainProblem(v) : "not a group of settings"),+};++/** Settings that name a file: a ticket names those only through its inputs. */+export const FILE_SETTINGS = ["images", "endImage", "mask", "video", "videos", "audio", "audio2", "voiceAudio", "voiceAudio2", "audios", "model3d"] as const;++/** Where an input may go. */+const SLOT = /^(images\.\d{1,2}|endImage|mask|video|videos\.\d{1,2}|audio|audio2|voiceAudio|voiceAudio2|audios\.\d{1,3}|model3d|extra\.[A-Za-z][A-Za-z0-9_]{0,63}|made\.\d{1,2})$/;+const SHA = /^[0-9a-f]{64}$/;+const FACTS = shape({+ container: token(/^[\w-]{1,16}$/),+ duration: num(0, 86_400),+ videoDuration: num(0, 86_400),+ width: num(0, 65_536),+ height: num(0, 65_536),+ fps: num(0, 1000),+ frames: num(0, 1e8),+ hasVideo: bool,+ hasAudio: bool,+ channels: num(0, 64),+});+/** A workflow's id as the catalog names it (a template's {n} too). */+export const WORKFLOW_ID = /^[a-z0-9][a-z0-9._-]{0,95}(\{n\}[a-z0-9._-]{0,32})?$/i;+const OP = /^[a-z0-9][a-z0-9-]{0,47}$/;+const OUTPUT_KINDS = ["image", "video", "audio", "text", "model3d", "frame", "file"];++/**+ * Why a ticket can't be used, or null. `o.catalogVersion`: the reader's own (another one is "update-worker"); `o.known`:+ * whether the catalog has a workflow; `o.inputs`: the files the task sends (each input must be one of them, with the+ * same SHA-256; a made file's copy is never read, so only its name counts).+ */+export function ticketProblem(t: unknown, o: { catalogVersion?: string; known?: (id: string) => boolean; inputs?: { name: string; sha256: string }[] } = {}): TicketRefusal | null {+ const bad = (detail: string): TicketRefusal => ({ reason: "bad-ticket", detail });+ if (!t || typeof t !== "object" || Array.isArray(t)) return bad("not a ticket");+ const k = t as Partial<JobTicket> & Record<string, unknown>;+ for (const key of Object.keys(k)) if (!["v", "workflowId", "catalogVersion", "op", "settings", "inputs", "outputs", "size", "loraSlot", "runLimitMs", "stallMs"].includes(key)) return bad(`${key} isn't part of a ticket`);+ if (k.v !== TICKET_VERSION) return { reason: "update-worker", detail: "another ticket version" };+ if (typeof k.catalogVersion !== "string" || !SHA.test(k.catalogVersion)) return bad("no catalog version");+ if (o.catalogVersion !== undefined && k.catalogVersion !== o.catalogVersion) return { reason: "update-worker", detail: "another catalog version" };+ if (typeof k.workflowId !== "string" || !WORKFLOW_ID.test(k.workflowId)) return bad("not a workflow id");+ if (o.known && !o.known(k.workflowId)) return bad("an unknown workflow");+ if (typeof k.op !== "string" || !OP.test(k.op)) return bad("not an operation");+ if (k.loraSlot !== undefined && typeof k.loraSlot !== "boolean") return bad("loraSlot isn't true or false");+ for (const f of ["runLimitMs", "stallMs"] as const) if (k[f] !== undefined && num(0, 7 * 86_400_000, true)(k[f])) return bad(`${f} out of range`);+ const out = k.outputs as { count?: unknown; kind?: unknown } | undefined;+ if (!out || num(1, 256, true)(out.count) || typeof out.kind !== "string" || !OUTPUT_KINDS.includes(out.kind) || Object.keys(out).some((x) => x !== "count" && x !== "kind")) return bad("outputs out of range");+ const size = k.size as Partial<TicketSize> | undefined;+ const sizeProblem = shape({ megapixels: num(0, 10_000), seconds: num(0, 86_400), outputs: num(0, 256, true) }, ["megapixels", "seconds", "outputs"])(size);+ if (sizeProblem) return bad(`size ${sizeProblem}`);+ // Settings.+ const settings = k.settings;+ if (!settings || typeof settings !== "object" || Array.isArray(settings)) return bad("no settings");+ for (const [key, v] of Object.entries(settings)) {+ if (v === undefined) continue;+ if ((FILE_SETTINGS as readonly string[]).includes(key)) return bad(`${key} names a file outside the inputs`);+ const check = TICKET_SETTINGS[key];+ if (!check) return bad(`${key} isn't a setting a ticket carries`);+ const p = check(v);+ if (p) return bad(`${key}: ${p}`);+ }+ // Inputs.+ if (!Array.isArray(k.inputs) || k.inputs.length > 64) return bad("inputs out of range");+ const names = new Set<string>();+ const slots = new Set<string>();+ const extraFiles = new Set<string>();+ for (const i of k.inputs as unknown[]) {+ const x = i as Partial<TicketInput> & Record<string, unknown>;+ if (!x || typeof x !== "object") return bad("an input isn't one");+ if (Object.keys(x).some((f) => !["slot", "name", "kind", "sha256", "facts"].includes(f))) return bad("an input has an unknown field");+ if (typeof x.slot !== "string" || !SLOT.test(x.slot)) return bad("an input's slot isn't one");+ if (typeof x.name !== "string" || !INPUT_NAME.test(x.name)) return bad("an input's name isn't one the studio makes");+ if (typeof x.sha256 !== "string" || !SHA.test(x.sha256)) return bad("an input has no SHA-256");+ if (!(TICKET_INPUT_KINDS as readonly string[]).includes(String(x.kind))) return bad("an input's kind isn't one");+ if (x.facts !== undefined && FACTS(x.facts)) return bad(`an input's facts: ${FACTS(x.facts)}`);+ if (slots.has(x.slot)) return bad("two inputs in one slot");+ slots.add(x.slot);+ names.add(x.name);+ if (x.slot.startsWith("extra.")) extraFiles.add(x.slot.slice(6));+ if (o.inputs) {+ const sent = o.inputs.find((s) => s.name === x.name);+ if (!sent || (!x.slot.startsWith("made.") && sent.sha256 !== x.sha256)) return bad("an input isn't one the job sends");+ }+ }+ // Lists of files have no gaps (images.0, images.1…).+ for (const list of ["images", "videos", "audios", "made"]) {+ const n = [...slots].filter((s) => s.startsWith(`${list}.`)).map((s) => Number(s.slice(list.length + 1)));+ if (n.some((x, _i, all) => x >= all.length)) return bad(`${list} has a gap`);+ }+ // A setting in params.extra names a file only through its slot.+ const extra = (settings as { extra?: Record<string, unknown> }).extra ?? {};+ for (const key of extraFiles) if (key in extra) return bad(`extra.${key} is both a setting and a file`);+ return null;+}++// ---------------------------------------------------------------------------+// The PC's ceiling++/**+ * What a worker's PC may ever run (worker.json `ceiling`): the lanes and workflows (absent: all), the largest picture in+ * megapixels, the longest clip in seconds and the most results per run (absent or 0: no limit of its own).+ */+export interface Ceiling {+ lanes?: string[];+ workflows?: string[];+ maxMegapixels?: number;+ maxSeconds?: number;+ maxOutputs?: number;+}++const LANE = /^([0-9a-f]{12}|small)$/;++/** A ceiling as it may be kept: known fields, capped; anything else is left out (no limit). */+export function cleanCeiling(raw: unknown): Ceiling {+ const o = (raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {}) as Record<string, unknown>;+ const ids = (v: unknown, re: RegExp) => (Array.isArray(v) ? [...new Set(v.filter((x): x is string => typeof x === "string" && re.test(x)))].slice(0, 2000).sort() : undefined);+ const cap = (v: unknown) => (finite(v) && v > 0 ? Math.min(v, 1e6) : undefined);+ const c: Ceiling = {};+ const lanes = ids(o.lanes, LANE);+ const workflows = ids(o.workflows, WORKFLOW_ID);+ if (lanes) c.lanes = lanes;+ if (workflows) c.workflows = workflows;+ for (const k of ["maxMegapixels", "maxSeconds", "maxOutputs"] as const) {+ const v = cap(o[k]);+ if (v !== undefined) c[k] = k === "maxOutputs" ? Math.floor(v) : v;+ }+ return c;+}++/** The ceiling lists lanes or workflows (else every one is inside it). */+const listsWork = (c: Ceiling) => c.lanes !== undefined || c.workflows !== undefined;++/** Is this lane or workflow inside the ceiling? */+export function insideCeiling(c: Ceiling | null | undefined, job: { workflowId?: string | null; lane?: string | null }): boolean {+ if (!c || !listsWork(c)) return true;+ return (!!job.lane && !!c.lanes?.includes(job.lane)) || (!!job.workflowId && !!c.workflows?.includes(job.workflowId));+}++/** Why a job is outside a PC's ceiling, or null. A job of unknown size is inside the size limits. */+export function ceilingProblem(c: Ceiling | null | undefined, job: { workflowId?: string | null; lane?: string | null; size?: Partial<TicketSize> | null }): string | null {+ if (!c) return null;+ if (!insideCeiling(c, job)) return "a lane this PC doesn't run";+ const s = job.size ?? {};+ if (c.maxMegapixels && (s.megapixels ?? 0) > c.maxMegapixels + 1e-9) return "a larger picture than this PC makes";+ if (c.maxSeconds && (s.seconds ?? 0) > c.maxSeconds + 1e-9) return "a longer clip than this PC makes";+ if (c.maxOutputs && (s.outputs ?? 0) > c.maxOutputs) return "more results than this PC makes";+ return null;+}++/** The lanes a worker may run: the studio's allowed lanes, narrowed to its PC's ceiling. */+export const lanesInside = (allowed: string[], c: Ceiling | null | undefined): string[] => (c?.lanes !== undefined && c.workflows === undefined ? allowed.filter((l) => c.lanes!.includes(l)) : allowed);diff --git a/src/lib/ticket-compose.ts b/src/lib/ticket-compose.tsnew file mode 100644index 00000000..ec805653--- /dev/null+++ b/src/lib/ticket-compose.ts@@ -0,0 +1,230 @@+/**+ * Job tickets on both sides (src/lib/job-ticket.ts says what a ticket is): the studio makes one from the request its+ * composer used (ticketFor), and the worker composes the graph from it with the same composer and its own copy of the+ * catalog (composeTicket). Both check the ticket the same way before anything else.+ *+ * Pure: the server, the worker program (scripts/build-worker.mjs builds this file and everything it imports into the+ * worker) and the tests share it.+ */+import crypto from "node:crypto";+import { installedReuse, type ReuseModel } from "./av/clean-voice";+import { IDOL_PACK_CLASS } from "./av/model3d";+import { installedDbs, type DbsModel } from "./av/split";+import type { GenInput, Operation } from "./catalog/types";+import type { ComfyWorkflow } from "./comfy";+import { ComposeError, composeWorkflow, withoutSaveMetadata, type ComposeCatalog, type ComposedSize, type ComposeRequest } from "./comfy-compose";+import { ceilingProblem, FILE_SETTINGS, ticketProblem, TICKET_VERSION, type Ceiling, type JobTicket, type TicketFacts, type TicketInput, type TicketInputKind } from "./job-ticket";+import type { MediaInfo } from "./media-probe";++export type { ComposeRequest };++/** The kind of an input file, from its content type. */+export function inputKind(contentType: string, name = ""): TicketInputKind {+ const type = contentType.split(";")[0].trim().toLowerCase();+ if (type.startsWith("image/")) return "image";+ if (type.startsWith("video/")) return "video";+ if (type.startsWith("audio/")) return "audio";+ if (type.startsWith("model/") || /\.(glb|gltf|ply|spz|splat)$/i.test(name)) return "model3d";+ return "file";+}++const FACT_KEYS = ["container", "duration", "videoDuration", "width", "height", "fps", "frames", "hasVideo", "hasAudio", "channels"] as const;++/** An upload's header facts as a ticket carries them. */+export function ticketFacts(m: MediaInfo | undefined): TicketFacts | undefined {+ if (!m) return undefined;+ const out: Record<string, unknown> = {};+ for (const k of FACT_KEYS) {+ const v = (m as unknown as Record<string, unknown>)[k];+ if (typeof v === "boolean" || (typeof v === "number" && Number.isFinite(v)) || (k === "container" && typeof v === "string")) out[k] = v;+ }+ return Object.keys(out).length ? (out as TicketFacts) : undefined;+}++/** Where each file of a request goes, as [slot, name]. */+function fileSlots(input: GenInput, sentExtra: string[]): [string, string][] {+ const out: [string, string][] = [];+ const one = (slot: string, v: unknown) => {+ if (typeof v === "string" && v) out.push([slot, v]);+ };+ const many = (slot: string, v: unknown) => (Array.isArray(v) ? v : []).forEach((x, i) => one(`${slot}.${i}`, x));+ many("images", input.images);+ one("endImage", input.endImage);+ one("mask", input.mask);+ one("video", input.video);+ many("videos", input.videos);+ one("audio", input.audio);+ one("audio2", (input as GenInput & { audio2?: unknown }).audio2);+ one("voiceAudio", input.voiceAudio);+ one("voiceAudio2", input.voiceAudio2);+ many("audios", input.audios);+ one("model3d", input.model3d);+ for (const k of sentExtra) one(`extra.${k}`, input.extra?.[k]);+ return out;+}++/**+ * The ticket for a request (the studio's side). `file` gives each staged input's SHA-256 and content type (null: not one+ * the run sent, which refuses the ticket); `facts` its header facts; `sent`: the params.extra keys whose files the run+ * sent. Settings are the request's, without its files (they go as inputs) and without a cloud voice's embedding.+ */+export function ticketFor(+ req: ComposeRequest,+ o: {+ catalogVersion: string;+ sent: string[];+ file: (name: string) => { sha256: string; contentType: string } | null;+ facts: (name: string) => MediaInfo | undefined;+ outputs: { count: number; kind: string };+ size: ComposedSize;+ },+): JobTicket {+ const inputs: TicketInput[] = [];+ const add = (slot: string, name: string) => {+ const f = o.file(name);+ if (!f) throw new Error(`${slot} isn't a file this run sent`);+ const facts = ticketFacts(o.facts(name));+ inputs.push({ slot, name, kind: inputKind(f.contentType, name), sha256: f.sha256, ...(facts && { facts }) });+ };+ for (const [slot, name] of fileSlots(req.input, o.sent)) add(slot, name);+ req.made.forEach((name, i) => add(`made.${i}`, name));+ const settings: Record<string, unknown> = { ...req.input };+ for (const k of [...FILE_SETTINGS, "voiceEmbedding"]) delete settings[k];+ if (req.input.extra) {+ const extra = { ...req.input.extra };+ for (const k of o.sent) delete extra[k];+ settings.extra = extra;+ }+ // A LoRA travels by its file name and how it's mixed (never an address to fetch it from).+ if (Array.isArray(req.input.loras)) settings.loras = req.input.loras.map((l) => ({ file: l.file, ...(l.strength !== undefined && { strength: l.strength }), ...(l.trigger && { trigger: l.trigger }), ...(l.target && { target: l.target }) }));+ for (const [k, v] of Object.entries(settings)) if (v === undefined) delete settings[k];+ return {+ v: TICKET_VERSION,+ workflowId: req.endpoint,+ catalogVersion: o.catalogVersion,+ op: req.op,+ settings,+ inputs,+ outputs: o.outputs,+ size: o.size,+ ...(req.loraSlot && { loraSlot: true }),+ };+}++/** What a worker's PC says of itself for the choices that depend on it (comfy-compose.ts ComposeContext). */+export interface WorkerFacts {+ device?: string;+ ramBytes?: number;+ vramBytes?: number;+ dbsModels?: DbsModel[];+ reuseModels?: ReuseModel[] | null;+ idolPack?: boolean;+}++/**+ * A worker's facts from its own ComfyUI's answers: GET /system_stats (`stats`), GET /models/dbs and /models/reuse (a+ * list of files; `null` for a folder its ComfyUI doesn't have, undefined when it couldn't say) and GET+ * /object_info/<the Idol pack's class> (`idol`). Anything it couldn't read stays unknown, and the composer then picks as the+ * studio would without the answer.+ */+export function workerFactsFrom(a: { stats?: unknown; dbs?: unknown; reuse?: unknown; idol?: unknown }): WorkerFacts {+ const out: WorkerFacts = {};+ const stats = (a.stats && typeof a.stats === "object" ? a.stats : {}) as { system?: { ram_total?: unknown }; devices?: { type?: unknown; vram_total?: unknown }[] };+ const dev = Array.isArray(stats.devices) ? stats.devices[0] : undefined;+ const pos = (v: unknown) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined);+ if (typeof dev?.type === "string" && /^[a-z]{2,16}$/.test(dev.type)) out.device = dev.type;+ const vram = pos(dev?.vram_total);+ const ram = pos(stats.system?.ram_total);+ if (vram) out.vramBytes = vram;+ if (ram) out.ramBytes = ram;+ const names = (v: unknown) => (Array.isArray(v) ? v.filter((f): f is string => typeof f === "string") : undefined);+ const dbs = names(a.dbs);+ if (dbs) out.dbsModels = installedDbs(dbs);+ if (a.reuse === null) out.reuseModels = null;+ else if (names(a.reuse)) out.reuseModels = installedReuse(names(a.reuse));+ if (a.idol && typeof a.idol === "object" && !Array.isArray(a.idol)) out.idolPack = IDOL_PACK_CLASS in a.idol;+ return out;+}++export type TicketOutcome =+ | { ok: true; graph: ComfyWorkflow; workflowId: string; size: ComposedSize; made: { name: string; data: Buffer; contentType: string }[] }+ | { ok: false; reason: "update-worker" | "bad-ticket" | "outside-ceiling"; detail: string };++/** A run's id as the studio makes them. */+const GENERATION_ID = /^[\w-]{1,64}$/;++/** Does the catalog have this workflow, or the template's variants (video-concat-{n})? */+export const catalogKnows = (catalog: ComposeCatalog, id: string) => catalog.has(id) || (id.includes("{n}") && [1, 2, 3, 4].some((n) => catalog.has(id.replace("{n}", String(n)))));++/**+ * The worker's side: check the ticket (its catalog version, its settings, its inputs against the files the job sends,+ * the PC's ceiling), then compose the graph with the composer and the worker's own catalog and facts. The files the+ * composer makes itself (made.<i>) are made here again: their copies on the studio are never read.+ */+export async function composeTicket(+ job: { ticket: unknown; generationId: string; inputs: { name: string; sha256: string }[] },+ env: { catalog: ComposeCatalog; catalogVersion: string; ceiling?: Ceiling | null; laneOf?: (workflowId: string) => string | null; facts?: WorkerFacts },+): Promise<TicketOutcome> {+ if (!GENERATION_ID.test(String(job.generationId))) return { ok: false, reason: "bad-ticket", detail: "not a run id" };+ const refused = ticketProblem(job.ticket, { catalogVersion: env.catalogVersion, known: (id) => catalogKnows(env.catalog, id), inputs: job.inputs });+ if (refused) return { ok: false, ...refused };+ const t = job.ticket as JobTicket;+ const lane = (id: string) => env.laneOf?.(id) ?? null;+ const before = ceilingProblem(env.ceiling, { workflowId: t.workflowId, lane: lane(t.workflowId), size: t.size });+ if (before) return { ok: false, reason: "outside-ceiling", detail: before };+ // The request, with each file in its slot.+ const input = { ...t.settings } as GenInput & Record<string, unknown>;+ const extra: Record<string, unknown> = { ...((t.settings.extra as Record<string, unknown> | undefined) ?? {}) };+ const facts = new Map<string, TicketFacts | undefined>();+ const made: TicketInput[] = [];+ const sent: string[] = [];+ for (const i of t.inputs) {+ facts.set(i.name, i.facts);+ const [slot, at] = i.slot.split(/\.(.*)/s);+ if (slot === "made") made[Number(at)] = i;+ else if (slot === "extra") {+ extra[at] = i.name;+ sent.push(at);+ } else if (at !== undefined) ((input[slot] as string[] | undefined) ?? (input[slot] = []) as string[])[Number(at)] = i.name;+ else input[slot] = i.name;+ }+ if (t.settings.extra !== undefined || sent.length) input.extra = extra;+ const madeHere: { name: string; data: Buffer; contentType: string }[] = [];+ const f = env.facts ?? {};+ try {+ const out = await composeWorkflow(t.workflowId, input, {+ generationId: job.generationId,+ op: t.op as Operation,+ catalog: env.catalog,+ loraSlot: t.loraSlot === true,+ sent,+ accountOnInstall: true,+ made: async (data, contentType) => {+ const slot = made[madeHere.length];+ if (!slot) throw new ComposeError("The ticket has no place for a file the graph makes");+ madeHere.push({ name: slot.name, data: Buffer.from(data), contentType });+ return slot.name;+ },+ media: (name) => {+ const m = facts.get(name);+ return m ? ({ hasVideo: false, hasAudio: false, ...m } as MediaInfo) : undefined;+ },+ serverRam: async () => f.ramBytes,+ vram: async () => f.vramBytes,+ device: async () => f.device,+ dbsModels: async () => f.dbsModels,+ reuseModels: async () => f.reuseModels,+ idolPack: async () => f.idolPack,+ });+ if (madeHere.length !== made.length) return { ok: false, reason: "bad-ticket", detail: "the ticket names files the graph doesn't make" };+ // A file made here is the studio's to the byte, or the ticket wasn't made for this graph.+ for (const [i, m] of madeHere.entries()) {+ if (crypto.createHash("sha256").update(m.data).digest("hex") !== made[i].sha256) return { ok: false, reason: "bad-ticket", detail: "a file the graph makes isn't the ticket's" };+ }+ const after = ceilingProblem(env.ceiling, { workflowId: out.manifest.id, lane: lane(out.manifest.id), size: out.size });+ if (after) return { ok: false, reason: "outside-ceiling", detail: after };+ return { ok: true, graph: withoutSaveMetadata(out.workflow), workflowId: out.manifest.id, size: out.size, made: madeHere };+ } catch (e) {+ return { ok: false, reason: "bad-ticket", detail: (e as Error).message?.slice(0, 200) || "the graph couldn't be made" };+ }+}diff --git a/src/server/computer/catalog-version.ts b/src/server/computer/catalog-version.tsnew file mode 100644index 00000000..72cd0d64--- /dev/null+++ b/src/server/computer/catalog-version.ts@@ -0,0 +1,82 @@+import "server-only";+import crypto from "node:crypto";+import fs from "node:fs";+import path from "node:path";++/**+ * The catalog version the studio makes job tickets for (src/lib/job-ticket.ts): one SHA-256 over the graph composer's+ * files (src/lib/ticket-compose.ts and everything it imports) and the catalog's workflows, with line ends made plain.+ * The worker program's build computes the same from its own checkout (bin/lib/worker/composer-files.mjs), so a worker+ * built from another catalog says "update the worker" and takes no ticket. Read from this server's own files once.+ */++const ROOTS = ["src/lib/ticket-compose.ts"];++function specifiers(src: string): string[] {+ const out = new Set<string>();+ for (const m of src.matchAll(/(?:^|[\n;])\s*(import|export)\s+(type\s+)?(?:[\w*{}\s,$]+?\s+from\s+)?["']([^"'\n]+)["']/g)) if (!m[2]) out.add(m[3]);+ for (const m of src.matchAll(/\bimport\(\s*["']([^"'\n]+)["']\s*\)/g)) out.add(m[1]);+ return [...out];+}++function resolveSpec(root: string, fromRel: string, spec: string): string | null {+ if (spec.startsWith("node:")) return null;+ const base = spec.startsWith("@/") ? path.join(root, "src", spec.slice(2)) : spec.startsWith(".") ? path.resolve(root, path.dirname(fromRel), spec) : null;+ if (!base) return null;+ for (const f of [`${base}.ts`, `${base}.tsx`, path.join(base, "index.ts"), base]) {+ if (fs.existsSync(f) && fs.statSync(f).isFile()) return path.relative(root, f).split(path.sep).join("/");+ }+ return null;+}++/** The composer's files, repo-relative and sorted. */+export function composerFiles(root = process.cwd()): string[] {+ const seen = new Set<string>();+ const walk = (rel: string) => {+ if (seen.has(rel)) return;+ seen.add(rel);+ if (rel.endsWith(".json")) return;+ for (const spec of specifiers(fs.readFileSync(path.join(root, rel), "utf8"))) {+ const r = resolveSpec(root, rel, spec);+ if (r) walk(r);+ }+ };+ for (const r of ROOTS) walk(r);+ return [...seen].sort();+}++const textSha = (file: string) => crypto.createHash("sha256").update(fs.readFileSync(file, "utf8").replace(/\r\n/g, "\n")).digest("hex");++/** The catalog version of the files under `root` (null when they aren't there to read). */+export function computeCatalogVersion(root = process.cwd(), catalogDir = path.join(root, "workflows", "comfyui")): string | null {+ try {+ const entries: [string, string][] = composerFiles(root).map((rel) => [rel, path.join(root, rel)]);+ for (const f of fs.readdirSync(catalogDir).filter((x) => x.endsWith(".json"))) entries.push([`workflows/comfyui/${f}`, path.join(catalogDir, f)]);+ entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));+ const all = crypto.createHash("sha256");+ for (const [name, file] of entries) all.update(`${name}\u0000${textSha(file)}\n`);+ return all.digest("hex");+ } catch {+ return null;+ }+}++declare global {+ var __fuobeCatalogVersion: { version: string | null } | undefined;+}++/**+ * This studio's catalog version (computed once; FUOBE_CATALOG_VERSION, a 64-hex value, wins: a server that runs from a+ * build without its sources sets it from the build). Null: unknown, and then no ticket is made (accounts' runs on the+ * workers are refused before they are queued).+ */+export function catalogVersion(): string | null {+ const env = process.env.FUOBE_CATALOG_VERSION;+ if (env && /^[0-9a-f]{64}$/.test(env)) return env;+ return (globalThis.__fuobeCatalogVersion ??= { version: computeCatalogVersion() }).version;+}++/** Forget the computed version (tests that change the catalog). */+export const forgetCatalogVersion = () => {+ globalThis.__fuobeCatalogVersion = undefined;+};diff --git a/tests/adding-a-model.test.ts b/tests/adding-a-model.test.tsindex 4b7525fd..133d231e 100644--- a/tests/adding-a-model.test.ts+++ b/tests/adding-a-model.test.ts@@ -328,6 +328,9 @@ describe("the worker build", () => {expect(perRunTextInputs(fake({ voice: "narrator", steps: 4 }, ["voice", "steps"], "OtherNode"), defs, { inputs: {} })).toEqual(["OtherNode.voice"]);});+ /** Every file a build wrote, with its path inside the build (the composer's are in a folder of their own). */+ const allFiles = (dir: string): string[] => (fs.readdirSync(dir, { recursive: true }) as string[]).map((f) => f.split(path.sep).join("/")).filter((f) => fs.statSync(path.join(dir, f)).isFile()).sort();+it("from the command line it builds however the script is reached, a linked folder included", () => {const link = path.join(tempDir("fuobe-worker-link-"), "repo");fs.symlinkSync(root, link, process.platform === "win32" ? "junction" : "dir");@@ -336,8 +339,8 @@ describe("the worker build", () => {const r = spawnSync(process.execPath, [path.join(link, "scripts/build-worker.mjs"), "--out", out], { cwd: link, encoding: "utf8" });expect(r.status, r.stderr).toBe(0);expect(r.stdout).toMatch(/^worker: /);- expect(fs.readdirSync(out).sort()).toEqual(fs.readdirSync(first).sort());- for (const f of fs.readdirSync(out)) expect(fs.readFileSync(path.join(out, f), "utf8"), f).toBe(fs.readFileSync(path.join(first, f), "utf8"));+ expect(allFiles(out)).toEqual(allFiles(first));+ for (const f of allFiles(out)) expect(fs.readFileSync(path.join(out, f), "utf8"), f).toBe(fs.readFileSync(path.join(first, f), "utf8"));} finally {fs.unlinkSync(link);}@@ -377,10 +380,10 @@ describe("the worker build", () => {}, 60_000);it("rebuilding gives no diff: two builds write the same files, and they match the catalog", () => {- const files = fs.readdirSync(first).sort();- expect(fs.readdirSync(second).sort()).toEqual(files);+ const files = allFiles(first);+ expect(allFiles(second)).toEqual(files);for (const f of files) expect(fs.readFileSync(path.join(second, f), "utf8"), f).toBe(fs.readFileSync(path.join(first, f), "utf8"));- expect(files).toEqual(expect.arrayContaining(["allowed-nodes.json", "input-rules.json", "file-pins.json", "computer-runner.mjs", "build-stamp.json"]));+ expect(files).toEqual(expect.arrayContaining(["allowed-nodes.json", "input-rules.json", "file-pins.json", "computer-runner.mjs", "build-stamp.json", "catalog-version.json", "compose/lib/ticket-compose.mjs", "compose/lib/comfy-compose.mjs"]));// Stamped with this checkout, so a worker starts on these parts (and on no older ones).expect(built(first, "build-stamp.json")).toEqual({ built: "scripts/build-worker.mjs", stamp: buildStamp(root) });expect(distProblem(root, first)).toBeNull();diff --git a/tests/job-tickets.test.ts b/tests/job-tickets.test.tsnew file mode 100644index 00000000..19be3d88--- /dev/null+++ b/tests/job-tickets.test.ts@@ -0,0 +1,324 @@+import crypto from "node:crypto";+import path from "node:path";+import { pathToFileURL } from "node:url";+import { describe, expect, it, vi } from "vitest";+import { MODELS } from "@/lib/catalog";+import type { GenInput, Operation } from "@/lib/catalog/types";+import { composeWorkflow, withoutSaveMetadata, type ComposeCatalog } from "@/lib/comfy-compose";+import { ceilingProblem, cleanCeiling, lanesInside, textProblem, ticketProblem, wordProblem, type JobTicket } from "@/lib/job-ticket";+import type { MediaInfo } from "@/lib/media-probe";+import { catalogKnows, composeTicket, ticketFor, workerFactsFrom } from "@/lib/ticket-compose";+import { catalogVersion as builtVersion, composerFiles } from "../bin/lib/worker/composer-files.mjs";+import { ceilingFrom, ceilingOf, graphInside } from "../bin/lib/worker/tickets.mjs";++/**+ * Job tickets (src/lib/job-ticket.ts): an account's run reaches a worker as a ticket, and the worker composes the graph+ * itself with the studio's own composer. A ticket composes the very graph the studio builds, for every workflow a run on+ * the workers can use; a ticket with an unknown workflow, another catalog, settings outside their rules or a path in a+ * text field is refused; the PC's ceiling is the most a worker runs.+ */++vi.setConfig({ testTimeout: 60_000 });++const { loadManifest, getWorkflow } = await import("@/server/providers/comfyui");+const { computeCatalogVersion } = await import("@/server/computer/catalog-version");++const ROOT = path.resolve(__dirname, "..");+const VERSION = computeCatalogVersion(ROOT)!;+const catalog: ComposeCatalog = { has: (id) => loadManifest().workflows.some((w) => w.id === id), get: getWorkflow };+const sha = (b: Buffer | string) => crypto.createHash("sha256").update(b).digest("hex");++/** The files a run sends, by kind, with what the studio read from their headers. */+const FACTS: Record<string, MediaInfo> = {+ png: { container: "image", width: 1024, height: 768, hasVideo: false, hasAudio: false },+ mp4: { container: "mp4", duration: 4, videoDuration: 4, width: 1280, height: 720, fps: 24, frames: 96, hasVideo: true, hasAudio: true, channels: 2 },+ wav: { container: "wav", duration: 5, hasVideo: false, hasAudio: true, channels: 2 },+ glb: undefined as unknown as MediaInfo,+};+const TYPES: Record<string, string> = { png: "image/png", mp4: "video/mp4", wav: "audio/wav", glb: "model/gltf-binary" };++/** A run's files: named as the studio names staged inputs, each with its SHA-256 and header facts. */+function files() {+ const all = new Map<string, { sha256: string; contentType: string; facts?: MediaInfo }>();+ let n = 0;+ const file = (ext: string, data?: Buffer) => {+ const name = `fuobe_t${String(++n).padStart(9, "0")}.${ext}`;+ all.set(name, { sha256: sha(data ?? name), contentType: TYPES[ext], ...(FACTS[ext] && { facts: FACTS[ext] }) });+ return name;+ };+ return { all, file };+}++const REFERENCE_SLOTS = ["image", "image2", "image3", "image4", "image5", "image6", "image7", "image8", "image9", "image10"];++/** A request that fills what a workflow's graph binds (pictures, clips, sound, a 3D model) for a route's operation. */+function requestFor(id: string, op: Operation, f: ReturnType<typeof files>["file"]): GenInput {+ const m = loadManifest().workflows.find((w) => w.id === id.replace("{n}", "2"))!;+ const b = m.bindings as Record<string, unknown>;+ const input: GenInput = { prompt: "A calm portrait in soft window light, black/white grade", seed: 1234, numOutputs: 1 };+ const images = REFERENCE_SLOTS.filter((k) => b[k]).length;+ if (images) input.images = Array.from({ length: images }, () => f("png"));+ if (b.endImage) input.endImage = f("png");+ if (b.mask) input.mask = f("png");+ const clips = ["video", "video2", "video3", "video4"].filter((k) => b[k]).length;+ if (id.includes("{n}")) input.videos = [f("mp4"), f("mp4")];+ else if (clips > 1) input.videos = Array.from({ length: clips }, () => f("mp4"));+ else if (clips) input.video = f("mp4");+ if (b.audio) input.audio = f("wav");+ if (m.expand === "audios" || op === "timeline") input.audios = [f("wav"), f("wav")];+ if (op === "tts" || op === "voice-change" || op === "dialogue") input.voiceAudio = f("wav");+ if (op === "dialogue") {+ input.voiceAudio2 = f("wav");+ input.dialogue = [{ text: "Good evening.", voice: "A" }, { text: "Welcome back.", voice: "B" }];+ }+ if (op === "voice-design") input.voiceDescription = "A warm, low voice with a slow pace";+ if (b.model3d) input.model3d = f("glb");+ return input;+}++/** Every route a run on the workers can take: each ComfyUI route of the catalog's models, once. */+function poolRoutes() {+ const seen = new Map<string, { endpoint: string; op: Operation; extra?: Record<string, unknown>; loraSlot?: boolean; kind: string }>();+ for (const m of MODELS) {+ for (const r of m.routes ?? []) {+ if (r.provider !== "comfyui") continue;+ const key = `${r.endpoint} ${r.op} ${JSON.stringify(r.extra ?? {})} ${!!r.loraSlot}`;+ if (!seen.has(key)) seen.set(key, { endpoint: r.endpoint, op: r.op, extra: r.extra, loraSlot: r.loraSlot, kind: m.kind });+ }+ }+ return [...seen.values()];+}++/** The studio's side, as prepareWorkflow composes an account's run on the workers (the seed picked, the files staged). */+async function studioSide(r: ReturnType<typeof poolRoutes>[number], gid: string, own?: (f: ReturnType<typeof files>["file"]) => GenInput) {+ const f = files();+ const asked = own ? own(f.file) : requestFor(r.endpoint, r.op, f.file);+ const input = r.extra ? { ...asked, extra: { ...r.extra, ...asked.extra } } : asked;+ const made: string[] = [];+ const out = await composeWorkflow(r.endpoint, input, {+ generationId: gid,+ op: r.op,+ catalog,+ loraSlot: r.loraSlot === true,+ sent: [],+ accountOnInstall: true,+ made: async (data, contentType, name) => {+ const ext = (name.split(".").pop() ?? "bin").toLowerCase();+ const staged = `fuobe_m${String(made.length).padStart(9, "0")}.${/^[a-z0-9]{1,5}$/.test(ext) ? ext : "bin"}`;+ f.all.set(staged, { sha256: sha(Buffer.from(data)), contentType });+ made.push(staged);+ return staged;+ },+ media: (name) => f.all.get(name)?.facts,+ });+ const used = out.dropped.length && input.extra ? { ...input, extra: Object.fromEntries(Object.entries(input.extra).filter(([k]) => !out.dropped.includes(k))) } : input;+ const ticket = ticketFor(+ { endpoint: r.endpoint, op: r.op, input: used, made, ...(r.loraSlot && { loraSlot: true }) },+ { catalogVersion: VERSION, sent: [], file: (n) => f.all.get(n) ?? null, facts: (n) => f.all.get(n)?.facts, outputs: { count: Math.max(1, out.manifest.outputs.length), kind: r.kind }, size: out.size },+ );+ const inputs = [...f.all.entries()].map(([name, x]) => ({ name, sha256: x.sha256 }));+ return { graph: withoutSaveMetadata(out.workflow), ticket, inputs, size: out.size };+}++describe("a ticket composes the graph the studio builds", () => {+ it("for every catalog workflow a run on the workers can use", async () => {+ const routes = poolRoutes();+ const composed = new Set<string>();+ const refusedByStudio: string[] = [];+ for (const [i, r] of routes.entries()) {+ const gid = `ticket-gen-${i}`;+ let studio: Awaited<ReturnType<typeof studioSide>>;+ try {+ studio = await studioSide(r, gid);+ } catch {+ // The studio refuses this request as it stands (a setting it needs): no ticket is made for it.+ refusedByStudio.push(`${r.endpoint} ${r.op}`);+ continue;+ }+ expect(ticketProblem(studio.ticket, { catalogVersion: VERSION, known: (id) => catalogKnows(catalog, id), inputs: studio.inputs }), r.endpoint).toBeNull();+ // Through JSON, as the claim hands it over.+ const ticket = JSON.parse(JSON.stringify(studio.ticket)) as JobTicket;+ const worker = await composeTicket({ ticket, generationId: gid, inputs: studio.inputs }, { catalog, catalogVersion: VERSION });+ expect(worker.ok ? null : worker, `${r.endpoint} ${r.op}`).toBeNull();+ if (!worker.ok) continue;+ expect(worker.graph, `${r.endpoint} ${r.op}`).toEqual(studio.graph);+ expect(worker.size).toEqual(studio.size);+ composed.add(worker.workflowId);+ }+ // Most of the catalog's workflows are reached this way (the rest need a setting a plain request doesn't carry).+ expect(composed.size).toBeGreaterThan(loadManifest().workflows.length * 0.6);+ expect(refusedByStudio.length).toBeLessThan(routes.length * 0.25);+ }, 240_000);++ it("with the files the graph makes itself (a palette swatch) made again on the worker, to the byte", async () => {+ const r = { endpoint: "palette-transfer-image", op: "color-match" as Operation, kind: "image" };+ const studio = await studioSide(r, "palette-gen-1", (f) => ({ images: [f("png")], palette: ["#112233", "#ddeeff", "#884422"], seed: 7 }));+ const made = studio.ticket.inputs.filter((i) => i.slot.startsWith("made."));+ expect(made.length).toBeGreaterThan(0);+ const worker = await composeTicket({ ticket: studio.ticket, generationId: "palette-gen-1", inputs: studio.inputs }, { catalog, catalogVersion: VERSION });+ expect(worker.ok && worker.made.map((m) => [m.name, sha(m.data)])).toEqual(made.map((m) => [m.name, m.sha256]));+ // A made file the studio says is something else: the ticket wasn't made for this graph.+ const other = { ...studio.ticket, inputs: studio.ticket.inputs.map((i) => (i.slot === "made.0" ? { ...i, sha256: "0".repeat(64) } : i)) };+ const refused = await composeTicket({ ticket: other, generationId: "palette-gen-1", inputs: studio.inputs }, { catalog, catalogVersion: VERSION });+ expect(refused).toMatchObject({ ok: false, reason: "bad-ticket" });+ });++ it("the worker's PC makes the choices that depend on it (its device, its memory)", async () => {+ const facts = workerFactsFrom({ stats: { system: { ram_total: 64 * 2 ** 30 }, devices: [{ type: "cuda", vram_total: 32 * 2 ** 30 }] }, dbs: ["DBS-BSRNN-DnR/model.safetensors", "DBS-BSRNN-DnR/config.json"], reuse: null, idol: { IdolPruneSplat: {} } });+ expect(facts).toEqual({ device: "cuda", vramBytes: 32 * 2 ** 30, ramBytes: 64 * 2 ** 30, dbsModels: ["DBS-BSRNN-DnR"], reuseModels: null, idolPack: true });+ // What it couldn't read stays unknown.+ expect(workerFactsFrom({ stats: undefined, dbs: undefined, reuse: undefined, idol: {} })).toEqual({ idolPack: false });+ expect(workerFactsFrom({ stats: { devices: [{ type: "../x", vram_total: -1 }] } })).toEqual({});+ });+});++describe("a ticket a worker refuses", () => {+ const base = async () => studioSide({ endpoint: "selftest-image", op: "edit", kind: "image" }, "refuse-gen-1");+ const compose = (ticket: unknown, inputs: { name: string; sha256: string }[], o: { version?: string } = {}) =>+ composeTicket({ ticket, generationId: "refuse-gen-1", inputs }, { catalog, catalogVersion: o.version ?? VERSION });++ it("composes the plain one", async () => {+ const s = await base();+ expect(await compose(s.ticket, s.inputs)).toMatchObject({ ok: true, workflowId: "selftest-image" });+ });++ it("an unknown workflow", async () => {+ const s = await base();+ expect(await compose({ ...s.ticket, workflowId: "no-such-workflow" }, s.inputs)).toMatchObject({ ok: false, reason: "bad-ticket" });+ expect(await compose({ ...s.ticket, workflowId: "../selftest-image" }, s.inputs)).toMatchObject({ ok: false, reason: "bad-ticket" });+ });++ it("a newer catalog version: update the worker", async () => {+ const s = await base();+ expect(await compose({ ...s.ticket, catalogVersion: "f".repeat(64) }, s.inputs)).toMatchObject({ ok: false, reason: "update-worker" });+ expect(await compose(s.ticket, s.inputs, { version: "e".repeat(64) })).toMatchObject({ ok: false, reason: "update-worker" });+ expect(await compose({ ...s.ticket, v: 2 }, s.inputs)).toMatchObject({ ok: false, reason: "update-worker" });+ });++ it("settings out of range, of the wrong kind, or unknown", async () => {+ const s = await base();+ for (const settings of [+ { ...s.ticket.settings, numOutputs: 99 },+ { ...s.ticket.settings, numOutputs: 1.5 },+ { ...s.ticket.settings, seed: -1 },+ { ...s.ticket.settings, duration: "long" },+ { ...s.ticket.settings, aspectRatio: "wide" },+ { ...s.ticket.settings, easing: "bounce" },+ { ...s.ticket.settings, generateAudio: "yes" },+ { ...s.ticket.settings, somethingElse: 1 },+ { ...s.ticket.settings, extra: { steps: Infinity } },+ { ...s.ticket.settings, extra: { "bad key": 1 } },+ { ...s.ticket.settings, loras: [{ file: "../../secrets.safetensors" }] },+ { ...s.ticket.settings, loras: [{ file: "C:/models/x.safetensors" }] },+ ]) {+ expect(await compose({ ...s.ticket, settings }, s.inputs), JSON.stringify(settings)).toMatchObject({ ok: false, reason: "bad-ticket" });+ }+ // Inside their rules, they compose.+ expect(await compose({ ...s.ticket, settings: { ...s.ticket.settings, numOutputs: 2, seed: 99 } }, s.inputs)).toMatchObject({ ok: true });+ expect(ticketProblem({ ...s.ticket, settings: { ...s.ticket.settings, loras: [{ file: "styles/film grain.safetensors", strength: 0.8, target: "both" }] } })).toBeNull();+ });++ it("a path in a text field, a file named in a setting, or a file the job doesn't send", async () => {+ const s = await base();+ for (const prompt of ["C:\\Windows\\System32\\config", "see ../../etc/passwd here", "/etc/passwd", "file:///home/me/x.png", "\\\\server\\share\\x.png", "~/secrets.txt"]) {+ expect(textProblem(prompt), prompt).toBe("a path");+ expect(await compose({ ...s.ticket, settings: { ...s.ticket.settings, prompt } }, s.inputs), prompt).toMatchObject({ ok: false, reason: "bad-ticket" });+ }+ // Words with a slash are words.+ expect(textProblem("black/white grade, 50/50 split")).toBeNull();+ for (const v of ["models/x", "x.safetensors", "https://example.com/a", "%APPDATA%", "${HOME}"]) expect(wordProblem(v), v).not.toBeNull();+ expect(await compose({ ...s.ticket, settings: { ...s.ticket.settings, extra: { image: "fuobe_someone_elses.png" } } }, s.inputs)).toMatchObject({ ok: false, reason: "bad-ticket" });+ expect(await compose({ ...s.ticket, settings: { ...s.ticket.settings, images: ["fuobe_t000000001.png"] } }, s.inputs)).toMatchObject({ ok: false, reason: "bad-ticket" });+ // An input the job doesn't send, or sends with other bytes.+ expect(await compose(s.ticket, [])).toMatchObject({ ok: false, reason: "bad-ticket" });+ expect(await compose(s.ticket, s.inputs.map((i) => ({ ...i, sha256: "0".repeat(64) })))).toMatchObject({ ok: false, reason: "bad-ticket" });+ // A slot that isn't one, or a name the studio never makes.+ expect(await compose({ ...s.ticket, inputs: s.ticket.inputs.map((i) => ({ ...i, slot: "workflow" })) }, s.inputs)).toMatchObject({ ok: false, reason: "bad-ticket" });+ expect(await compose({ ...s.ticket, inputs: s.ticket.inputs.map((i) => ({ ...i, name: "../../x.png" })) }, s.inputs)).toMatchObject({ ok: false, reason: "bad-ticket" });+ // A graph in a ticket's place is no ticket.+ expect(await compose({ "1": { class_type: "LoadImage", inputs: { image: "x.png" } } }, s.inputs)).toMatchObject({ ok: false, reason: "bad-ticket" });+ });+});++describe("the PC's ceiling", () => {+ it("a ticket bigger than the PC allows is refused before composing, and after (by the size the graph came out at)", async () => {+ const s = await studioSide({ endpoint: "selftest-image", op: "edit", kind: "image" }, "ceil-gen-1");+ expect(s.size.megapixels).toBeGreaterThan(0);+ const run = (ceiling: Parameters<typeof ceilingProblem>[0], ticket: JobTicket = s.ticket) => composeTicket({ ticket, generationId: "ceil-gen-1", inputs: s.inputs }, { catalog, catalogVersion: VERSION, ceiling, laneOf: () => "small" });+ expect(await run({ maxMegapixels: s.size.megapixels / 2 })).toMatchObject({ ok: false, reason: "outside-ceiling" });+ expect(await run({ workflows: ["video-trim"] })).toMatchObject({ ok: false, reason: "outside-ceiling" });+ expect(await run({ lanes: ["small"] })).toMatchObject({ ok: true });+ expect(await run({ maxMegapixels: 100, maxOutputs: 4, workflows: ["selftest-image"] })).toMatchObject({ ok: true });+ // A ticket that understates its size is held to the size its graph comes out at.+ expect(await run({ maxMegapixels: s.size.megapixels / 2 }, { ...s.ticket, size: { ...s.ticket.size, megapixels: 0 } })).toMatchObject({ ok: false, reason: "outside-ceiling" });+ });++ it("a ceiling is kept the same way on the worker (worker.json) and in the studio", () => {+ const raw = { lanes: ["small", "0123456789ab", "nope"], workflows: ["selftest-image", "../x"], maxMegapixels: 4, maxSeconds: 0, maxOutputs: 2.7, other: true };+ expect(ceilingOf(raw)).toEqual(cleanCeiling(raw));+ expect(cleanCeiling(raw)).toEqual({ lanes: ["0123456789ab", "small"], workflows: ["selftest-image"], maxMegapixels: 4, maxOutputs: 2 });+ expect(ceilingOf({})).toBeNull();+ expect(ceilingOf("all")).toBeNull();+ // The studio's allowed lanes only narrow inside it.+ expect(lanesInside(["small", "aaaaaaaaaaaa"], { lanes: ["small"] })).toEqual(["small"]);+ expect(lanesInside(["small", "aaaaaaaaaaaa"], null)).toEqual(["small", "aaaaaaaaaaaa"]);+ // A graph job (the owner's own) by its lane or workflow.+ expect(graphInside({ lanes: ["small"] }, { lane: "small" })).toBe(true);+ expect(graphInside({ workflows: ["video-trim"] }, { lane: "small", workflowId: "selftest-image" })).toBe(false);+ expect(graphInside(null, { lane: "x" })).toBe(true);+ });++ it("setup's answers make the ceiling, and a name that isn't in the catalog is refused", () => {+ const known = (id: string) => catalog.has(id);+ expect(ceilingFrom({ work: "all", megapixels: "0", seconds: "", outputs: "0" }, known)).toEqual({ ceiling: null });+ expect(ceilingFrom({ work: "selftest-image, small", megapixels: "4.2", seconds: "10", outputs: "2" }, known)).toEqual({ ceiling: { lanes: ["small"], workflows: ["selftest-image"], maxMegapixels: 4.2, maxSeconds: 10, maxOutputs: 2 } });+ expect(ceilingFrom({ work: "not-a-workflow" }, known)).toHaveProperty("error");+ expect(ceilingFrom({ work: "all", megapixels: "lots" }, known)).toHaveProperty("error");+ expect(ceilingFrom({ work: "all", seconds: "-1" }, known)).toHaveProperty("error");+ });+});++describe("the catalog version", () => {+ it("is the same in the studio and in the worker's build, and changes with the composer or the catalog", async () => {+ expect(VERSION).toMatch(/^[0-9a-f]{64}$/);+ expect(builtVersion(ROOT)).toBe(VERSION);+ const fsMod = await import("node:fs");+ const os = await import("node:os");+ // A copy whose catalog differs in one workflow: another version.+ const dir = fsMod.mkdtempSync(path.join(os.tmpdir(), "fuobe-catalog-version-"));+ try {+ const lib = path.join(ROOT, "workflows/comfyui");+ for (const f of fsMod.readdirSync(lib).filter((x) => x.endsWith(".json"))) fsMod.copyFileSync(path.join(lib, f), path.join(dir, f));+ expect(builtVersion(ROOT, dir)).toBe(VERSION);+ fsMod.writeFileSync(path.join(dir, "selftest-image.json"), fsMod.readFileSync(path.join(dir, "selftest-image.json"), "utf8").replace("ImageInvert", "ImageInvert "));+ expect(builtVersion(ROOT, dir)).not.toBe(VERSION);+ expect(computeCatalogVersion(ROOT, dir)).toBe(builtVersion(ROOT, dir));+ } finally {+ fsMod.rmSync(dir, { recursive: true, force: true });+ }+ // The composer's files: its own, and every one it imports (no package: the worker installs none).+ const names = composerFiles(ROOT);+ expect(names).toEqual(expect.arrayContaining(["src/lib/ticket-compose.ts", "src/lib/comfy-compose.ts", "src/lib/job-ticket.ts"]));+ expect(names.every((n: string) => n.startsWith("src/"))).toBe(true);+ });++ it("the composer as built into the worker composes the same graph as the studio's", async () => {+ const { spawnSync } = await import("node:child_process");+ const fsMod = await import("node:fs");+ const os = await import("node:os");+ const out = fsMod.mkdtempSync(path.join(os.tmpdir(), "fuobe-composer-built-"));+ try {+ const r = spawnSync(process.execPath, [path.join(ROOT, "scripts/build-worker.mjs"), "--out", out], { cwd: ROOT, encoding: "utf8" });+ expect(r.status, r.stderr).toBe(0);+ expect(JSON.parse(fsMod.readFileSync(path.join(out, "catalog-version.json"), "utf8")).version).toBe(VERSION);+ const built = (await import(pathToFileURL(path.join(out, "compose/lib/ticket-compose.mjs")).href)) as typeof import("@/lib/ticket-compose");+ const { workerCatalog } = await import("../bin/lib/worker/tickets.mjs");+ const s = await studioSide({ endpoint: "palette-transfer-image", op: "color-match", kind: "image" }, "built-gen-1", (f) => ({ images: [f("png")], palette: ["#102030", "#f0e0d0"], seed: 7 }));+ expect(s.ticket.inputs.some((i) => i.slot === "made.0")).toBe(true);+ const got = await built.composeTicket({ ticket: JSON.parse(JSON.stringify(s.ticket)), generationId: "built-gen-1", inputs: s.inputs }, { catalog: workerCatalog(path.join(ROOT, "workflows/comfyui")), catalogVersion: VERSION });+ expect(got.ok && got.graph).toEqual(s.graph);+ } finally {+ fsMod.rmSync(out, { recursive: true, force: true });+ }+ }, 120_000);+});diff --git a/tests/no-higgsfield.test.ts b/tests/no-higgsfield.test.tsindex 0a60e27b..26f4b746 100644--- a/tests/no-higgsfield.test.ts+++ b/tests/no-higgsfield.test.ts@@ -131,6 +131,8 @@ function walk(p: string, out: string[]) {if (!fs.existsSync(full)) return;const st = fs.statSync(full);const posix = p.replace(/\\/g, "/");+ // The worker's built parts are copies of scanned sources (scripts/build-worker.mjs), and never committed.+ if (posix === "bin/lib/worker/dist") return;if (st.isFile()) {if (TEXT.test(posix)) out.push(posix);return;