"""Render monitor: what the current (or last) chain run has finished, read from the hop cache. The hop cache keeps one entry per finished hop (a .mkv, the audio and a .json meta with `hop`, `of`, `prev_key`, `frames`, `fps`, `written`). That is enough to follow a run from any browser, whoever queued it: ComfyUI only sends live previews to the tab that queued the prompt, but the cache is on disk for everyone. `run_state()` finds the newest cached hop and walks back along `prev_key` (the exact chain of this run); where a hop has no `prev_key` (hop 1, a restart, a hand_tie hop), it takes the newest entry for hop n-1 of the same run length written before hop n. Labels (a title, each shot's id, its length and its place) come from the running or last prompt's HandTieClips `shot_plan` / `ref_plan` and the save prefix; they are kept in the cache folder so a ComfyUI restart does not lose them. The page at /h3_ref_chain/monitor polls it and plays each hop through the existing /hop_clip route. """ import glob import json import os import time from . import store as _store META_EXT = getattr(_store, "META_EXT", ".json") LABELS_FILE = "monitor_labels.json" def _roots(): for loc in ("user", "temp"): try: root = _store.cache_root(loc) except Exception: # noqa: BLE001 continue if os.path.isdir(root): yield root def _metas(): out = [] for root in _roots(): for p in glob.glob(os.path.join(root, "*" + META_EXT)): name = os.path.basename(p) if name.startswith("ptr_") or name == LABELS_FILE: continue key = name[: -len(META_EXT)] if not all(c in "0123456789abcdef" for c in key): continue try: with open(p, encoding="utf-8") as fh: m = json.load(fh) hop, of = int(m.get("hop")), int(m.get("of")) except Exception: # noqa: BLE001 continue if m.get("dry_run") or hop < 1 or of < 1: continue w = float(m.get("written") or os.path.getmtime(p)) out.append(dict(key=key, hop=hop, of=of, prev=m.get("prev_key"), written=w, frames=int(m.get("frames") or 0), fps=float(m.get("fps") or 24), w=int(m.get("width") or 0), h=int(m.get("height") or 0), pin_mech=m.get("pin_mech"))) return out def _queue(): """(running, pending count, the newest prompt dict we can see) from ComfyUI.""" try: from server import PromptServer q = PromptServer.instance.prompt_queue running, pending = q.get_current_queue() prompt = running[0][2] if running else None if prompt is None: hist = q.get_history(max_items=1) or {} for v in hist.values(): prompt = (v.get("prompt") or [None, None, None])[2] return len(running) > 0, len(pending), prompt except Exception: # noqa: BLE001 return None, None, None def _labels_from_prompt(prompt): """Title + one label per shot from a HandTieClips node in an API prompt, or None.""" if not isinstance(prompt, dict): return None chain = next((n for n in prompt.values() if isinstance(n, dict) and n.get("class_type") == "HandTieClips"), None) if not chain: return None inp = chain.get("inputs") or {} try: shots = json.loads(inp.get("shot_plan") or "{}").get("shots") or [] except Exception: # noqa: BLE001 return None plates = set() try: for r in (json.loads(inp.get("ref_plan") or "{}").get("refs") or []): if r.get("retention") == "reference" and r.get("tag"): plates.add(str(r["tag"])) except Exception: # noqa: BLE001 pass title = "" for n in prompt.values(): if isinstance(n, dict) and n.get("class_type") in ("HTCSaveVideo", "SaveVideo", "VHS_VideoCombine"): pre = str((n.get("inputs") or {}).get("filename_prefix") or "") if pre: title = pre.replace("\\", "/").rstrip("/").split("/")[-1] break out, place = [], "" for i, s in enumerate(shots): for t in (s.get("refs") or []): if str(t) in plates: place = str(t) break out.append({"id": str(s.get("id") or f"s{i + 1}"), "dur": str(s.get("duration") or ""), "place": place}) if not out: return None return {"title": title, "shots": out, "at": time.time()} def _labels(prompt): lab = _labels_from_prompt(prompt) roots = list(_roots()) if lab and roots: try: with open(os.path.join(roots[0], LABELS_FILE), "w", encoding="utf-8") as fh: json.dump(lab, fh) except OSError: pass return lab for root in roots: try: with open(os.path.join(root, LABELS_FILE), encoding="utf-8") as fh: return json.load(fh) except (OSError, ValueError): continue return None def run_state(max_age_h=36.0): metas = _metas() now = time.time() running, pending, prompt = _queue() base = {"ok": True, "running": running, "pending": pending, "now": now, "hops": [], "of": 0, "title": "", "shots": []} metas = [m for m in metas if now - m["written"] < max_age_h * 3600] lab = _labels(prompt) if not metas: if lab: base.update(title=lab.get("title", ""), shots=lab.get("shots", [])) return base by_key = {m["key"]: m for m in metas} newest = max(metas, key=lambda m: m["written"]) chain = {newest["hop"]: newest} cur = newest while cur["hop"] > 1: prev = by_key.get(cur["prev"]) if cur.get("prev") else None if prev is None or prev["hop"] != cur["hop"] - 1: cands = [m for m in metas if m["hop"] == cur["hop"] - 1 and m["of"] == cur["of"] and m["written"] <= cur["written"]] prev = max(cands, key=lambda m: m["written"]) if cands else None if prev is None: break chain[prev["hop"]] = prev cur = prev hops = [chain[k] for k in sorted(chain)] base.update(of=newest["of"], hops=[{k: v for k, v in h.items() if k != "prev"} for h in hops], last_hop=newest["hop"], last_written=newest["written"]) if lab and len(lab.get("shots") or []) == newest["of"]: base.update(title=lab.get("title", ""), shots=lab["shots"]) return base def links(port=None, listen=None): """Where this page can be opened from. `lan` is None when ComfyUI listens on loopback only (no --listen), so a phone cannot reach it. Nothing goes on the network: the address comes from the machine's own name lookup.""" import socket try: from comfy.cli_args import args # noqa: PLC0415 port = port or args.port listen = listen if listen is not None else args.listen except Exception: # noqa: BLE001 port, listen = port or 8188, listen or "127.0.0.1" hosts = [h.strip() for h in str(listen or "").split(",") if h.strip()] loopback = all(h in ("127.0.0.1", "localhost", "::1") for h in hosts) if hosts else True lan = None if not loopback: ip = next((h for h in hosts if h not in ("0.0.0.0", "::") and ":" not in h), None) if ip is None: # The machine's own addresses by name lookup (no socket opened): the # first private IPv4 is the one a phone on the same network can reach. try: addrs = socket.gethostbyname_ex(socket.gethostname())[2] except OSError: addrs = [] private = [a for a in addrs if a.startswith(("192.168.", "10.")) or (a.startswith("172.") and 16 <= int(a.split(".")[1]) <= 31)] ip = (private or [None])[0] if ip: lan = f"http://{ip}:{port}" return {"lan": lan, "port": port, "listen": listen} PAGE = r""" Render Monitor

Hand-Tie-Clips · render monitor

Waiting
for a render

Each tile starts looping as soon as its hop is finished. Tap one to watch it with sound. Updates every 15 s.

IDLE
Hop–
Per hop–
Est. finish–
Updated–

Hops

"""