Files
ComfyUI/comfy_api/feature_flags.py
Christian Byrne 860a7fdc77 Report a per-start server_boot_id in server feature flags (#17835)
## What

Adds `server_boot_id` to the server feature flags (the `feature_flags`
WebSocket message and `GET /api/features`). It is a random hex id
generated once per server process, so it changes on every restart.

## Why

When `/ws` reconnects, the frontend cannot tell a dropped socket from a
real restart. After a restart, custom node packs may have been installed
or updated, so the page's node definitions can be stale. Today the
frontend guesses: it refreshes after Manager's own restart, after the
agent's `restart_comfyui`, and when `/object_info` has node types the
page doesn't know. It misses a restart that only changes an existing
pack's inputs, and it can refresh twice on the same restart.

With a boot id, the frontend can refresh node definitions exactly once
per real restart and skip the refresh after a plain socket drop.
Frontend follow-up: https://linear.app/comfyorg/issue/FRONT-3668

## Details

- Core flag, so `--feature-flag server_boot_id=...` cannot override it.
- Documented in `openapi.yaml` as local-only.
- Older frontends ignore the unknown key.

## Tests

`tests-unit/feature_flags_test.py`: the id is a 32-character string,
stable within a process, and not overridable from the CLI. The three new
tests fail before the change. `feature_flags_test.py` (41) and
`websocket_feature_flags_test.py` (4) pass; ruff is clean.
2026-11-21 01:07:45 -08:00

202 lines
6.4 KiB
Python

"""
Feature flags module for ComfyUI WebSocket protocol negotiation.
This module handles capability negotiation between frontend and backend,
allowing graceful protocol evolution while maintaining backward compatibility.
"""
import logging
import uuid
from typing import Any, TypedDict
from comfy.cli_args import args
class FeatureFlagInfo(TypedDict):
type: str
default: Any
description: str
# Registry of known CLI-settable feature flags.
# Launchers can query this via --list-feature-flags to discover valid flags.
CLI_FEATURE_FLAG_REGISTRY: dict[str, FeatureFlagInfo] = {
"show_signin_button": {
"type": "bool",
"default": False,
"description": "Show the sign-in button in the frontend even when not signed in",
},
"enable_telemetry": {
"type": "bool",
"default": False,
"description": "Signal the frontend that telemetry collection is enabled",
},
"partner_run_gate_enabled": {
"type": "bool",
"default": True,
"description": "Gate the local Run button behind sign-in when the graph contains partner nodes",
},
"partner_node_token": {
"type": "bool",
"default": True,
"description": "Queue Local API-node prompts with a renewable partner-node token instead of the workspace token",
},
"local_web_sso": {
"type": "bool",
"default": True,
"description": "Offer Sign in with browser (Cloud OAuth + PKCE) on Local ComfyUI opened at localhost or 127.0.0.1",
},
}
def _coerce_bool(v: str) -> bool:
"""Strict bool coercion: only 'true'/'false' (case-insensitive).
Anything else raises ValueError so the caller can warn and drop the flag,
rather than silently treating typos like 'ture' or 'yes' as False.
"""
lower = v.lower()
if lower == "true":
return True
if lower == "false":
return False
raise ValueError(f"expected 'true' or 'false', got {v!r}")
_COERCE_FNS: dict[str, Any] = {
"bool": _coerce_bool,
"int": lambda v: int(v),
"float": lambda v: float(v),
}
def _coerce_flag_value(key: str, raw_value: str) -> Any:
"""Coerce a raw string value using the registry type, or keep as string.
Returns the raw string if the key is unregistered or the type is unknown.
Raises ValueError/TypeError if the key is registered with a known type but
the value cannot be coerced; callers are expected to warn and drop the flag.
"""
info = CLI_FEATURE_FLAG_REGISTRY.get(key)
if info is None:
return raw_value
coerce = _COERCE_FNS.get(info["type"])
if coerce is None:
return raw_value
return coerce(raw_value)
def _parse_cli_feature_flags() -> dict[str, Any]:
"""Parse --feature-flag key=value pairs from CLI args into a dict.
Items without '=' default to the value 'true' (bare flag form).
Flags whose value cannot be coerced to the registered type are dropped
with a warning, so a typo like '--feature-flag some_bool=ture' does not
silently take effect as the wrong value.
"""
result: dict[str, Any] = {}
for item in getattr(args, "feature_flag", []):
key, sep, raw_value = item.partition("=")
key = key.strip()
if not key:
continue
if not sep:
raw_value = "true"
try:
result[key] = _coerce_flag_value(key, raw_value.strip())
except (ValueError, TypeError) as e:
info = CLI_FEATURE_FLAG_REGISTRY.get(key, {})
logging.warning(
"Could not coerce --feature-flag %s=%r to %s (%s); dropping flag.",
key, raw_value.strip(), info.get("type", "?"), e,
)
return result
# Default server capabilities
_CORE_FEATURE_FLAGS: dict[str, Any] = {
"supports_preview_metadata": True,
"supports_model_type_tags": True,
"max_upload_size": args.max_upload_size * 1024 * 1024, # Convert MB to bytes
"extension": {"manager": {"supports_v4": True}},
"node_replacements": True,
# main.py replaces this at startup with the selected AssetManager's state.
"assets": not args.disable_assets,
# New on every server start. A client that reconnects and sees a different
# value knows the server restarted, so its node definitions may be stale.
"server_boot_id": uuid.uuid4().hex,
}
# Owned by app.deploy_to_cloud, which sets it via set_server_feature.
_SERVER_SET_FEATURE_FLAGS = ("deploy_to_cloud",)
def _server_feature_flags() -> dict[str, Any]:
"""Registry defaults, then core flags, then CLI flags. CLI flags cannot overwrite core or server-set flags; main.py may still set "assets"."""
registry_defaults = {k: info["default"] for k, info in CLI_FEATURE_FLAG_REGISTRY.items()}
cli_flags = {
k: v for k, v in _parse_cli_feature_flags().items()
if k not in _CORE_FEATURE_FLAGS and k not in _SERVER_SET_FEATURE_FLAGS
}
return {**registry_defaults, **_CORE_FEATURE_FLAGS, **cli_flags}
SERVER_FEATURE_FLAGS: dict[str, Any] = _server_feature_flags()
def get_connection_feature(
sockets_metadata: dict[str, dict[str, Any]],
sid: str,
feature_name: str,
default: Any = False
) -> Any:
"""
Get a feature flag value for a specific connection.
Args:
sockets_metadata: Dictionary of socket metadata
sid: Session ID of the connection
feature_name: Name of the feature to check
default: Default value if feature not found
Returns:
Feature value or default if not found
"""
if sid not in sockets_metadata:
return default
return sockets_metadata[sid].get("feature_flags", {}).get(feature_name, default)
def supports_feature(
sockets_metadata: dict[str, dict[str, Any]],
sid: str,
feature_name: str
) -> bool:
"""
Check if a connection supports a specific feature.
Args:
sockets_metadata: Dictionary of socket metadata
sid: Session ID of the connection
feature_name: Name of the feature to check
Returns:
Boolean indicating if feature is supported
"""
return get_connection_feature(sockets_metadata, sid, feature_name, False) is True
def get_server_features() -> dict[str, Any]:
"""
Get the server's feature flags.
Returns:
Dictionary of server feature flags
"""
return SERVER_FEATURE_FLAGS.copy()
def set_server_feature(name: str, value: Any) -> None:
"""Set a server feature flag reported to clients and returned by get_server_features."""
SERVER_FEATURE_FLAGS[name] = value