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: clips and SVGs come back without the run's graph in them

Adarsha2a79332f433
diff --git a/bin/lib/worker/results.mjs b/bin/lib/worker/results.mjs
new file mode 100644
index 00000000..3d442f99
--- /dev/null
+++ b/bin/lib/worker/results.mjs
@@ -0,0 +1,132 @@
+// A finished job's results, as the worker reads them from its own ComfyUI for the studio (docs/gpu-workers.md). Each
+// is the file its ComfyUI saved, but without what a save node writes into it that the run never asked for. Two save
+// nodes write the run's graph whatever --disable-metadata says:
+// - VideoHelperSuite's save node (VHS_VideoCombine) writes it, and the PC's local time, into each clip unless its
+// save_metadata is false. The worker sets save_metadata false on every such node in each prompt it sends.
+// - Core ComfyUI's SVG save node puts it into every SVG it saves (a <metadata> element). The worker takes that
+// element out, so the kept copy and the upload both come without it.
+
+/** Does a <metadata> element start at `i` (not "<metadataX")? */
+function opensAt(lower, i) {
+ if (!lower.startsWith("<metadata", i)) return false;
+ const next = lower[i + 9];
+ return next === undefined || next === ">" || next === "/" || /\s/.test(next);
+}
+
+/** Where a <metadata> element starts at or after `from`, or -1. */
+function openTag(lower, from) {
+ for (let i = lower.indexOf("<metadata", from); i >= 0; i = lower.indexOf("<metadata", i + 1)) if (opensAt(lower, i)) return i;
+ return -1;
+}
+
+/**
+ * An SVG's text without its <metadata> elements (with what they hold: CDATA sections, comments, other elements).
+ * An element that never closes takes the rest of the text with it. Everything else stays as it was, byte for byte.
+ */
+export function svgWithoutMetadata(text) {
+ // Only A to Z made lower case, so each index in `lower` is the same place in `text` (toLowerCase can change a length).
+ const lower = text.replace(/[A-Z]/g, (c) => c.toLowerCase());
+ let out = "";
+ let i = 0;
+ for (;;) {
+ const start = openTag(lower, i);
+ if (start < 0) return out + text.slice(i);
+ out += text.slice(i, start);
+ const gt = text.indexOf(">", start);
+ if (gt < 0) return out;
+ if (text[gt - 1] === "/") {
+ i = gt + 1;
+ continue;
+ }
+ // Its end: the matching close tag, past any CDATA section, comment or element of the same name inside it.
+ let depth = 1;
+ let j = gt + 1;
+ while (depth > 0) {
+ const lt = text.indexOf("<", j);
+ if (lt < 0) return out;
+ const skip = text.startsWith("<![CDATA[", lt) ? "]]>" : text.startsWith("<!--", lt) ? "-->" : null;
+ if (skip) {
+ const e = text.indexOf(skip, lt + 4);
+ if (e < 0) return out;
+ j = e + skip.length;
+ } else if (/^<\/metadata\s*>/.test(lower.slice(lt, lt + 32))) {
+ depth--;
+ j = text.indexOf(">", lt) + 1;
+ } else if (opensAt(lower, lt)) {
+ const e = text.indexOf(">", lt);
+ if (e < 0) return out;
+ if (text[e - 1] !== "/") depth++;
+ j = e + 1;
+ } else j = lt + 1;
+ }
+ i = j;
+ }
+}
+
+/** Is this a read of an SVG result from ComfyUI's /view? */
+function svgView(url, init) {
+ if (init?.method && init.method.toUpperCase() !== "GET") return false;
+ let u;
+ try {
+ u = new URL(url, "http://127.0.0.1");
+ } catch {
+ return false;
+ }
+ return /(^|\/)view$/.test(u.pathname) && /\.svg$/i.test(u.searchParams.get("filename") ?? "");
+}
+
+/** A result read from its ComfyUI: an SVG comes without its <metadata> elements; every other answer as it came. */
+export async function plainResult(url, res, init) {
+ if (!res?.ok || !svgView(url, init)) return res;
+ const text = svgWithoutMetadata(await res.text());
+ const headers = new Headers(res.headers);
+ headers.delete("content-length");
+ headers.delete("content-encoding");
+ return new Response(text, { status: res.status, statusText: res.statusText, headers });
+}
+
+/**
+ * A graph whose save nodes are told to write no metadata. VideoHelperSuite's save node (VHS_VideoCombine) writes the
+ * run's graph and the PC's local time into each clip unless its save_metadata is false, whatever --disable-metadata
+ * says. Every such node gets save_metadata false (a format that has no such option ignores it). Nothing else changes.
+ */
+export function graphWithoutMetadata(graph) {
+ if (!graph || typeof graph !== "object" || Array.isArray(graph)) return graph;
+ const out = {};
+ for (const [id, n] of Object.entries(graph)) {
+ out[id] = n && typeof n === "object" && n.class_type === "VHS_VideoCombine" ? { ...n, inputs: { ...(n.inputs ?? {}), save_metadata: false } } : n;
+ }
+ return out;
+}
+
+/** Is this a prompt sent to ComfyUI (a POST to /prompt)? */
+function promptPost(url, init) {
+ if ((init?.method ?? "GET").toUpperCase() !== "POST") return false;
+ try {
+ return /(^|\/)prompt$/.test(new URL(url, "http://127.0.0.1").pathname);
+ } catch {
+ return false;
+ }
+}
+
+/** A prompt's body, as JSON text, with its graph's save nodes told to write no metadata. Any other body stays as it is. */
+export function plainPromptBody(body) {
+ if (typeof body !== "string") return body;
+ let parsed;
+ try {
+ parsed = JSON.parse(body);
+ } catch {
+ return body;
+ }
+ if (!parsed || typeof parsed !== "object" || !parsed.prompt || typeof parsed.prompt !== "object") return body;
+ return JSON.stringify({ ...parsed, prompt: graphWithoutMetadata(parsed.prompt) });
+}
+
+/**
+ * A fetch to its own ComfyUI: each prompt goes with its save nodes told to write no metadata (plainPromptBody), and
+ * result reads go through plainResult.
+ */
+export const withPlainResults = (fetchFn) => (url, init) => {
+ const sent = promptPost(url, init) ? { ...init, body: plainPromptBody(init.body) } : init;
+ return fetchFn(url, sent).then((res) => plainResult(url, res, sent));
+};
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjs
index 8331ae23..8ce87567 100644
--- a/bin/lib/worker/run.mjs
+++ b/bin/lib/worker/run.mjs
@@ -26,6 +26,7 @@ import { inventoryHash, modelFiles, packFolders } from "./inventory.mjs";
import { readCounters, readListeners, readLock, splitMemory, unknownHolder } from "./local-work.mjs";
import { takeLock, workerLives } from "./lock.mjs";
import { ffmpegVersion, fileSize, mediaKind, outputCap, reencode } from "./media.mjs";
+import { withPlainResults } from "./results.mjs";
import { retrying } from "./retry.mjs";
import { SiteTurns, writeSite } from "./turns.mjs";
@@ -175,7 +176,9 @@ async function work(saved, deps, owner) {
const rules = deps.rules ?? inputRules();
const comfy = new OwnComfy(cfg, { now, fetch: fetchFn, folderNames: index.folders ?? [], log, owner, workerLives: (rec) => workerLives(rec, { commandLineOf: deps.comfy?.commandLineOf }), ...deps.comfy });
// Only its own ComfyUI, and only while the process it started is up and ready: never whatever listens on that port.
- const own = (url, init) => (comfy.alive() && comfy.ready ? comfy.fetch(url, init) : Promise.reject(new Error("Its own ComfyUI isn't running")));
+ // Its results come without what a save node writes into them unasked (results.mjs).
+ const ownFetch = withPlainResults((url, init) => comfy.fetch(url, init));
+ const own = (url, init) => (comfy.alive() && comfy.ready ? ownFetch(url, init) : Promise.reject(new Error("Its own ComfyUI isn't running")));
// A ComfyUI that a stopped worker left running is stopped now, before anything else uses the GPU.
await comfy.stopLeftover();
// Studio jobs first: only with a turns folder set in worker.json. Without one, every program counts the same, as before.
diff --git a/tests/helpers/fake-local-comfy.ts b/tests/helpers/fake-local-comfy.ts
index db62468e..7ea2502d 100644
--- a/tests/helpers/fake-local-comfy.ts
+++ b/tests/helpers/fake-local-comfy.ts
@@ -80,6 +80,8 @@ export interface LocalComfyOptions {
workerGuard?: string;
/** Each prompt posted adds a line to this file (a count that outlives the process, for a test in another one). */
countFile?: string;
+ /** Each prompt posted adds its graph to this file, as one line of JSON (what a test in another process sent). */
+ graphFile?: string;
}
/** One live render the stand-in made (for the bookkeeping checks). */
@@ -530,6 +532,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc
entry.prompt = json;
posts++;
if (opts.countFile) appendFileSync(opts.countFile, `prompt ${json.prompt_id ?? "?"}\n`);
+ if (opts.graphFile) appendFileSync(opts.graphFile, `${JSON.stringify(json.prompt ?? null)}\n`);
const fail = opts.failNext;
opts.failNext = undefined;
if (fail === "missing_node") {
@@ -755,7 +758,8 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc
// [--has workflows/comfyui/requirements.json]: everything that index names is installed. [--guard 1]: Fuobe's guard answers.
// [--connect <origin>]: Fuobe Connect is installed, trusting that origin. [--worker-guard 1]: a worker's guard, with the
// key in FUOBE_WORKER_GUARD_KEY (as a worker starts its ComfyUI). [--count-file <path>]: a line for each prompt posted.
-// [--fail-next oom|never]: what the first prompt does. [--outputs video,audio]: what a job saves.
+// [--graph-file <path>]: each prompt's graph, a line of JSON each. [--fail-next oom|never]: what the first prompt does.
+// [--outputs video,audio]: what a job saves.
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const arg = (name: string) => {
const i = process.argv.indexOf(`--${name}`);
@@ -775,6 +779,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
...(arg("connect") && { connect: arg("connect") }),
...(workerGuard && { workerGuard }),
...(arg("count-file") && { countFile: arg("count-file") }),
+ ...(arg("graph-file") && { graphFile: arg("graph-file") }),
...(arg("fail-next") && { failNext: arg("fail-next") as LocalComfyOptions["failNext"] }),
...(arg("outputs") && { outputs: arg("outputs")!.split(",") as LocalComfyOptions["outputs"] }),
has,
diff --git a/tests/worker-recovery.test.ts b/tests/worker-recovery.test.ts
index aa490f6c..80ac819e 100644
--- a/tests/worker-recovery.test.ts
+++ b/tests/worker-recovery.test.ts
@@ -46,7 +46,7 @@ const ROOT = path.resolve(__dirname, "..");
const FAKE = path.join(ROOT, "tests/helpers/fake-local-comfy.ts");
const SITE = "http://127.0.0.1:9";
const RULES = inputRules(readCatalog(ROOT));
-const ALLOWED = new Set(["LoadImage", "KSampler", "SaveImage", "LoadVideo"]);
+const ALLOWED = new Set(["LoadImage", "KSampler", "SaveImage", "LoadVideo", "VHS_VideoCombine"]);
const hasFfmpeg = spawnSync("ffmpeg", ["-hide_banner", "-version"]).status === 0;
const realFetch = globalThis.fetch;
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
@@ -77,8 +77,8 @@ function addWorker(): W {
}
let gens = 0;
-/** A job for the workers that loads one input (a picture, or a clip) and saves a picture. */
-function addTask(o: { clip?: Buffer } = {}): { id: string; input: string } {
+/** A job for the workers that loads one input (a picture, or a clip) and saves a picture (or what `save` says). */
+function addTask(o: { clip?: Buffer; save?: { class_type: string; inputs: Record<string, unknown> } } = {}): { id: string; input: string } {
const gid = `recovery-gen-${++gens}`;
const now = Date.now();
db()
@@ -89,7 +89,7 @@ function addTask(o: { clip?: Buffer } = {}): { id: string; input: string } {
const t = tasks.createTask({
principal: "owner",
generationId: gid,
- graph: { "1": loader, "3": { class_type: "KSampler", inputs: { seed: 1, steps: 4 } }, "9": { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "fuobe/worker-test" } } },
+ graph: { "1": loader, "3": { class_type: "KSampler", inputs: { seed: 1, steps: 4 } }, "9": o.save ?? { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "fuobe/worker-test" } } },
pool: { pools: ["pool"], rankAt: now, lane: "small", needs: { workflowId: "wf-test", files: [], packs: [], minVramBytes: 0 } },
});
return { id: t.id, input };
@@ -136,6 +136,8 @@ interface Pc {
workDir: string;
comfyDir: string;
countFile: string;
+ /** Each prompt its ComfyUI got, as a line of JSON. */
+ graphFile: string;
logs: string[];
/** When each log line was written. */
logAt: number[];
@@ -144,7 +146,7 @@ interface Pc {
function pc(): Pc {
const base = tempDir("fuobe-worker-pc-");
- const p = { home: path.join(base, "home"), workDir: path.join(base, "work"), comfyDir: path.join(base, "comfy"), countFile: path.join(base, "prompts.txt"), logs: [], logAt: [], awake: [] };
+ const p = { home: path.join(base, "home"), workDir: path.join(base, "work"), comfyDir: path.join(base, "comfy"), countFile: path.join(base, "prompts.txt"), graphFile: path.join(base, "graphs.jsonl"), logs: [], logAt: [], awake: [] };
for (const d of [p.home, p.workDir, p.comfyDir]) fs.mkdirSync(d, { recursive: true });
return p;
}
@@ -165,7 +167,7 @@ function start(
modelDirs: o.modelDirs ?? [],
comfyCommand: o.command ?? [
process.execPath, "--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", FAKE, "--port", "{port}", "--cors", "off",
- "--steps", String(o.steps ?? 4), "--step-ms", String(o.stepMs ?? 40), "--worker-guard", "1", "--count-file", p.countFile,
+ "--steps", String(o.steps ?? 4), "--step-ms", String(o.stepMs ?? 40), "--worker-guard", "1", "--count-file", p.countFile, "--graph-file", p.graphFile,
...(o.failNext ? ["--fail-next", o.failNext] : []),
],
comfyGuard: true,
@@ -538,6 +540,26 @@ http.createServer((q, s) => { s.writeHead(200, { "content-type": "application/js
});
});
+describe("results carry no metadata", () => {
+ it("every clip save node goes to its ComfyUI told to write no metadata; the rest of the graph as the studio sent it", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const save = { class_type: "VHS_VideoCombine", inputs: { images: ["1", 0], frame_rate: 8, loop_count: 0, filename_prefix: "fuobe/worker-test", format: "video/h264-mp4", pingpong: false, save_output: true, save_metadata: true } };
+ const { id, input } = addTask({ save });
+ start(w, s, p);
+ const t = await ended(id);
+ expect(t.state).toBe("done");
+ const graphs = fs.readFileSync(p.graphFile, "utf8").trim().split(/\r?\n/).map((l) => JSON.parse(l));
+ expect(graphs).toHaveLength(1);
+ expect(graphs[0]).toEqual({
+ "1": { class_type: "LoadImage", inputs: { image: input } },
+ "3": { class_type: "KSampler", inputs: { seed: 1, steps: 4 } },
+ "9": { ...save, inputs: { ...save.inputs, save_metadata: false } },
+ });
+ });
+});
+
describe("clips and sound", () => {
const clip = (dirName: string) => {
const out = path.join(tempDir(dirName), "clip.mp4");
diff --git a/tests/worker-results.test.ts b/tests/worker-results.test.ts
new file mode 100644
index 00000000..d7880cdc
--- /dev/null
+++ b/tests/worker-results.test.ts
@@ -0,0 +1,130 @@
+/**
+ * A finished job's results as a worker reads them from its own ComfyUI (bin/lib/worker/results.mjs): an SVG comes without
+ * the <metadata> element that ComfyUI's SVG save node writes into it (the run's graph, its prompt included), in the
+ * kept copy and in what goes up to the studio. Every other result is read as it is. Each prompt goes to its ComfyUI
+ * with every clip save node told to write no metadata.
+ */
+import { describe, expect, it } from "vitest";
+import { Hold } from "../bin/lib/worker/hold.mjs";
+import { graphWithoutMetadata, plainPromptBody, plainResult, svgWithoutMetadata, withPlainResults } from "../bin/lib/worker/results.mjs";
+import { tempDir } from "./helpers/temp-dir";
+
+/** An SVG as ComfyUI's SVG save node writes it: the graph in a CDATA section, right after the opening tag. */
+const graph = { "1": { class_type: "LoadImage", inputs: { image: "fuobe_abcdefgh01.png" } }, "5": { class_type: "CLIPTextEncode", inputs: { text: "a private prompt </metadata> with İstanbul in it" } } };
+const shapes = '<path d="M0 0h10v10H0z" fill="#1a2b3c"/><path d="M2 2h6v6H2z" fill="#ffffff"/>';
+const saved = (meta = graph) =>
+ `<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="10" height="10">\n <metadata>\n <![CDATA[\n ${JSON.stringify({ prompt: meta }, null, 2)}\n ]]>\n </metadata>\n ${shapes}</svg>`;
+const clean = `<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="10" height="10">\n \n ${shapes}</svg>`;
+
+const view = (filename: string, type = "output") => `http://127.0.0.1:41234/view?${new URLSearchParams({ filename, subfolder: "fuobe", type })}`;
+
+describe("a worker's results carry nothing a save node wrote into them unasked", () => {
+ it("takes the <metadata> element out of an SVG, and leaves the rest byte for byte", () => {
+ expect(svgWithoutMetadata(saved())).toBe(clean);
+ expect(svgWithoutMetadata(saved())).not.toMatch(/prompt|CLIPTextEncode|fuobe_abcdefgh01|İstanbul/);
+ // No metadata: nothing changes.
+ expect(svgWithoutMetadata(`<svg>${shapes}</svg>`)).toBe(`<svg>${shapes}</svg>`);
+ // Other shapes of the element: empty, with attributes, in capitals, nested, more than one, a comment inside.
+ expect(svgWithoutMetadata(`<svg><metadata/>${shapes}<metadata id="m" /></svg>`)).toBe(`<svg>${shapes}</svg>`);
+ expect(svgWithoutMetadata(`<svg><METADATA lang="en">x<rdf:RDF><metadata>y</metadata></rdf:RDF></Metadata >${shapes}</svg>`)).toBe(`<svg>${shapes}</svg>`);
+ expect(svgWithoutMetadata(`<svg><metadata>a</metadata>${shapes}<metadata><!-- </metadata> -->b</metadata></svg>`)).toBe(`<svg>${shapes}</svg>`);
+ // A name that only starts the same stays.
+ expect(svgWithoutMetadata(`<svg><metadataX>a</metadataX></svg>`)).toBe(`<svg><metadataX>a</metadataX></svg>`);
+ // An element that never closes takes the rest with it (nothing of the graph goes up).
+ expect(svgWithoutMetadata(`<svg>${shapes}<metadata><![CDATA[{"prompt": 1}`)).toBe(`<svg>${shapes}`);
+ expect(svgWithoutMetadata(`<svg>${shapes}<metadata`)).toBe(`<svg>${shapes}`);
+ });
+
+ it("reads an SVG result from /view without it; every other answer comes as it is", async () => {
+ const svgRes = () => new Response(saved(), { headers: { "Content-Type": "image/svg+xml", "Content-Length": "9999" } });
+ const res = await plainResult(view("fuobe_x_00001_.svg"), svgRes());
+ expect(await res.text()).toBe(clean);
+ expect(res.headers.get("content-type")).toBe("image/svg+xml");
+ expect(res.headers.get("content-length")).toBeNull();
+ expect(await (await plainResult(view("fuobe_x_00001_.SVG", "temp"), svgRes())).text()).toBe(clean);
+ // A picture, a clip, another path, a failed answer, a POST: untouched.
+ for (const [url, init] of [
+ [view("fuobe_x_00001_.png"), undefined],
+ [view("fuobe_x_00001_.mp4"), undefined],
+ ["http://127.0.0.1:41234/history/0b4c3c1e-8d4f-4b8e-9f0a-2a1b3c4d5e6f", undefined],
+ ["http://127.0.0.1:41234/upload/image?filename=x.svg", undefined],
+ [view("fuobe_x_00001_.svg"), { method: "POST" }],
+ ] as [string, RequestInit | undefined][]) {
+ const r = svgRes();
+ expect(await plainResult(url, r, init), url).toBe(r);
+ }
+ const missing = new Response("Not found", { status: 404 });
+ expect(await plainResult(view("x.svg"), missing)).toBe(missing);
+ });
+
+ it("the kept copy and the upload come without it", async () => {
+ const local = withPlainResults(async (url: string) => {
+ const name = new URL(url).searchParams.get("filename") ?? "";
+ return name.endsWith(".svg") ? new Response(saved(), { headers: { "Content-Type": "image/svg+xml" } }) : new Response(new Uint8Array([137, 80, 78, 71]), { headers: { "Content-Type": "image/png" } });
+ });
+ const hold = new Hold(tempDir("fuobe-worker-results-"));
+ const t = { id: "abcdefgh01234567", promptId: "0b4c3c1e-8d4f-4b8e-9f0a-2a1b3c4d5e6f" };
+ const files = [
+ { filename: "fuobe_x_00001_.svg", subfolder: "fuobe", type: "output" },
+ { filename: "fuobe_x_00001_.png", subfolder: "fuobe", type: "output" },
+ ];
+ const entries = [{ status: { completed: true }, outputs: { "4": { images: files } } }];
+ await hold.keep(t, { kind: "finished", entries }, (f: { filename: string; subfolder: string; type: string }) => local(`http://127.0.0.1:41234/view?${new URLSearchParams(f)}`));
+ const svg = await hold.file(t, files[0]);
+ expect(await svg!.text()).toBe(clean);
+ const png = await hold.file(t, files[1]);
+ expect([...new Uint8Array(await png!.arrayBuffer())]).toEqual([137, 80, 78, 71]);
+ // Read again straight from its ComfyUI (no kept copy): the same.
+ expect(await (await local(view("fuobe_x_00001_.svg"))).text()).toBe(clean);
+ });
+
+ it("tells every clip save node to write no metadata, and changes nothing else", () => {
+ const combine = (inputs: Record<string, unknown>) => ({ class_type: "VHS_VideoCombine", inputs: { images: ["2", 0], frame_rate: 24, filename_prefix: "fuobe/x", format: "video/h264-mp4", ...inputs } });
+ const g = {
+ "1": combine({ save_metadata: true }),
+ "2": { class_type: "KSampler", inputs: { seed: 1, save_metadata: true } },
+ "3": combine({}),
+ "4": combine({ save_metadata: ["9", 0] }),
+ "5": { class_type: "VHS_VideoCombine" },
+ };
+ const before = structuredClone(g);
+ const out = graphWithoutMetadata(g);
+ expect(out["1"].inputs.save_metadata).toBe(false);
+ expect(out["3"].inputs.save_metadata).toBe(false);
+ expect(out["4"].inputs.save_metadata).toBe(false);
+ expect(out["5"]).toEqual({ class_type: "VHS_VideoCombine", inputs: { save_metadata: false } });
+ // Another node keeps its inputs, and every other input of the save node stays.
+ expect(out["2"]).toEqual(g["2"]);
+ expect({ ...out["1"].inputs, save_metadata: true }).toEqual(g["1"].inputs);
+ // The graph it was given is left as it was.
+ expect(g).toEqual(before);
+ for (const v of [null, undefined, "x", [1, 2]]) expect(graphWithoutMetadata(v)).toBe(v);
+ });
+
+ it("a prompt goes to its ComfyUI with its clip save nodes told to write no metadata", async () => {
+ const body = { prompt: { "9": { class_type: "VHS_VideoCombine", inputs: { format: "video/h264-mp4", save_metadata: true } } }, prompt_id: "0b4c3c1e-8d4f-4b8e-9f0a-2a1b3c4d5e6f", client_id: "c" };
+ expect(JSON.parse(plainPromptBody(JSON.stringify(body)))).toEqual({ ...body, prompt: { "9": { class_type: "VHS_VideoCombine", inputs: { format: "video/h264-mp4", save_metadata: false } } } });
+ // Anything that isn't a prompt as JSON stays as it is.
+ for (const b of ["not json", '{"delete":["x"]}', "[1]", "null", undefined]) expect(plainPromptBody(b)).toBe(b);
+ const form = new FormData();
+ expect(plainPromptBody(form)).toBe(form);
+
+ const seen: { url: string; init?: RequestInit }[] = [];
+ const local = withPlainResults(async (url: string, init?: RequestInit) => {
+ seen.push({ url, init });
+ return Response.json({ prompt_id: body.prompt_id, number: 1 });
+ });
+ await local("http://127.0.0.1:41234/prompt", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+ expect(JSON.parse(String(seen[0].init?.body)).prompt["9"].inputs.save_metadata).toBe(false);
+ expect(new Headers(seen[0].init?.headers).get("content-type")).toBe("application/json");
+ // Other calls go as they came: a read, another path, a prompt read back.
+ for (const [url, init] of [
+ ["http://127.0.0.1:41234/history", { method: "POST", body: JSON.stringify(body) }],
+ ["http://127.0.0.1:41234/prompt", undefined],
+ ["http://127.0.0.1:41234/api/prompt/x", { method: "POST", body: JSON.stringify(body) }],
+ ] as [string, RequestInit | undefined][]) {
+ await local(url, init);
+ expect(seen.at(-1)!.init, url).toBe(init);
+ }
+ });
+});