Compare commits

..
Author SHA1 Message Date
Gerald LonlasandClaude Opus 4.7 bf84d0d068 refactor(routes): extract shared probe helper from _models_handler and _test_handler
The two handlers shared identical query parsing, normalization, model
fetching, and error handling and only diverged in their success response
shape and error-string prefix. Extract a private `_probe_server` helper
that returns either a `web.Response` (errors) or a `(url, models)` tuple
so each handler is reduced to formatting its success body. Behavior,
status codes, and error semantics are unchanged.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 00:45:25 +08:00
3 changed files with 26 additions and 55 deletions
+1 -9
View File
@@ -1,7 +1,5 @@
from __future__ import annotations
from typing import Any
from comfy_api.latest import io, ui
from .client import (
@@ -117,13 +115,7 @@ class LMStudioConnect(io.ComfyNode):
)
@classmethod
def validate_inputs(
cls,
server_url: str,
timeout_seconds: int,
max_tokens: int,
**_: Any,
) -> bool | str:
def validate_inputs(cls, server_url: str, timeout_seconds: int, max_tokens: int) -> bool | str:
try:
normalize_server_url(server_url)
except ValueError as exc:
+25 -25
View File
@@ -22,7 +22,15 @@ def _query_int(request: web.Request, key: str, default: int) -> int:
return value
async def _models_handler(request: web.Request) -> web.Response:
async def _probe_server(
request: web.Request, *, error_prefix: str
) -> tuple[str, list[str]] | web.Response:
"""Shared work for the models/test endpoints.
Returns either an error ``web.Response`` (to be returned directly by the
caller) or a ``(normalized_url, models)`` tuple for the caller to format
into a success response.
"""
server_url = (request.query.get("server_url") or "").strip()
api_token = (request.query.get("api_token") or "-").strip() or "-"
@@ -40,11 +48,20 @@ async def _models_handler(request: web.Request) -> web.Response:
return web.json_response(
{
"ok": False,
"error": f"Failed to list models from LMStudio: {exc}",
"error": f"{error_prefix}: {exc}",
},
status=502,
)
return normalized_url, models
async def _models_handler(request: web.Request) -> web.Response:
result = await _probe_server(request, error_prefix="Failed to list models from LMStudio")
if isinstance(result, web.Response):
return result
normalized_url, models = result
return web.json_response(
{
"ok": True,
@@ -56,29 +73,12 @@ async def _models_handler(request: web.Request) -> web.Response:
async def _test_handler(request: web.Request) -> web.Response:
server_url = (request.query.get("server_url") or "").strip()
api_token = (request.query.get("api_token") or "-").strip() or "-"
try:
# Use the same short default as _models_handler; the JS always sends the
# widget value anyway, so this only matters when the endpoint is called directly.
timeout_seconds = _query_int(request, "timeout_seconds", 15)
normalized_url = normalize_server_url(server_url)
models = get_server_models(
server_url=normalized_url,
api_key=api_token,
timeout_seconds=timeout_seconds,
)
except ValueError as exc:
return web.json_response({"ok": False, "error": str(exc)}, status=400)
except Exception as exc:
return web.json_response(
{
"ok": False,
"error": f"Connection test failed: {exc}",
},
status=502,
)
# The JS always sends the widget value, so the default only matters when the
# endpoint is called directly; keep it aligned with ``_models_handler``.
result = await _probe_server(request, error_prefix="Connection test failed")
if isinstance(result, web.Response):
return result
normalized_url, models = result
return web.json_response(
{
-21
View File
@@ -49,27 +49,6 @@ def test_validate_inputs() -> None:
assert cls.validate_inputs("http://127.0.0.1:1234", 10, 0) == "max_tokens must be >= 1"
def test_validate_inputs_accepts_extra_kwargs() -> None:
connect_node = _connect_module()
cls = connect_node.LMStudioConnect
# ComfyUI may pass any of the schema inputs by name; the method must tolerate them.
assert (
cls.validate_inputs(
"http://127.0.0.1:1234",
10,
128,
api_token="-",
model="placeholder",
reasoning_enabled=False,
use_tooling_mcp=False,
temperature=0.7,
test_connectivity=True,
)
is True
)
def test_execute_with_placeholder_model_uses_discovered_default(
monkeypatch: pytest.MonkeyPatch,
) -> None: