Transform your 3D texturing workflow with the power of generative AI, directly within Blender!
check that comfyui is reachable before starting work
sakalondcfb03c6f3ee0
diff --git a/stablegen/__init__.py b/stablegen/__init__.pyindex f5a91d3..c17ef19 100644--- a/stablegen/__init__.py+++ b/stablegen/__init__.py@@ -53,6 +53,7 @@ from .cameras import (MoveCameraOrder, ApplyCameraOrderPreset,)from .debug_tools import debug_classes as _debug_classes+from .core import server_monitorfrom .texturing.regression import REGRESSION_CLASSESfrom .texturing import masked_editfrom .utils import AddHDRI, ApplyModifiers, CurvesToMesh@@ -222,9 +223,11 @@ def register():)register_variant_properties()register_studio_ui()+ server_monitor.register()def unregister():+ server_monitor.unregister()unregister_studio_ui()unregister_variant_properties()masked_edit.unregister_properties()diff --git a/stablegen/core/callbacks.py b/stablegen/core/callbacks.pyindex 1b955df..fa8ccf6 100644--- a/stablegen/core/callbacks.py+++ b/stablegen/core/callbacks.py@@ -243,10 +243,9 @@ def update_combined(self, context):if not server_address:prefs.server_online = False- # Must mutate the lists in-place to keep existing references valid- import stablegen.core.state as _state- _state._cached_checkpoint_list = [("NO_SERVER", "Set Server Address", "...")]- _state._cached_lora_list = [("NO_SERVER", "Set Server Address", "...")]+ from . import state as _state+ _state._cached_checkpoint_list = [_state.no_server_item("")]+ _state._cached_lora_list = [_state.no_server_item("")]return Noneprint("[StableGen] Server address changed, checking asynchronously...")@@ -277,6 +276,8 @@ def update_combined(self, context):if not result.get('online', False):print("[StableGen] ComfyUI server is not reachable.")+ from . import state as _state+ _state.show_offline_lists(server_address)returnupdate_parameters(None, bpy.context)diff --git a/stablegen/core/preferences.py b/stablegen/core/preferences.pyindex 198f2ea..fd22aae 100644--- a/stablegen/core/preferences.py+++ b/stablegen/core/preferences.py@@ -321,6 +321,8 @@ class CheckServerStatus(bpy.types.Operator):bpy.app.timers.register(_deferred_refresh, first_interval=0.1)else:print(f"[StableGen] ComfyUI server unreachable or timed out at {server_addr}.")+ from . import state as _state+ _state.show_offline_lists(server_addr)type(self)._checking = Truetry:diff --git a/stablegen/core/properties.py b/stablegen/core/properties.pyindex 421de18..9f753b6 100644--- a/stablegen/core/properties.py+++ b/stablegen/core/properties.py@@ -276,19 +276,16 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,def initial_refresh():print("[StableGen] StableGen: Performing initial model list refresh...")try:- bpy.ops.stablegen.check_server_status('INVOKE_DEFAULT')prefs = bpy.context.preferences.addons.get(ADDON_PKG)- if not prefs or not prefs.preferences.server_online:- print("[StableGen] StableGen: Server not reachable during initial refresh.")- return None+ if prefs:+ # The saved value is from the last session; only a fresh check counts.+ prefs.preferences.server_online = False+ _sg_queue_load()if prefs and prefs.preferences.server_address:- bpy.ops.stablegen.refresh_checkpoint_list('INVOKE_DEFAULT')- bpy.ops.stablegen.refresh_lora_list('INVOKE_DEFAULT')- bpy.ops.stablegen.refresh_controlnet_mappings('INVOKE_DEFAULT')+ # Once the server answers, the check refreshes model lists and nodes.+ bpy.ops.stablegen.check_server_status('INVOKE_DEFAULT')else:print("[StableGen] StableGen: Server address not set, skipping initial refresh.")- load_handler(None)- _sg_queue_load()except Exception as e:print(f"[StableGen] StableGen: Error during initial refresh: {e}")return Nonediff --git a/stablegen/core/server_api.py b/stablegen/core/server_api.pyindex c137ae6..34419e7 100644--- a/stablegen/core/server_api.py+++ b/stablegen/core/server_api.py@@ -40,6 +40,36 @@ def check_server_availability(server_address, timeout=0.5):except requests.exceptions.ConnectionError:print("[StableGen] Initial server check failed: Connection Error.")return False+ except (requests.exceptions.RequestException, ValueError) as exc:+ # An HTTP error or malformed address is offline too; letting it escape+ # would leave the previous online state in place.+ print(f"[StableGen] Initial server check failed: {type(exc).__name__}: {exc}")+ return False+++def confirm_server(operator, context):+ """Ping ComfyUI right before starting work, since the saved status can be stale.++ Main thread only. Reports the problem on *operator* and marks the server+ offline when it is unreachable. Returns True when the work may start.+ """+ import bpy # pylint: disable=import-error+ if not bpy.app.online_access:+ operator.report({'ERROR'}, "Blender's online access is disabled (Preferences → System)")+ return False+ prefs = context.preferences.addons[ADDON_PKG].preferences+ if check_server_availability(prefs.server_address, timeout=get_timeout('ping')):+ prefs.server_online = True+ return True+ prefs.server_online = False+ operator.report({'ERROR'}, offline_message(prefs.server_address))+ return False+++def offline_message(server_address):+ if not server_address:+ return "Set the ComfyUI server address in StableGen preferences"+ return f"ComfyUI isn't reachable at {server_address}. Start ComfyUI or check the server address."def check_trellis2_available(server_address, timeout=1.0):diff --git a/stablegen/core/server_monitor.py b/stablegen/core/server_monitor.pynew file mode 100644index 0000000..52ed3e9--- /dev/null+++ b/stablegen/core/server_monitor.py@@ -0,0 +1,95 @@+"""Keep the ComfyUI online status current while a StableGen sidebar is open.++The status is otherwise only checked at startup and on demand, so the Generate+button kept trusting it after ComfyUI stopped, and needed a manual refresh+after ComfyUI started.+"""+import logging++import bpy # pylint: disable=import-error++from . import ADDON_PKG+from .server_api import check_server_availability+from .state import _run_async, show_offline_lists+from ..timeout_config import get_timeout+from ..utils import sg_modal_active++INTERVAL = 10.0+SIDEBAR_TABS = {'StableGen', 'StableGen Print'}++_log = logging.getLogger(__name__)+_in_flight = False+++def _sidebar_open(context):+ for window in context.window_manager.windows:+ for area in window.screen.areas:+ if area.type != 'VIEW_3D' or not area.spaces.active.show_region_ui:+ continue+ region = next((r for r in area.regions if r.type == 'UI'), None)+ if region and region.active_panel_category in SIDEBAR_TABS:+ return True+ return False+++def _busy(context):+ """Generation keeps its own connection; don't ping alongside it or another check."""+ from .preferences import CheckServerStatus+ scene = context.scene+ return (CheckServerStatus._checking or sg_modal_active(context)+ or (scene is not None and getattr(scene, 'generation_status', 'idle') == 'waiting'))+++def _redraw(context):+ for window in context.window_manager.windows:+ for area in window.screen.areas:+ if area.type == 'VIEW_3D':+ area.tag_redraw()+++def _apply(address, online):+ global _in_flight+ _in_flight = False+ context = bpy.context+ wrapper = context.preferences.addons.get(ADDON_PKG)+ # None means the check failed or a newer server check superseded it.+ if online is None or wrapper is None or wrapper.preferences.server_address != address:+ return+ prefs = wrapper.preferences+ if online and not prefs.server_online:+ # The full check also refreshes model lists and node availability.+ if bpy.ops.stablegen.check_server_status.poll():+ bpy.ops.stablegen.check_server_status('INVOKE_DEFAULT')+ elif not online and prefs.server_online:+ print(f"[StableGen] ComfyUI went offline at {address}.")+ prefs.server_online = False+ show_offline_lists(address)+ _redraw(context)+++def _tick():+ global _in_flight+ try:+ context = bpy.context+ wrapper = context.preferences.addons.get(ADDON_PKG)+ if (_in_flight or wrapper is None or not wrapper.preferences.server_address+ or not bpy.app.online_access or not _sidebar_open(context) or _busy(context)):+ return INTERVAL+ address = wrapper.preferences.server_address+ _in_flight = True+ _run_async(lambda: check_server_availability(address, timeout=get_timeout('ping')),+ lambda online: _apply(address, online))+ except Exception:+ _in_flight = False+ _log.exception('ComfyUI status check failed')+ return INTERVAL+++def register():+ if not bpy.app.background and not bpy.app.timers.is_registered(_tick):+ bpy.app.timers.register(_tick, first_interval=INTERVAL, persistent=True)+++def unregister():+ if bpy.app.timers.is_registered(_tick):+ bpy.app.timers.unregister(_tick)diff --git a/stablegen/core/state.py b/stablegen/core/state.pyindex 47ecd71..f520a49 100644--- a/stablegen/core/state.py+++ b/stablegen/core/state.py@@ -20,6 +20,22 @@ _pending_checkpoint_refresh_architecture = None_updating_print_preset = False+def no_server_item(server_address):+ """Model-list placeholder that says why the list is empty."""+ if not server_address:+ return ("NO_SERVER", "Set Server Address", "No ComfyUI server address is configured")+ return ("NO_SERVER", "No connection to ComfyUI", f"ComfyUI isn't reachable at {server_address}")+++def show_offline_lists(server_address):+ """Replace empty placeholders with the offline one; keep lists fetched earlier."""+ global _cached_checkpoint_list, _cached_lora_list+ if _cached_checkpoint_list[0][0] in {"NONE_AVAILABLE", "NO_SERVER"}:+ _cached_checkpoint_list = [no_server_item(server_address)]+ if _cached_lora_list[0][0] in {"NONE_AVAILABLE", "NO_SERVER"}:+ _cached_lora_list = [no_server_item(server_address)]++# ── In-flight refresh counter ─────────────────────────────────────────────_pending_refreshes = 0_refresh_started_at = 0.0 # monotonic timestamp of first in-flight refreshdiff --git a/stablegen/dae_import/batch_texture.py b/stablegen/dae_import/batch_texture.pyindex e79a934..296ca60 100644--- a/stablegen/dae_import/batch_texture.py+++ b/stablegen/dae_import/batch_texture.py@@ -11,6 +11,7 @@ import osfrom datetime import datetimeimport bpy # pylint: disable=import-error+from ..core import ADDON_PKGfrom ..utils import sg_modal_activefrom .batch_manifest import (discover_model_files,@@ -1160,7 +1161,7 @@ class BatchTextureDAE(bpy.types.Operator):return Falseif sg_modal_active(context):return False- addon_prefs = context.preferences.addons.get('stablegen')+ addon_prefs = context.preferences.addons.get(ADDON_PKG)if addon_prefs:prefs = addon_prefs.preferencesif not getattr(prefs, 'server_online', False):@@ -1220,6 +1221,9 @@ class BatchTextureDAE(bpy.types.Operator):box.prop(self, "continue_on_error")def execute(self, context):+ from ..core.server_api import confirm_server+ if not confirm_server(self, context):+ return {'CANCELLED'}manifest_path = bpy.path.abspath(self.manifest_path).strip()if manifest_path:try:diff --git a/stablegen/mesh_gen/trellis2.py b/stablegen/mesh_gen/trellis2.pyindex 0ce7189..4b3c338 100644--- a/stablegen/mesh_gen/trellis2.py+++ b/stablegen/mesh_gen/trellis2.py@@ -1305,6 +1305,10 @@ class Trellis2Generate(bpy.types.Operator):self.report({'WARNING'}, "TRELLIS.2 generation cancelled")return {'FINISHED'}+ from ..core.server_api import confirm_server+ if not confirm_server(self, context):+ return {'CANCELLED'}+scene = context.scenegen_from = getattr(scene, 'trellis2_generate_from', 'image')tex_mode = getattr(scene, 'trellis2_texture_mode', 'native')@@ -2784,6 +2788,10 @@ class StableGenAutoRigSelectedMesh(bpy.types.Operator):self.report({'WARNING'}, "Auto-rigging cancelled")return {'FINISHED'}+ from ..core.server_api import confirm_server+ if not confirm_server(self, context):+ return {'CANCELLED'}+selected_objects = list(context.selected_objects)selected_meshes = self._collect_character_meshes(selected_objects)if not selected_meshes:diff --git a/stablegen/texturing/generator.py b/stablegen/texturing/generator.pyindex 434c75d..d8c53e2 100644--- a/stablegen/texturing/generator.py+++ b/stablegen/texturing/generator.py@@ -805,6 +805,10 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):if is_masked_edit_mode(context.scene):return bpy.ops.stablegen.masked_edit()+ from ..core.server_api import confirm_server+ if not confirm_server(self, context):+ return {'CANCELLED'}+self._generation_method_on_start = context.scene.generation_method# Clear the upload cache at the start of a new generationdiff --git a/stablegen/texturing/masked_edit.py b/stablegen/texturing/masked_edit.pyindex 165ef14..468f34f 100644--- a/stablegen/texturing/masked_edit.py+++ b/stablegen/texturing/masked_edit.py@@ -743,6 +743,9 @@ class SG_OT_MaskedEdit(bpy.types.Operator):def execute(self, context):self.timer = Noneself.objects = []+ from ..core.server_api import confirm_server+ if not confirm_server(self, context):+ return {'CANCELLED'}try:finish_paint(context)if context.object and context.object.mode != 'OBJECT':diff --git a/stablegen/ui/model_units.py b/stablegen/ui/model_units.pyindex 4f736f9..7c01eec 100644--- a/stablegen/ui/model_units.py+++ b/stablegen/ui/model_units.py@@ -240,7 +240,7 @@ class RefreshCheckpointList(bpy.types.Operator):desc = result.get('model_type_desc', 'Model')if model_list is None:- _state._cached_checkpoint_list = [("NO_SERVER", "Set Server Address", "Cannot fetch")]+ _state._cached_checkpoint_list = [_state.no_server_item(server_address)]_state._cached_checkpoint_architecture = Noneprint("[StableGen] Checkpoint refresh: cannot reach server.")elif not model_list:@@ -318,7 +318,7 @@ class RefreshLoRAList(bpy.types.Operator):lora_list = result.get('lora_list')if lora_list is None:- _state._cached_lora_list = [("NO_SERVER", "Set Server Address", "Cannot fetch")]+ _state._cached_lora_list = [_state.no_server_item(server_address)]print("[StableGen] LoRA refresh: cannot reach server.")elif not lora_list:_state._cached_lora_list = [("NONE_FOUND", "No LoRAs Found", "Server list is empty")]diff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.pyindex d683490..8ee546f 100644--- a/stablegen/ui/panel.py+++ b/stablegen/ui/panel.py@@ -198,7 +198,7 @@ class StableGenPanel(bpy.types.Panel):elif not addon_prefs.server_address:config_error_message = "Server Address Missing"elif not addon_prefs.server_online:- config_error_message = "Cannot reach server"+ config_error_message = "ComfyUI offline"# Determine if we are in TRELLIS.2 mode (used by generate button & later sections)_arch_mode = getattr(scene, 'architecture_mode', 'sdxl')@@ -255,7 +255,7 @@ class StableGenPanel(bpy.types.Panel):) if not trellis2_op and not comfy_tex_op else Noneif config_error_message:- if config_error_message == "Cannot reach server":+ if config_error_message == "ComfyUI offline":split = action_row.split(factor=0.85, align=True)split.operator("object.trellis2_generate", text="Cannot generate: " + config_error_message, icon="ERROR")split.operator("stablegen.check_server_status", text="", icon='FILE_REFRESH')@@ -510,7 +510,7 @@ class StableGenPanel(bpy.types.Panel):status_row.label(text=scene.sg_masked_status)elif config_error_message:# Split the row to have the error message/disabled button and the refresh button- if config_error_message == "Cannot reach server":+ if config_error_message == "ComfyUI offline":split = action_row.split(factor=0.85, align=True) # Adjust factor as neededsplit.operator("object.test_stable", text="Cannot generate: " + config_error_message, icon="ERROR") # Use ERROR icon# Use the operator from __init__.py