diff --git a/nodes/api/__init__.py b/nodes/api/__init__.py index 85c565e9..1cc5994d 100644 --- a/nodes/api/__init__.py +++ b/nodes/api/__init__.py @@ -90,6 +90,7 @@ async def control_server(request): # Extract host and port from settings if provided host = settings.get("host") if settings else None port = settings.get("port") if settings else None + enable_metrics = settings.get("enableMetrics") if settings else None if action == "status": # Simply return the current server status @@ -98,7 +99,11 @@ async def control_server(request): "status": server_manager.get_status() }) elif action == "start": - success = await server_manager.start(port=port, host=host) + success = await server_manager.start( + port=port, + host=host, + enable_metrics=enable_metrics + ) return web.json_response({ "success": success, "status": server_manager.get_status() @@ -120,7 +125,11 @@ async def control_server(request): "message": "Forced server shutdown due to error" }) elif action == "restart": - success = await server_manager.restart(port=port, host=host) + success = await server_manager.restart( + port=port, + host=host, + enable_metrics=enable_metrics + ) return web.json_response({ "success": success, "status": server_manager.get_status() @@ -178,10 +187,16 @@ async def manage_configuration(request): name = data.get("name") host = data.get("host") port = data.get("port") + enable_metrics = data.get("enableMetrics") if not name or not host or not port: return web.json_response({"error": "Missing required parameters"}, status=400) - success = settings_storage.add_configuration(name, host, port) + success = settings_storage.add_configuration( + name, + host, + port, + enable_metrics + ) return web.json_response({ "success": success, "settings": settings_storage.load_settings() @@ -214,4 +229,3 @@ async def manage_configuration(request): except Exception as e: logging.error(f"Error managing configuration: {str(e)}") return web.json_response({"error": str(e)}, status=500) - diff --git a/nodes/server_manager.py b/nodes/server_manager.py index a7436d33..c38cfa67 100644 --- a/nodes/server_manager.py +++ b/nodes/server_manager.py @@ -34,15 +34,18 @@ def __init__(self, host="0.0.0.0", port=None): self.host = host self.port = port self.is_running = False + self.enable_metrics = False logging.info(f"Initializing {self.__class__.__name__}") @abstractmethod - async def start(self, port=None, host=None) -> bool: + async def start(self, port=None, host=None, enable_metrics=None) -> bool: """Start the ComfyStream server Args: port: Optional port to use. If None, implementation should choose a port. host: Optional host to use. If None, implementation should use the default host. + enable_metrics: Optional flag to enable metrics endpoint. If None, use the + current setting. Returns: bool: True if server started successfully, False otherwise @@ -76,22 +79,32 @@ def check_server_health(self) -> bool: """ pass - async def restart(self, port=None, host=None) -> bool: - """Restart the ComfyStream server + async def restart(self, port=None, host=None, enable_metrics=None) -> bool: + """Restart the ComfyStream server. Args: port: Optional port to use. If None, use the current port. host: Optional host to use. If None, use the current host. + enable_metrics: Optional flag to enable metrics endpoint. If None, use the + current setting. Returns: - bool: True if server restarted successfully, False otherwise + bool: True if server restarted successfully, False otherwise. """ logging.info("Restarting ComfyStream server...") # Use provided values or current values port_to_use = port if port is not None else self.port host_to_use = host if host is not None else self.host + enable_metrics = ( + enable_metrics if enable_metrics is not None else self.enable_metrics + ) + await self.stop() - return await self.start(port=port_to_use, host=host_to_use) + return await self.start( + port=port_to_use, + host=host_to_use, + enable_metrics=enable_metrics + ) class LocalComfyStreamServer(ComfyStreamServerBase): """Local ComfyStream server implementation""" @@ -136,8 +149,18 @@ def log_subprocess_output(self, pipe, level): for line in iter(pipe.readline, b''): logging.log(level, line.decode().strip()) - async def start(self, port=None, host=None): - """Start the ComfyStream server""" + async def start(self, port=None, host=None, enable_metrics=None): + """Start the ComfyStream server. + + Args: + port: Optional port to use. If None, find an available port. + host: Optional host to use. If None, use the current host. + enable_metrics: Optional flag to enable metrics endpoint. If None, use the + current setting. + + Returns: + bool: True if server started successfully, False otherwise. + """ if self.is_running: logging.info("Server is already running") return False @@ -146,7 +169,9 @@ async def start(self, port=None, host=None): self.port = port or self.find_available_port() if host is not None: self.host = host - + if enable_metrics is not None: + self.enable_metrics = enable_metrics + # Get the path to the ComfyStream server directory and script server_dir = Path(__file__).parent.parent / "server" server_script = server_dir / "app.py" @@ -161,6 +186,8 @@ async def start(self, port=None, host=None): "--port", str(self.port), "--host", str(self.host), "--workspace", str(comfyui_workspace)] + if self.enable_metrics: + cmd.append("--monitor") logging.info(f"Starting server with command: {' '.join(cmd)}") @@ -247,4 +274,4 @@ def cleanup(self): except Exception as e: logging.error(f"Error cleaning up server process: {str(e)}") self.process = None - self.is_running = False \ No newline at end of file + self.is_running = False diff --git a/nodes/settings_storage.py b/nodes/settings_storage.py index 5d888b61..7fb33f71 100644 --- a/nodes/settings_storage.py +++ b/nodes/settings_storage.py @@ -15,6 +15,7 @@ DEFAULT_SETTINGS = { "host": "0.0.0.0", "port": 8889, + "enableMetrics": False, "configurations": [], "selectedConfigIndex": -1 } @@ -78,12 +79,17 @@ def update_settings(new_settings): return save_settings(current_settings) -def add_configuration(name, host, port): +def add_configuration(name, host, port, enable_metrics): """Add a new configuration""" settings = load_settings() # Create the new configuration - config = {"name": name, "host": host, "port": port} + config = { + "name": name, + "host": host, + "port": port, + "enableMetrics": enable_metrics + } # Add to configurations list settings["configurations"].append(config) @@ -125,9 +131,10 @@ def select_configuration(index): config = settings["configurations"][index] settings["host"] = config["host"] settings["port"] = config["port"] + settings["enableMetrics"] = config["enableMetrics"] # Save updated settings return save_settings(settings) else: logging.error(f"Invalid configuration index: {index}") - return False \ No newline at end of file + return False diff --git a/nodes/web/js/launcher.js b/nodes/web/js/launcher.js index 7caf6e4f..ce3924cd 100644 --- a/nodes/web/js/launcher.js +++ b/nodes/web/js/launcher.js @@ -101,7 +101,7 @@ document.addEventListener('comfy-extension-registered', (event) => { async function controlServer(action) { try { // Get settings from the settings manager - const settings = settingsManager.getCurrentHostPort(); + const settings = settingsManager.getCurrentServerSettings(); // Set transitional state based on action if (action === 'start') { @@ -308,4 +308,4 @@ const extension = { } }; -app.registerExtension(extension); \ No newline at end of file +app.registerExtension(extension); diff --git a/nodes/web/js/settings.js b/nodes/web/js/settings.js index 888917e8..23ce669a 100644 --- a/nodes/web/js/settings.js +++ b/nodes/web/js/settings.js @@ -4,10 +4,22 @@ console.log("[ComfyStream Settings] Initializing settings module"); const DEFAULT_SETTINGS = { host: "0.0.0.0", port: 8889, + enableMetrics: false, configurations: [], selectedConfigIndex: -1 // -1 means no configuration is selected }; +/** + * Updates the metrics toggle button UI. + * @param {HTMLButtonElement} button - The toggle button element. + * @param {boolean} enabled - Whether metrics are enabled. + */ +function updateMetricsToggleButton(button, enabled) { + button.textContent = enabled ? "Enabled" : "Disabled"; + button.classList.toggle("primary", enabled); + button.classList.toggle("selected", enabled); +} + class ComfyStreamSettings { constructor() { this.settings = DEFAULT_SETTINGS; @@ -94,7 +106,7 @@ class ComfyStreamSettings { return this.settings; } - async addConfiguration(name, host, port) { + async addConfiguration(name, host, port, enableMetrics) { try { const response = await fetch('/comfystream/settings/configuration', { method: 'POST', @@ -105,7 +117,8 @@ class ComfyStreamSettings { action: 'add', name, host, - port + port, + enableMetrics }) }); @@ -116,7 +129,7 @@ class ComfyStreamSettings { const result = await response.json(); if (result.success) { this.settings = result.settings; - return { name, host, port }; + return { name, host, port, enableMetrics }; } else { throw new Error("Failed to add configuration"); } @@ -124,7 +137,7 @@ class ComfyStreamSettings { console.error("[ComfyStream Settings] Error adding configuration:", error); // Fallback to local operation - const config = { name, host, port }; + const config = { name, host, port, enableMetrics }; this.settings.configurations.push(config); await this.saveSettings(); return config; @@ -207,11 +220,12 @@ class ComfyStreamSettings { if (index >= -1 && index < this.settings.configurations.length) { this.settings.selectedConfigIndex = index; - // If a valid configuration is selected, update host and port + // If a valid configuration is selected, update the settings. if (index >= 0) { const config = this.settings.configurations[index]; this.settings.host = config.host; this.settings.port = config.port; + this.settings.enableMetrics = config.enableMetrics; } await this.saveSettings(); @@ -221,10 +235,11 @@ class ComfyStreamSettings { } } - getCurrentHostPort() { + getCurrentServerSettings() { return { host: this.settings.host, - port: this.settings.port + port: this.settings.port, + enableMetrics: this.settings.enableMetrics }; } @@ -557,6 +572,7 @@ async function showSettingsModal() { const hostLabel = document.createElement("label"); hostLabel.textContent = "Host:"; hostLabel.className = "cs-label"; + hostLabel.title = "Host address for the ComfyStream server"; const hostInput = document.createElement("input"); hostInput.id = "comfystream-host"; @@ -574,6 +590,7 @@ async function showSettingsModal() { const portLabel = document.createElement("label"); portLabel.textContent = "Port:"; portLabel.className = "cs-label"; + portLabel.title = "Port number for the ComfyStream server"; const portInput = document.createElement("input"); portInput.id = "comfystream-port"; @@ -585,6 +602,42 @@ async function showSettingsModal() { portGroup.appendChild(portLabel); portGroup.appendChild(portInput); + + // Metrics setting + const metricsGroup = document.createElement("div"); + metricsGroup.className = "cs-input-group"; + metricsGroup.style.display = "flex"; + metricsGroup.style.alignItems = "center"; + metricsGroup.style.gap = "18px"; + metricsGroup.style.marginBottom = "15px"; + + const metricsLabel = document.createElement("label"); + metricsLabel.textContent = "Metrics:"; + metricsLabel.className = "cs-label"; + metricsLabel.style.marginBottom = "0"; + metricsLabel.style.marginRight = "0"; + metricsLabel.style.flex = "none"; + metricsLabel.title = "Enable Prometheus metrics endpoint"; + + const metricsToggleButton = document.createElement("button"); + metricsToggleButton.className = "cs-button"; + metricsToggleButton.type = "button"; + console.log("[ComfyStream Settings] Initial metrics button state:", settingsManager.settings.enableMetrics); + metricsToggleButton.textContent = settingsManager.settings.enableMetrics ? "Enabled" : "Disabled"; + metricsToggleButton.style.minWidth = "90px"; + metricsToggleButton.style.alignSelf = "center"; + updateMetricsToggleButton(metricsToggleButton, settingsManager.settings.enableMetrics); + + metricsToggleButton.onclick = () => { + console.log("[ComfyStream Settings] Toggling metrics"); + const enabled = !settingsManager.settings.enableMetrics; + console.log("[ComfyStream Settings] New metrics state:", enabled); + settingsManager.settings.enableMetrics = enabled; + updateMetricsToggleButton(metricsToggleButton, enabled); + }; + + metricsGroup.appendChild(metricsLabel); + metricsGroup.appendChild(metricsToggleButton); // Configurations section const configsSection = document.createElement("div"); @@ -636,11 +689,16 @@ async function showSettingsModal() { saveButton.onclick = async () => { const host = hostInput.value; const port = parseInt(portInput.value); + const enableMetrics = settingsManager.settings.enableMetrics; // If the current values match a saved configuration, select it let matchingConfigIndex = -1; settingsManager.settings.configurations.forEach((config, index) => { - if (config.host === host && config.port === port) { + if ( + config.host === host && + config.port === port && + config.enableMetrics === enableMetrics + ) { matchingConfigIndex = index; } }); @@ -649,9 +707,10 @@ async function showSettingsModal() { await settingsManager.selectConfiguration(matchingConfigIndex); } else { // No matching configuration, just update the settings - await settingsManager.updateSettings({ - host, + await settingsManager.updateSettings({ + host, port, + enableMetrics, selectedConfigIndex: -1 // Reset selected config since we're using custom values }); } @@ -666,6 +725,7 @@ async function showSettingsModal() { form.appendChild(currentConfigDiv); form.appendChild(hostGroup); form.appendChild(portGroup); + form.appendChild(metricsGroup); form.appendChild(configsSection); modalContent.appendChild(closeButton); @@ -700,6 +760,7 @@ async function showSettingsModal() { const configInfo = document.createElement("span"); configInfo.className = "cs-config-info"; configInfo.textContent = `${config.name} (${config.host}:${config.port})`; + configInfo.style.minWidth = "190px"; const buttonsGroup = document.createElement("div"); buttonsGroup.className = "cs-buttons-group"; @@ -709,6 +770,7 @@ async function showSettingsModal() { selectButton.className = `cs-button comfystream-config-select ${index === settingsManager.settings.selectedConfigIndex ? 'selected' : ''}`; selectButton.dataset.index = index; selectButton.disabled = index === settingsManager.settings.selectedConfigIndex; + selectButton.style.marginLeft = "10px"; const loadButton = document.createElement("button"); loadButton.textContent = "Load"; @@ -748,6 +810,8 @@ async function showSettingsModal() { const config = settingsManager.settings.configurations[index]; hostInput.value = config.host; portInput.value = config.port; + settingsManager.settings.enableMetrics = config.enableMetrics; + updateMetricsToggleButton(metricsToggleButton, config.enableMetrics); // Refresh the list to update highlighting await updateConfigsList(); @@ -784,10 +848,11 @@ async function showSettingsModal() { const name = configNameInput.value.trim(); const host = hostInput.value; const port = parseInt(portInput.value); + const enableMetrics = settingsManager.settings.enableMetrics; if (name) { // Add the configuration - await settingsManager.addConfiguration(name, host, port); + await settingsManager.addConfiguration(name, host, port, enableMetrics); // Select the newly added configuration const newIndex = settingsManager.settings.configurations.length - 1; @@ -833,7 +898,11 @@ async function showSettingsModal() { const selectedIndex = settingsManager.settings.selectedConfigIndex; if (selectedIndex >= 0) { const config = settingsManager.settings.configurations[selectedIndex]; - if (hostInput.value !== config.host || parseInt(portInput.value) !== config.port) { + if ( + hostInput.value !== config.host || + parseInt(portInput.value) !== config.port || + settingsManager.settings.enableMetrics !== config.enableMetrics + ) { currentConfigName.textContent = "Custom (unsaved)"; currentConfigName.style.fontStyle = "italic"; } else { @@ -857,4 +926,4 @@ export { settingsManager, showSettingsModal }; window.comfyStreamSettings = { settingsManager, showSettingsModal -}; \ No newline at end of file +}; diff --git a/settings/comfystream_settings.json b/settings/comfystream_settings.json index d1b78d99..06e5c424 100644 --- a/settings/comfystream_settings.json +++ b/settings/comfystream_settings.json @@ -5,13 +5,16 @@ { "name": "RunPod", "host": "0.0.0.0", - "port": 8889 + "port": 8889, + "enableMetrics": false }, { "name": "Localhost", "host": "localhost", - "port": 8889 + "port": 8889, + "enableMetrics": false } ], - "selectedConfigIndex": 1 -} \ No newline at end of file + "selectedConfigIndex": 1, + "enableMetrics": false +}