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.

Fuobe Connect: a ComfyUI node pack that connects in one install

Adarsh793e51f828d9
diff --git a/integrations/fuobe-connect/LICENSE b/integrations/fuobe-connect/LICENSE
new file mode 100644
index 00000000..4746ad80
--- /dev/null
+++ b/integrations/fuobe-connect/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 workingprototype and the Fuobe contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/integrations/fuobe-connect/README.md b/integrations/fuobe-connect/README.md
new file mode 100644
index 00000000..89b69a15
--- /dev/null
+++ b/integrations/fuobe-connect/README.md
@@ -0,0 +1,74 @@
+# Fuobe Connect
+
+A ComfyUI custom node pack. It lets [Fuobe](https://github.com/workingprototype/Fuobe) use your ComfyUI with one
+install, the way ComfyUI's own page uses it at `http://127.0.0.1:8188`. You do not need a start flag, a second file or
+a changed start file. It adds no nodes.
+
+## Install
+
+**ComfyUI-Manager:** open the Manager, choose **Custom Nodes Manager**, search for `Fuobe Connect`, press **Install**,
+then press **Restart**.
+
+**Git:** in a terminal, in ComfyUI's `custom_nodes` folder:
+
+```
+git clone https://github.com/workingprototype/ComfyUI-Fuobe-Connect
+```
+
+Then restart ComfyUI.
+
+Then open Fuobe in Chrome, Edge or Firefox and choose **Connect your GPU**. Your browser asks once to let the page reach
+apps on this computer. Press **Allow**. Fuobe finds ComfyUI and connects.
+
+## What it does
+
+**Direct mode (the default).** ComfyUI turns away requests from every other website. Fuobe Connect adds one exception:
+the Fuobe studios you trust (`https://fuobe.com` unless you name others). For a trusted studio it:
+
+- answers the browser's CORS preflight and Chrome's Private Network Access preflight, for that exact origin only;
+- lets through only what a Fuobe run needs: ComfyUI's facts, its model lists, its queue and history, the run's
+ results, uploading the run's inputs and queueing its prompt.
+
+A trusted studio cannot reach the Manager's install calls, your user files, your settings or your input folder. Every
+other website still meets ComfyUI's own check, unchanged. Nothing in ComfyUI's own files changes.
+
+If ComfyUI runs with `--enable-cors-header` (an older Fuobe setup), ComfyUI's own check is off. Fuobe Connect then also
+turns away every website except ComfyUI's own page, the site that the setting names and the trusted studios. This is
+what Fuobe's guard file did, so you can delete `fuobe_guard.py` and the setting.
+
+**Pairing mode (for Safari, phones and PCs with no screen).** Some browsers do not let a website reach apps on your
+computer. In ComfyUI, open **Extensions → Connect to Fuobe** and press **Connect**. ComfyUI shows a short code. Open the
+link on any device, sign in to Fuobe and approve the code. From then on, ComfyUI gets that one person's jobs from the
+studio over HTTPS, and it runs them with no Fuobe tab open. It opens no port. The token belongs to you alone, so another
+person's jobs never reach your PC. To stop, press **Disconnect** in the same window, or remove the computer in Fuobe's
+settings.
+
+On a PC with no screen, start ComfyUI with `FUOBE_CONNECT_PAIR=1`. The code and the link then appear in ComfyUI's
+console.
+
+## Your own Fuobe studio
+
+To use a studio that you host yourself, open ComfyUI's **Settings → Fuobe Connect** and enter its address, for example
+`https://studio.example.com`. You can also set the environment variable
+`FUOBE_CONNECT_ORIGINS=https://studio.example.com` before you start ComfyUI. Separate several studios with commas. The
+first one is also the studio that pairing uses.
+
+## Files
+
+Fuobe Connect keeps one file, `fuobe-connect.json`, in ComfyUI's `user` folder. The file holds the studios that you
+trust and, after pairing, the studio's address and the token. Only your user account can read the file. ComfyUI does
+not serve this file to web pages.
+
+## Tests
+
+```
+python -m unittest discover -s tests
+```
+
+The tests load ComfyUI's own origin check and run it behind Fuobe Connect over real HTTP on port 3360. Set
+`FUOBE_CONNECT_TEST_PORT` to choose another port. Set `COMFYUI_DIR` to a ComfyUI folder to read the middleware from that
+copy of ComfyUI. The tests need only `aiohttp`. They do not need models, a GPU or a running ComfyUI.
+
+## Licence
+
+MIT
diff --git a/integrations/fuobe-connect/__init__.py b/integrations/fuobe-connect/__init__.py
new file mode 100644
index 00000000..c89cc47c
--- /dev/null
+++ b/integrations/fuobe-connect/__init__.py
@@ -0,0 +1,22 @@
+"""Fuobe Connect, a ComfyUI custom node pack.
+
+It adds no nodes. It lets a Fuobe studio (https://fuobe.com, or your own) use this ComfyUI from your browser, with no
+start flag and no extra file, and it keeps ComfyUI's own check against every other website. For browsers that can't
+reach this computer (Safari, phones) and PCs with no screen, it can pair this ComfyUI with your Fuobe account instead.
+See README.md.
+"""
+
+import logging
+
+NODE_CLASS_MAPPINGS = {}
+NODE_DISPLAY_NAME_MAPPINGS = {}
+WEB_DIRECTORY = "./web"
+
+try:
+ from .fuobe_connect.plugin import install
+
+ install()
+except Exception as e: # never stop ComfyUI from starting
+ logging.warning("[Fuobe Connect] Couldn't start: %s", e)
+
+__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
diff --git a/integrations/fuobe-connect/fuobe_connect/__init__.py b/integrations/fuobe-connect/fuobe_connect/__init__.py
new file mode 100644
index 00000000..282d5c4b
--- /dev/null
+++ b/integrations/fuobe-connect/fuobe_connect/__init__.py
@@ -0,0 +1,3 @@
+"""Fuobe Connect: use this ComfyUI from Fuobe with one install."""
+
+__version__ = "1.0.0"
diff --git a/integrations/fuobe-connect/fuobe_connect/agent.py b/integrations/fuobe-connect/fuobe_connect/agent.py
new file mode 100644
index 00000000..f2cf7c03
--- /dev/null
+++ b/integrations/fuobe-connect/fuobe_connect/agent.py
@@ -0,0 +1,178 @@
+"""Pairing mode: Fuobe Connect runs your Fuobe jobs on this ComfyUI with no browser tab, after one approval.
+
+For browsers that can't reach this computer from a website (Safari, Firefox in some setups, phones) and for PCs with no
+screen. It runs in its own thread with its own event loop, so ComfyUI's own work is never held up by it.
+
+1. "Connect to Fuobe" (ComfyUI's menu, or FUOBE_CONNECT_PAIR=1 on a PC with no screen) asks the studio for a short code.
+2. You open the studio's /connect page, signed in, and approve that code.
+3. This ComfyUI gets a token for you alone, kept in fuobe-connect.json, and runs your jobs (runner.py).
+
+"Disconnect" in ComfyUI, or Disconnect in the studio's settings, ends it.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import socket
+import threading
+import time
+
+import aiohttp
+
+from .net import Comfy, Site, site_base
+from .runner import Runner, Unpaired
+from .store import Store
+
+log = logging.getLogger("fuobe_connect")
+
+
+class Agent:
+ def __init__(self, store: Store, comfy_base: str, port: int, default_site: str):
+ self.store = store
+ self.comfy_base = comfy_base
+ self.port = port
+ self.default_site = default_site
+ self.loop = asyncio.new_event_loop()
+ self.state = "unpaired"
+ self.message: str | None = None
+ self.pairing: dict | None = None
+ self._runner_task: asyncio.Future | None = None
+ self._pair_task: asyncio.Future | None = None
+ self._session: aiohttp.ClientSession | None = None
+ self._thread: threading.Thread | None = None
+
+ # ------------------------------------------------------------------
+ # Thread
+
+ def start(self):
+ self._thread = threading.Thread(target=self._main, name="fuobe-connect", daemon=True)
+ self._thread.start()
+
+ def _main(self):
+ asyncio.set_event_loop(self.loop)
+ self.loop.run_until_complete(self._boot())
+ self.loop.run_forever()
+
+ async def _boot(self):
+ self._session = aiohttp.ClientSession()
+ if self.store.load().get("token"):
+ self._start_runner()
+
+ def call(self, coro):
+ """Run a coroutine on the agent's loop from any thread; returns a concurrent future."""
+ return asyncio.run_coroutine_threadsafe(coro, self.loop)
+
+ # ------------------------------------------------------------------
+ # State
+
+ def status(self) -> dict:
+ data = self.store.load()
+ out = {"state": self.state, "message": self.message}
+ if data.get("token"):
+ out["paired"] = {"site": data.get("site"), "name": data.get("name"), "since": data.get("pairedAt")}
+ if self.pairing and self.state == "pairing":
+ out["pairing"] = {k: self.pairing[k] for k in ("code", "url", "expiresAt", "site")}
+ return out
+
+ def _set(self, state: str, message: str | None = None):
+ if (state, message) != (self.state, self.message):
+ self.state, self.message = state, message
+ if message:
+ log.info("[Fuobe Connect] %s", message)
+
+ # ------------------------------------------------------------------
+ # Pairing
+
+ async def start_pairing(self, site: str | None = None) -> dict:
+ base = site_base(site or self.default_site)
+ if self._pair_task and not self._pair_task.done():
+ self._pair_task.cancel()
+ comfy = Comfy(self._session, self.comfy_base)
+ facts = {}
+ try:
+ stats = await comfy.get_json("/system_stats", timeout=10)
+ dev = (stats.get("devices") or [{}])[0] or {}
+ facts = {k: v for k, v in {"device": dev.get("name"), "vramBytes": dev.get("vram_total"), "version": (stats.get("system") or {}).get("comfyui_version")}.items() if v}
+ except Exception:
+ pass
+ a = await Site(self._session, base).pair_start(socket.gethostname()[:48] or "ComfyUI", facts)
+ if a.status != 200 or not a.body.get("code"):
+ raise RuntimeError(a.body.get("error") or f"The studio answered HTTP {a.status}")
+ self.pairing = {**a.body, "site": base}
+ self._set("pairing", f"To connect this ComfyUI, open {a.body['url']} and approve the code {a.body['code']}.")
+ self._pair_task = asyncio.ensure_future(self._poll(base, a.body["id"], a.body["secret"], a.body.get("pollMs") or 2000, a.body.get("expiresAt")))
+ return self.status()
+
+ async def _poll(self, base: str, pair_id: str, secret: str, poll_ms: int, expires_at: int | None):
+ site = Site(self._session, base)
+ until = time.time() + 11 * 60
+ while time.time() < until:
+ await asyncio.sleep(max(1.0, poll_ms / 1000))
+ try:
+ a = await site.pair_poll(pair_id, secret)
+ except Exception:
+ continue
+ if a.status == 200 and a.body.get("state") == "approved" and a.body.get("token"):
+ self.store.update(site=base, token=a.body["token"], name=a.body.get("name"), workerId=a.body.get("workerId"), pairedAt=int(time.time() * 1000))
+ self.pairing = None
+ self._set("connected", f"Connected to {base}. Your Fuobe jobs now run on this ComfyUI.")
+ self._start_runner()
+ return
+ if a.status == 404 or a.body.get("state") == "gone":
+ break
+ self.pairing = None
+ self._set("unpaired", "The code wasn't approved. Press Connect to Fuobe again for a new one.")
+
+ def cancel_pairing(self):
+ if self._pair_task and not self._pair_task.done():
+ self._pair_task.cancel()
+ self.pairing = None
+ if self.state == "pairing":
+ self._set("unpaired", None)
+
+ async def unpair(self) -> dict:
+ """Forget the token here, and tell the studio to forget it too (best effort)."""
+ data = self.store.load()
+ if self._runner_task and not self._runner_task.done():
+ self._runner_task.cancel()
+ self.store.update(token=None, workerId=None, pairedAt=None)
+ self._set("unpaired", "Disconnected from Fuobe.")
+ if data.get("token") and data.get("site"):
+ try:
+ await Site(self._session, data["site"], data["token"]).call("POST", "/api/gpu/computer/unpair", {}, timeout=10)
+ except Exception:
+ pass
+ return self.status()
+
+ # ------------------------------------------------------------------
+ # Running jobs
+
+ def _start_runner(self):
+ if self._runner_task and not self._runner_task.done():
+ return
+ self._runner_task = asyncio.ensure_future(self._run())
+
+ async def _run(self):
+ backoff = 5
+ while True:
+ data = self.store.load()
+ token, site = data.get("token"), data.get("site")
+ if not token or not site:
+ return
+ device = f"connect-{(data.get('workerId') or 'here')}"[:64]
+ runner = Runner(Site(self._session, site, token), Comfy(self._session, self.comfy_base), device, self.port, on_state=self._set)
+ try:
+ await runner.run_forever()
+ backoff = 5
+ except Unpaired:
+ self.store.update(token=None, workerId=None, pairedAt=None)
+ self._set("unpaired", "This ComfyUI was disconnected from Fuobe. Press Connect to Fuobe to pair it again.")
+ return
+ except asyncio.CancelledError:
+ runner.alive = False
+ raise
+ except Exception as e:
+ self._set("offline", f"Fuobe Connect stopped for a moment: {e}")
+ await asyncio.sleep(backoff)
+ backoff = min(backoff * 2, 120)
diff --git a/integrations/fuobe-connect/fuobe_connect/graph.py b/integrations/fuobe-connect/fuobe_connect/graph.py
new file mode 100644
index 00000000..c2f0fc9b
--- /dev/null
+++ b/integrations/fuobe-connect/fuobe_connect/graph.py
@@ -0,0 +1,98 @@
+"""Checks Fuobe Connect makes on its own, whatever the studio sends (the same ones the Fuobe tab makes):
+
+- a job's graph may read only the input files that job sent (no file of yours);
+- a result is downloaded only when this job's own prompt saved it.
+
+Pure, so the tests run it alone.
+"""
+
+from __future__ import annotations
+
+import re
+
+INPUT_NAME = re.compile(r"^fuobe_[A-Za-z0-9_-]{8,24}\.[a-z0-9]{1,5}$")
+UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
+
+FILE_LOADERS = {
+ "LoadImage": ["image"],
+ "LoadImageMask": ["image"],
+ "LoadImageOutput": ["image"],
+ "LoadVideo": ["file"],
+ "LoadAudio": ["audio"],
+ "VHS_LoadVideo": ["video"],
+ "VHS_LoadVideoPath": ["video"],
+ "VHS_LoadAudio": ["audio_file"],
+ "VHS_LoadAudioUpload": ["audio"],
+ "VHS_LoadImages": ["directory"],
+ "VHS_LoadImagesPath": ["directory"],
+}
+_FILEISH = re.compile(r"image|video|audio|file|path|directory", re.I)
+
+
+def graph_problem(graph, staged: list[str]) -> str | None:
+ """Every loader names one of this job's own inputs, or a value from another node. Else: what is wrong."""
+ if not isinstance(graph, dict):
+ return "No graph"
+ for node_id, node in graph.items():
+ if not isinstance(node, dict):
+ return f"Node {node_id} isn't a node"
+ cls = node.get("class_type") if isinstance(node.get("class_type"), str) else ""
+ inputs = node.get("inputs") if isinstance(node.get("inputs"), dict) else {}
+ keys = FILE_LOADERS.get(cls)
+ if keys is None:
+ keys = [k for k in inputs if _FILEISH.search(k)] if re.match(r"^(Load|VHS_Load)", cls) else []
+ for k in keys:
+ v = inputs.get(k)
+ if v is None or isinstance(v, list):
+ continue
+ if not isinstance(v, str) or re.sub(r" \[input\]$", "", v) not in staged:
+ return f"Node {node_id} ({cls}) reads a file this run didn't send"
+ return None
+
+
+def files_in(entries: list) -> list[dict]:
+ out = []
+ for e in entries or []:
+ outputs = e.get("outputs") if isinstance(e, dict) else None
+ for ui in (outputs or {}).values():
+ if not isinstance(ui, dict):
+ continue
+ for v in ui.values():
+ if isinstance(v, list):
+ for f in v:
+ if isinstance(f, dict) and isinstance(f.get("filename"), str) and isinstance(f.get("type"), str):
+ out.append(f)
+ return out
+
+
+def may_download(w: dict, entries: list) -> bool:
+ return any(
+ x["filename"] == w.get("filename") and (x.get("subfolder") or "") == w.get("subfolder") and x["type"] == w.get("type") for x in files_in(entries)
+ )
+
+
+def safe_wanted(w: dict) -> bool:
+ """A wanted file the server named: a plain file name in output or temp, no way out of the folder."""
+ name = w.get("filename")
+ sub = w.get("subfolder") or ""
+ if not isinstance(name, str) or not name or re.search(r"[\\/]", name) or name in (".", ".."):
+ return False
+ if not isinstance(sub, str) or any(p == ".." for p in re.split(r"[\\/]", sub)):
+ return False
+ return w.get("type") in ("output", "temp")
+
+
+def has_prefix(prompt, prefix: str) -> bool:
+ if not isinstance(prompt, dict):
+ return False
+ return any(isinstance(n, dict) and isinstance(n.get("inputs"), dict) and n["inputs"].get("filename_prefix") == prefix for n in prompt.values())
+
+
+def slim(e: dict) -> dict:
+ """A history entry as the studio needs it: its status and outputs, not the whole graph again."""
+ p = e.get("prompt")
+ return {
+ "prompt": [p[0], p[1]] if isinstance(p, list) and len(p) >= 2 else None,
+ "status": e.get("status"),
+ "outputs": e.get("outputs"),
+ }
diff --git a/integrations/fuobe-connect/fuobe_connect/middleware.py b/integrations/fuobe-connect/fuobe_connect/middleware.py
new file mode 100644
index 00000000..1fbe2dbb
--- /dev/null
+++ b/integrations/fuobe-connect/fuobe_connect/middleware.py
@@ -0,0 +1,110 @@
+"""The middleware that lets a trusted Fuobe studio use this ComfyUI from the browser, with no start flag.
+
+ComfyUI turns away every request from another website (its origin check). This middleware runs before that check and
+handles exactly one case: a request from a trusted studio (an exact origin) for a path a Fuobe run needs
+(origins.allowed). For that request it:
+
+- answers the browser's CORS preflight, and Chrome's Private Network Access preflight, for that origin only;
+- passes the request on without its Origin and Sec-Fetch-Site headers, so ComfyUI's own check sees what it sees for a
+ program on this computer, and adds Access-Control-Allow-Origin for that origin to the answer.
+
+Every other request goes on untouched, so ComfyUI's own check still turns away every other website.
+
+When ComfyUI was started with --enable-cors-header (which switches its own check off), the middleware also does what
+Fuobe's guard does: a request from a web page gets in only when the page is ComfyUI's own, the origin the setting
+names, or a trusted studio. With "--enable-cors-header *" (every site, the person's choice) it adds no check.
+
+Pure aiohttp: the tests load it with ComfyUI's own middleware and nothing else.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Callable, Iterable
+
+from aiohttp import web
+
+from .origins import allowed, normalise, same_host
+
+ALLOW_METHODS = "GET, POST, OPTIONS"
+# Set on a trusted studio's request as it goes on (and dropped from every incoming one), so Fuobe Connect's own status
+# answer gives a studio less than ComfyUI's own page.
+MARKER = "X-Fuobe-Connect-Studio"
+ALLOW_HEADERS = {"content-type"}
+MAX_AGE = "600"
+
+_told: set[str] = set()
+
+
+def _note(why: str) -> None:
+ if why not in _told and len(_told) < 50:
+ _told.add(why)
+ logging.warning("[Fuobe Connect] Turned away a request from %s", why)
+
+
+def _cors_headers(origin: str) -> dict[str, str]:
+ return {"Access-Control-Allow-Origin": origin, "Vary": "Origin"}
+
+
+def preflight(request: web.Request, origin: str) -> web.Response | None:
+ """The answer to a preflight from a trusted origin, or None when it asks for something a run never does."""
+ method = request.headers.get("Access-Control-Request-Method", "").upper()
+ if not method or not allowed(method, request.path, request.query_string):
+ return None
+ asked = {h.strip().lower() for h in request.headers.get("Access-Control-Request-Headers", "").split(",") if h.strip()}
+ if not asked <= ALLOW_HEADERS:
+ return None
+ headers = {
+ **_cors_headers(origin),
+ "Access-Control-Allow-Methods": ALLOW_METHODS,
+ "Access-Control-Max-Age": MAX_AGE,
+ }
+ if asked:
+ headers["Access-Control-Allow-Headers"] = ", ".join(sorted(asked))
+ # Chrome's Private Network Access: a public page asking for an app on this computer.
+ if request.headers.get("Access-Control-Request-Private-Network", "").lower() == "true":
+ headers["Access-Control-Allow-Private-Network"] = "true"
+ return web.Response(status=204, headers=headers)
+
+
+def make_middleware(trusted: Callable[[], Iterable[str]], cors_flag: str | None = None):
+ """`trusted`: the trusted origins now (read on each request, so a change applies at once).
+ `cors_flag`: ComfyUI's --enable-cors-header value, when it was started with one."""
+ flag = (cors_flag or "").strip()
+ flag_origin = normalise(flag) if flag and flag != "*" else None
+ guard_on = bool(flag) and flag != "*"
+
+ @web.middleware
+ async def fuobe_connect(request: web.Request, handler):
+ raw = request.headers.get("Origin")
+ if raw is not None:
+ origin = normalise(raw)
+ if origin and origin in set(trusted()):
+ if request.method == "OPTIONS":
+ answer = preflight(request, origin)
+ if answer is not None:
+ return answer
+ elif allowed(request.method, request.path, request.query_string):
+ headers = request.headers.copy()
+ headers.popall("Origin", None)
+ headers.popall("Sec-Fetch-Site", None)
+ headers[MARKER] = origin
+ response = await handler(request.clone(headers=headers))
+ if isinstance(response, web.StreamResponse) and not response.prepared:
+ response.headers.update(_cors_headers(origin))
+ return response
+ # A trusted site asking for anything else is any other website: ComfyUI decides (and turns it away).
+ if guard_on and origin != flag_origin and not same_host(raw, request.headers.get("Host")):
+ if not (origin and origin in set(trusted())):
+ _note(raw[:120])
+ return web.Response(status=403)
+ elif guard_on and request.headers.get("Sec-Fetch-Site", "").lower() in ("cross-site", "same-site"):
+ _note("another website")
+ return web.Response(status=403)
+ if MARKER in request.headers:
+ headers = request.headers.copy()
+ headers.popall(MARKER, None)
+ request = request.clone(headers=headers)
+ return await handler(request)
+
+ return fuobe_connect
diff --git a/integrations/fuobe-connect/fuobe_connect/net.py b/integrations/fuobe-connect/fuobe_connect/net.py
new file mode 100644
index 00000000..b8bc4f37
--- /dev/null
+++ b/integrations/fuobe-connect/fuobe_connect/net.py
@@ -0,0 +1,155 @@
+"""The two places Fuobe Connect talks to: the paired Fuobe studio (over HTTPS, with its token) and this ComfyUI itself
+(on this computer, as a program: no browser headers, so ComfyUI's own checks treat it as it treats any local tool).
+
+Only aiohttp, which ComfyUI already has.
+"""
+
+from __future__ import annotations
+
+import json
+import ssl
+from dataclasses import dataclass
+from urllib.parse import urlencode, urlsplit
+
+import aiohttp
+
+from . import __version__
+
+USER_AGENT = f"FuobeConnect/{__version__}"
+
+
+class SiteError(Exception):
+ def __init__(self, status: int, message: str = "", body: dict | None = None):
+ super().__init__(message or f"HTTP {status}")
+ self.status = status
+ self.body = body or {}
+
+
+@dataclass
+class Answer:
+ status: int
+ body: dict
+ headers: dict
+
+
+def site_base(site: str) -> str:
+ u = urlsplit(site.strip())
+ if u.scheme not in ("https", "http") or not u.hostname:
+ raise ValueError("The studio's address must start with https://")
+ return f"{u.scheme}://{u.netloc}"
+
+
+class Site:
+ """The Fuobe studio. Every call says who is calling (FuobeConnect/<version>); job calls carry the worker token."""
+
+ def __init__(self, session: aiohttp.ClientSession, site: str, token: str | None = None):
+ self.session = session
+ self.base = site_base(site)
+ self.token = token
+
+ def _headers(self, extra: dict | None = None) -> dict:
+ h = {"User-Agent": USER_AGENT}
+ if self.token:
+ h["Authorization"] = f"Bearer {self.token}"
+ if extra:
+ h.update(extra)
+ return h
+
+ async def call(self, method: str, path: str, body=None, headers: dict | None = None, data: bytes | None = None, timeout: float = 60) -> Answer:
+ kwargs = {"headers": self._headers(headers), "timeout": aiohttp.ClientTimeout(total=timeout)}
+ if body is not None:
+ kwargs["data"] = json.dumps(body)
+ kwargs["headers"]["Content-Type"] = "application/json"
+ elif data is not None:
+ kwargs["data"] = data
+ async with self.session.request(method, self.base + path, **kwargs) as res:
+ text = await res.text()
+ try:
+ parsed = json.loads(text) if text else {}
+ except ValueError:
+ parsed = {}
+ return Answer(res.status, parsed if isinstance(parsed, dict) else {}, dict(res.headers))
+
+ async def read(self, path: str, headers: dict | None = None) -> tuple[int, bytes, dict]:
+ async with self.session.get(self.base + path, headers=self._headers(headers), timeout=aiohttp.ClientTimeout(total=600)) as res:
+ return res.status, await res.read(), dict(res.headers)
+
+ # Pairing (no token yet).
+ async def pair_start(self, name: str, facts: dict) -> Answer:
+ return await self.call("POST", "/api/gpu/pair/start", {"name": name, "facts": facts}, timeout=20)
+
+ async def pair_poll(self, pair_id: str, secret: str) -> Answer:
+ return await self.call("POST", "/api/gpu/pair/poll", {"id": pair_id, "secret": secret}, timeout=20)
+
+
+class Comfy:
+ """This ComfyUI, from inside it: only the calls a run needs, to its own address."""
+
+ def __init__(self, session: aiohttp.ClientSession, base: str):
+ self.session = session
+ self.base = base.rstrip("/")
+ self._ssl = False if base.startswith("https://") else None
+
+ def _kw(self, timeout: float = 30) -> dict:
+ kw = {"timeout": aiohttp.ClientTimeout(total=timeout)}
+ if self._ssl is False:
+ kw["ssl"] = False
+ return kw
+
+ async def get_json(self, path: str, timeout: float = 30):
+ async with self.session.get(self.base + path, **self._kw(timeout)) as res:
+ if res.status != 200:
+ raise SiteError(res.status, f"ComfyUI {path.split('?')[0]} answered HTTP {res.status}")
+ return await res.json(content_type=None)
+
+ async def get_status(self, path: str) -> tuple[int, object]:
+ async with self.session.get(self.base + path, **self._kw()) as res:
+ body = await res.json(content_type=None) if res.status == 200 else None
+ return res.status, body
+
+ async def post_json(self, path: str, body: dict, timeout: float = 60) -> tuple[int, dict]:
+ async with self.session.post(self.base + path, data=json.dumps(body), headers={"Content-Type": "application/json"}, **self._kw(timeout)) as res:
+ text = await res.text()
+ try:
+ parsed = json.loads(text) if text else {}
+ except ValueError:
+ parsed = {}
+ return res.status, parsed if isinstance(parsed, dict) else {}
+
+ async def upload_input(self, name: str, data: bytes, content_type: str) -> int:
+ form = aiohttp.FormData()
+ form.add_field("image", data, filename=name, content_type=content_type or "application/octet-stream")
+ form.add_field("type", "input")
+ form.add_field("overwrite", "true")
+ async with self.session.post(self.base + "/upload/image", data=form, **self._kw(600)) as res:
+ await res.read()
+ return res.status
+
+ async def view(self, filename: str, subfolder: str, kind: str) -> bytes | None:
+ q = urlencode({"filename": filename, "subfolder": subfolder, "type": kind})
+ async with self.session.get(f"{self.base}/view?{q}", **self._kw(600)) as res:
+ return await res.read() if res.status == 200 else None
+
+ def ws_url(self, client_id: str) -> str:
+ return self.base.replace("http", "ws", 1) + "/ws?" + urlencode({"clientId": client_id})
+
+
+def loopback_base(listen: str | None, port: int, tls: bool) -> str:
+ """Where this ComfyUI answers on this computer, from its --listen and --port."""
+ hosts = [h.strip() for h in (listen or "127.0.0.1").split(",") if h.strip()]
+ pick = "127.0.0.1"
+ for h in hosts:
+ if h in ("127.0.0.1", "localhost"):
+ pick = "127.0.0.1"
+ break
+ if h == "::1":
+ pick = "[::1]"
+ break
+ else:
+ if hosts and hosts[0] not in ("0.0.0.0", "::", ""):
+ pick = f"[{hosts[0]}]" if ":" in hosts[0] else hosts[0]
+ return f"{'https' if tls else 'http'}://{pick}:{int(port)}"
+
+
+def ssl_context() -> ssl.SSLContext:
+ return ssl.create_default_context()
diff --git a/integrations/fuobe-connect/fuobe_connect/origins.py b/integrations/fuobe-connect/fuobe_connect/origins.py
new file mode 100644
index 00000000..393b2649
--- /dev/null
+++ b/integrations/fuobe-connect/fuobe_connect/origins.py
@@ -0,0 +1,127 @@
+"""Which websites Fuobe Connect trusts, and the paths they may use.
+
+Pure (no ComfyUI imports), so the tests load it on its own.
+
+A trusted site is a Fuobe studio: https://fuobe.com unless you name others. Only an exact origin counts (scheme, host
+and port). A trusted site may use only what a Fuobe run needs: the facts about this ComfyUI, its queue and history,
+its results, uploading a run's inputs and queueing its prompt. It never reaches the Manager's install calls, your
+user files or settings: those stay behind ComfyUI's own check, as for every other website.
+"""
+
+from __future__ import annotations
+
+import re
+from urllib.parse import parse_qs, urlsplit
+
+DEFAULT_STUDIOS = ("https://fuobe.com",)
+
+# A site that is also reached under "www.".
+_WWW_TWINS = {"fuobe.com"}
+
+_DEFAULT_PORTS = {"http": 80, "https": 443}
+
+
+def normalise(origin: str | None) -> str | None:
+ """'https://Fuobe.com/' -> 'https://fuobe.com'. None for anything that isn't an http(s) origin."""
+ if not origin or not isinstance(origin, str):
+ return None
+ text = origin.strip()
+ if len(text) > 300:
+ return None
+ try:
+ u = urlsplit(text)
+ port = u.port
+ except ValueError:
+ return None
+ if u.scheme not in ("http", "https") or not u.hostname:
+ return None
+ if u.username or u.password or u.query or u.fragment or u.path not in ("", "/"):
+ return None
+ host = u.hostname.lower().rstrip(".")
+ if ":" in host:
+ host = f"[{host}]"
+ if port is not None and port != _DEFAULT_PORTS[u.scheme]:
+ return f"{u.scheme}://{host}:{port}"
+ return f"{u.scheme}://{host}"
+
+
+def parse_list(text: str | list | tuple | None) -> list[str]:
+ """A comma- or space-separated list (or a list) of origins: the valid ones, in order, without repeats."""
+ if text is None:
+ return []
+ items = text if isinstance(text, (list, tuple)) else re.split(r"[\s,]+", str(text))
+ out: list[str] = []
+ for item in items:
+ o = normalise(item) if isinstance(item, str) else None
+ if o and o not in out:
+ out.append(o)
+ return out
+
+
+def with_twins(origins: list[str]) -> list[str]:
+ out = list(origins)
+ for o in origins:
+ u = urlsplit(o)
+ if u.hostname in _WWW_TWINS:
+ twin = f"{u.scheme}://www.{u.hostname}" + (f":{u.port}" if u.port else "")
+ if twin not in out:
+ out.append(twin)
+ return out
+
+
+def trusted_origins(env_value: str | None, configured: str | list | None) -> tuple[str, ...]:
+ """FUOBE_CONNECT_ORIGINS when set, else the configured studios, else https://fuobe.com."""
+ for source in (env_value, configured):
+ found = parse_list(source)
+ if found:
+ return tuple(with_twins(found))
+ return tuple(with_twins(list(DEFAULT_STUDIOS)))
+
+
+# ---------------------------------------------------------------------------
+# What a trusted site may use (ComfyUI answers each path with and without "/api" in front).
+
+_GET = re.compile(
+ r"^/(?:"
+ r"system_stats|object_info(?:/[^/]{1,128})?|models(?:/[A-Za-z0-9_.-]{1,64})?|embeddings|queue|features"
+ r"|history(?:/[0-9a-f-]{36})?|jobs(?:/[0-9a-f-]{36})?|view|ws"
+ r"|experiment/models(?:/[A-Za-z0-9_.-]{1,64})?"
+ r"|(?:v2/)?manager/(?:version|queue/status)|(?:v2/)?customnode/installed"
+ r"|fuobe/connect|fuobe/guard"
+ r")$"
+)
+_POST = re.compile(
+ r"^/(?:upload/image|prompt|queue|interrupt|jobs/[0-9a-f-]{36}/cancel|(?:v2/)?customnode/import_fail_info(?:_bulk)?)$"
+)
+
+
+def _bare(path: str) -> str:
+ return path[4:] if path.startswith("/api/") else path
+
+
+def allowed(method: str, path: str, query: str = "") -> bool:
+ """May a trusted site send this? (`query`: the raw query string; /view is only for results.)"""
+ p = _bare(path)
+ m = method.upper()
+ if m in ("GET", "HEAD"):
+ if not _GET.match(p):
+ return False
+ if p == "/view":
+ q = parse_qs(query, keep_blank_values=True)
+ return q.get("type", ["output"])[0] in ("output", "temp")
+ return True
+ if m == "POST":
+ return bool(_POST.match(p))
+ return False
+
+
+def same_host(origin: str, host: str | None) -> bool:
+ """The page is ComfyUI's own (the origin's host and port are the Host header's)."""
+ try:
+ o = urlsplit(origin)
+ h = urlsplit("//" + (host or "").strip().lower())
+ if not o.hostname or not h.hostname or o.hostname.lower() != h.hostname:
+ return False
+ return o.port is None or h.port is None or o.port == h.port
+ except ValueError:
+ return False
diff --git a/integrations/fuobe-connect/fuobe_connect/plugin.py b/integrations/fuobe-connect/fuobe_connect/plugin.py
new file mode 100644
index 00000000..94b7de9b
--- /dev/null
+++ b/integrations/fuobe-connect/fuobe_connect/plugin.py
@@ -0,0 +1,126 @@
+"""Fuobe Connect inside ComfyUI: the middleware, its own small API for ComfyUI's page, and the pairing agent.
+
+ComfyUI loads custom nodes after it made its web app and before it starts serving, so the middleware can still be put
+in front of ComfyUI's own (once ComfyUI serves, the list is frozen and nothing can be added). Nothing in ComfyUI's own
+files changes.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+
+from aiohttp import web
+
+from . import __version__
+from .middleware import make_middleware, MARKER
+from .origins import normalise, parse_list, same_host, trusted_origins
+
+log = logging.getLogger("fuobe_connect")
+
+_state: dict = {}
+
+
+def trusted() -> tuple[str, ...]:
+ store = _state.get("store")
+ configured = store.load().get("studios") if store else None
+ return trusted_origins(os.environ.get("FUOBE_CONNECT_ORIGINS"), configured)
+
+
+def _own_page(request: web.Request) -> bool:
+ """A call from ComfyUI's own page, or from a program on this computer: never from a trusted studio or any website."""
+ if request.headers.get(MARKER):
+ return False
+ origin = request.headers.get("Origin")
+ return origin is None or same_host(origin, request.headers.get("Host"))
+
+
+async def status(request: web.Request) -> web.Response:
+ """GET /fuobe/connect. A studio sees only that Fuobe Connect is here; ComfyUI's own page sees the rest."""
+ base = {"connect": 1, "version": __version__, "guard": 1}
+ if not _own_page(request):
+ return web.json_response(base)
+ agent = _state.get("agent")
+ return web.json_response({**base, "studios": list(trusted()), "fromEnv": bool(os.environ.get("FUOBE_CONNECT_ORIGINS")), **(agent.status() if agent else {"state": "off"})})
+
+
+async def set_studios(request: web.Request) -> web.Response:
+ """POST /fuobe/connect/studios {studios: "https://a, https://b"}: the studios that may use this ComfyUI."""
+ if not _own_page(request):
+ return web.Response(status=403)
+ body = await request.json()
+ studios = parse_list(body.get("studios") if isinstance(body, dict) else None)
+ if not studios:
+ return web.json_response({"error": "Name at least one studio, like https://fuobe.com"}, status=400)
+ _state["store"].update(studios=studios)
+ return web.json_response({"studios": list(trusted())})
+
+
+async def pair(request: web.Request) -> web.Response:
+ """POST /fuobe/connect/pair {site?}: a code to approve on the studio."""
+ if not _own_page(request):
+ return web.Response(status=403)
+ agent = _state.get("agent")
+ try:
+ body = await request.json()
+ except ValueError:
+ body = {}
+ site = normalise((body or {}).get("site")) if isinstance(body, dict) else None
+ try:
+ fut = agent.call(agent.start_pairing(site or trusted()[0]))
+ import asyncio
+
+ return web.json_response(await asyncio.wrap_future(fut))
+ except Exception as e:
+ return web.json_response({"error": str(e)}, status=502)
+
+
+async def unpair(request: web.Request) -> web.Response:
+ if not _own_page(request):
+ return web.Response(status=403)
+ import asyncio
+
+ agent = _state["agent"]
+ agent.cancel_pairing()
+ return web.json_response(await asyncio.wrap_future(agent.call(agent.unpair())))
+
+
+def install():
+ """Called once when ComfyUI loads this custom node."""
+ import folder_paths
+ import server
+ from comfy.cli_args import args
+
+ from .agent import Agent
+ from .net import loopback_base
+ from .store import Store
+
+ instance = getattr(server.PromptServer, "instance", None)
+ if instance is None:
+ log.warning("[Fuobe Connect] ComfyUI's server isn't there, so Fuobe Connect is off.")
+ return
+ app = instance.app
+ if any(getattr(m, "__name__", "") == "fuobe_connect" for m in app.middlewares):
+ return
+ store = Store(folder_paths.get_user_directory())
+ _state["store"] = store
+ try:
+ app.middlewares.insert(0, make_middleware(trusted, getattr(args, "enable_cors_header", None)))
+ except RuntimeError:
+ log.warning("[Fuobe Connect] ComfyUI had already started, so Fuobe Connect is off. Restart ComfyUI.")
+ return
+ instance.routes.get("/fuobe/connect")(status)
+ instance.routes.post("/fuobe/connect/studios")(set_studios)
+ instance.routes.post("/fuobe/connect/pair")(pair)
+ instance.routes.post("/fuobe/connect/unpair")(unpair)
+
+ port = int(getattr(args, "port", 8188) or 8188)
+ agent = Agent(store, loopback_base(getattr(args, "listen", None), port, bool(getattr(args, "tls_keyfile", None))), port, trusted()[0])
+ _state["agent"] = agent
+ agent.start()
+ log.info("[Fuobe Connect] %s can use this ComfyUI from the browser.", ", ".join(trusted()))
+ if os.environ.get("FUOBE_CONNECT_PAIR") == "1" and not store.load().get("token"):
+ # A PC with no screen: the code and the address go to ComfyUI's console.
+ agent.call(agent.start_pairing(os.environ.get("FUOBE_CONNECT_SITE") or trusted()[0]))
+ elif not store.load().get("token"):
+ log.info("[Fuobe Connect] To run Fuobe jobs here with no browser tab open: ComfyUI menu → Extensions → Connect to Fuobe.")
diff --git a/integrations/fuobe-connect/fuobe_connect/runner.py b/integrations/fuobe-connect/fuobe_connect/runner.py
new file mode 100644
index 00000000..43e7622a
--- /dev/null
+++ b/integrations/fuobe-connect/fuobe_connect/runner.py
@@ -0,0 +1,611 @@
+"""Running a person's Fuobe jobs on this ComfyUI, after pairing.
+
+The same protocol the Fuobe tab speaks (src/lib/computer-runner.ts in the Fuobe repo): beat to say this computer is
+here, claim the person's next job, send its inputs and its exact graph to this ComfyUI, follow it, report back, and
+upload the results the studio asks for. It decides nothing about a result. Only that person's jobs reach it: the studio
+picks them by the token, which belongs to one person.
+
+A job's graph may read only the files that job sent, and a result is uploaded only when this job's own prompt saved it
+(graph.py). One job at a time.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import json
+import logging
+import time
+import uuid
+
+import aiohttp
+
+from .graph import graph_problem, has_prefix, may_download, safe_wanted, slim, UUID
+from .net import Comfy, Site
+
+log = logging.getLogger("fuobe_connect")
+
+BEAT_S = 10
+BUSY_BEAT_S = 5
+POLL_S = 1.0
+PROGRESS_EVERY_S = 0.5
+PART_BYTES = 16 * 2**20
+SAVE_WAIT_S = 60 * 60
+
+
+class Stopped(Exception):
+ """The job ended on the studio, or another computer has it now: let go of it."""
+
+
+class Unpaired(Exception):
+ """The studio no longer knows this token."""
+
+
+def _retry_after(headers: dict) -> float:
+ try:
+ return min(30.0, max(1.0, float(headers.get("Retry-After") or headers.get("retry-after") or 2)))
+ except ValueError:
+ return 2.0
+
+
+class Runner:
+ def __init__(self, site: Site, comfy: Comfy, device: str, port: int, on_state=None, sleep=asyncio.sleep, clock=time.monotonic):
+ self.site = site
+ self.comfy = comfy
+ self.device = device
+ self.port = port
+ self.client_id = uuid.uuid4().hex
+ self.on_state = on_state or (lambda state, message=None: None)
+ self.sleep = sleep
+ self.clock = clock
+ self.alive = True
+ self.jobs: dict[str, dict] = {}
+ self.events: dict[str, dict] = {}
+ self.stopped_done: set[str] = set()
+ self.stopping: set[str] = set()
+ self.jobs_api: bool | None = None
+ self.facts_at = -1e9
+ self.loras_at = -1e9
+ self.runner = False
+ self.ws_task: asyncio.Task | None = None
+ self.ws_open = False
+ self.comfy_ok = False
+
+ # ------------------------------------------------------------------
+ # This ComfyUI
+
+ async def look(self) -> dict | None:
+ try:
+ stats = await self.comfy.get_json("/system_stats", timeout=10)
+ self.comfy_ok = True
+ return stats
+ except Exception:
+ self.comfy_ok = False
+ return None
+
+ async def facts(self, loras: bool) -> dict | None:
+ s = await self.look()
+ if not s:
+ return None
+ system = s.get("system") or {}
+ dev = (s.get("devices") or [{}])[0] or {}
+ f = {"guard": True}
+ if isinstance(dev.get("name"), str):
+ f["device"] = dev["name"][:120]
+ if isinstance(dev.get("vram_total"), (int, float)):
+ f["vramBytes"] = dev["vram_total"]
+ if isinstance(system.get("ram_total"), (int, float)):
+ f["ramBytes"] = system["ram_total"]
+ if system.get("comfyui_version"):
+ f["version"] = str(system["comfyui_version"])[:40]
+ if system.get("os"):
+ f["os"] = str(system["os"])[:40]
+ if isinstance(system.get("embedded_python"), bool):
+ f["portable"] = system["embedded_python"]
+ if loras:
+ try:
+ names = await self.comfy.get_json("/models/loras")
+ if isinstance(names, list):
+ f["loras"] = [n for n in names if isinstance(n, str)][:20000]
+ except Exception:
+ pass
+ return f
+
+ def _socket(self):
+ if self.ws_task and not self.ws_task.done():
+ return
+ self.ws_task = asyncio.ensure_future(self._listen())
+
+ async def _listen(self):
+ try:
+ async with self.comfy.session.ws_connect(self.comfy.ws_url(self.client_id), heartbeat=30, ssl=self.comfy._ssl) as ws:
+ self.ws_open = True
+ async for msg in ws:
+ if msg.type != aiohttp.WSMsgType.TEXT:
+ continue
+ try:
+ m = json.loads(msg.data)
+ except ValueError:
+ continue
+ d = m.get("data") if isinstance(m, dict) and isinstance(m.get("data"), dict) else {}
+ pid = d.get("prompt_id")
+ if not isinstance(pid, str):
+ continue
+ cur = self.events.setdefault(pid, {"nodesDone": 0})
+ t = m.get("type")
+ if t == "progress" and isinstance(d.get("value"), (int, float)) and isinstance(d.get("max"), (int, float)):
+ cur.update(value=d["value"], max=d["max"], node=d.get("node"))
+ elif t == "executing" and d.get("node"):
+ cur.update(node=d["node"], nodesDone=cur["nodesDone"] + 1, value=None, max=None)
+ except Exception:
+ pass
+ finally:
+ self.ws_open = False
+
+ async def where(self, prompt_id: str, prefix: str | None = None) -> dict:
+ if self.jobs_api is None:
+ try:
+ await self.comfy.get_json("/api/jobs")
+ self.jobs_api = True
+ except Exception:
+ self.jobs_api = False
+ if self.jobs_api:
+ status, j = await self.comfy.get_status(f"/api/jobs/{prompt_id}")
+ if status == 404:
+ return await self.where_by_queue(prompt_id) if prefix else {"s": "absent"}
+ if status != 200:
+ raise RuntimeError(f"ComfyUI answered HTTP {status}")
+ st = (j or {}).get("status")
+ if st == "in_progress":
+ return {"s": "running"}
+ if st == "pending":
+ return await self.where_by_queue(prompt_id)
+ entry = (await self.comfy.get_json(f"/history/{prompt_id}")).get(prompt_id)
+ return {"s": "done", "entry": entry} if entry else {"s": "absent"}
+ entry = (await self.comfy.get_json(f"/history/{prompt_id}")).get(prompt_id)
+ if entry and ((entry.get("status") or {}).get("completed") or (entry.get("status") or {}).get("status_str")):
+ return {"s": "done", "entry": entry}
+ return await self.where_by_queue(prompt_id)
+
+ async def where_by_queue(self, prompt_id: str) -> dict:
+ q = await self.comfy.get_json("/queue")
+ running = q.get("queue_running") or []
+ if any(len(r) > 1 and r[1] == prompt_id for r in running):
+ return {"s": "running"}
+ pending = sorted(q.get("queue_pending") or [], key=lambda r: float(r[0]) if r else 0)
+ for i, r in enumerate(pending):
+ if len(r) > 1 and r[1] == prompt_id:
+ return {"s": "pending", "ahead": i + len(running)}
+ entry = (await self.comfy.get_json(f"/history/{prompt_id}")).get(prompt_id)
+ return {"s": "done", "entry": entry} if entry else {"s": "absent"}
+
+ # ------------------------------------------------------------------
+ # The studio
+
+ async def report(self, t: dict, event: dict) -> dict:
+ until = self.clock() + 120
+ tries = 0
+ while True:
+ a = await self.site.call("POST", f"/api/gpu/computer/tasks/{t['id']}/report", event, headers={"X-Fuobe-Lease": t["lease"]})
+ if a.status == 200:
+ return a.body
+ if a.status == 401:
+ raise Unpaired()
+ if a.status in (404, 409):
+ raise Stopped()
+ if a.status == 429 and self.clock() < until:
+ await self.sleep(_retry_after(a.headers))
+ continue
+ tries += 1
+ if tries > 4:
+ raise RuntimeError(f"The studio answered HTTP {a.status}")
+ await self.sleep(tries)
+
+ async def beat(self) -> dict | None:
+ now = self.clock()
+ due = now - self.facts_at > 60
+ loras = due and now - self.loras_at > 300
+ read = await self.facts(loras) if due else (await self.look() and {})
+ body: dict = {"device": self.device, "port": self.port, "ready": read is not None}
+ if due and read:
+ self.facts_at = now
+ if loras:
+ self.loras_at = now
+ body["facts"] = read
+ running = []
+ for task_id, j in self.jobs.items():
+ if j["phase"] in ("done", "failed"):
+ continue
+ item = {"task": task_id}
+ if j.get("position") is not None:
+ item["position"] = j["position"]
+ ev = self.events.get(j.get("promptId", ""))
+ if j["phase"] == "running" and ev:
+ item.update({k: ev[k] for k in ("value", "max", "nodesDone") if ev.get(k) is not None})
+ running.append(item)
+ body["running"] = running
+ stopped = list(self.stopped_done)
+ if stopped:
+ body["stopped"] = stopped
+ a = await self.site.call("POST", "/api/gpu/computer/beat", body)
+ if a.status == 401:
+ raise Unpaired()
+ if a.status != 200:
+ self.runner = False
+ self.on_state("waiting", a.body.get("error") or f"The studio answered HTTP {a.status}")
+ return None
+ for s in stopped:
+ self.stopped_done.discard(s)
+ self.runner = bool(a.body.get("runner"))
+ if not self.comfy_ok:
+ self.on_state("comfy-down", "ComfyUI isn't answering here.")
+ elif self.runner:
+ self.on_state("connected", None)
+ else:
+ self.on_state("elsewhere", "Another computer runs your Fuobe jobs now.")
+ for s in a.body.get("stops") or []:
+ asyncio.ensure_future(self.take_off(s))
+ return a.body
+
+ async def take_off(self, s: dict):
+ task_id = s.get("task")
+ pid = s.get("promptId")
+ if not isinstance(task_id, str) or task_id in self.stopping or not isinstance(pid, str) or not UUID.match(pid):
+ return
+ self.stopping.add(task_id)
+ try:
+ if self.jobs_api is not False:
+ status, _ = await self.comfy.post_json(f"/api/jobs/{pid}/cancel", {})
+ if status == 404:
+ self.jobs_api = False
+ if self.jobs_api is False:
+ await self.comfy.post_json("/queue", {"delete": [pid]})
+ q = await self.comfy.get_json("/queue")
+ if any(len(r) > 1 and r[1] == pid for r in q.get("queue_running") or []):
+ await self.comfy.post_json("/interrupt", {"prompt_id": pid})
+ prefix = s.get("prefix")
+ if isinstance(prefix, str) and prefix:
+ for _ in range(5):
+ q = await self.comfy.get_json("/queue")
+ ids = [str(r[1]) for r in (q.get("queue_running") or []) + (q.get("queue_pending") or []) if len(r) > 2 and has_prefix(r[2], prefix)]
+ if not ids:
+ break
+ for i in ids:
+ await self.comfy.post_json(f"/api/jobs/{i}/cancel", {})
+ await self.sleep(1)
+ self.stopped_done.add(task_id)
+ except Exception as e:
+ log.warning("[Fuobe Connect] Couldn't stop a job: %s", e)
+ finally:
+ self.stopping.discard(task_id)
+ j = self.jobs.get(task_id)
+ if j and j["phase"] != "done":
+ j["phase"] = "failed"
+
+ async def claim_and_run(self) -> bool:
+ if not self.alive or not self.runner or not await self.look():
+ return False
+ running = [k for k, j in self.jobs.items() if j["phase"] not in ("done", "failed")]
+ a = await self.site.call("POST", "/api/gpu/computer/claim", {"device": self.device, "running": running})
+ if a.status == 401:
+ raise Unpaired()
+ if a.status != 200:
+ return False
+ t = a.body.get("task")
+ if not isinstance(t, dict):
+ return False
+ try:
+ await self.run(t)
+ except (Stopped, asyncio.CancelledError):
+ raise
+ except Unpaired:
+ raise
+ except Exception as e:
+ log.warning("[Fuobe Connect] A job stopped here: %s", e)
+ self.jobs.pop(t["id"], None)
+ return True
+
+ # ------------------------------------------------------------------
+ # One job
+
+ def _job(self, t: dict, **patch):
+ j = self.jobs.setdefault(t["id"], {"phase": "sending", "promptId": t.get("promptId")})
+ j.update(patch)
+ done = [k for k, v in self.jobs.items() if v["phase"] in ("done", "failed")]
+ for k in done[:-6]:
+ self.jobs.pop(k, None)
+
+ async def run(self, t: dict):
+ resume = t.get("resume")
+ self._job(t, phase={"collecting": "saving", "running": "running", "queued": "queued"}.get(resume, "sending"), promptId=t.get("promptId"))
+ try:
+ names = [i["name"] for i in t.get("inputs") or []]
+ if graph_problem(t.get("graph"), names):
+ await self.report(t, {"event": "failed", "reason": "unsafe-graph"})
+ return self._job(t, phase="failed")
+ entries = None
+ wanted = t.get("wanted")
+ phase = resume or "sending"
+ for _ in range(3):
+ if phase == "collecting":
+ break
+ if phase == "sending" and not await self.send_job(t):
+ return
+ self._socket()
+ done = await self.follow(t)
+ if done == "gone":
+ a = await self.report(t, {"event": "gone"})
+ if a.get("state") != "sending":
+ return self._job(t, phase="failed")
+ phase = "sending"
+ continue
+ entries = done["entries"]
+ if not done["answer"].get("wanted"):
+ return self._job(t, phase="done" if done["answer"].get("state") == "done" else "failed")
+ wanted = done["answer"]["wanted"]
+ phase = "collecting"
+ if phase != "collecting" or not wanted:
+ return
+ if entries is None:
+ entries = await self.own_entries(t)
+ await self.collect(t, wanted, entries, t.get("received") or [])
+ except Stopped:
+ self._job(t, phase="failed")
+
+ async def own_entries(self, t: dict) -> list:
+ try:
+ own = (await self.comfy.get_json(f"/history/{t['promptId']}")).get(t["promptId"])
+ except Exception:
+ own = None
+ passes = []
+ if t.get("prefix"):
+ try:
+ recent = await self.comfy.get_json("/history?max_items=64")
+ passes = [e for e in recent.values() if has_prefix((e.get("prompt") or [None, None, None])[2], t["prefix"])]
+ except Exception:
+ pass
+ return ([own] if own else []) + passes
+
+ async def wait_for_comfy(self, t: dict):
+ told = False
+ while True:
+ if not self.alive:
+ raise Stopped()
+ if await self.look():
+ return
+ if not told:
+ a = await self.report(t, {"event": "comfy-down"})
+ if a.get("stop"):
+ raise Stopped()
+ told = True
+ await self.sleep(3)
+
+ async def send_job(self, t: dict) -> bool:
+ self._job(t, phase="sending")
+ try:
+ there = await self.where(t["promptId"])
+ except Exception:
+ there = None
+ if there and there["s"] != "absent":
+ await self.report(t, {"event": "sent", "promptId": t["promptId"]})
+ return True
+ if there is None:
+ await self.wait_for_comfy(t)
+ for inp in t.get("inputs") or []:
+ status, data, headers = await self.site.read(f"/api/gpu/computer/tasks/{t['id']}/inputs/{inp['n']}", headers={"X-Fuobe-Lease": t["lease"]})
+ if status == 401:
+ raise Unpaired()
+ if status in (404, 409):
+ raise Stopped()
+ if status != 200:
+ raise RuntimeError(f"The studio answered HTTP {status} for a file")
+ if hashlib.sha256(data).hexdigest() != inp.get("sha256"):
+ await self.report(t, {"event": "failed", "reason": "input-changed"})
+ self._job(t, phase="failed")
+ return False
+ try:
+ up = await self.comfy.upload_input(inp["name"], data, inp.get("contentType") or "application/octet-stream")
+ except Exception:
+ await self.wait_for_comfy(t)
+ return await self.send_job(t)
+ if up != 200:
+ await self.report(t, {"event": "failed", "reason": "input-too-big" if up == 413 else "comfy-error", "status": up})
+ self._job(t, phase="failed")
+ return False
+ body = {"prompt": t["graph"], "prompt_id": t["promptId"], "client_id": self.client_id}
+ if t.get("preview"):
+ body["extra_data"] = {"preview_method": "auto"}
+ try:
+ status, answer = await self.comfy.post_json("/prompt", body)
+ except Exception:
+ await self.wait_for_comfy(t)
+ return await self.send_job(t)
+ if status == 400:
+ await self.report(t, {"event": "refused", "status": 400, "body": answer})
+ self._job(t, phase="failed")
+ return False
+ if status != 200 or not isinstance(answer.get("prompt_id"), str):
+ await self.report(t, {"event": "failed", "reason": "comfy-error", "status": status})
+ self._job(t, phase="failed")
+ return False
+ if answer["prompt_id"] != t["promptId"]:
+ t["promptId"] = answer["prompt_id"]
+ self._job(t, promptId=t["promptId"])
+ ev = {"event": "sent", "promptId": answer["prompt_id"]}
+ if isinstance(answer.get("number"), (int, float)):
+ ev["number"] = answer["number"]
+ await self.report(t, ev)
+ return True
+
+ async def follow(self, t: dict):
+ last_sent = -1e9
+ last_key = ""
+ following = None
+ while True:
+ if not self.alive:
+ raise Stopped()
+ if following:
+ try:
+ q = await self.comfy.get_json("/queue")
+ except Exception:
+ await self.wait_for_comfy(t)
+ continue
+ running = any(len(r) > 2 and has_prefix(r[2], following) for r in (q.get("queue_running") or []) + (q.get("queue_pending") or []))
+ try:
+ recent = await self.comfy.get_json("/history?max_items=64")
+ except Exception:
+ recent = {}
+ passes = [e for e in recent.values() if has_prefix((e.get("prompt") or [None, None, None])[2], following)]
+ a = await self.report(t, {"event": "passes", "running": running, "entries": [] if running else [slim(e) for e in passes]})
+ if a.get("stop"):
+ raise Stopped()
+ if not running:
+ return {"entries": passes, "answer": a}
+ self._job(t, phase="running")
+ await self.sleep(POLL_S * 2)
+ continue
+ try:
+ w = await self.where(t["promptId"])
+ except Exception:
+ await self.wait_for_comfy(t)
+ continue
+ if w["s"] == "absent":
+ return "gone"
+ if w["s"] == "done":
+ a = await self.report(t, {"event": "finished", "entry": slim(w["entry"])})
+ if a.get("stop"):
+ raise Stopped()
+ if a.get("follow"):
+ following = a["follow"]
+ continue
+ return {"entries": [w["entry"]], "answer": a}
+ ev = self.events.get(t["promptId"]) or {}
+ if w["s"] == "pending":
+ rep = {"event": "queued", "position": w["ahead"]}
+ else:
+ rep = {"event": "running", **{k: ev[k] for k in ("value", "max", "node", "nodesDone") if ev.get(k) is not None}}
+ key = json.dumps(rep, sort_keys=True)
+ if key != last_key and self.clock() - last_sent >= PROGRESS_EVERY_S:
+ a = await self.report(t, rep)
+ if a.get("stop"):
+ raise Stopped()
+ last_key = key
+ last_sent = self.clock()
+ self._job(t, phase="queued" if w["s"] == "pending" else "running", position=w.get("ahead"))
+ await self.sleep(PROGRESS_EVERY_S if self.ws_open else POLL_S)
+
+ async def collect(self, t: dict, wanted: list, entries: list, received: list):
+ self._job(t, phase="saving")
+ for w in wanted:
+ got = next((r for r in received if r.get("n") == w.get("n")), None)
+ if got and got.get("done"):
+ continue
+ if not safe_wanted(w) or not may_download(w, entries):
+ await self.report(t, {"event": "failed", "reason": "output-missing"})
+ return self._job(t, phase="failed")
+ data = await self.comfy.view(w["filename"], w.get("subfolder") or "", w["type"])
+ if data is None:
+ await self.report(t, {"event": "failed", "reason": "output-missing"})
+ return self._job(t, phase="failed")
+ offset = (got or {}).get("bytes") or 0
+ if offset > 0:
+ s = await self.site.call("GET", f"/api/gpu/computer/tasks/{t['id']}/outputs/{w['n']}", headers={"X-Fuobe-Lease": t["lease"]})
+ offset = s.body.get("received", 0) if s.status == 200 else 0
+ if not await self.upload(t, w, data, offset):
+ return self._job(t, phase="failed")
+ self._job(t, phase="done")
+
+ async def upload(self, t: dict, w: dict, data: bytes, offset: int) -> bool:
+ fails = 0
+ until = self.clock() + SAVE_WAIT_S
+ total = len(data)
+ while offset < total or total == 0:
+ if not self.alive:
+ raise Stopped()
+ part = data[offset : offset + PART_BYTES]
+ try:
+ a = await self.site.call(
+ "PUT",
+ f"/api/gpu/computer/tasks/{t['id']}/outputs/{w['n']}?offset={offset}&total={total}",
+ data=part,
+ headers={"X-Fuobe-Lease": t["lease"], "Content-Type": "application/octet-stream"},
+ timeout=600,
+ )
+ except Exception:
+ a = None
+ if a and a.status == 200:
+ offset = int(a.body.get("received", offset))
+ fails = 0
+ if a.body.get("done"):
+ return True
+ continue
+ if a and a.status == 429 and self.clock() < until:
+ await self.sleep(_retry_after(a.headers))
+ continue
+ if a and a.status in (404, 413, 415):
+ return False
+ if a and a.status == 401:
+ raise Unpaired()
+ if a and a.status == 409:
+ s = await self.site.call("GET", f"/api/gpu/computer/tasks/{t['id']}/outputs/{w['n']}", headers={"X-Fuobe-Lease": t["lease"]})
+ if s.status != 200:
+ return False
+ if s.body.get("done"):
+ return True
+ offset = int(s.body.get("received", 0))
+ fails += 1
+ if fails >= 3:
+ try:
+ await self.report(t, {"event": "failed", "reason": "save-failed"})
+ except Exception:
+ pass
+ return False
+ await self.sleep(1.5 * fails)
+ return True
+
+ # ------------------------------------------------------------------
+ # The loops
+
+ async def beat_loop(self):
+ while self.alive:
+ busy = any(j["phase"] not in ("done", "failed") for j in self.jobs.values())
+ try:
+ a = await self.beat()
+ wait = BUSY_BEAT_S if busy or (a and a.get("waiting")) else BEAT_S
+ if a is None:
+ wait = 30
+ except Unpaired:
+ raise
+ except Exception as e:
+ self.on_state("offline", f"Can't reach the studio: {e}")
+ wait = 30
+ await self.sleep(wait)
+
+ async def work_loop(self):
+ while self.alive:
+ try:
+ did = await self.claim_and_run()
+ except Stopped:
+ did = True
+ except Unpaired:
+ raise
+ except Exception as e:
+ log.warning("[Fuobe Connect] %s", e)
+ did = False
+ if not did:
+ await self.sleep(2)
+
+ async def run_forever(self):
+ """Beat and work until stopped. Raises Unpaired when the studio forgot this token."""
+ beats = asyncio.ensure_future(self.beat_loop())
+ work = asyncio.ensure_future(self.work_loop())
+ try:
+ done, _ = await asyncio.wait({beats, work}, return_when=asyncio.FIRST_EXCEPTION)
+ for d in done:
+ if d.exception():
+ raise d.exception()
+ finally:
+ self.alive = False
+ for task in (beats, work, self.ws_task):
+ if task and not task.done():
+ task.cancel()
diff --git a/integrations/fuobe-connect/fuobe_connect/store.py b/integrations/fuobe-connect/fuobe_connect/store.py
new file mode 100644
index 00000000..302bb207
--- /dev/null
+++ b/integrations/fuobe-connect/fuobe_connect/store.py
@@ -0,0 +1,48 @@
+"""Fuobe Connect's own small file: the studios this ComfyUI trusts, and its pairing (the studio and its token).
+
+It lives in ComfyUI's user folder, beside (not inside) the folder ComfyUI serves as user data, and only this Windows
+or Unix user may read it.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import threading
+
+FILE_NAME = "fuobe-connect.json"
+
+
+class Store:
+ def __init__(self, folder: str):
+ self.path = os.path.join(folder, FILE_NAME)
+ self._lock = threading.Lock()
+
+ def load(self) -> dict:
+ try:
+ with open(self.path, "r", encoding="utf-8") as f:
+ data = json.load(f)
+ return data if isinstance(data, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+ def update(self, **changes) -> dict:
+ """Change some keys (None removes one) and save at once."""
+ with self._lock:
+ data = self.load()
+ for k, v in changes.items():
+ if v is None:
+ data.pop(k, None)
+ else:
+ data[k] = v
+ os.makedirs(os.path.dirname(self.path) or ".", exist_ok=True)
+ tmp = self.path + ".tmp"
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
+ json.dump(data, f, indent=2)
+ os.replace(tmp, self.path)
+ try:
+ os.chmod(self.path, 0o600)
+ except OSError:
+ pass
+ return data
diff --git a/integrations/fuobe-connect/pyproject.toml b/integrations/fuobe-connect/pyproject.toml
new file mode 100644
index 00000000..8f2e3018
--- /dev/null
+++ b/integrations/fuobe-connect/pyproject.toml
@@ -0,0 +1,16 @@
+[project]
+name = "comfyui-fuobe-connect"
+description = "Use this ComfyUI from Fuobe with one install: no start flag, no extra file. Trusts only the Fuobe studios you name, keeps ComfyUI's own check for every other website, and can pair with your Fuobe account for Safari, phones and PCs with no screen."
+version = "1.0.0"
+license = { file = "LICENSE" }
+dependencies = []
+
+[project.urls]
+Repository = "https://github.com/workingprototype/ComfyUI-Fuobe-Connect"
+Documentation = "https://github.com/workingprototype/Fuobe/blob/main/docs/gpu-workers.md"
+
+[tool.comfy]
+PublisherId = "workingprototype"
+DisplayName = "Fuobe Connect"
+Icon = ""
+includes = []
diff --git a/integrations/fuobe-connect/tests/comfy_stack.py b/integrations/fuobe-connect/tests/comfy_stack.py
new file mode 100644
index 00000000..41c68795
--- /dev/null
+++ b/integrations/fuobe-connect/tests/comfy_stack.py
@@ -0,0 +1,157 @@
+"""A stand-in ComfyUI web app for the tests, with ComfyUI's own middleware.
+
+With COMFYUI_DIR set to a ComfyUI folder, the middleware functions are read from that ComfyUI's own server.py and
+middleware/cache_middleware.py (only those functions: nothing else of ComfyUI is imported, so no models, no GPU and no
+torch are needed). Without it, a copy of ComfyUI 0.42's origin check is used. Either way the app is built the way
+ComfyUI's PromptServer builds it: [cache_control, deprecation_warning] then the CORS middleware when started with
+--enable-cors-header, else the origin check. Fuobe Connect then goes in front, as in ComfyUI.
+
+The routes answer like ComfyUI's, with fixed values: enough to see who gets in.
+"""
+
+from __future__ import annotations
+
+import ast
+import ipaddress
+import json
+import logging
+import os
+import socket
+import urllib
+import urllib.parse
+
+from aiohttp import web
+
+WANTED = {"create_cors_middleware", "is_loopback", "create_origin_only_middleware", "deprecation_warning"}
+
+
+def _from_comfyui(folder: str) -> dict:
+ ns: dict = {"web": web, "urllib": urllib, "ipaddress": ipaddress, "socket": socket, "logging": logging, "_deprecated_paths_warned": set()}
+ with open(os.path.join(folder, "server.py"), encoding="utf-8") as f:
+ tree = ast.parse(f.read())
+ picked = [n for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name in WANTED]
+ missing = WANTED - {n.name for n in picked}
+ if missing:
+ raise RuntimeError(f"ComfyUI's server.py has no {', '.join(sorted(missing))}")
+ exec(compile(ast.Module(body=picked, type_ignores=[]), "comfyui/server.py", "exec"), ns)
+ with open(os.path.join(folder, "middleware", "cache_middleware.py"), encoding="utf-8") as f:
+ exec(compile(f.read(), "comfyui/middleware/cache_middleware.py", "exec"), ns)
+ ns["source"] = f"ComfyUI at {folder}"
+ return ns
+
+
+def _copy() -> dict:
+ """ComfyUI 0.42's origin check and CORS middleware, as they are in its server.py."""
+
+ def create_cors_middleware(allowed_origin):
+ @web.middleware
+ async def cors_middleware(request, handler):
+ response = web.Response() if request.method == "OPTIONS" else await handler(request)
+ response.headers["Access-Control-Allow-Origin"] = allowed_origin
+ response.headers["Access-Control-Allow-Methods"] = "POST, GET, DELETE, PUT, OPTIONS, PATCH"
+ response.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
+ response.headers["Access-Control-Allow-Credentials"] = "true"
+ return response
+
+ return cors_middleware
+
+ def is_loopback(host):
+ if host is None:
+ return False
+ try:
+ return ipaddress.ip_address(host).is_loopback
+ except ValueError:
+ pass
+ return host == "localhost"
+
+ def create_origin_only_middleware():
+ @web.middleware
+ async def origin_only_middleware(request, handler):
+ if request.headers.get("Sec-Fetch-Site") == "cross-site":
+ return web.Response(status=403)
+ if "Host" in request.headers and "Origin" in request.headers:
+ host_domain = request.headers["Host"].lower()
+ parsed = urllib.parse.urlparse(request.headers["Origin"])
+ origin_domain = parsed.netloc.lower()
+ host_parsed = urllib.parse.urlsplit("//" + host_domain)
+ loopback = is_loopback(host_parsed.hostname)
+ if parsed.port is None:
+ host_domain = host_parsed.hostname
+ if host_parsed.port is None:
+ origin_domain = parsed.hostname
+ if loopback and host_domain and origin_domain and host_domain != origin_domain:
+ return web.Response(status=403)
+ return web.Response() if request.method == "OPTIONS" else await handler(request)
+
+ return origin_only_middleware
+
+ @web.middleware
+ async def deprecation_warning(request, handler):
+ return await handler(request)
+
+ @web.middleware
+ async def cache_control(request, handler):
+ return await handler(request)
+
+ return {
+ "create_cors_middleware": create_cors_middleware,
+ "create_origin_only_middleware": create_origin_only_middleware,
+ "deprecation_warning": deprecation_warning,
+ "cache_control": cache_control,
+ "source": "a copy of ComfyUI 0.42's checks",
+ }
+
+
+def comfy_middleware() -> dict:
+ folder = os.environ.get("COMFYUI_DIR")
+ return _from_comfyui(folder) if folder else _copy()
+
+
+def build_app(cors_flag: str | None = None, fuobe_connect=None, extra_routes=None) -> tuple[web.Application, str]:
+ ns = comfy_middleware()
+ middlewares = [ns["cache_control"], ns["deprecation_warning"]]
+ middlewares.append(ns["create_cors_middleware"](cors_flag) if cors_flag else ns["create_origin_only_middleware"]())
+ app = web.Application(middlewares=middlewares)
+ routes = web.RouteTableDef()
+
+ @routes.get("/system_stats")
+ async def stats(request):
+ return web.json_response({"system": {"os": "nt", "comfyui_version": "0.42.0", "ram_total": 1}, "devices": [{"name": "cuda:0 Test GPU", "vram_total": 2}]})
+
+ @routes.post("/prompt")
+ async def prompt(request):
+ body = await request.json()
+ return web.json_response({"prompt_id": body.get("prompt_id"), "number": 1})
+
+ @routes.get("/view")
+ async def view(request):
+ return web.Response(body=b"\x89PNG\r\n\x1a\nfake", content_type="image/png")
+
+ @routes.get("/userdata/{file}")
+ async def userdata(request):
+ return web.json_response({"secret": "settings"})
+
+ @routes.post("/v2/manager/queue/install")
+ async def install(request):
+ return web.json_response({"installed": True})
+
+ @routes.get("/ws")
+ async def ws(request):
+ sock = web.WebSocketResponse()
+ await sock.prepare(request)
+ await sock.send_str(json.dumps({"type": "status", "data": {"sid": "x"}}))
+ await sock.close()
+ return sock
+
+ for method, path, handler in extra_routes or []:
+ routes.route(method, path)(handler)
+
+ # ComfyUI answers every route under /api too.
+ api = web.RouteTableDef()
+ for r in routes:
+ api.route(r.method, "/api" + r.path)(r.handler)
+ app.add_routes(api)
+ app.add_routes(routes)
+ if fuobe_connect is not None:
+ app.middlewares.insert(0, fuobe_connect)
+ return app, ns["source"]
diff --git a/integrations/fuobe-connect/tests/pair_and_run.py b/integrations/fuobe-connect/tests/pair_and_run.py
new file mode 100644
index 00000000..d39e507e
--- /dev/null
+++ b/integrations/fuobe-connect/tests/pair_and_run.py
@@ -0,0 +1,63 @@
+"""Fuobe Connect's pairing and job runner outside ComfyUI, for the end-to-end test (tests/e2e/fuobe-connect.mjs in the
+Fuobe repo): it asks the studio for a code, prints it as one JSON line, waits for the approval, then runs that person's
+jobs on the ComfyUI at --comfy until it is stopped (or unpaired).
+
+ python tests/pair_and_run.py --site http://127.0.0.1:3361 --comfy http://127.0.0.1:3362
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import os
+import sys
+
+import aiohttp
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from fuobe_connect.net import Comfy, Site # noqa: E402
+from fuobe_connect.runner import Runner, Unpaired # noqa: E402
+
+
+def say(**kw):
+ print(json.dumps(kw), flush=True)
+
+
+async def main(site_url: str, comfy_url: str, name: str, token: str | None):
+ async with aiohttp.ClientSession() as session:
+ site = Site(session, site_url)
+ if not token:
+ a = await site.pair_start(name, {"device": "Test GPU", "vramBytes": 8 * 2**30})
+ if a.status != 200:
+ say(event="error", status=a.status, body=a.body)
+ return 2
+ say(event="code", code=a.body["code"], url=a.body["url"])
+ for _ in range(300):
+ await asyncio.sleep(0.5)
+ p = await site.pair_poll(a.body["id"], a.body["secret"])
+ if p.status == 200 and p.body.get("state") == "approved":
+ token = p.body["token"]
+ say(event="paired", workerId=p.body["workerId"], token=token)
+ break
+ if p.status == 404:
+ say(event="gone")
+ return 3
+ runner = Runner(Site(session, site_url, token), Comfy(session, comfy_url), f"connect-{name}", int(comfy_url.rsplit(":", 1)[1]), on_state=lambda s, m=None: say(event="state", state=s, message=m))
+ try:
+ await runner.run_forever()
+ except Unpaired:
+ say(event="unpaired")
+ return 4
+ return 0
+
+
+if __name__ == "__main__":
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--site", required=True)
+ ap.add_argument("--comfy", required=True)
+ ap.add_argument("--name", default="test-pc")
+ ap.add_argument("--token")
+ args = ap.parse_args()
+ sys.exit(asyncio.run(main(args.site, args.comfy, args.name, args.token)))
diff --git a/integrations/fuobe-connect/tests/test_middleware.py b/integrations/fuobe-connect/tests/test_middleware.py
new file mode 100644
index 00000000..63469372
--- /dev/null
+++ b/integrations/fuobe-connect/tests/test_middleware.py
@@ -0,0 +1,271 @@
+"""Fuobe Connect's middleware in front of ComfyUI's own (tests/comfy_stack.py), over real HTTP on this computer.
+
+Run: python -m unittest discover -s tests (from integrations/fuobe-connect). FUOBE_CONNECT_TEST_PORT picks the port
+(3360 by default); COMFYUI_DIR=<a ComfyUI folder> reads ComfyUI's own middleware from it.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import sys
+import unittest
+
+import aiohttp
+from aiohttp import web
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+from comfy_stack import build_app # noqa: E402
+from fuobe_connect import plugin # noqa: E402
+from fuobe_connect.middleware import MARKER, make_middleware # noqa: E402
+from fuobe_connect.origins import allowed, normalise, parse_list, trusted_origins # noqa: E402
+
+PORT = int(os.environ.get("FUOBE_CONNECT_TEST_PORT", "3360"))
+BASE = f"http://127.0.0.1:{PORT}"
+FUOBE = "https://fuobe.com"
+EVIL = "https://evil.example"
+
+
+def browser(origin: str, site: str = "cross-site", **extra) -> dict:
+ return {"Origin": origin, "Sec-Fetch-Site": site, "Sec-Fetch-Mode": "cors", **extra}
+
+
+class Server:
+ def __init__(self, app: web.Application):
+ self.app = app
+
+ async def __aenter__(self):
+ self.runner = web.AppRunner(self.app)
+ await self.runner.setup()
+ await web.TCPSite(self.runner, "127.0.0.1", PORT).start()
+ self.session = aiohttp.ClientSession()
+ return self
+
+ async def __aexit__(self, *exc):
+ await self.session.close()
+ await self.runner.cleanup()
+
+ async def req(self, method: str, path: str, headers: dict | None = None, **kw):
+ async with self.session.request(method, BASE + path, headers=headers or {}, **kw) as res:
+ return res.status, dict(res.headers), await res.read()
+
+
+class FakeStore:
+ def __init__(self, data=None):
+ self.data = data or {}
+
+ def load(self):
+ return dict(self.data)
+
+ def update(self, **c):
+ self.data.update({k: v for k, v in c.items() if v is not None})
+ return self.data
+
+
+def with_connect(trusted=trusted_origins(None, None), cors_flag=None):
+ plugin._state.clear()
+ plugin._state["store"] = FakeStore()
+ routes = [("GET", "/fuobe/connect", plugin.status), ("POST", "/fuobe/connect/studios", plugin.set_studios)]
+ app, source = build_app(cors_flag, make_middleware(lambda: trusted, cors_flag), routes)
+ return app, source
+
+
+def run(coro):
+ return asyncio.run(coro)
+
+
+class OriginsTest(unittest.TestCase):
+ def test_normalise(self):
+ self.assertEqual(normalise("https://Fuobe.com/"), "https://fuobe.com")
+ self.assertEqual(normalise("https://fuobe.com:443"), "https://fuobe.com")
+ self.assertEqual(normalise("http://localhost:3000"), "http://localhost:3000")
+ for bad in ["fuobe.com", "https://fuobe.com/path", "javascript:alert(1)", "null", "", "https://[email protected]", "ftp://fuobe.com"]:
+ self.assertIsNone(normalise(bad), bad)
+
+ def test_trusted(self):
+ self.assertEqual(trusted_origins(None, None), ("https://fuobe.com", "https://www.fuobe.com"))
+ self.assertEqual(trusted_origins("https://studio.example.com", ["https://fuobe.com"]), ("https://studio.example.com",))
+ self.assertEqual(trusted_origins(None, "https://a.example, https://b.example:8443"), ("https://a.example", "https://b.example:8443"))
+ self.assertEqual(parse_list("nonsense"), [])
+
+ def test_allowed_paths(self):
+ for m, p in [("GET", "/system_stats"), ("GET", "/api/system_stats"), ("POST", "/prompt"), ("POST", "/upload/image"), ("GET", "/ws"), ("GET", "/history/0f0e0d0c-0000-4000-8000-000000000000"), ("POST", "/api/jobs/0f0e0d0c-0000-4000-8000-000000000000/cancel"), ("GET", "/v2/customnode/installed")]:
+ self.assertTrue(allowed(m, p), p)
+ for m, p in [("GET", "/userdata/comfy.settings.json"), ("POST", "/v2/manager/queue/install"), ("POST", "/history"), ("POST", "/fuobe/connect/studios"), ("POST", "/fuobe/connect/pair"), ("DELETE", "/prompt"), ("GET", "/internal/logs")]:
+ self.assertFalse(allowed(m, p), p)
+ self.assertFalse(allowed("GET", "/view", "filename=a.png&type=input&subfolder="))
+ self.assertTrue(allowed("GET", "/view", "filename=a.png&type=output&subfolder="))
+
+
+class WithoutConnectTest(unittest.TestCase):
+ """What a person sees today: ComfyUI turns the Fuobe page away."""
+
+ def test_comfyui_refuses_the_studio(self):
+ async def go():
+ app, _ = build_app()
+ async with Server(app) as s:
+ status, _, _ = await s.req("GET", "/system_stats", browser(FUOBE))
+ self.assertEqual(status, 403)
+
+ run(go())
+
+
+class DirectModeTest(unittest.TestCase):
+ def test_studio_reads_and_queues(self):
+ async def go():
+ app, source = with_connect()
+ print(f"\n (middleware from {source})", end="")
+ async with Server(app) as s:
+ status, h, body = await s.req("GET", "/system_stats", browser(FUOBE))
+ self.assertEqual(status, 200)
+ self.assertEqual(h.get("Access-Control-Allow-Origin"), FUOBE)
+ self.assertIn("Origin", h.get("Vary", ""))
+ self.assertIn(b"comfyui_version", body)
+ status, h, _ = await s.req("GET", "/api/system_stats", browser("https://www.fuobe.com"))
+ self.assertEqual((status, h.get("Access-Control-Allow-Origin")), (200, "https://www.fuobe.com"))
+ status, h, body = await s.req("POST", "/prompt", browser(FUOBE, **{"Content-Type": "application/json"}), data=b'{"prompt_id":"p1"}')
+ self.assertEqual((status, h.get("Access-Control-Allow-Origin")), (200, FUOBE))
+ self.assertIn(b"p1", body)
+ status, h, _ = await s.req("GET", "/view?filename=a.png&subfolder=&type=output", browser(FUOBE))
+ self.assertEqual(status, 200)
+
+ run(go())
+
+ def test_preflights(self):
+ async def go():
+ app, _ = with_connect()
+ async with Server(app) as s:
+ status, h, _ = await s.req(
+ "OPTIONS",
+ "/prompt",
+ browser(FUOBE, **{"Access-Control-Request-Method": "POST", "Access-Control-Request-Headers": "content-type", "Access-Control-Request-Private-Network": "true"}),
+ )
+ self.assertEqual(status, 204)
+ self.assertEqual(h.get("Access-Control-Allow-Origin"), FUOBE)
+ self.assertEqual(h.get("Access-Control-Allow-Private-Network"), "true")
+ self.assertIn("POST", h.get("Access-Control-Allow-Methods", ""))
+ self.assertEqual(h.get("Access-Control-Allow-Headers"), "content-type")
+ self.assertNotIn("Access-Control-Allow-Credentials", h)
+ # A simple GET that Chrome preflights only for Private Network Access.
+ status, h, _ = await s.req("OPTIONS", "/system_stats", browser(FUOBE, **{"Access-Control-Request-Method": "GET", "Access-Control-Request-Private-Network": "true"}))
+ self.assertEqual((status, h.get("Access-Control-Allow-Private-Network")), (204, "true"))
+ # A header a run never sends: no preflight answer from Fuobe Connect, so ComfyUI's check refuses it.
+ status, h, _ = await s.req("OPTIONS", "/prompt", browser(FUOBE, **{"Access-Control-Request-Method": "POST", "Access-Control-Request-Headers": "x-custom"}))
+ self.assertEqual(status, 403)
+ self.assertNotIn("Access-Control-Allow-Origin", h)
+ # Another website's preflight: refused by ComfyUI, as before.
+ status, h, _ = await s.req("OPTIONS", "/prompt", browser(EVIL, **{"Access-Control-Request-Method": "POST", "Access-Control-Request-Private-Network": "true"}))
+ self.assertEqual(status, 403)
+ self.assertNotIn("Access-Control-Allow-Private-Network", h)
+
+ run(go())
+
+ def test_other_websites_stay_out(self):
+ async def go():
+ app, _ = with_connect()
+ async with Server(app) as s:
+ for origin in [EVIL, "https://fuobe.com.evil.example", "http://fuobe.com", "https://fuobe.com:444", "null"]:
+ for method, path in [("GET", "/system_stats"), ("POST", "/prompt")]:
+ status, h, _ = await s.req(method, path, browser(origin), data=b"{}" if method == "POST" else None)
+ self.assertEqual(status, 403, f"{origin} {method} {path}")
+ self.assertNotIn("Access-Control-Allow-Origin", h)
+ # Without Sec-Fetch-Site (an older browser): ComfyUI's host check still refuses it.
+ status, _, _ = await s.req("POST", "/prompt", {"Origin": EVIL}, data=b"{}")
+ self.assertEqual(status, 403)
+
+ run(go())
+
+ def test_studio_reaches_only_what_a_run_needs(self):
+ async def go():
+ app, _ = with_connect()
+ async with Server(app) as s:
+ for method, path in [("GET", "/userdata/comfy.settings.json"), ("POST", "/v2/manager/queue/install"), ("POST", "/fuobe/connect/studios"), ("GET", "/view?filename=a.png&subfolder=&type=input")]:
+ status, h, _ = await s.req(method, path, browser(FUOBE, **{"Content-Type": "application/json"}), data=b'{"studios":"https://evil.example"}' if method == "POST" else None)
+ self.assertEqual(status, 403, path)
+ self.assertNotIn("Access-Control-Allow-Origin", h)
+ status, h, _ = await s.req("OPTIONS", "/v2/manager/queue/install", browser(FUOBE, **{"Access-Control-Request-Method": "POST", "Access-Control-Request-Headers": "content-type"}))
+ self.assertEqual(status, 403)
+ self.assertNotIn("Access-Control-Allow-Origin", h)
+
+ run(go())
+
+ def test_comfyui_page_and_programs_unchanged(self):
+ async def go():
+ app, _ = with_connect()
+ async with Server(app) as s:
+ status, h, _ = await s.req("POST", "/prompt", {"Origin": BASE, "Sec-Fetch-Site": "same-origin", "Content-Type": "application/json"}, data=b"{}")
+ self.assertEqual(status, 200)
+ self.assertNotIn("Access-Control-Allow-Origin", h)
+ status, _, _ = await s.req("GET", "/userdata/x")
+ self.assertEqual(status, 200)
+
+ run(go())
+
+ def test_websocket(self):
+ async def go():
+ app, _ = with_connect()
+ async with Server(app) as s:
+ async with s.session.ws_connect(f"ws://127.0.0.1:{PORT}/ws?clientId=abc12345", headers=browser(FUOBE, **{"Sec-Fetch-Mode": "websocket"})) as ws:
+ msg = await ws.receive(timeout=5)
+ self.assertIn("status", msg.data)
+ with self.assertRaises(aiohttp.WSServerHandshakeError) as e:
+ async with s.session.ws_connect(f"ws://127.0.0.1:{PORT}/ws?clientId=abc12345", headers=browser(EVIL, **{"Sec-Fetch-Mode": "websocket"})):
+ pass
+ self.assertEqual(e.exception.status, 403)
+
+ run(go())
+
+ def test_status_says_less_to_a_studio(self):
+ async def go():
+ app, _ = with_connect()
+ async with Server(app) as s:
+ status, h, body = await s.req("GET", "/fuobe/connect", browser(FUOBE))
+ self.assertEqual((status, h.get("Access-Control-Allow-Origin")), (200, FUOBE))
+ self.assertNotIn(b"studios", body)
+ self.assertIn(b'"connect": 1', body)
+ status, _, body = await s.req("GET", "/fuobe/connect")
+ self.assertIn(b"studios", body)
+ # A program can't pass itself off as a studio to get less, or more: the marker is dropped on the way in.
+ status, _, body = await s.req("GET", "/fuobe/connect", {MARKER: FUOBE})
+ self.assertIn(b"studios", body)
+ # Only ComfyUI's own page changes the studios.
+ status, _, _ = await s.req("POST", "/fuobe/connect/studios", {"Origin": BASE, "Content-Type": "application/json"}, data=b'{"studios":"https://studio.example.com"}')
+ self.assertEqual(status, 200)
+
+ run(go())
+
+
+class WithCorsFlagTest(unittest.TestCase):
+ """ComfyUI started with --enable-cors-header: its own check is off, so Fuobe Connect does what Fuobe's guard did."""
+
+ def test_guard(self):
+ async def go():
+ app, _ = with_connect(cors_flag="https://other-studio.example")
+ async with Server(app) as s:
+ status, h, _ = await s.req("GET", "/system_stats", browser(FUOBE))
+ self.assertEqual((status, h.get("Access-Control-Allow-Origin")), (200, FUOBE))
+ status, _, _ = await s.req("POST", "/prompt", browser(EVIL), data=b"{}")
+ self.assertEqual(status, 403)
+ status, _, _ = await s.req("POST", "/prompt", browser("https://other-studio.example"), data=b"{}")
+ self.assertEqual(status, 200)
+ status, _, _ = await s.req("POST", "/v2/manager/queue/install", browser(FUOBE), data=b"{}")
+ self.assertEqual(status, 403)
+ status, _, _ = await s.req("POST", "/prompt", {"Sec-Fetch-Site": "cross-site"}, data=b"{}")
+ self.assertEqual(status, 403)
+
+ run(go())
+
+ def test_star_adds_no_check(self):
+ async def go():
+ app, _ = with_connect(cors_flag="*")
+ async with Server(app) as s:
+ status, _, _ = await s.req("POST", "/prompt", browser(EVIL), data=b"{}")
+ self.assertEqual(status, 200)
+
+ run(go())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/integrations/fuobe-connect/web/fuobe_connect.js b/integrations/fuobe-connect/web/fuobe_connect.js
new file mode 100644
index 00000000..65c969bc
--- /dev/null
+++ b/integrations/fuobe-connect/web/fuobe_connect.js
@@ -0,0 +1,128 @@
+// Fuobe Connect in ComfyUI's page: a setting for the studios that may use this ComfyUI, and "Connect to Fuobe"
+// (pairing: a short code you approve on the studio, for Safari, phones and PCs with no screen).
+import { app } from "../../scripts/app.js";
+
+const get = async () => (await fetch("/fuobe/connect", { cache: "no-store" })).json();
+const post = async (path, body) => {
+ const res = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body ?? {}) });
+ const json = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(json.error || `HTTP ${res.status}`);
+ return json;
+};
+
+function el(tag, attrs = {}, ...children) {
+ const node = document.createElement(tag);
+ for (const [k, v] of Object.entries(attrs)) {
+ if (k === "style") Object.assign(node.style, v);
+ else if (k.startsWith("on")) node.addEventListener(k.slice(2), v);
+ else node.setAttribute(k, v);
+ }
+ for (const c of children) node.append(c);
+ return node;
+}
+
+let dialog = null;
+let timer = null;
+
+function close() {
+ clearInterval(timer);
+ timer = null;
+ dialog?.remove();
+ dialog = null;
+}
+
+function render(box, s) {
+ box.replaceChildren();
+ const line = (text, style = {}) => box.append(el("p", { style: { margin: "0 0 10px", ...style } }, text));
+ const button = (label, onclick, primary) =>
+ el(
+ "button",
+ {
+ onclick,
+ style: {
+ marginRight: "8px",
+ padding: "6px 12px",
+ borderRadius: "6px",
+ border: "1px solid #666",
+ cursor: "pointer",
+ background: primary ? "#2563eb" : "transparent",
+ color: primary ? "#fff" : "inherit",
+ },
+ },
+ label,
+ );
+ if (s.paired && s.state !== "unpaired") {
+ line(`Connected to ${s.paired.site}.`, { fontWeight: "600" });
+ line(s.state === "connected" ? "Your Fuobe jobs run on this ComfyUI, even with no Fuobe tab open." : s.message || "Waiting for the studio…");
+ box.append(
+ button("Disconnect", async () => {
+ await post("/fuobe/connect/unpair");
+ render(box, await get());
+ }),
+ button("Close", close),
+ );
+ return;
+ }
+ if (s.state === "pairing" && s.pairing) {
+ line("Approve this code on Fuobe, signed in:");
+ box.append(el("p", { style: { fontSize: "28px", letterSpacing: "4px", fontFamily: "monospace", margin: "4px 0 12px" } }, s.pairing.code));
+ box.append(button("Open Fuobe to approve", () => window.open(s.pairing.url, "_blank", "noopener"), true), button("Cancel", async () => {
+ await post("/fuobe/connect/unpair");
+ close();
+ }));
+ line(`Or open ${s.pairing.url} on any device.`, { marginTop: "10px", fontSize: "12px", opacity: "0.75" });
+ return;
+ }
+ line("Run your Fuobe jobs on this ComfyUI, with no browser tab open. Useful for Safari, phones and PCs with no screen.");
+ if (s.message) line(s.message, { fontSize: "12px", opacity: "0.75" });
+ const site = s.studios?.[0] ?? "https://fuobe.com";
+ box.append(
+ button(`Connect to ${new URL(site).host}`, async (e) => {
+ e.target.disabled = true;
+ try {
+ render(box, await post("/fuobe/connect/pair", { site }));
+ } catch (err) {
+ render(box, { ...s, message: String(err.message || err) });
+ }
+ }, true),
+ button("Close", close),
+ );
+}
+
+async function open() {
+ close();
+ const box = el("div", {});
+ dialog = el(
+ "div",
+ {
+ role: "dialog",
+ "aria-label": "Fuobe Connect",
+ style: { position: "fixed", top: "80px", right: "24px", zIndex: "10000", width: "360px", maxWidth: "calc(100vw - 48px)", padding: "16px", borderRadius: "10px", background: "var(--comfy-menu-bg, #222)", color: "var(--fg-color, #ddd)", boxShadow: "0 8px 30px rgba(0,0,0,.4)", font: "14px system-ui, sans-serif" },
+ },
+ el("p", { style: { margin: "0 0 10px", fontWeight: "700" } }, "Fuobe Connect"),
+ box,
+ );
+ document.body.append(dialog);
+ render(box, await get());
+ timer = setInterval(async () => dialog && render(box, await get()), 2000);
+}
+
+app.registerExtension({
+ name: "Fuobe.Connect",
+ settings: [
+ {
+ id: "FuobeConnect.Studios",
+ category: ["Fuobe Connect", "Studios", "Studios"],
+ name: "Fuobe studios that may use this ComfyUI",
+ tooltip: "Their pages may use this ComfyUI from your browser (to run their jobs). Separate several with commas. Every other website stays out.",
+ type: "text",
+ defaultValue: "https://fuobe.com",
+ onChange: (value, old) => {
+ if (old === undefined || value === old) return;
+ post("/fuobe/connect/studios", { studios: value }).catch((e) => console.warn("[Fuobe Connect]", e));
+ },
+ },
+ ],
+ commands: [{ id: "FuobeConnect.Open", label: "Connect to Fuobe", icon: "pi pi-link", function: open }],
+ menuCommands: [{ path: ["Extensions"], commands: ["FuobeConnect.Open"] }],
+});
diff --git a/tests/e2e/fuobe-connect.mjs b/tests/e2e/fuobe-connect.mjs
new file mode 100644
index 00000000..c78616f7
--- /dev/null
+++ b/tests/e2e/fuobe-connect.mjs
@@ -0,0 +1,180 @@
+// Fuobe Connect's pairing mode, end to end: a studio on 3361 with a throwaway data folder, the stand-in ComfyUI
+// (tests/helpers/fake-local-comfy.ts) on 3362, and Fuobe Connect's own runner (integrations/fuobe-connect, run outside
+// ComfyUI by its tests/pair_and_run.py). No browser and no real ComfyUI: nothing touches any other port.
+//
+// pnpm build && node tests/e2e/fuobe-connect.mjs
+// E2E_DEV=1 node tests/e2e/fuobe-connect.mjs (next dev instead of a build)
+// FUOBE_CONNECT_PYTHON=/path/to/python (a Python with aiohttp; default: python3, then python)
+//
+// Checks: a code is approved only by a signed-in person; the ComfyUI gets a token for that person alone and runs their
+// run to the end with no browser; another person's ComfyUI never gets that run; the token can't act as the owner or
+// reach any other route; an owner API token can't act as a worker; Disconnect in the studio stops the token at its
+// next call.
+import { spawn, spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import readline from "node:readline";
+import { root } from "./_browser.mjs";
+
+const APP_PORT = Number(process.env.E2E_APP_PORT ?? 3361);
+const FAKE_PORT = Number(process.env.E2E_FAKE_PORT ?? 3362);
+const SITE = `http://127.0.0.1:${APP_PORT}`;
+const FAKE = `http://127.0.0.1:${FAKE_PORT}`;
+const data = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-connect-e2e-"));
+const results = [];
+const check = (name, ok, detail = "") => {
+ results.push({ name, ok: !!ok, detail });
+ console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? ` — ${detail}` : ""}`);
+};
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+async function until(fn, ms = 30_000, every = 250) {
+ const end = Date.now() + ms;
+ for (;;) {
+ try {
+ const v = await fn();
+ if (v) return v;
+ } catch {}
+ if (Date.now() > end) return null;
+ await sleep(every);
+ }
+}
+
+const python = process.env.FUOBE_CONNECT_PYTHON ?? (spawnSync("python3", ["-c", "import aiohttp"]).status === 0 ? "python3" : "python");
+const password = `e2e-${Math.random().toString(36).slice(2)}`;
+const server = spawn(process.execPath, [path.join(root, "node_modules/next/dist/bin/next"), process.env.E2E_DEV ? "dev" : "start", "-p", String(APP_PORT), "-H", "127.0.0.1"], {
+ cwd: root,
+ env: { ...process.env, FUOBE_DATA_DIR: data, FUOBE_PASSWORD: password, FUOBE_PUBLIC_SIGNUP: "1", COMFYUI_URL: "http://127.0.0.1:3399", ...(process.env.E2E_DEV ? {} : { NODE_ENV: "production" }) },
+ stdio: ["ignore", "pipe", "pipe"],
+});
+let serverLog = "";
+server.stdout.on("data", (d) => (serverLog += d));
+server.stderr.on("data", (d) => (serverLog += d));
+
+const fake = spawn(process.execPath, ["--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", path.join(root, "tests/helpers/fake-local-comfy.ts"), "--port", String(FAKE_PORT), "--cors", "off", "--steps", "4", "--step-ms", "200", "--has", path.join(root, "workflows/comfyui/requirements.json")], {
+ stdio: ["ignore", "pipe", "inherit"],
+});
+
+const clients = [];
+/** Fuobe Connect's runner as its own process: its JSON lines, one by one. */
+function connect(name, token) {
+ const p = spawn(python, [path.join(root, "integrations/fuobe-connect/tests/pair_and_run.py"), "--site", SITE, "--comfy", FAKE, "--name", name, ...(token ? ["--token", token] : [])], { stdio: ["ignore", "pipe", "pipe"] });
+ clients.push(p);
+ const lines = [];
+ let err = "";
+ readline.createInterface({ input: p.stdout }).on("line", (l) => {
+ try {
+ lines.push(JSON.parse(l));
+ } catch {}
+ });
+ p.stderr.on("data", (d) => (err += d));
+ return { p, lines, err: () => err, next: (event, ms = 30_000) => until(() => lines.find((l) => l.event === event), ms) };
+}
+
+/** A signed-up account's calls (its session cookie), as a browser on the studio's page would send them. */
+async function account(email) {
+ const r = await fetch(`${SITE}/api/auth/signup`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ email, password: "long enough password" }) });
+ const cookie = (r.headers.get("set-cookie") ?? "").split(";")[0];
+ if (!cookie.startsWith("fuobe_session=")) throw new Error(`sign-up answered ${r.status}`);
+ return async (url, init = {}) => {
+ const res = await fetch(`${SITE}${url}`, { ...init, headers: { cookie, origin: SITE, "sec-fetch-site": "same-origin", "content-type": "application/json", ...(init.headers ?? {}) } });
+ return { status: res.status, body: await res.json().catch(() => null) };
+ };
+}
+
+async function finish() {
+ for (const c of clients) c.kill();
+ fake.kill();
+ server.kill();
+ await sleep(500);
+ try {
+ fs.rmSync(data, { recursive: true, force: true });
+ } catch {}
+ const failed = results.filter((r) => !r.ok);
+ console.log(`\n${results.length - failed.length}/${results.length} passed.`);
+ if (failed.length) console.log(serverLog.split("\n").slice(-40).join("\n"));
+ process.exit(failed.length ? 1 : 0);
+}
+
+try {
+ if (!(await until(() => fetch(`${SITE}/api/auth/me`).then((r) => r.ok), 180_000, 500))) throw new Error(`the studio didn't start:\n${serverLog}`);
+ if (!(await until(() => fetch(`${FAKE}/__fake/stats`).then((r) => r.ok), 15_000))) throw new Error("the stand-in ComfyUI didn't start");
+ const alice = await account("[email protected]");
+ const bob = await account("[email protected]");
+
+ // Pairing: a code, approved by Alice while signed in.
+ const a = connect("alice-pc");
+ const code = await a.next("code");
+ check("Fuobe Connect gets a code and a link to the studio", code && /^[A-Z2-9]{4}-[A-Z2-9]{4}$/.test(code.code) && code.url.startsWith(`${SITE}/connect?code=`), code ? `${code.code} ${code.url}` : a.err());
+ const anon = await fetch(`${SITE}/api/gpu/pair`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code: code.code }) });
+ check("a signed-out visitor can't approve a code", anon.status === 401, `${anon.status}`);
+ const look = await alice(`/api/gpu/pair?code=${encodeURIComponent(code.code)}`);
+ check("the person sees the computer before approving", look.status === 200 && look.body?.name === "alice-pc" && look.body?.facts?.device === "Test GPU", JSON.stringify(look.body));
+ const wrong = await alice(`/api/gpu/pair?code=ABCD-EFGH`);
+ check("an unknown code is no code", wrong.status === 404, `${wrong.status}`);
+ const ok = await alice("/api/gpu/pair", { method: "POST", body: JSON.stringify({ code: code.code }) });
+ check("Alice approves the code", ok.status === 200 && ok.body?.ok, JSON.stringify(ok.body));
+ const paired = await a.next("paired");
+ check("the ComfyUI gets its token once approved", paired?.token?.startsWith("fuobe_wkr_"), paired ? paired.workerId : a.err());
+ const again = await alice("/api/gpu/pair", { method: "POST", body: JSON.stringify({ code: code.code }) });
+ check("an approved code can't be used again", again.status === 404, `${again.status}`);
+ const gpu = await alice("/api/account/gpu");
+ check("Alice's GPU is now her computer", gpu.body?.gpu?.mode === "computer", JSON.stringify(gpu.body));
+ const list = await alice("/api/gpu/paired");
+ check("Alice's paired ComfyUIs list it", list.body?.paired?.length === 1 && list.body.paired[0].name === "alice-pc", JSON.stringify(list.body));
+ check("Bob's list is empty", (await bob("/api/gpu/paired")).body?.paired?.length === 0);
+
+ // The token is a worker's, nothing more.
+ const token = paired.token;
+ const bearer = { authorization: `Bearer ${token}` };
+ const other = await fetch(`${SITE}/api/settings`, { headers: bearer });
+ check("the worker token gets 403 on any other route", other.status === 403, `${other.status}`);
+ const gens = await fetch(`${SITE}/api/generations`, { headers: bearer });
+ check("the worker token can't read runs", gens.status === 403, `${gens.status}`);
+
+ // Bob pairs a ComfyUI too, and starts nothing.
+ const b = connect("bob-pc");
+ const bcode = await b.next("code");
+ await bob("/api/gpu/pair", { method: "POST", body: JSON.stringify({ code: bcode.code }) });
+ const bpaired = await b.next("paired");
+ check("Bob's ComfyUI is paired to Bob", !!bpaired?.token);
+ await sleep(1500);
+
+ // Alice's run goes to Alice's ComfyUI, with no browser open anywhere.
+ const run = await alice("/api/generations", { method: "POST", body: JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a red door" }) });
+ const gid = run.body?.items?.[0]?.id;
+ check("Alice starts a run", run.status === 200 || run.status === 201, `${run.status} ${JSON.stringify(run.body).slice(0, 200)}`);
+ const done = await until(async () => {
+ const g = await alice(`/api/generations/${gid}`);
+ return ["succeeded", "failed", "canceled"].includes(g.body?.status) ? g.body : null;
+ }, 90_000, 1000);
+ check("Alice's run finishes on her paired ComfyUI", done?.status === "succeeded", done ? `${done.status} ${done.error ?? ""}` : "timed out");
+ const stats = await fetch(`${FAKE}/__fake/stats`).then((r) => r.json()).catch(() => null);
+ check("the stand-in ComfyUI ran exactly one prompt", stats?.posts === 1, JSON.stringify(stats)?.slice(0, 200));
+ const bobRuns = await bob("/api/generations?limit=5");
+ check("Bob sees none of Alice's runs", (bobRuns.body?.items ?? []).length === 0);
+ const bobClaim = await fetch(`${SITE}/api/gpu/computer/claim`, { method: "POST", headers: { authorization: `Bearer ${bpaired.token}`, "content-type": "application/json" }, body: JSON.stringify({ device: "connect-bob-x", running: [] }) });
+ check("Bob's ComfyUI gets no job of Alice's", bobClaim.status === 204, `${bobClaim.status}`);
+
+ // An owner API token is never a worker.
+ const owner = await fetch(`${SITE}/api/auth/login`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ password }) });
+ const ownerCookie = (owner.headers.get("set-cookie") ?? "").split(";")[0];
+ const made = await fetch(`${SITE}/api/auth/tokens`, { method: "POST", headers: { cookie: ownerCookie, origin: SITE, "content-type": "application/json" }, body: JSON.stringify({ name: "e2e" }) }).then((r) => r.json()).catch(() => null);
+ if (made?.token) {
+ const asWorker = await fetch(`${SITE}/api/gpu/computer/beat`, { method: "POST", headers: { authorization: `Bearer ${made.token}`, "content-type": "application/json" }, body: JSON.stringify({ device: "owner-token-x" }) });
+ check("an owner API token can't act as a worker", asWorker.status === 403, `${asWorker.status}`);
+ } else check("an owner API token can't act as a worker", false, "couldn't make an owner token");
+
+ // Disconnect in the studio: the token stops at its next call, and the runner says so.
+ const id = list.body.paired[0].id;
+ const gone = await alice(`/api/gpu/paired/${id}`, { method: "DELETE" });
+ check("Alice disconnects her ComfyUI", gone.status === 200);
+ const after = await fetch(`${SITE}/api/gpu/computer/beat`, { method: "POST", headers: { ...bearer, "content-type": "application/json" }, body: JSON.stringify({ device: "connect-alice-pc" }) });
+ check("a disconnected token gets 401 at once", after.status === 401, `${after.status}`);
+ check("the runner hears it and stops", !!(await a.next("unpaired", 30_000)));
+ const bobUnpair = await fetch(`${SITE}/api/gpu/computer/unpair`, { method: "POST", headers: { authorization: `Bearer ${bpaired.token}` } });
+ check("Fuobe Connect's own Disconnect revokes its token", bobUnpair.status === 200 && (await fetch(`${SITE}/api/gpu/computer/claim`, { method: "POST", headers: { authorization: `Bearer ${bpaired.token}` }, body: "{}" })).status === 401);
+} catch (e) {
+ check("the run", false, String(e?.stack ?? e));
+}
+await finish();