From 8d61fa1f9365f291452ca9fc7230f21b42c0abce Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Tue, 1 Dec 2026 21:03:16 -0500 Subject: [PATCH 1/7] feat(comfyui): the engine runs the FormBridge pack's workflows on a clip or picture from the media bin, in the person's own ComfyUI, and brings the results back into the bin --- backend/app/formbridge.py | 316 ++++++++++++++++++++++++++++++++++++++ backend/app/main.py | 2 + 2 files changed, 318 insertions(+) create mode 100644 backend/app/formbridge.py diff --git a/backend/app/formbridge.py b/backend/app/formbridge.py new file mode 100644 index 00000000..53124cda --- /dev/null +++ b/backend/app/formbridge.py @@ -0,0 +1,316 @@ +"""ComfyUI through the FormBridge pack (Comfy-FormBridge-Suite, contract 1): a clip or picture from the media bin is sent +to the person's own ComfyUI server, one of the pack's workflows runs on it there, and what comes back lands in the +media bin as new items (frames joined into a movie), or as text for a caption. + +The address is kept in formbridge.json in the data folder. The engine sends nothing but the chosen media to that +address, follows no redirect and uses no system proxy. The pack's routes are the only ones called.""" + +from __future__ import annotations + +import contextlib +import shutil +import subprocess +import tempfile +import time +import urllib.parse +import uuid +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +import httpx +from fastapi import APIRouter, HTTPException +from pydantic import BaseModel, Field + +from . import jobs, media +from .durable import read_json, write_json +from .media import ingest_path +from .paths import DATA_DIR +from .tools import ffmpeg + +router = APIRouter(prefix="/api/formbridge", tags=["formbridge"]) + +STORE = DATA_DIR / "formbridge.json" +STAGING = DATA_DIR / "formbridge-staging" +DEFAULT_BASE = "http://127.0.0.1:8188" +PREFIX = "/formbridge/v1" +PACK = "Comfy-FormBridge-Suite" +CLIENT_ID = "formcut-" + uuid.uuid4().hex[:16] +STATUS_SECONDS = 5 +TRANSFER_SECONDS = 600 +POLL_SECONDS = 1.5 +MEDIA_TYPES = {"image", "mask", "frames", "movie", "video", "media"} +SKIPPED_OUTPUTS = {"layer", "preview"} +NOT_INSTALLED = ( + f"The {PACK} pack does not answer at {{base}}. Put it in ComfyUI's custom_nodes folder, install its " + "requirements with ComfyUI's own Python, restart ComfyUI, then press Check again." +) + + +def normalize_base(base: str) -> str: + refused = HTTPException(422, "Give ComfyUI's address, such as http://127.0.0.1:8188") + try: + parts = urllib.parse.urlsplit((base or "").strip()) + host, port = parts.hostname, parts.port + except ValueError as exc: + raise refused from exc + if parts.scheme not in ("http", "https") or not host or parts.username or parts.password or parts.query or parts.fragment: + raise refused + shown = f"[{host}]" if ":" in host else host + return f"{parts.scheme}://{shown}" + (f":{port}" if port is not None else "") + parts.path.rstrip("/") + + +def settings() -> dict: + stored = read_json(STORE, {}) + base = stored.get("base") if isinstance(stored, dict) else None + return {"base": str(base or DEFAULT_BASE), "default": DEFAULT_BASE} + + +def _client(seconds: float) -> httpx.Client: + return httpx.Client(timeout=seconds, follow_redirects=False, trust_env=False) + + +def _headers(json_body: bool = False) -> dict: + from .main import APP_VERSION + + headers = {"X-FormBridge-Contract": "1", "X-FormBridge-Client": f"formcut/{APP_VERSION}", "Accept": "application/json"} + if json_body: + headers["Content-Type"] = "application/json" + return headers + + +def _answer(response: httpx.Response, base: str) -> dict: + if response.status_code in (404, 405) and "error" not in response.text[:200]: + raise HTTPException(404, NOT_INSTALLED.format(base=base)) + try: + body = response.json() + except ValueError: + body = {} + if response.status_code >= 400: + err = body.get("error") if isinstance(body, dict) else None + message = err.get("message") if isinstance(err, dict) else None + status = response.status_code if response.status_code in (400, 404, 409, 413, 422) else 502 + raise HTTPException(status, message or f"ComfyUI answered with status {response.status_code}.") + return body if isinstance(body, dict) else {} + + +def call(method: str, path: str, base: str | None = None, body: dict | None = None, seconds: float = STATUS_SECONDS) -> dict: + root = normalize_base(base or settings()["base"]) + try: + with _client(seconds) as client: + response = client.request(method, root + PREFIX + path, json=body, headers=_headers(body is not None)) + except httpx.HTTPError as exc: + raise HTTPException(502, f"Nothing answers at {root}: start ComfyUI there, or set its address.") from exc + return _answer(response, root) + + +def handshake(base: str) -> dict: + found = call("GET", "/handshake", base) + comfy = found.get("comfyui") or {} + out = { + "ok": True, + "pack": found.get("pack"), + "comfyui": comfy, + "device": found.get("device"), + "packs": (found.get("nodes") or {}).get("packs") or [], + "message": "", + } + if 1 not in (found.get("contract") or []): + out.update(ok=False, message="This ComfyUI's FormBridge pack does not serve contract 1. Update the pack.") + elif not comfy.get("supported"): + wanted = comfy.get("minimum") or "a newer version" + out.update(ok=False, message=f"ComfyUI {comfy.get('version') or ''} is too old for the pack; update it to {wanted} or later.") + return out + + +def _quoted(workflow: str) -> str: + return urllib.parse.quote(workflow, safe=".") + + +def readiness(workflow: str, base: str | None = None) -> dict: + return call("GET", f"/workflows/{_quoted(workflow)}/readiness", base) + + +def workflows(base: str | None = None) -> list[dict]: + listed = [w for w in call("GET", "/workflows", base).get("workflows") or [] if isinstance(w, dict)] + + def with_readiness(entry: dict) -> dict: + try: + ready = readiness(str(entry.get("id")), base) + except HTTPException: + ready = {"ready": False, "models": []} + missing = [f"{m.get('file')} in {m.get('place') or m.get('folder')}" for m in ready.get("models") or [] if not m.get("present")] + missing += [f"the {p.get('name')} node pack" for p in ready.get("packs") or [] if not p.get("present")] + missing += [f"the {n.get('class')} node" for n in ready.get("nodes") or [] if not n.get("present")] + return {**entry, "ready": bool(ready.get("ready")), "missing": missing} + + with ThreadPoolExecutor(max_workers=6) as pool: + return list(pool.map(with_readiness, listed)) + + +def _item(media_id: str) -> tuple[dict, Path]: + item = next((m for m in media._read() if m.get("id") == media_id), None) + path = media.media_path(media_id) if item else None + if not item or not path: + raise HTTPException(404, "That media item is not in the media bin, or its file is missing.") + return item, path + + +def _input_kind(slot_type: str, item: dict) -> str: + if slot_type in ("image", "mask"): + if item.get("kind") != "image": + raise HTTPException(400, f"{item.get('name')} is not a picture.") + return "still" + if item.get("kind") == "video": + if slot_type == "frames": + raise HTTPException(400, "This workflow takes a frame sequence, not a movie.") + return "movie" + if item.get("kind") == "image" and slot_type == "media": + return "still" + raise HTTPException(400, f"{item.get('name')} cannot go in a {slot_type} slot.") + + +def _upload(root: str, kind: str, path: Path, name: str) -> str: + with _client(TRANSFER_SECONDS) as client, open(path, "rb") as fh: + response = client.post( + root + PREFIX + "/inputs", + data={"kind": kind}, + files={"files": (name, fh)}, + headers={k: v for k, v in _headers().items() if k != "Accept"}, + ) + return str((_answer(response, root).get("input") or {}).get("id") or "") + + +def _download(root: str, file_id: str, dest: Path) -> Path: + url = root + PREFIX + f"/files/{urllib.parse.quote(file_id)}" + with _client(TRANSFER_SECONDS) as client, client.stream("GET", url, headers=_headers()) as response: + if response.status_code >= 400: + response.read() + _answer(response, root) + with open(dest, "wb") as fh: + fh.writelines(response.iter_bytes(1 << 20)) + return dest + + +def _join(frames: list[Path], fps: float, dest: Path) -> Path: + folder = frames[0].parent + for index, frame in enumerate(frames): + frame.rename(folder / f"{index:06d}{frame.suffix}") + pattern = str(folder / f"%06d{frames[0].suffix}") + command = [ffmpeg(), "-y", "-loglevel", "error", "-framerate", f"{fps:g}", "-start_number", "0", "-i", pattern] + command += ["-c:v", "libx264", "-crf", "12", "-pix_fmt", "yuv420p", "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2", str(dest)] + done = subprocess.run(command, capture_output=True, text=True, check=False) + if done.returncode or not dest.is_file(): + raise ValueError("ffmpeg could not join the result frames into a movie: " + (done.stderr or "").strip()[-300:]) + return dest + + +def _land(root: str, workflow: str, job: dict, item: dict, folder: Path) -> dict: + made, caption = [], "" + for output in job.get("outputs") or []: + name, kind, files = str(output.get("name") or "result"), output.get("kind"), output.get("files") or [] + if not files or name in SKIPPED_OUTPUTS: + continue + label = f"{item.get('name')} ({workflow} {name})" + extra = {"source": "comfyui", "workflow": workflow, "output": name, "from": item.get("id")} + if kind == "text": + got = _download(root, files[0]["file_id"], folder / f"{uuid.uuid4().hex}.txt") + caption = got.read_text(encoding="utf-8", errors="replace").strip() + continue + got = [ + _download(root, f["file_id"], folder / (uuid.uuid4().hex + (Path(str(f.get("name") or "")).suffix or ".png"))) for f in files + ] + if kind in ("frames", "matte", "mask") and len(got) > 1: + fps = float(output.get("fps") or item.get("fps") or 24) + sub = folder / uuid.uuid4().hex + sub.mkdir() + moved = [p.rename(sub / p.name) for p in got] + made.append(ingest_path(_join(moved, fps, folder / f"{uuid.uuid4().hex}.mp4"), label, extra=extra)) + else: + made.append(ingest_path(got[0], label, extra=extra)) + return {"media": made, "caption": caption, "cached": bool(job.get("cached"))} + + +class SettingsBody(BaseModel): + base: str = Field(default=DEFAULT_BASE, max_length=500) + + +class RunBody(BaseModel): + workflow: str = Field(min_length=1, max_length=120) + slots: dict = Field(default_factory=dict) + media: dict[str, str] = Field(default_factory=dict) + reuse: bool = True + + +@router.get("") +def get_settings() -> dict: + return settings() + + +@router.put("") +def put_settings(body: SettingsBody) -> dict: + write_json(STORE, {"base": normalize_base(body.base)}) + return settings() + + +@router.get("/handshake") +def get_handshake(base: str | None = None) -> dict: + try: + return handshake(normalize_base(base or settings()["base"])) + except HTTPException as exc: + return {"ok": False, "message": str(exc.detail)} + + +@router.get("/workflows") +def get_workflows() -> dict: + return {"workflows": workflows()} + + +@router.post("/run", status_code=202) +def run(body: RunBody) -> dict: + root = normalize_base(settings()["base"]) + entry = call("GET", f"/workflows/{_quoted(body.workflow)}", root) + types = {str(s.get("name")): str(s.get("type")) for s in entry.get("slots") or [] if isinstance(s, dict)} + picked = {} + for slot, media_id in body.media.items(): + if types.get(slot) not in MEDIA_TYPES: + raise HTTPException(400, f"The workflow has no picture or video slot called {slot}.") + item, path = _item(media_id) + picked[slot] = (item, path, _input_kind(types[slot], item)) + if not picked: + raise HTTPException(400, "Choose a clip or picture from the media bin.") + first = next(iter(picked.values()))[0] + + def operation(job_id, report, cancelled): + STAGING.mkdir(parents=True, exist_ok=True) + folder = Path(tempfile.mkdtemp(dir=STAGING)) + sent: list[str] = [] + try: + slots = dict(body.slots) + for slot, (item, path, kind) in picked.items(): + input_id = _upload(root, kind, path, str(item.get("name") or path.name).replace("/", "_") + path.suffix) + sent.append(input_id) + slots[slot] = input_id + report(0.1) + asked = {"workflow": body.workflow, "slots": slots, "client_id": CLIENT_ID, "reuse": body.reuse} + job = call("POST", "/jobs", root, asked, 30).get("job") or {} + while job.get("state") in ("queued", "running"): + if cancelled(): + call("POST", f"/jobs/{job['id']}/cancel", root, {}, 10) + raise InterruptedError("Cancelled") + time.sleep(POLL_SECONDS) + job = call("GET", f"/jobs/{job['id']}", root).get("job") or {} + step = job.get("progress") or {} + if step.get("max"): + report(0.1 + 0.75 * min(1.0, float(step.get("value") or 0) / float(step["max"]))) + if job.get("state") != "done": + err = job.get("error") or {} + raise ValueError(err.get("message") or f"The ComfyUI job ended {job.get('state')}.") + report(0.85) + return _land(root, body.workflow, job, first, folder) + finally: + for input_id in sent: + with contextlib.suppress(HTTPException): + call("DELETE", f"/inputs/{urllib.parse.quote(input_id)}", root) + shutil.rmtree(folder, ignore_errors=True) + + return jobs.submit("comfyui", operation) diff --git a/backend/app/main.py b/backend/app/main.py index ef4c8fc3..0b63066b 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -11,6 +11,7 @@ from .brush import router as brush_router from .cloud import router as cloud_router from .features import router as features_router +from .formbridge import router as formbridge_router from .instagram import router as instagram_router from .library import router as library_router from .media import router as media_router @@ -172,6 +173,7 @@ def filter(self, record: logging.LogRecord) -> bool: app.include_router(stock_router) app.include_router(tts_router) app.include_router(voice_app_router) +app.include_router(formbridge_router) app.include_router(presets_router) from .generate import router as generate_router From af8c45b0ca7ab9e20fab9f74f1e8b6087e4ad8fa Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Tue, 1 Dec 2026 21:03:16 -0500 Subject: [PATCH 2/7] feat(studio): a ComfyUI page in the Studio window with Address and Check, each workflow's slots as fields, and Run in ComfyUI --- frontend/src/ui/comfyui-page.ts | 173 ++++++++++++++++++++++++++++++++ frontend/src/ui/studio-tools.ts | 6 +- 2 files changed, 178 insertions(+), 1 deletion(-) create mode 100644 frontend/src/ui/comfyui-page.ts diff --git a/frontend/src/ui/comfyui-page.ts b/frontend/src/ui/comfyui-page.ts new file mode 100644 index 00000000..5957950d --- /dev/null +++ b/frontend/src/ui/comfyui-page.ts @@ -0,0 +1,173 @@ +import { text } from "../i18n/text"; +import type { MediaBin, MediaItem } from "../engine/media"; +import { api } from "../engine/api"; + +type Slot = { name: string; type: string; required?: boolean; default?: unknown; min?: number; max?: number; step?: number; choices?: string[]; description?: string }; +type Workflow = { id: string; title?: string; media?: string; description?: string; slots: Slot[]; ready: boolean; missing: string[] }; +type Handshake = { ok: boolean; message?: string; pack?: { version?: string }; comfyui?: { version?: string }; device?: { name?: string } }; +type Ran = { media?: Array<{ name: string }>; caption?: string; cached?: boolean }; +type Deps = { + bin: MediaBin; + job: (path: string, data?: unknown) => Promise; + say: (value: string) => void; + run: (work: () => unknown) => Promise; + reconcileOptions: (select: HTMLSelectElement, entries: Array<{ id: string; name: string }>) => void; +}; + +const MEDIA = new Set(["image", "mask", "frames", "movie", "video", "media"]); +const UNSENT = new Set(["points", "keyframes", "size"]); + +function accepts(type: string, item: MediaItem): boolean { + if (type === "image" || type === "mask") return item.kind === "image"; + if (type === "media") return item.kind === "image" || item.kind === "video"; + return item.kind === "video" && type !== "frames"; +} + +export function mountComfyPage(section: HTMLElement, deps: Deps): { show: () => Promise } { + const { bin, job, say, run, reconcileOptions } = deps; + section.innerHTML = ` +
${text("ComfyUI")}${text("Runs the FormBridge pack's workflows on your own ComfyUI server. Install Comfy-FormBridge-Suite in ComfyUI's custom_nodes folder, then press Check.")}
+ +
+

+
+
${text("Workflow")}
+ +

+
+
+ +
`; + const q = (name: string) => section.querySelector(`[data-cf-${name}]`)!; + const setText = (node: HTMLElement, value: string) => { if (node.textContent !== value) node.textContent = value; }; + const flows = new Map(); + const rows = new Map(); + let checked = false; + + const mediaChoices = (slot: Slot) => [ + ...(slot.required ? [] : [{ id: "", name: text("None") }]), + ...bin.all.filter((item) => accepts(slot.type, item)).map((item) => ({ id: item.id, name: item.name })), + ]; + const paintMedia = () => { + for (const { field, slot } of rows.values()) if (MEDIA.has(slot.type)) reconcileOptions(field as HTMLSelectElement, mediaChoices(slot)); + }; + + const fieldFor = (slot: Slot): HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement => { + if (MEDIA.has(slot.type)) { + const select = document.createElement("select"); + reconcileOptions(select, mediaChoices(slot)); + return select; + } + if (slot.type === "choice") { + const select = document.createElement("select"); + reconcileOptions(select, (slot.choices ?? []).map((choice) => ({ id: choice, name: choice }))); + if (slot.default !== undefined) select.value = String(slot.default); + return select; + } + if (slot.type === "text") { + const area = document.createElement("textarea"); + area.rows = 3; + area.value = typeof slot.default === "string" ? slot.default : ""; + return area; + } + const input = document.createElement("input"); + if (slot.type === "bool") { + input.type = "checkbox"; + input.checked = slot.default === true; + return input; + } + input.type = "number"; + if (slot.min !== undefined) input.min = String(slot.min); + if (slot.max !== undefined) input.max = String(slot.max); + input.step = slot.type === "float" ? String(slot.step ?? "any") : String(slot.step ?? 1); + input.value = slot.type === "seed" ? String(slot.default ?? -1) : slot.default === undefined || slot.default === null ? "" : String(slot.default); + return input; + }; + + const ensureRows = (flow: Workflow) => { + for (const slot of flow.slots) { + const key = `${flow.id}\u0000${slot.name}`; + if (rows.has(key) || UNSENT.has(slot.type)) continue; + const row = document.createElement("label"); + row.dataset.cfFlow = flow.id; + row.hidden = true; + row.title = slot.description ?? ""; + const field = fieldFor(slot); + row.append(document.createTextNode(`${slot.name} `), field); + q("slots").append(row); + rows.set(key, { row, field, slot }); + } + }; + + const unsendable = (flow: Workflow) => flow.slots.filter((slot) => slot.required && UNSENT.has(slot.type)).map((slot) => slot.name); + + const showFlow = () => { + const flow = flows.get(q("workflow").value); + if (!flow) { + for (const { row } of rows.values()) row.hidden = true; setText(q("about"), ""); setText(q("missing"), ""); q("go").disabled = true; return; } + ensureRows(flow); + for (const { row } of rows.values()) row.hidden = row.dataset.cfFlow !== flow.id; + setText(q("about"), flow.description ?? ""); + const blocked = unsendable(flow); + const missing = blocked.length + ? `${text("formcut cannot fill these slots yet:")} ${blocked.join(", ")}` + : flow.ready ? "" : `${text("Not ready. Missing:")} ${flow.missing.join("; ")}`; + setText(q("missing"), missing); + q("go").disabled = !flow.ready || blocked.length > 0; + }; + + const loadFlows = async () => { + const listed = (await api<{ workflows: Workflow[] }>("/api/formbridge/workflows")).workflows; + flows.clear(); + for (const flow of listed) flows.set(flow.id, flow); + reconcileOptions(q("workflow"), listed.map((flow) => ({ id: flow.id, name: `${flow.title ?? flow.id}${flow.ready ? "" : ` (${text("not ready")})`}` }))); + showFlow(); + }; + + const check = async () => { + const saved = await api<{ base: string }>("/api/formbridge", { base: q("base").value.trim() }, "PUT"); + if (document.activeElement !== q("base")) q("base").value = saved.base; + const found = await api("/api/formbridge/handshake"); + if (!found.ok) { setText(q("state"), found.message ?? ""); return; } + setText(q("state"), `${text("Connected")}: ComfyUI ${found.comfyui?.version ?? ""}, FormBridge ${found.pack?.version ?? ""}, ${found.device?.name ?? ""}`); + checked = true; + await loadFlows(); + }; + + const values = (flow: Workflow) => { + const slots: Record = {}, media: Record = {}; + for (const { row, field, slot } of rows.values()) { + if (row.dataset.cfFlow !== flow.id) continue; + if (MEDIA.has(slot.type)) { if (field.value) media[slot.name] = field.value; continue; } + if (slot.type === "bool") { slots[slot.name] = (field as HTMLInputElement).checked; continue; } + if (slot.type === "text" || slot.type === "choice") { if (field.value !== "" || slot.required) slots[slot.name] = field.value; continue; } + if (field.value !== "") slots[slot.name] = Number(field.value); + } + return { slots, media }; + }; + + q("check").addEventListener("click", () => void run(check)); + q("workflow").addEventListener("change", showFlow); + q("go").addEventListener("click", () => void run(async () => { + const flow = flows.get(q("workflow").value); + if (!flow) return; + const { slots, media } = values(flow); + const ran = await job("/api/formbridge/run", { workflow: flow.id, slots, media, reuse: q("reuse").checked }) as Ran; + await bin.load(); + const names = (ran.media ?? []).map((item) => item.name); + if (ran.caption) { + q("caption").value = ran.caption; + q("caption-row").hidden = false; + } + say(names.length ? `${text("Added to the media bin")}: ${names.join(", ")}` : ran.caption ? text("Caption ready.") : text("Done.")); + })); + bin.subscribe(paintMedia); + + return { + show: async () => { + const stored = await api<{ base: string }>("/api/formbridge"); + if (document.activeElement !== q("base")) q("base").value = stored.base; + if (!checked) await check().catch((error) => setText(q("state"), error instanceof Error ? error.message : String(error))); + }, + }; +} diff --git a/frontend/src/ui/studio-tools.ts b/frontend/src/ui/studio-tools.ts index 3470ef86..17e94129 100644 --- a/frontend/src/ui/studio-tools.ts +++ b/frontend/src/ui/studio-tools.ts @@ -11,6 +11,7 @@ import { buildCreatorPanel } from "./creator-panel"; import { buildRecording } from "./recorder"; import { icon } from "./icons"; import { reconcile } from "./keyed-list"; +import { mountComfyPage } from "./comfyui-page"; export function installStudioTools(engine: ProjectEngine, bin: MediaBin): void { const inspector = buildCreatorPanel(engine); @@ -27,7 +28,7 @@ export function installStudioTools(engine: ProjectEngine, bin: MediaBin): void { modal.innerHTML = `
+