comfy-peer-host 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- comfy_peer_host/__init__.py +8 -0
- comfy_peer_host/__main__.py +143 -0
- comfy_peer_host/binarypack.py +198 -0
- comfy_peer_host/comfy.py +118 -0
- comfy_peer_host/host.py +375 -0
- comfy_peer_host/peerjs.py +327 -0
- comfy_peer_host-0.1.0.dist-info/METADATA +119 -0
- comfy_peer_host-0.1.0.dist-info/RECORD +10 -0
- comfy_peer_host-0.1.0.dist-info/WHEEL +4 -0
- comfy_peer_host-0.1.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Headless collaboration host for Comfy UI Web."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("comfy-peer-host")
|
|
7
|
+
except PackageNotFoundError: # running from a source checkout without install
|
|
8
|
+
__version__ = "0.0.0"
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""comfy-peer-host: run a Comfy UI Web collaboration session from this machine, no browser needed."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import asyncio
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import os
|
|
10
|
+
import secrets
|
|
11
|
+
import signal
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from . import __version__
|
|
15
|
+
from .comfy import ComfyClient
|
|
16
|
+
from .host import Host
|
|
17
|
+
from .peerjs import DEFAULT_STUN, PEERJS_TURN, Peer
|
|
18
|
+
|
|
19
|
+
DEFAULT_APP = "https://mastashake08.github.io/comfy-ui-web/"
|
|
20
|
+
ID_CHARS = "abcdefghijkmnpqrstuvwxyz23456789"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def parse_args(argv=None) -> argparse.Namespace:
|
|
24
|
+
p = argparse.ArgumentParser(
|
|
25
|
+
prog="comfy-peer-host",
|
|
26
|
+
description="Host a Comfy UI Web collaboration session from this computer. Guests join with the invite "
|
|
27
|
+
"link, edit a shared graph, and every run executes on this machine's ComfyUI.",
|
|
28
|
+
)
|
|
29
|
+
p.add_argument("--comfy-url", default=os.environ.get("COMFY_URL", "http://127.0.0.1:8188"), help="ComfyUI server (default: %(default)s)")
|
|
30
|
+
p.add_argument("--name", default=os.environ.get("COMFY_PEER_NAME", "Host"), help="name shown to guests (default: %(default)s)")
|
|
31
|
+
p.add_argument("--session-id", help="fixed session id (cuw-…); by default one is generated once and reused")
|
|
32
|
+
p.add_argument("--new-id", action="store_true", help="generate a fresh session id (invalidates old invite links)")
|
|
33
|
+
p.add_argument("--state-dir", type=Path, default=Path(os.environ.get("COMFY_PEER_STATE", Path.home() / ".comfy-peer-host")), help="where the session id and shared graph are kept (default: %(default)s)")
|
|
34
|
+
p.add_argument("--workflow", type=Path, help="start the shared graph from a workflow saved in Comfy UI Web (Workflow → Save)")
|
|
35
|
+
p.add_argument("--app-url", default=DEFAULT_APP, help="web app used in the invite link (default: %(default)s)")
|
|
36
|
+
p.add_argument("--turn", action="store_true", help="also offer PeerJS's public TURN relay (helps behind strict NATs, slower setup)")
|
|
37
|
+
p.add_argument("--peerjs-host", default="0.peerjs.com", help="PeerJS signalling server (default: %(default)s)")
|
|
38
|
+
p.add_argument("--peerjs-port", type=int, default=443)
|
|
39
|
+
p.add_argument("--peerjs-path", default="/")
|
|
40
|
+
p.add_argument("--peerjs-key", default="peerjs")
|
|
41
|
+
p.add_argument("--insecure-signalling", action="store_true", help="use ws:// instead of wss:// for a self-hosted PeerJS server")
|
|
42
|
+
p.add_argument("-v", "--verbose", action="store_true")
|
|
43
|
+
p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
44
|
+
return p.parse_args(argv)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def session_id(args) -> str:
|
|
48
|
+
cfg_file = args.state_dir / "config.json"
|
|
49
|
+
cfg = {}
|
|
50
|
+
try:
|
|
51
|
+
cfg = json.loads(cfg_file.read_text())
|
|
52
|
+
except (FileNotFoundError, json.JSONDecodeError):
|
|
53
|
+
pass
|
|
54
|
+
sid = args.session_id or (None if args.new_id else cfg.get("session_id"))
|
|
55
|
+
if not sid:
|
|
56
|
+
sid = "cuw-" + "".join(secrets.choice(ID_CHARS) for _ in range(12))
|
|
57
|
+
if not sid.startswith("cuw-") or not sid[4:].isalnum():
|
|
58
|
+
raise SystemExit("--session-id must look like cuw-<letters and digits>")
|
|
59
|
+
args.state_dir.mkdir(parents=True, exist_ok=True)
|
|
60
|
+
cfg["session_id"] = sid
|
|
61
|
+
cfg_file.write_text(json.dumps(cfg, indent=2))
|
|
62
|
+
return sid
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
async def run(args) -> None:
|
|
66
|
+
sid = session_id(args)
|
|
67
|
+
ice = list(DEFAULT_STUN) + ([PEERJS_TURN] if args.turn else [])
|
|
68
|
+
peer = Peer(
|
|
69
|
+
sid,
|
|
70
|
+
host=args.peerjs_host,
|
|
71
|
+
port=args.peerjs_port,
|
|
72
|
+
path=args.peerjs_path,
|
|
73
|
+
key=args.peerjs_key,
|
|
74
|
+
secure=not args.insecure_signalling,
|
|
75
|
+
ice_servers=ice,
|
|
76
|
+
)
|
|
77
|
+
async with ComfyClient(args.comfy_url) as comfy:
|
|
78
|
+
host = Host(peer, comfy, name=args.name, state_dir=args.state_dir)
|
|
79
|
+
if args.workflow:
|
|
80
|
+
host.load_workflow_file(args.workflow)
|
|
81
|
+
|
|
82
|
+
try:
|
|
83
|
+
info = await comfy.object_info()
|
|
84
|
+
logging.info("ComfyUI at %s: %d node types", args.comfy_url, len(info))
|
|
85
|
+
except Exception as e: # noqa: BLE001
|
|
86
|
+
logging.warning("ComfyUI at %s is not reachable yet (%s); guests can join once it is", args.comfy_url, e)
|
|
87
|
+
|
|
88
|
+
tasks = [
|
|
89
|
+
asyncio.create_task(peer.run(), name="peerjs"),
|
|
90
|
+
asyncio.create_task(comfy.listen(host.on_comfy_message, host.on_comfy_preview, host.on_comfy_state), name="comfy"),
|
|
91
|
+
]
|
|
92
|
+
try:
|
|
93
|
+
await peer.wait_open(30)
|
|
94
|
+
except asyncio.TimeoutError:
|
|
95
|
+
logging.warning("still waiting for the PeerJS server…")
|
|
96
|
+
link = f"{args.app_url.rstrip('/')}/#join={sid}"
|
|
97
|
+
print(
|
|
98
|
+
"\n Comfy UI Web host is running.\n"
|
|
99
|
+
f" Invite link: {link}\n"
|
|
100
|
+
f" Session code: {sid}\n"
|
|
101
|
+
f" Shared graph: {host.graph_file}\n"
|
|
102
|
+
" Anyone with the link can edit the graph and run it on this computer. Ctrl-C to stop.\n",
|
|
103
|
+
flush=True,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
stop = asyncio.Event()
|
|
107
|
+
loop = asyncio.get_running_loop()
|
|
108
|
+
for sig in (signal.SIGINT, signal.SIGTERM):
|
|
109
|
+
try:
|
|
110
|
+
loop.add_signal_handler(sig, stop.set)
|
|
111
|
+
except NotImplementedError: # Windows
|
|
112
|
+
pass
|
|
113
|
+
done = asyncio.create_task(stop.wait())
|
|
114
|
+
finished, _ = await asyncio.wait([done, *tasks], return_when=asyncio.FIRST_COMPLETED)
|
|
115
|
+
for t in finished:
|
|
116
|
+
if t is not done and t.exception():
|
|
117
|
+
logging.error("stopped: %s", t.exception())
|
|
118
|
+
logging.info("shutting down…")
|
|
119
|
+
await host.shutdown()
|
|
120
|
+
await peer.stop()
|
|
121
|
+
for t in tasks:
|
|
122
|
+
t.cancel()
|
|
123
|
+
await asyncio.gather(*tasks, return_exceptions=True)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def main(argv=None) -> None:
|
|
127
|
+
args = parse_args(argv)
|
|
128
|
+
logging.basicConfig(
|
|
129
|
+
level=logging.DEBUG if args.verbose else logging.INFO,
|
|
130
|
+
format="%(asctime)s %(levelname)-7s %(name)s: %(message)s",
|
|
131
|
+
datefmt="%H:%M:%S",
|
|
132
|
+
)
|
|
133
|
+
if not args.verbose:
|
|
134
|
+
for noisy in ("aioice", "aiortc", "aiohttp"):
|
|
135
|
+
logging.getLogger(noisy).setLevel(logging.WARNING)
|
|
136
|
+
try:
|
|
137
|
+
asyncio.run(run(args))
|
|
138
|
+
except KeyboardInterrupt:
|
|
139
|
+
pass
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
if __name__ == "__main__":
|
|
143
|
+
main()
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""BinaryPack: the serialization PeerJS uses for "binary" data connections.
|
|
2
|
+
|
|
3
|
+
A port of peerjs-js-binarypack (a msgpack variant). It must match the JavaScript implementation
|
|
4
|
+
byte for byte, so the type tags differ from standard msgpack:
|
|
5
|
+
0xa0+n / 0xda / 0xdb raw bytes (JS ArrayBuffer)
|
|
6
|
+
0xb0+n / 0xd8 / 0xd9 UTF-8 string
|
|
7
|
+
JavaScript has a single number type, so whole-valued floats are packed as integers, as JS does.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
import struct
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class BinaryPackError(ValueError):
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# ----------------------------------------------------------------------------- pack
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def pack(value: Any) -> bytes:
|
|
25
|
+
out = bytearray()
|
|
26
|
+
_pack(value, out)
|
|
27
|
+
return bytes(out)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _pack(v: Any, out: bytearray) -> None:
|
|
31
|
+
if v is None:
|
|
32
|
+
out.append(0xC0)
|
|
33
|
+
elif v is True:
|
|
34
|
+
out.append(0xC3)
|
|
35
|
+
elif v is False:
|
|
36
|
+
out.append(0xC2)
|
|
37
|
+
elif isinstance(v, str):
|
|
38
|
+
_pack_sized(v.encode("utf-8"), out, 0xB0, 0xD8, 0xD9)
|
|
39
|
+
elif isinstance(v, int):
|
|
40
|
+
_pack_int(v, out)
|
|
41
|
+
elif isinstance(v, float):
|
|
42
|
+
if math.isfinite(v) and v == math.floor(v) and abs(v) <= 2**63:
|
|
43
|
+
_pack_int(int(v), out)
|
|
44
|
+
else:
|
|
45
|
+
out.append(0xCB)
|
|
46
|
+
out += struct.pack(">d", v)
|
|
47
|
+
elif isinstance(v, (bytes, bytearray, memoryview)):
|
|
48
|
+
_pack_sized(bytes(v), out, 0xA0, 0xDA, 0xDB)
|
|
49
|
+
elif isinstance(v, (list, tuple)):
|
|
50
|
+
_pack_len(len(v), out, 0x90, 0xDC, 0xDD)
|
|
51
|
+
for item in v:
|
|
52
|
+
_pack(item, out)
|
|
53
|
+
elif isinstance(v, dict):
|
|
54
|
+
_pack_len(len(v), out, 0x80, 0xDE, 0xDF)
|
|
55
|
+
for k, item in v.items():
|
|
56
|
+
_pack(str(k) if not isinstance(k, str) else k, out)
|
|
57
|
+
_pack(item, out)
|
|
58
|
+
else:
|
|
59
|
+
raise BinaryPackError(f"Type {type(v).__name__} not supported")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _pack_len(n: int, out: bytearray, fix: int, tag16: int, tag32: int) -> None:
|
|
63
|
+
if n <= 0x0F:
|
|
64
|
+
out.append(fix + n)
|
|
65
|
+
elif n <= 0xFFFF:
|
|
66
|
+
out.append(tag16)
|
|
67
|
+
out += struct.pack(">H", n)
|
|
68
|
+
elif n <= 0xFFFFFFFF:
|
|
69
|
+
out.append(tag32)
|
|
70
|
+
out += struct.pack(">I", n)
|
|
71
|
+
else:
|
|
72
|
+
raise BinaryPackError("Invalid length")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _pack_sized(data: bytes, out: bytearray, fix: int, tag16: int, tag32: int) -> None:
|
|
76
|
+
_pack_len(len(data), out, fix, tag16, tag32)
|
|
77
|
+
out += data
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _pack_int(n: int, out: bytearray) -> None:
|
|
81
|
+
if -32 <= n <= 0x7F:
|
|
82
|
+
out.append(n & 0xFF)
|
|
83
|
+
elif 0 <= n <= 0xFF:
|
|
84
|
+
out += b"\xcc" + struct.pack(">B", n)
|
|
85
|
+
elif -128 <= n <= 0x7F:
|
|
86
|
+
out += b"\xd0" + struct.pack(">b", n)
|
|
87
|
+
elif 0 <= n <= 0xFFFF:
|
|
88
|
+
out += b"\xcd" + struct.pack(">H", n)
|
|
89
|
+
elif -32768 <= n <= 0x7FFF:
|
|
90
|
+
out += b"\xd1" + struct.pack(">h", n)
|
|
91
|
+
elif 0 <= n <= 0xFFFFFFFF:
|
|
92
|
+
out += b"\xce" + struct.pack(">I", n)
|
|
93
|
+
elif -(2**31) <= n <= 2**31 - 1:
|
|
94
|
+
out += b"\xd2" + struct.pack(">i", n)
|
|
95
|
+
elif -(2**63) <= n <= 2**63 - 1:
|
|
96
|
+
out += b"\xd3" + struct.pack(">q", n)
|
|
97
|
+
elif 0 <= n <= 2**64 - 1:
|
|
98
|
+
out += b"\xcf" + struct.pack(">Q", n)
|
|
99
|
+
else:
|
|
100
|
+
raise BinaryPackError("Invalid integer")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# ----------------------------------------------------------------------------- unpack
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def unpack(data: bytes) -> Any:
|
|
107
|
+
value, _ = _unpack(memoryview(data), 0)
|
|
108
|
+
return value
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _unpack(b: memoryview, i: int) -> tuple[Any, int]:
|
|
112
|
+
if i >= len(b):
|
|
113
|
+
raise BinaryPackError("read index out of range")
|
|
114
|
+
t = b[i]
|
|
115
|
+
i += 1
|
|
116
|
+
if t < 0x80:
|
|
117
|
+
return t, i
|
|
118
|
+
if (t ^ 0xE0) < 0x20:
|
|
119
|
+
return (t ^ 0xE0) - 0x20, i
|
|
120
|
+
if (t ^ 0xA0) <= 0x0F:
|
|
121
|
+
return _raw(b, i, t ^ 0xA0)
|
|
122
|
+
if (t ^ 0xB0) <= 0x0F:
|
|
123
|
+
return _str(b, i, t ^ 0xB0)
|
|
124
|
+
if (t ^ 0x90) <= 0x0F:
|
|
125
|
+
return _array(b, i, t ^ 0x90)
|
|
126
|
+
if (t ^ 0x80) <= 0x0F:
|
|
127
|
+
return _map(b, i, t ^ 0x80)
|
|
128
|
+
|
|
129
|
+
def num(fmt: str, size: int) -> tuple[Any, int]:
|
|
130
|
+
if i + size > len(b):
|
|
131
|
+
raise BinaryPackError("read index out of range")
|
|
132
|
+
return struct.unpack_from(fmt, b, i)[0], i + size
|
|
133
|
+
|
|
134
|
+
if t in (0xC0, 0xC1, 0xD4, 0xD5, 0xD6, 0xD7):
|
|
135
|
+
return None, i
|
|
136
|
+
if t == 0xC2:
|
|
137
|
+
return False, i
|
|
138
|
+
if t == 0xC3:
|
|
139
|
+
return True, i
|
|
140
|
+
if t == 0xCA:
|
|
141
|
+
return num(">f", 4)
|
|
142
|
+
if t == 0xCB:
|
|
143
|
+
return num(">d", 8)
|
|
144
|
+
if t == 0xCC:
|
|
145
|
+
return num(">B", 1)
|
|
146
|
+
if t == 0xCD:
|
|
147
|
+
return num(">H", 2)
|
|
148
|
+
if t == 0xCE:
|
|
149
|
+
return num(">I", 4)
|
|
150
|
+
if t == 0xCF:
|
|
151
|
+
return num(">Q", 8)
|
|
152
|
+
if t == 0xD0:
|
|
153
|
+
return num(">b", 1)
|
|
154
|
+
if t == 0xD1:
|
|
155
|
+
return num(">h", 2)
|
|
156
|
+
if t == 0xD2:
|
|
157
|
+
return num(">i", 4)
|
|
158
|
+
if t == 0xD3:
|
|
159
|
+
return num(">q", 8)
|
|
160
|
+
if t in (0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF):
|
|
161
|
+
size, i = num(">H", 2) if t % 2 == 0 else num(">I", 4)
|
|
162
|
+
if t in (0xD8, 0xD9):
|
|
163
|
+
return _str(b, i, size)
|
|
164
|
+
if t in (0xDA, 0xDB):
|
|
165
|
+
return _raw(b, i, size)
|
|
166
|
+
if t in (0xDC, 0xDD):
|
|
167
|
+
return _array(b, i, size)
|
|
168
|
+
return _map(b, i, size)
|
|
169
|
+
raise BinaryPackError(f"Unknown type tag 0x{t:02x}")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _raw(b: memoryview, i: int, size: int) -> tuple[bytes, int]:
|
|
173
|
+
if i + size > len(b):
|
|
174
|
+
raise BinaryPackError("index is out of range")
|
|
175
|
+
return bytes(b[i : i + size]), i + size
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _str(b: memoryview, i: int, size: int) -> tuple[str, int]:
|
|
179
|
+
if i + size > len(b):
|
|
180
|
+
raise BinaryPackError("read index out of range")
|
|
181
|
+
return bytes(b[i : i + size]).decode("utf-8", errors="replace"), i + size
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _array(b: memoryview, i: int, size: int) -> tuple[list, int]:
|
|
185
|
+
items = []
|
|
186
|
+
for _ in range(size):
|
|
187
|
+
v, i = _unpack(b, i)
|
|
188
|
+
items.append(v)
|
|
189
|
+
return items, i
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _map(b: memoryview, i: int, size: int) -> tuple[dict, int]:
|
|
193
|
+
d = {}
|
|
194
|
+
for _ in range(size):
|
|
195
|
+
k, i = _unpack(b, i)
|
|
196
|
+
v, i = _unpack(b, i)
|
|
197
|
+
d[k] = v
|
|
198
|
+
return d, i
|
comfy_peer_host/comfy.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Async client for the ComfyUI HTTP + websocket API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import struct
|
|
9
|
+
import uuid
|
|
10
|
+
from typing import Any, Awaitable, Callable
|
|
11
|
+
from urllib.parse import urlencode
|
|
12
|
+
|
|
13
|
+
import aiohttp
|
|
14
|
+
|
|
15
|
+
log = logging.getLogger("comfy")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ComfyError(RuntimeError):
|
|
19
|
+
def __init__(self, message: str, status: int | None = None, body: Any = None):
|
|
20
|
+
super().__init__(message)
|
|
21
|
+
self.status = status
|
|
22
|
+
self.body = body
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ComfyClient:
|
|
26
|
+
def __init__(self, base_url: str = "http://127.0.0.1:8188", client_id: str | None = None):
|
|
27
|
+
self.base = base_url.rstrip("/")
|
|
28
|
+
self.client_id = client_id or str(uuid.uuid4())
|
|
29
|
+
self.session: aiohttp.ClientSession | None = None
|
|
30
|
+
|
|
31
|
+
async def __aenter__(self):
|
|
32
|
+
self.session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=None, sock_connect=10))
|
|
33
|
+
return self
|
|
34
|
+
|
|
35
|
+
async def __aexit__(self, *exc):
|
|
36
|
+
await self.session.close()
|
|
37
|
+
|
|
38
|
+
def url(self, path: str) -> str:
|
|
39
|
+
return f"{self.base}/api{path}"
|
|
40
|
+
|
|
41
|
+
async def request(self, method: str, path: str, **kw) -> Any:
|
|
42
|
+
async with self.session.request(method, self.url(path), **kw) as res:
|
|
43
|
+
text = await res.text()
|
|
44
|
+
try:
|
|
45
|
+
body = json.loads(text) if text else None
|
|
46
|
+
except json.JSONDecodeError:
|
|
47
|
+
body = text
|
|
48
|
+
if res.status >= 400:
|
|
49
|
+
raise ComfyError(_error_message(body) or f"{res.status} {res.reason}", res.status, body)
|
|
50
|
+
return body
|
|
51
|
+
|
|
52
|
+
async def object_info(self) -> dict:
|
|
53
|
+
return await self.request("GET", "/object_info")
|
|
54
|
+
|
|
55
|
+
async def queue_prompt(self, prompt: dict, extra_data: dict | None = None) -> dict:
|
|
56
|
+
return await self.request(
|
|
57
|
+
"POST", "/prompt", json={"prompt": prompt, "client_id": self.client_id, "extra_data": extra_data or {}}
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
async def view(self, filename: str, subfolder: str = "", type_: str = "output") -> tuple[bytes, str]:
|
|
61
|
+
q = urlencode({"filename": filename, "subfolder": subfolder, "type": type_})
|
|
62
|
+
async with self.session.get(self.url(f"/view?{q}")) as res:
|
|
63
|
+
res.raise_for_status()
|
|
64
|
+
return await res.read(), res.headers.get("Content-Type", "application/octet-stream")
|
|
65
|
+
|
|
66
|
+
async def listen(
|
|
67
|
+
self,
|
|
68
|
+
on_message: Callable[[str, Any], Awaitable[None] | None],
|
|
69
|
+
on_preview: Callable[[bytes, str], Awaitable[None] | None] | None = None,
|
|
70
|
+
on_state: Callable[[bool], Awaitable[None] | None] | None = None,
|
|
71
|
+
) -> None:
|
|
72
|
+
"""Follow the ComfyUI websocket forever, reconnecting when it drops."""
|
|
73
|
+
ws_url = self.base.replace("http", "ws", 1) + f"/ws?clientId={self.client_id}"
|
|
74
|
+
delay = 1.0
|
|
75
|
+
while True:
|
|
76
|
+
try:
|
|
77
|
+
async with self.session.ws_connect(ws_url, heartbeat=30) as ws:
|
|
78
|
+
log.info("connected to ComfyUI websocket")
|
|
79
|
+
delay = 1.0
|
|
80
|
+
await _maybe(on_state, True)
|
|
81
|
+
async for msg in ws:
|
|
82
|
+
if msg.type == aiohttp.WSMsgType.TEXT:
|
|
83
|
+
try:
|
|
84
|
+
m = json.loads(msg.data)
|
|
85
|
+
except json.JSONDecodeError:
|
|
86
|
+
continue
|
|
87
|
+
await _maybe(on_message, m.get("type"), m.get("data"))
|
|
88
|
+
elif msg.type == aiohttp.WSMsgType.BINARY and on_preview and len(msg.data) > 8:
|
|
89
|
+
event, fmt = struct.unpack(">II", msg.data[:8])
|
|
90
|
+
if event == 1: # preview image
|
|
91
|
+
await _maybe(on_preview, msg.data[8:], "image/png" if fmt == 2 else "image/jpeg")
|
|
92
|
+
except (aiohttp.ClientError, OSError, asyncio.TimeoutError) as e:
|
|
93
|
+
log.warning("ComfyUI websocket unavailable (%s); retrying in %.0fs", e, delay)
|
|
94
|
+
await _maybe(on_state, False)
|
|
95
|
+
await asyncio.sleep(delay)
|
|
96
|
+
delay = min(delay * 2, 30)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
async def _maybe(fn, *args):
|
|
100
|
+
if fn is None:
|
|
101
|
+
return
|
|
102
|
+
res = fn(*args)
|
|
103
|
+
if asyncio.iscoroutine(res):
|
|
104
|
+
await res
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _error_message(body: Any) -> str:
|
|
108
|
+
if not body:
|
|
109
|
+
return ""
|
|
110
|
+
if isinstance(body, str):
|
|
111
|
+
return body[:300]
|
|
112
|
+
err = body.get("error") if isinstance(body, dict) else None
|
|
113
|
+
if isinstance(err, str):
|
|
114
|
+
return err
|
|
115
|
+
if isinstance(err, dict):
|
|
116
|
+
msg = err.get("message", "")
|
|
117
|
+
return f"{msg}: {err['details']}" if err.get("details") else msg
|
|
118
|
+
return ""
|
comfy_peer_host/host.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
"""The collaboration host: speaks the Comfy UI Web session protocol (see the web app's
|
|
2
|
+
src/lib/collab.js) so browsers can join, edit a shared graph and run it on this machine's ComfyUI.
|
|
3
|
+
|
|
4
|
+
guest -> host : hello {name} | ops {ops} | cursor {x, y} | queue {count, reqId, prompts?}
|
|
5
|
+
host -> guest : welcome {self, peers, objectInfo, graph, exec}
|
|
6
|
+
ops {ops, from} | peers {peers} | cursor {id, x, y} | exec {...}
|
|
7
|
+
image {nodeId, promptId, filename, mime, buf} | preview {mime, buf}
|
|
8
|
+
queued {reqId, ok, count | error} | bye {reason}
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import asyncio
|
|
14
|
+
import json
|
|
15
|
+
import logging
|
|
16
|
+
import time
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from .comfy import ComfyClient, ComfyError
|
|
22
|
+
from .peerjs import DataConnection, Peer
|
|
23
|
+
|
|
24
|
+
log = logging.getLogger("host")
|
|
25
|
+
|
|
26
|
+
COLORS = ["#7aa2ff", "#ff7ab6", "#5fd08b", "#ffb454", "#b18cff", "#4dd4e8", "#ff6b6b", "#d4e157"]
|
|
27
|
+
STRIDE = 16 # id slots, as in the web app: max participants
|
|
28
|
+
MAX_IMAGE_BYTES = 12 * 1024 * 1024
|
|
29
|
+
OBJECT_INFO_TTL = 30.0
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class Guest:
|
|
34
|
+
conn: DataConnection
|
|
35
|
+
info: dict
|
|
36
|
+
outbox: asyncio.Queue = field(default_factory=asyncio.Queue)
|
|
37
|
+
sender: asyncio.Task | None = None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class Host:
|
|
41
|
+
def __init__(self, peer: Peer, comfy: ComfyClient, *, name: str, state_dir: Path):
|
|
42
|
+
self.peer = peer
|
|
43
|
+
self.comfy = comfy
|
|
44
|
+
self.state_dir = state_dir
|
|
45
|
+
self.self_info = {"id": peer.id, "name": name, "color": COLORS[0], "slot": 0, "host": True}
|
|
46
|
+
self.guests: dict[str, Guest] = {}
|
|
47
|
+
self.graph = self._load_graph()
|
|
48
|
+
self._save_handle: asyncio.TimerHandle | None = None
|
|
49
|
+
self._object_info: tuple[float, str] | None = None
|
|
50
|
+
self._lock = asyncio.Lock() # serialises guest messages so ops land before a queue request
|
|
51
|
+
self.comfy_up = False
|
|
52
|
+
# Execution state mirrored to guests (same shape as the web app's store).
|
|
53
|
+
self.running: dict | None = None
|
|
54
|
+
self.queue_remaining = 0
|
|
55
|
+
self.executed: set[str] = set()
|
|
56
|
+
self.node_errors: dict[str, list[str]] = {}
|
|
57
|
+
self._exec_handle: asyncio.TimerHandle | None = None
|
|
58
|
+
peer.on_connection = self._on_connection
|
|
59
|
+
|
|
60
|
+
# ------------------------------------------------------------------ graph persistence
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def graph_file(self) -> Path:
|
|
64
|
+
return self.state_dir / "graph.json"
|
|
65
|
+
|
|
66
|
+
def _load_graph(self) -> dict:
|
|
67
|
+
try:
|
|
68
|
+
g = json.loads(self.graph_file.read_text())
|
|
69
|
+
return {
|
|
70
|
+
"nodes": {n["id"]: n for n in g.get("nodes", [])},
|
|
71
|
+
"edges": {e["id"]: e for e in g.get("edges", [])},
|
|
72
|
+
"viewport": g.get("viewport"),
|
|
73
|
+
}
|
|
74
|
+
except (FileNotFoundError, json.JSONDecodeError, KeyError, TypeError):
|
|
75
|
+
return {"nodes": {}, "edges": {}, "viewport": None}
|
|
76
|
+
|
|
77
|
+
def serialize(self) -> dict:
|
|
78
|
+
out = {
|
|
79
|
+
"format": "comfy-ui-web",
|
|
80
|
+
"version": 1,
|
|
81
|
+
"nodes": list(self.graph["nodes"].values()),
|
|
82
|
+
"edges": list(self.graph["edges"].values()),
|
|
83
|
+
}
|
|
84
|
+
if self.graph.get("viewport"):
|
|
85
|
+
out["viewport"] = self.graph["viewport"]
|
|
86
|
+
return out
|
|
87
|
+
|
|
88
|
+
def _schedule_save(self) -> None:
|
|
89
|
+
if self._save_handle:
|
|
90
|
+
self._save_handle.cancel()
|
|
91
|
+
self._save_handle = asyncio.get_running_loop().call_later(1.0, self._save_now)
|
|
92
|
+
|
|
93
|
+
def _save_now(self) -> None:
|
|
94
|
+
self.state_dir.mkdir(parents=True, exist_ok=True)
|
|
95
|
+
tmp = self.graph_file.with_suffix(".tmp")
|
|
96
|
+
tmp.write_text(json.dumps(self.serialize()))
|
|
97
|
+
tmp.replace(self.graph_file)
|
|
98
|
+
|
|
99
|
+
def load_workflow_file(self, path: Path) -> None:
|
|
100
|
+
"""Seed the shared graph from a Comfy UI Web workflow file (Workflow → Save)."""
|
|
101
|
+
data = json.loads(path.read_text())
|
|
102
|
+
if data.get("format") != "comfy-ui-web":
|
|
103
|
+
raise ValueError("Expected a workflow saved from Comfy UI Web (Workflow → Save)")
|
|
104
|
+
self.graph = {
|
|
105
|
+
"nodes": {n["id"]: n for n in data.get("nodes", [])},
|
|
106
|
+
"edges": {e["id"]: e for e in data.get("edges", [])},
|
|
107
|
+
"viewport": data.get("viewport"),
|
|
108
|
+
}
|
|
109
|
+
self._save_now()
|
|
110
|
+
|
|
111
|
+
def apply_ops(self, ops: list[dict]) -> None:
|
|
112
|
+
nodes, edges = self.graph["nodes"], self.graph["edges"]
|
|
113
|
+
for o in ops:
|
|
114
|
+
kind = o.get("op")
|
|
115
|
+
if kind in ("node+", "node~"):
|
|
116
|
+
node = nodes.get(o.get("id"))
|
|
117
|
+
if node is None:
|
|
118
|
+
if kind == "node+" or ("position" in o and "data" in o):
|
|
119
|
+
nodes[o["id"]] = {
|
|
120
|
+
"id": o["id"],
|
|
121
|
+
"type": "comfy",
|
|
122
|
+
"position": o.get("position") or {"x": 0, "y": 0},
|
|
123
|
+
"data": o.get("data") or {},
|
|
124
|
+
}
|
|
125
|
+
else:
|
|
126
|
+
if "position" in o:
|
|
127
|
+
node["position"] = o["position"]
|
|
128
|
+
if "data" in o:
|
|
129
|
+
node["data"] = o["data"]
|
|
130
|
+
elif kind == "node-":
|
|
131
|
+
nid = o.get("id")
|
|
132
|
+
nodes.pop(nid, None)
|
|
133
|
+
# Vue Flow drops a removed node's edges on every client; mirror that.
|
|
134
|
+
for eid in [k for k, e in edges.items() if e.get("source") == nid or e.get("target") == nid]:
|
|
135
|
+
del edges[eid]
|
|
136
|
+
elif kind == "edge+":
|
|
137
|
+
e = o.get("edge") or {}
|
|
138
|
+
for eid in [
|
|
139
|
+
k for k, x in edges.items()
|
|
140
|
+
if k != e.get("id") and x.get("target") == e.get("target") and x.get("targetHandle") == e.get("targetHandle")
|
|
141
|
+
]:
|
|
142
|
+
del edges[eid]
|
|
143
|
+
if e.get("id"):
|
|
144
|
+
edges[e["id"]] = e
|
|
145
|
+
elif kind == "edge-":
|
|
146
|
+
edges.pop(o.get("id"), None)
|
|
147
|
+
self._schedule_save()
|
|
148
|
+
|
|
149
|
+
# ------------------------------------------------------------------ guests
|
|
150
|
+
|
|
151
|
+
async def _on_connection(self, conn: DataConnection) -> None:
|
|
152
|
+
conn.on_data = lambda c, msg: asyncio.ensure_future(self._serial(c, msg))
|
|
153
|
+
conn.on_close = self._on_close
|
|
154
|
+
|
|
155
|
+
async def _serial(self, conn: DataConnection, msg: Any) -> None:
|
|
156
|
+
async with self._lock:
|
|
157
|
+
try:
|
|
158
|
+
await self._on_message(conn, msg)
|
|
159
|
+
except Exception: # noqa: BLE001
|
|
160
|
+
log.exception("error handling message from %s", conn.peer_id)
|
|
161
|
+
|
|
162
|
+
def _send(self, guest: Guest, msg: dict) -> None:
|
|
163
|
+
guest.outbox.put_nowait(msg)
|
|
164
|
+
|
|
165
|
+
async def _sender(self, guest: Guest) -> None:
|
|
166
|
+
while True:
|
|
167
|
+
msg = await guest.outbox.get()
|
|
168
|
+
try:
|
|
169
|
+
await guest.conn.send(msg)
|
|
170
|
+
except Exception as e: # noqa: BLE001
|
|
171
|
+
log.warning("send to %s failed: %s", guest.info["name"], e)
|
|
172
|
+
|
|
173
|
+
def broadcast(self, msg: dict, except_id: str | None = None) -> None:
|
|
174
|
+
for pid, g in self.guests.items():
|
|
175
|
+
if pid != except_id:
|
|
176
|
+
self._send(g, msg)
|
|
177
|
+
|
|
178
|
+
def peers(self) -> list[dict]:
|
|
179
|
+
return [self.self_info, *(g.info for g in self.guests.values())]
|
|
180
|
+
|
|
181
|
+
def _publish_peers(self) -> None:
|
|
182
|
+
self.broadcast({"t": "peers", "peers": self.peers()})
|
|
183
|
+
|
|
184
|
+
def _free_slot(self) -> int:
|
|
185
|
+
used = {0, *(g.info["slot"] for g in self.guests.values())}
|
|
186
|
+
return next((s for s in range(1, STRIDE) if s not in used), -1)
|
|
187
|
+
|
|
188
|
+
async def _object_info_json(self) -> str:
|
|
189
|
+
now = time.monotonic()
|
|
190
|
+
if self._object_info is None or now - self._object_info[0] > OBJECT_INFO_TTL:
|
|
191
|
+
self._object_info = (now, json.dumps(await self.comfy.object_info()))
|
|
192
|
+
return self._object_info[1]
|
|
193
|
+
|
|
194
|
+
async def _on_message(self, conn: DataConnection, msg: Any) -> None:
|
|
195
|
+
if not isinstance(msg, dict):
|
|
196
|
+
return
|
|
197
|
+
t = msg.get("t")
|
|
198
|
+
guest = self.guests.get(conn.peer_id)
|
|
199
|
+
|
|
200
|
+
if t == "hello" and guest is None:
|
|
201
|
+
name = str(msg.get("name") or "Guest")[:40]
|
|
202
|
+
slot = self._free_slot()
|
|
203
|
+
if slot < 0:
|
|
204
|
+
await conn.send({"t": "bye", "reason": "Session is full."})
|
|
205
|
+
return
|
|
206
|
+
try:
|
|
207
|
+
object_info = await self._object_info_json()
|
|
208
|
+
except (ComfyError, OSError, Exception) as e: # noqa: BLE001
|
|
209
|
+
log.warning("cannot reach ComfyUI for %s: %s", name, e)
|
|
210
|
+
await conn.send({"t": "bye", "reason": "The host's ComfyUI server isn't running right now."})
|
|
211
|
+
return
|
|
212
|
+
info = {"id": conn.peer_id, "name": name, "color": COLORS[slot % len(COLORS)], "slot": slot}
|
|
213
|
+
guest = Guest(conn, info)
|
|
214
|
+
guest.sender = asyncio.create_task(self._sender(guest))
|
|
215
|
+
self.guests[conn.peer_id] = guest
|
|
216
|
+
self._send(guest, {
|
|
217
|
+
"t": "welcome",
|
|
218
|
+
"self": info,
|
|
219
|
+
"objectInfo": object_info,
|
|
220
|
+
"graph": self.serialize(),
|
|
221
|
+
"exec": self.exec_snapshot(),
|
|
222
|
+
})
|
|
223
|
+
self._publish_peers()
|
|
224
|
+
log.info("%s joined (%d guest%s)", name, len(self.guests), "" if len(self.guests) == 1 else "s")
|
|
225
|
+
return
|
|
226
|
+
|
|
227
|
+
if guest is None:
|
|
228
|
+
return
|
|
229
|
+
if t == "ops" and isinstance(msg.get("ops"), list):
|
|
230
|
+
self.apply_ops(msg["ops"])
|
|
231
|
+
self.broadcast({"t": "ops", "ops": msg["ops"], "from": conn.peer_id}, except_id=conn.peer_id)
|
|
232
|
+
elif t == "cursor":
|
|
233
|
+
self.broadcast({"t": "cursor", "id": conn.peer_id, "x": msg.get("x"), "y": msg.get("y")}, except_id=conn.peer_id)
|
|
234
|
+
elif t == "queue":
|
|
235
|
+
result = await self._queue(guest, msg)
|
|
236
|
+
self._send(guest, {"t": "queued", "reqId": msg.get("reqId"), **result})
|
|
237
|
+
|
|
238
|
+
def _on_close(self, conn: DataConnection) -> None:
|
|
239
|
+
guest = self.guests.pop(conn.peer_id, None)
|
|
240
|
+
if guest is None:
|
|
241
|
+
return
|
|
242
|
+
if guest.sender:
|
|
243
|
+
guest.sender.cancel()
|
|
244
|
+
log.info("%s left", guest.info["name"])
|
|
245
|
+
self._publish_peers()
|
|
246
|
+
|
|
247
|
+
# ------------------------------------------------------------------ running prompts
|
|
248
|
+
|
|
249
|
+
async def _queue(self, guest: Guest, msg: dict) -> dict:
|
|
250
|
+
prompts = msg.get("prompts")
|
|
251
|
+
if not isinstance(prompts, list) or not prompts:
|
|
252
|
+
return {"ok": False, "error": "Please reload the web app: this host needs prompts built by the client."}
|
|
253
|
+
if not self.comfy_up:
|
|
254
|
+
return {"ok": False, "error": "The host's ComfyUI server isn't running right now."}
|
|
255
|
+
log.info("%s queued %d prompt(s)", guest.info["name"], len(prompts))
|
|
256
|
+
self.node_errors = {}
|
|
257
|
+
count = 0
|
|
258
|
+
for prompt in prompts[:100]:
|
|
259
|
+
try:
|
|
260
|
+
await self.comfy.queue_prompt(prompt, {"extra_pnginfo": {"workflow": self.serialize()}})
|
|
261
|
+
count += 1
|
|
262
|
+
except ComfyError as e:
|
|
263
|
+
errors = (e.body or {}).get("node_errors") if isinstance(e.body, dict) else None
|
|
264
|
+
lines = []
|
|
265
|
+
if errors:
|
|
266
|
+
for nid, info in errors.items():
|
|
267
|
+
msgs = [f"{er.get('message')}: {er.get('details')}" if er.get("details") else er.get("message") for er in info.get("errors", [])]
|
|
268
|
+
self.node_errors[str(nid)] = msgs
|
|
269
|
+
lines += [f"• {info.get('class_type')} #{nid}: {er.get('details') or er.get('message')}" for er in info.get("errors", [])]
|
|
270
|
+
self._exec_changed()
|
|
271
|
+
return {"ok": False, "error": "\n".join([f"Queue failed: {e}", *lines[:6]])}
|
|
272
|
+
except (OSError, Exception) as e: # noqa: BLE001
|
|
273
|
+
return {"ok": False, "error": f"Queue failed: {e}"}
|
|
274
|
+
return {"ok": True, "count": count}
|
|
275
|
+
|
|
276
|
+
def exec_snapshot(self) -> dict:
|
|
277
|
+
return {
|
|
278
|
+
"running": self.running,
|
|
279
|
+
"queueRemaining": self.queue_remaining,
|
|
280
|
+
"executedNodes": sorted(self.executed),
|
|
281
|
+
"nodeErrors": self.node_errors,
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
def _exec_changed(self) -> None:
|
|
285
|
+
if self._exec_handle:
|
|
286
|
+
self._exec_handle.cancel()
|
|
287
|
+
self._exec_handle = asyncio.get_running_loop().call_later(
|
|
288
|
+
0.06, lambda: self.broadcast({"t": "exec", **self.exec_snapshot()})
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
def _finish_run(self) -> None:
|
|
292
|
+
if self.running and self.running.get("nodeId"):
|
|
293
|
+
self.executed.add(self.running["nodeId"])
|
|
294
|
+
self.running = None
|
|
295
|
+
self._exec_changed()
|
|
296
|
+
|
|
297
|
+
async def on_comfy_message(self, kind: str, data: Any) -> None:
|
|
298
|
+
data = data or {}
|
|
299
|
+
if kind == "status":
|
|
300
|
+
self.queue_remaining = (data.get("status") or {}).get("exec_info", {}).get("queue_remaining", 0)
|
|
301
|
+
elif kind == "execution_start":
|
|
302
|
+
self.running = {"promptId": data.get("prompt_id"), "nodeId": None, "value": 0, "max": 0}
|
|
303
|
+
self.executed = set()
|
|
304
|
+
self.node_errors = {}
|
|
305
|
+
elif kind == "execution_cached":
|
|
306
|
+
self.executed.update(str(n) for n in data.get("nodes") or [])
|
|
307
|
+
elif kind == "executing":
|
|
308
|
+
if data.get("node") is None:
|
|
309
|
+
self._finish_run()
|
|
310
|
+
return
|
|
311
|
+
if self.running is None:
|
|
312
|
+
self.running = {"promptId": data.get("prompt_id"), "nodeId": None, "value": 0, "max": 0}
|
|
313
|
+
if self.running.get("nodeId"):
|
|
314
|
+
self.executed.add(self.running["nodeId"])
|
|
315
|
+
self.running.update(nodeId=str(data.get("display_node") or data.get("node")), value=0, max=0)
|
|
316
|
+
elif kind == "progress":
|
|
317
|
+
if self.running is not None:
|
|
318
|
+
self.running.update(nodeId=str(data.get("node") or self.running.get("nodeId")), value=data.get("value"), max=data.get("max"))
|
|
319
|
+
elif kind == "executed":
|
|
320
|
+
await self._forward_images(data)
|
|
321
|
+
return
|
|
322
|
+
elif kind in ("execution_success", "execution_interrupted"):
|
|
323
|
+
self._finish_run()
|
|
324
|
+
return
|
|
325
|
+
elif kind == "execution_error":
|
|
326
|
+
nid = str(data.get("node_id"))
|
|
327
|
+
self.node_errors = {**self.node_errors, nid: [data.get("exception_message", "Error")]}
|
|
328
|
+
log.warning("run failed at %s #%s: %s", data.get("node_type"), nid, data.get("exception_message"))
|
|
329
|
+
self._finish_run()
|
|
330
|
+
return
|
|
331
|
+
else:
|
|
332
|
+
return
|
|
333
|
+
self._exec_changed()
|
|
334
|
+
|
|
335
|
+
async def _forward_images(self, data: dict) -> None:
|
|
336
|
+
node_id = str(data.get("display_node") or data.get("node"))
|
|
337
|
+
for im in (data.get("output") or {}).get("images") or []:
|
|
338
|
+
if not im.get("filename") or not self.guests:
|
|
339
|
+
continue
|
|
340
|
+
try:
|
|
341
|
+
buf, mime = await self.comfy.view(im["filename"], im.get("subfolder", ""), im.get("type", "output"))
|
|
342
|
+
except Exception as e: # noqa: BLE001
|
|
343
|
+
log.warning("could not fetch %s: %s", im.get("filename"), e)
|
|
344
|
+
continue
|
|
345
|
+
if len(buf) > MAX_IMAGE_BYTES:
|
|
346
|
+
continue
|
|
347
|
+
self.broadcast({
|
|
348
|
+
"t": "image",
|
|
349
|
+
"nodeId": node_id,
|
|
350
|
+
"promptId": data.get("prompt_id"),
|
|
351
|
+
"filename": im["filename"],
|
|
352
|
+
"mime": mime,
|
|
353
|
+
"buf": buf,
|
|
354
|
+
})
|
|
355
|
+
|
|
356
|
+
async def on_comfy_preview(self, buf: bytes, mime: str) -> None:
|
|
357
|
+
if self.guests and self.running:
|
|
358
|
+
self.broadcast({"t": "preview", "mime": mime, "buf": buf})
|
|
359
|
+
|
|
360
|
+
async def on_comfy_state(self, up: bool) -> None:
|
|
361
|
+
if up != self.comfy_up:
|
|
362
|
+
self.comfy_up = up
|
|
363
|
+
log.info("ComfyUI is %s", "reachable" if up else "unreachable")
|
|
364
|
+
if not up and self.running:
|
|
365
|
+
self._finish_run()
|
|
366
|
+
|
|
367
|
+
async def shutdown(self) -> None:
|
|
368
|
+
if self._save_handle:
|
|
369
|
+
self._save_handle.cancel()
|
|
370
|
+
self._save_now()
|
|
371
|
+
for g in list(self.guests.values()):
|
|
372
|
+
try:
|
|
373
|
+
await asyncio.wait_for(g.conn.send({"t": "bye", "reason": "The host stopped the session."}), 2)
|
|
374
|
+
except Exception: # noqa: BLE001
|
|
375
|
+
pass
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
"""A minimal PeerJS-compatible peer that *accepts* data connections, built on aiortc.
|
|
2
|
+
|
|
3
|
+
Implements just what a host needs to interoperate with the PeerJS 1.5 browser client:
|
|
4
|
+
* the signalling protocol (websocket to a PeerJS server: OPEN / HEARTBEAT / OFFER / ANSWER /
|
|
5
|
+
CANDIDATE / LEAVE / EXPIRE / ID-TAKEN)
|
|
6
|
+
* answering offers with aiortc (our ICE candidates are bundled in the SDP answer; the browser's
|
|
7
|
+
trickled candidates are added as they arrive)
|
|
8
|
+
* "binary" serialization: BinaryPack, with PeerJS's chunking of messages over 16300 bytes into
|
|
9
|
+
{__peerData: id, n, total, data} pieces, and the {__peerData: {type: "close"}} goodbye
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import asyncio
|
|
15
|
+
import json
|
|
16
|
+
import logging
|
|
17
|
+
import math
|
|
18
|
+
import secrets
|
|
19
|
+
from collections import defaultdict
|
|
20
|
+
from typing import Any, Awaitable, Callable
|
|
21
|
+
|
|
22
|
+
import aiohttp
|
|
23
|
+
from aiortc import RTCConfiguration, RTCIceServer, RTCPeerConnection, RTCSessionDescription
|
|
24
|
+
from aiortc.sdp import candidate_from_sdp
|
|
25
|
+
|
|
26
|
+
from . import binarypack
|
|
27
|
+
|
|
28
|
+
log = logging.getLogger("peerjs")
|
|
29
|
+
|
|
30
|
+
CHUNKED_MTU = 16300 # must match PeerJS (Firefox↔Chrome friendly size)
|
|
31
|
+
HEARTBEAT_SECONDS = 5
|
|
32
|
+
MAX_BUFFERED = 8 * 1024 * 1024
|
|
33
|
+
PEERJS_CLIENT_VERSION = "1.5.5"
|
|
34
|
+
|
|
35
|
+
DEFAULT_STUN = [RTCIceServer(urls="stun:stun.l.google.com:19302")]
|
|
36
|
+
PEERJS_TURN = RTCIceServer(
|
|
37
|
+
urls=["turn:eu-0.turn.peerjs.com:3478", "turn:us-0.turn.peerjs.com:3478"],
|
|
38
|
+
username="peerjs",
|
|
39
|
+
credential="peerjsp",
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class PeerError(RuntimeError):
|
|
44
|
+
def __init__(self, kind: str, message: str):
|
|
45
|
+
super().__init__(message)
|
|
46
|
+
self.kind = kind
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class DataConnection:
|
|
50
|
+
"""One browser peer connected to us over an RTCDataChannel."""
|
|
51
|
+
|
|
52
|
+
def __init__(self, peer: "Peer", peer_id: str, connection_id: str, payload: dict):
|
|
53
|
+
self.peer = peer
|
|
54
|
+
self.peer_id = peer_id
|
|
55
|
+
self.connection_id = connection_id
|
|
56
|
+
self.metadata = payload.get("metadata")
|
|
57
|
+
self.serialization = payload.get("serialization", "binary")
|
|
58
|
+
self.pc = RTCPeerConnection(peer.rtc_config)
|
|
59
|
+
self.channel = None
|
|
60
|
+
self.open = False
|
|
61
|
+
self._chunks: dict[int, dict] = {}
|
|
62
|
+
self._chunk_id = 1
|
|
63
|
+
self._closed = False
|
|
64
|
+
self.on_open: Callable[[DataConnection], Any] | None = None
|
|
65
|
+
self.on_data: Callable[[DataConnection, Any], Any] | None = None
|
|
66
|
+
self.on_close: Callable[[DataConnection], Any] | None = None
|
|
67
|
+
|
|
68
|
+
@self.pc.on("datachannel")
|
|
69
|
+
def _on_channel(channel):
|
|
70
|
+
self.channel = channel
|
|
71
|
+
channel.on("message", self._on_message)
|
|
72
|
+
channel.on("close", lambda: asyncio.ensure_future(self.close()))
|
|
73
|
+
if channel.readyState == "open":
|
|
74
|
+
self._mark_open()
|
|
75
|
+
else:
|
|
76
|
+
channel.on("open", self._mark_open)
|
|
77
|
+
|
|
78
|
+
@self.pc.on("connectionstatechange")
|
|
79
|
+
async def _on_state():
|
|
80
|
+
log.debug("%s connection state %s", self.peer_id, self.pc.connectionState)
|
|
81
|
+
if self.pc.connectionState in ("failed", "closed"):
|
|
82
|
+
await self.close()
|
|
83
|
+
|
|
84
|
+
def _mark_open(self):
|
|
85
|
+
if self.open:
|
|
86
|
+
return
|
|
87
|
+
self.open = True
|
|
88
|
+
log.info("data channel open with %s", self.peer_id)
|
|
89
|
+
if self.on_open:
|
|
90
|
+
self.on_open(self)
|
|
91
|
+
|
|
92
|
+
async def accept(self, offer_sdp: dict) -> None:
|
|
93
|
+
if self.serialization not in ("binary", "default"):
|
|
94
|
+
raise PeerError("serialization", f"Unsupported serialization {self.serialization!r} (only binary)")
|
|
95
|
+
await self.pc.setRemoteDescription(RTCSessionDescription(sdp=offer_sdp["sdp"], type=offer_sdp["type"]))
|
|
96
|
+
answer = await self.pc.createAnswer()
|
|
97
|
+
await self.pc.setLocalDescription(answer) # waits for ICE gathering; candidates go in the SDP
|
|
98
|
+
await self.peer.signal(
|
|
99
|
+
{
|
|
100
|
+
"type": "ANSWER",
|
|
101
|
+
"payload": {
|
|
102
|
+
"sdp": {"type": self.pc.localDescription.type, "sdp": self.pc.localDescription.sdp},
|
|
103
|
+
"type": "data",
|
|
104
|
+
"connectionId": self.connection_id,
|
|
105
|
+
},
|
|
106
|
+
"dst": self.peer_id,
|
|
107
|
+
}
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
async def add_candidate(self, cand: dict) -> None:
|
|
111
|
+
text = (cand or {}).get("candidate") or ""
|
|
112
|
+
if not text:
|
|
113
|
+
return
|
|
114
|
+
try:
|
|
115
|
+
candidate = candidate_from_sdp(text.split(":", 1)[1] if text.startswith("candidate:") else text)
|
|
116
|
+
except Exception: # noqa: BLE001 - malformed/unsupported candidate (e.g. unresolved mDNS)
|
|
117
|
+
log.debug("ignoring candidate %r", text)
|
|
118
|
+
return
|
|
119
|
+
candidate.sdpMid = cand.get("sdpMid")
|
|
120
|
+
candidate.sdpMLineIndex = cand.get("sdpMLineIndex")
|
|
121
|
+
try:
|
|
122
|
+
await self.pc.addIceCandidate(candidate)
|
|
123
|
+
except Exception as e: # noqa: BLE001
|
|
124
|
+
log.debug("addIceCandidate failed: %s", e)
|
|
125
|
+
|
|
126
|
+
# ------------------------------------------------------------------ data
|
|
127
|
+
|
|
128
|
+
def _on_message(self, message):
|
|
129
|
+
if isinstance(message, str):
|
|
130
|
+
log.debug("ignoring text message from %s", self.peer_id)
|
|
131
|
+
return
|
|
132
|
+
self._handle(bytes(message))
|
|
133
|
+
|
|
134
|
+
def _handle(self, raw: bytes):
|
|
135
|
+
try:
|
|
136
|
+
data = binarypack.unpack(raw)
|
|
137
|
+
except binarypack.BinaryPackError as e:
|
|
138
|
+
log.warning("bad message from %s: %s", self.peer_id, e)
|
|
139
|
+
return
|
|
140
|
+
peer_data = data.get("__peerData") if isinstance(data, dict) else None
|
|
141
|
+
if peer_data is not None:
|
|
142
|
+
if isinstance(peer_data, dict) and peer_data.get("type") == "close":
|
|
143
|
+
asyncio.ensure_future(self.close())
|
|
144
|
+
return
|
|
145
|
+
info = self._chunks.setdefault(peer_data, {"parts": {}, "total": data.get("total", 0)})
|
|
146
|
+
info["parts"][data.get("n", 0)] = data.get("data") or b""
|
|
147
|
+
if len(info["parts"]) == info["total"]:
|
|
148
|
+
del self._chunks[peer_data]
|
|
149
|
+
self._handle(b"".join(info["parts"][i] for i in range(info["total"])))
|
|
150
|
+
return
|
|
151
|
+
if self.on_data:
|
|
152
|
+
self.on_data(self, data)
|
|
153
|
+
|
|
154
|
+
async def send(self, data: Any) -> None:
|
|
155
|
+
"""Serialize, chunk if needed, and send with simple back-pressure."""
|
|
156
|
+
if not self.open or self.channel is None or self.channel.readyState != "open":
|
|
157
|
+
return
|
|
158
|
+
blob = binarypack.pack(data)
|
|
159
|
+
if len(blob) <= CHUNKED_MTU:
|
|
160
|
+
await self._send_raw(blob)
|
|
161
|
+
return
|
|
162
|
+
total = math.ceil(len(blob) / CHUNKED_MTU)
|
|
163
|
+
chunk_id = self._chunk_id
|
|
164
|
+
self._chunk_id += 1
|
|
165
|
+
for n in range(total):
|
|
166
|
+
piece = blob[n * CHUNKED_MTU : (n + 1) * CHUNKED_MTU]
|
|
167
|
+
await self._send_raw(binarypack.pack({"__peerData": chunk_id, "n": n, "data": piece, "total": total}))
|
|
168
|
+
|
|
169
|
+
async def _send_raw(self, blob: bytes) -> None:
|
|
170
|
+
while self.channel is not None and self.channel.bufferedAmount > MAX_BUFFERED:
|
|
171
|
+
await asyncio.sleep(0.02)
|
|
172
|
+
if self.channel is not None and self.channel.readyState == "open":
|
|
173
|
+
self.channel.send(blob)
|
|
174
|
+
|
|
175
|
+
async def close(self) -> None:
|
|
176
|
+
if self._closed:
|
|
177
|
+
return
|
|
178
|
+
self._closed = True
|
|
179
|
+
was_open = self.open
|
|
180
|
+
self.open = False
|
|
181
|
+
self.peer.connections.pop(self.connection_id, None)
|
|
182
|
+
try:
|
|
183
|
+
await self.pc.close()
|
|
184
|
+
except Exception: # noqa: BLE001
|
|
185
|
+
pass
|
|
186
|
+
if was_open and self.on_close:
|
|
187
|
+
self.on_close(self)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class Peer:
|
|
191
|
+
"""Registers an id with a PeerJS server and accepts incoming data connections."""
|
|
192
|
+
|
|
193
|
+
def __init__(
|
|
194
|
+
self,
|
|
195
|
+
peer_id: str,
|
|
196
|
+
*,
|
|
197
|
+
host: str = "0.peerjs.com",
|
|
198
|
+
port: int = 443,
|
|
199
|
+
path: str = "/",
|
|
200
|
+
key: str = "peerjs",
|
|
201
|
+
secure: bool = True,
|
|
202
|
+
ice_servers: list[RTCIceServer] | None = None,
|
|
203
|
+
):
|
|
204
|
+
self.id = peer_id
|
|
205
|
+
scheme = "wss" if secure else "ws"
|
|
206
|
+
self.base_url = f"{scheme}://{host}:{port}{path.rstrip('/')}/peerjs?key={key}"
|
|
207
|
+
self.rtc_config = RTCConfiguration(iceServers=ice_servers or DEFAULT_STUN)
|
|
208
|
+
self.connections: dict[str, DataConnection] = {}
|
|
209
|
+
self.on_connection: Callable[[DataConnection], Awaitable[None] | None] | None = None
|
|
210
|
+
self._ws: aiohttp.ClientWebSocketResponse | None = None
|
|
211
|
+
self._session: aiohttp.ClientSession | None = None
|
|
212
|
+
self._pending: dict[str, list[dict]] = defaultdict(list) # candidates before their offer
|
|
213
|
+
self._opened = asyncio.Event()
|
|
214
|
+
self._stopping = False
|
|
215
|
+
|
|
216
|
+
async def signal(self, message: dict) -> None:
|
|
217
|
+
if self._ws is not None and not self._ws.closed:
|
|
218
|
+
await self._ws.send_str(json.dumps(message))
|
|
219
|
+
|
|
220
|
+
async def run(self) -> None:
|
|
221
|
+
"""Stay registered with the signalling server, reconnecting with backoff."""
|
|
222
|
+
self._session = aiohttp.ClientSession()
|
|
223
|
+
delay = 1.0
|
|
224
|
+
try:
|
|
225
|
+
while not self._stopping:
|
|
226
|
+
try:
|
|
227
|
+
await self._run_once()
|
|
228
|
+
delay = 1.0
|
|
229
|
+
except PeerError as e:
|
|
230
|
+
if e.kind == "unavailable-id":
|
|
231
|
+
# Our id is still held by a previous socket; the server frees it shortly.
|
|
232
|
+
log.warning("%s; retrying", e)
|
|
233
|
+
else:
|
|
234
|
+
raise
|
|
235
|
+
except (aiohttp.ClientError, OSError, asyncio.TimeoutError) as e:
|
|
236
|
+
log.warning("signalling connection problem: %s", e)
|
|
237
|
+
if self._stopping:
|
|
238
|
+
break
|
|
239
|
+
await asyncio.sleep(delay)
|
|
240
|
+
delay = min(delay * 2, 30)
|
|
241
|
+
finally:
|
|
242
|
+
await self._session.close()
|
|
243
|
+
|
|
244
|
+
async def _run_once(self) -> None:
|
|
245
|
+
token = secrets.token_hex(8)
|
|
246
|
+
url = f"{self.base_url}&id={self.id}&token={token}&version={PEERJS_CLIENT_VERSION}"
|
|
247
|
+
async with self._session.ws_connect(url, heartbeat=None) as ws:
|
|
248
|
+
self._ws = ws
|
|
249
|
+
heartbeat = asyncio.create_task(self._heartbeat(ws))
|
|
250
|
+
try:
|
|
251
|
+
async for msg in ws:
|
|
252
|
+
if msg.type != aiohttp.WSMsgType.TEXT:
|
|
253
|
+
continue
|
|
254
|
+
try:
|
|
255
|
+
await self._handle_server(json.loads(msg.data))
|
|
256
|
+
except PeerError:
|
|
257
|
+
raise
|
|
258
|
+
except Exception: # noqa: BLE001
|
|
259
|
+
log.exception("error handling signalling message")
|
|
260
|
+
finally:
|
|
261
|
+
heartbeat.cancel()
|
|
262
|
+
self._ws = None
|
|
263
|
+
self._opened.clear()
|
|
264
|
+
log.warning("signalling socket closed")
|
|
265
|
+
|
|
266
|
+
async def _heartbeat(self, ws) -> None:
|
|
267
|
+
while not ws.closed:
|
|
268
|
+
await asyncio.sleep(HEARTBEAT_SECONDS)
|
|
269
|
+
if not ws.closed:
|
|
270
|
+
await ws.send_str('{"type":"HEARTBEAT"}')
|
|
271
|
+
|
|
272
|
+
async def wait_open(self, timeout: float = 30) -> None:
|
|
273
|
+
await asyncio.wait_for(self._opened.wait(), timeout)
|
|
274
|
+
|
|
275
|
+
async def _handle_server(self, m: dict) -> None:
|
|
276
|
+
kind = m.get("type")
|
|
277
|
+
payload = m.get("payload") or {}
|
|
278
|
+
src = m.get("src")
|
|
279
|
+
if kind == "OPEN":
|
|
280
|
+
log.info("registered with PeerJS server as %s", self.id)
|
|
281
|
+
self._opened.set()
|
|
282
|
+
elif kind == "ID-TAKEN":
|
|
283
|
+
raise PeerError("unavailable-id", f'ID "{self.id}" is taken')
|
|
284
|
+
elif kind == "INVALID-KEY":
|
|
285
|
+
raise PeerError("invalid-key", "PeerJS API key is invalid")
|
|
286
|
+
elif kind == "ERROR":
|
|
287
|
+
raise PeerError("server-error", str(payload.get("msg")))
|
|
288
|
+
elif kind == "OFFER" and payload.get("type") == "data":
|
|
289
|
+
cid = payload.get("connectionId")
|
|
290
|
+
old = self.connections.pop(cid, None)
|
|
291
|
+
if old:
|
|
292
|
+
await old.close()
|
|
293
|
+
conn = DataConnection(self, src, cid, payload)
|
|
294
|
+
self.connections[cid] = conn
|
|
295
|
+
if self.on_connection:
|
|
296
|
+
res = self.on_connection(conn)
|
|
297
|
+
if asyncio.iscoroutine(res):
|
|
298
|
+
await res
|
|
299
|
+
try:
|
|
300
|
+
await conn.accept(payload["sdp"])
|
|
301
|
+
except Exception as e: # noqa: BLE001
|
|
302
|
+
log.warning("could not accept connection from %s: %s", src, e)
|
|
303
|
+
await conn.close()
|
|
304
|
+
return
|
|
305
|
+
for cand in self._pending.pop(cid, []):
|
|
306
|
+
await conn.add_candidate(cand)
|
|
307
|
+
elif kind == "CANDIDATE":
|
|
308
|
+
cid = payload.get("connectionId")
|
|
309
|
+
conn = self.connections.get(cid)
|
|
310
|
+
if conn:
|
|
311
|
+
await conn.add_candidate(payload.get("candidate"))
|
|
312
|
+
else:
|
|
313
|
+
self._pending[cid].append(payload.get("candidate"))
|
|
314
|
+
elif kind in ("LEAVE", "EXPIRE"):
|
|
315
|
+
for conn in [c for c in self.connections.values() if c.peer_id == src]:
|
|
316
|
+
await conn.close()
|
|
317
|
+
elif kind == "HEARTBEAT":
|
|
318
|
+
pass
|
|
319
|
+
else:
|
|
320
|
+
log.debug("unhandled server message %s", kind)
|
|
321
|
+
|
|
322
|
+
async def stop(self) -> None:
|
|
323
|
+
self._stopping = True
|
|
324
|
+
for conn in list(self.connections.values()):
|
|
325
|
+
await conn.close()
|
|
326
|
+
if self._ws is not None:
|
|
327
|
+
await self._ws.close()
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: comfy-peer-host
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Headless collaboration host for Comfy UI Web: lets people build and run ComfyUI graphs on this machine over WebRTC (PeerJS), no browser needed.
|
|
5
|
+
Project-URL: Homepage, https://github.com/mastashake08/comfy-peer-host
|
|
6
|
+
Project-URL: Repository, https://github.com/mastashake08/comfy-peer-host
|
|
7
|
+
Project-URL: Issues, https://github.com/mastashake08/comfy-peer-host/issues
|
|
8
|
+
Project-URL: Web app, https://mastashake08.github.io/comfy-ui-web/
|
|
9
|
+
Keywords: collaboration,comfyui,peerjs,stable-diffusion,webrtc
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Framework :: AsyncIO
|
|
13
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Multimedia :: Graphics
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Requires-Dist: aiohttp>=3.9
|
|
22
|
+
Requires-Dist: aiortc>=1.9
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# comfy-peer-host
|
|
26
|
+
|
|
27
|
+
A headless host for [Comfy UI Web](https://github.com/mastashake08/comfy-ui-web) collaboration sessions.
|
|
28
|
+
Run it on the computer that has ComfyUI, and people can join from their browser with an invite link.
|
|
29
|
+
They build the graph together and run it on this computer's ComfyUI, even when nobody has the web app open here.
|
|
30
|
+
|
|
31
|
+
It speaks the same peer-to-peer protocol as the web app's own **Collaborate** host (WebRTC over [PeerJS](https://peerjs.com)), so guests can't tell the difference:
|
|
32
|
+
|
|
33
|
+
- Guests get this server's node list and the shared graph, and their edits sync live between everyone.
|
|
34
|
+
- Anyone can press **Queue**. The prompt runs on this machine's ComfyUI, and progress, live previews, errors and result images stream back to every guest.
|
|
35
|
+
- The shared graph is saved to disk, and the session ID (so the invite link) stays the same across restarts.
|
|
36
|
+
|
|
37
|
+
## Install and run
|
|
38
|
+
|
|
39
|
+
Requires Python 3.11+.
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pipx install comfy-peer-host # or: uv tool install comfy-peer-host
|
|
43
|
+
comfy-peer-host # ComfyUI at http://127.0.0.1:8188
|
|
44
|
+
comfy-peer-host --comfy-url http://127.0.0.1:8189 --name "Studio PC"
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Or run it once without installing: `uvx comfy-peer-host`. From a source checkout: `uv run comfy-peer-host`.
|
|
48
|
+
|
|
49
|
+
It prints the invite link:
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
Comfy UI Web host is running.
|
|
53
|
+
Invite link: https://mastashake08.github.io/comfy-ui-web/#join=cuw-txvwcd8gectw
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Share the link, or have people paste the code into **Collaborate → Join** in the web app.
|
|
57
|
+
|
|
58
|
+
| Option | Default | |
|
|
59
|
+
| --- | --- | --- |
|
|
60
|
+
| `--comfy-url` | `http://127.0.0.1:8188` (or `$COMFY_URL`) | ComfyUI server to run prompts on |
|
|
61
|
+
| `--name` | `Host` | Name shown to guests |
|
|
62
|
+
| `--workflow FILE` | | Start the shared graph from a workflow saved in the web app (Workflow → Save) |
|
|
63
|
+
| `--state-dir` | `~/.comfy-peer-host` | Where the session ID and shared graph (`graph.json`) are kept |
|
|
64
|
+
| `--new-id` | | Make a new session ID; old invite links stop working |
|
|
65
|
+
| `--session-id cuw-…` | | Use a specific session ID |
|
|
66
|
+
| `--app-url` | the hosted web app | Web app used in the invite link |
|
|
67
|
+
| `--turn` | off | Also offer PeerJS's public TURN relay, for guests behind very strict networks |
|
|
68
|
+
| `--peerjs-host/-port/-path/-key`, `--insecure-signalling` | PeerJS cloud | Use your own PeerJS server |
|
|
69
|
+
|
|
70
|
+
ComfyUI needs no special flags: the host talks to it from the same machine.
|
|
71
|
+
|
|
72
|
+
### Keep it running (macOS)
|
|
73
|
+
|
|
74
|
+
Save this as `~/Library/LaunchAgents/com.comfy-peer-host.plist`, adjusting the paths, then run
|
|
75
|
+
`launchctl load ~/Library/LaunchAgents/com.comfy-peer-host.plist`:
|
|
76
|
+
|
|
77
|
+
```xml
|
|
78
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
79
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
80
|
+
<plist version="1.0"><dict>
|
|
81
|
+
<key>Label</key><string>com.comfy-peer-host</string>
|
|
82
|
+
<key>ProgramArguments</key><array>
|
|
83
|
+
<string>/path/to/comfy-peer-host</string> <!-- output of: which comfy-peer-host -->
|
|
84
|
+
<string>--name</string><string>Studio PC</string>
|
|
85
|
+
</array>
|
|
86
|
+
<key>RunAtLoad</key><true/>
|
|
87
|
+
<key>KeepAlive</key><true/>
|
|
88
|
+
<key>StandardOutPath</key><string>/tmp/comfy-peer-host.log</string>
|
|
89
|
+
<key>StandardErrorPath</key><string>/tmp/comfy-peer-host.log</string>
|
|
90
|
+
</dict></plist>
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Security
|
|
94
|
+
|
|
95
|
+
Anyone who has the invite link can edit the shared graph and run prompts on your GPU. Treat the link like a password.
|
|
96
|
+
Use `--new-id` to revoke it. Guests can't read your files: they only see the node list and the shared graph, and they can only queue prompts.
|
|
97
|
+
|
|
98
|
+
## How it works
|
|
99
|
+
|
|
100
|
+
- `peerjs.py`: a small PeerJS-compatible peer built on [aiortc](https://github.com/aiortc/aiortc). It registers with the PeerJS signalling server, answers guests' WebRTC offers, and uses PeerJS's "binary" data-channel format (BinaryPack, with messages over 16,300 bytes split into chunks).
|
|
101
|
+
- `binarypack.py`: a byte-for-byte port of `peerjs-js-binarypack`, tested against vectors produced by the JavaScript library.
|
|
102
|
+
- `comfy.py`: async ComfyUI HTTP and websocket client.
|
|
103
|
+
- `host.py`: the session protocol (welcome, graph ops, cursors, queueing, forwarding progress, previews and images), matching the web app's `src/lib/collab.js`.
|
|
104
|
+
|
|
105
|
+
## Development
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
uv run --group dev pytest
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### Releasing
|
|
112
|
+
|
|
113
|
+
1. Bump `version` in `pyproject.toml` and commit.
|
|
114
|
+
2. Tag and push: `git tag v0.2.0 && git push origin v0.2.0`.
|
|
115
|
+
|
|
116
|
+
The **Release** workflow tests, checks the tag matches the version, builds the wheel and sdist, publishes them to
|
|
117
|
+
PyPI (trusted publishing, no token stored) and creates a GitHub Release with both files attached.
|
|
118
|
+
|
|
119
|
+
To regenerate the BinaryPack test vectors, run `tests/make_vectors.mjs` with Node from a `comfy-ui-web` checkout (it imports `peerjs-js-binarypack`).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
comfy_peer_host/__init__.py,sha256=RmCOXR3X3uZrdo1CaTJAreZ6GPRmjpnk8YTgWADOuQA,270
|
|
2
|
+
comfy_peer_host/__main__.py,sha256=sKWj5vzq78Iy6YesJfXrBjCRn2funVLoEtnqp8J7C6w,6079
|
|
3
|
+
comfy_peer_host/binarypack.py,sha256=OIsWsBAPAcpF1WeCcyXaIlqcQOW71Mdk0p3b5DQySfg,5838
|
|
4
|
+
comfy_peer_host/comfy.py,sha256=1fsCj9B77VUOeJcQ1SaEoudNBvcxtTlUauyCOc-a50c,4582
|
|
5
|
+
comfy_peer_host/host.py,sha256=xZ_L-GedoudPhX-th1GZdGD8_PVRq-tX458JSaR9f10,16130
|
|
6
|
+
comfy_peer_host/peerjs.py,sha256=Jgw5dOgzFkZTfliqNxBDUP0HEqlRcJRP55PsF8esDmA,13117
|
|
7
|
+
comfy_peer_host-0.1.0.dist-info/METADATA,sha256=pGBHf9PMH2fHSYKPFC3CG1CXoY8gl5LoW-TTOk2c148,5823
|
|
8
|
+
comfy_peer_host-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
comfy_peer_host-0.1.0.dist-info/entry_points.txt,sha256=LM4sY5jPMgSDGW8uWqzvfC-2RD2IjiueFDyLgrvPr2Y,66
|
|
10
|
+
comfy_peer_host-0.1.0.dist-info/RECORD,,
|