Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 135 additions & 7 deletions comfy_cli/command/models/search.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""``comfy models`` — live model discovery against local or cloud.

Four subcommands, all routed by ``--where`` (cloud auto-detect by default):
Four subcommands, all routed by ``--where`` (cloud auto-detect by default);
each also accepts ``--host``/``--port`` to aim a *local* query at a specific
ComfyUI (rejected against a cloud target), mirroring ``comfy upload``:

comfy models list-folders # GET /api/experiment/models | /models
comfy models list-folder <folder> # GET /api/experiment/models/<folder> | /models/<folder>
Expand Down Expand Up @@ -178,18 +180,106 @@ def _emit_http_error(e: urllib.error.HTTPError, *, renderer, target, message: st
raise typer.Exit(code=1) from e


def _resolve_and_stamp(renderer, where: str | None):
# How a `cloud` routing decision was reached, in words, for the --host/--port
# rejection message. Keys are `where.WhereResolution.source` values. Mirrors the
# copy `cmdline.upload` uses — kept local rather than imported so this
# module stays free of a `cmdline` import cycle.
_WHERE_SOURCE_PHRASES = {
"flag": "targeting cloud via --where cloud",
"env": "targeting cloud via the COMFY_WHERE environment variable",
"project": "targeting cloud via this project's configured default",
"config": "targeting cloud via your saved `where_default` setting",
"auto": "targeting cloud because you're signed in (no explicit --where)",
}


def _resolve_and_stamp(renderer, where: str | None, *, command: str, host: str | None = None, port: int | None = None):
"""Resolve the routing Target for a ``models`` verb and stamp it on the renderer.

Every verb here calls this at the point it decides local-vs-cloud, so the
error envelopes raised downstream carry ``where`` instead of ``null``.
Errors raised *before* this (an unsafe path segment) keep ``where: null``,
which is correct — nothing had routed yet. Explicit
``emit(..., where=...)`` arguments still take precedence over the stamp.

``host``/``port`` route a **local** ``models`` query at a specific ComfyUI
(the ``--host``/``--port`` flags), mirroring ``comfy upload``:
they are validated the same way, rejected against an effective ``cloud``
target, and otherwise handed to ``resolve_target``, which applies the local
precedence explicit flag > ``COMFY_LOCAL_URL`` > ``127.0.0.1:8188``. With
both ``None`` (no flags), resolution is exactly what it was before the flags
existed. The cloud target's address comes from the signed-in account and
ignores host/port entirely, so pairing them with a cloud target is a usage
error rather than a silently-ignored flag — the root cause of the comfy-mcp
bug where ``search_models`` answered from the local machine regardless of
the configured remote target.
"""
from comfy_cli import where as where_module
from comfy_cli.host_port import report_usage_error, validate_host
from comfy_cli.target import resolve_target

target = resolve_target(where=where)
# Stamp the subcommand too, so every failure envelope from here down —
# the usage-error, ``where_invalid`` and ``host_flag_cloud`` rejections
# and the verb's own downstream errors — names the same ``command`` as
# the verb's success envelope rather than the renderer's group default.
renderer.command = command

# Validate the flags before resolving anything: the host lands verbatim in
# ``http://{host}:{port}/...``, so a URL-special or control character is a
# usage error (BadParameter, exit 2) regardless of target. Port range is
# checked the same way ``comfy upload`` does. ``report_usage_error`` emits
# the terminating envelope for that rejection in JSON/NDJSON mode; the
# exception still escapes, so click's exit-2 usage contract is unchanged.
with report_usage_error(renderer):
Comment thread
mattmillerai marked this conversation as resolved.
Resolved
if host is not None:
host = validate_host(host)
Comment thread
mattmillerai marked this conversation as resolved.
Resolved
# ``validate_host`` only proves the host *can* be IDNA-encoded; it
# hands back the Unicode form. ``urllib`` copies the URL authority
# into the ``Host`` header, which ``http.client`` encodes as
# Latin-1, so ``--host 例え.test`` would raise an uncaught
# ``UnicodeEncodeError`` before connecting. Forward the ASCII
# (punycode) form instead; IP literals are already ASCII. IDNA's
# NFKC step can fold characters into ones ``validate_host`` rejects
# (fullwidth ``%`` becomes ``%``, so ``localhost%0d%0a`` turns into
# a percent-encoded CRLF), so validate the converted form too.
if not host.isascii():
host = validate_host(host.encode("idna").decode("ascii"))
if port is not None and not (1 <= port <= 65535):
raise typer.BadParameter(f"invalid port: {port} is out of range (1-65535)")

# ``resolve_default_or_exit`` reads the persisted ``where_default``
# defensively (a broken config drops to the next precedence source, as
# ``resolve_target`` did before these flags existed) and turns a bad
# --where / COMFY_WHERE / project / config value into a ``where_invalid``
# envelope whose hint names all of those sources.
decision = where_module.resolve_default_or_exit(flag=where)

effective_where = "cloud" if decision.target is where_module.WhereTarget.CLOUD else "local"
# Routing is decided, so every error envelope from here down can name the
# target — including the `host_flag_cloud` rejection immediately below.
renderer.where = effective_where
# --host/--port address a local ComfyUI; the cloud target's address comes
# from the signed-in account and ignores them (``Target.host``/``port`` are
# documented local-only). Reject the combination rather than silently
# answering from a machine the caller didn't name.
if effective_where == "cloud" and (host is not None or port is not None):
# The cloud target can come from an explicit --where, but equally from
# COMFY_WHERE, a project/config default, or credential auto-detection —
# so name the source rather than accusing the user of a flag they may
# never have typed.
source = _WHERE_SOURCE_PHRASES.get(decision.source, f"resolved to cloud by {decision.source}")
renderer.error(
code="host_flag_cloud",
message=f"--host/--port target a local ComfyUI server, but this run is {source}",
hint=(
"pass --where local to aim at a local server; to reach a different cloud address "
"set COMFY_CLOUD_BASE_URL or run `comfy cloud set-base-url`"
),
details={"host": host, "port": port, "where": effective_where, "where_source": decision.source},
)
raise typer.Exit(code=1)

target = resolve_target(where=effective_where, host=host, port=port)
renderer.where = target.kind
return target

Expand All @@ -211,9 +301,17 @@ def list_folders_cmd(
str | None,
typer.Option("--where", show_default=False, help="Override the resolved routing mode."),
] = None,
host: Annotated[
Comment thread
mattmillerai marked this conversation as resolved.
Resolved
str | None,
typer.Option(help="Server host (defaults to COMFY_LOCAL_URL or 127.0.0.1). Local targets only."),
] = None,
port: Annotated[
int | None,
typer.Option(help="Server port (defaults to COMFY_LOCAL_URL or 8188). Local targets only."),
] = None,
):
renderer = get_renderer()
target = _resolve_and_stamp(renderer, where)
target = _resolve_and_stamp(renderer, where, command="models list-folders", host=host, port=port)
url = target.url(*_models_path_parts(target))

try:
Expand Down Expand Up @@ -286,10 +384,18 @@ def list_folder_cmd(
int | None,
typer.Option("--limit", show_default=False, help="Cap output to N rows."),
] = None,
host: Annotated[
str | None,
typer.Option(help="Server host (defaults to COMFY_LOCAL_URL or 127.0.0.1). Local targets only."),
] = None,
port: Annotated[
int | None,
typer.Option(help="Server port (defaults to COMFY_LOCAL_URL or 8188). Local targets only."),
] = None,
):
renderer = get_renderer()
_reject_unsafe_path_segment(folder, kind="folder", renderer=renderer)
target = _resolve_and_stamp(renderer, where)
target = _resolve_and_stamp(renderer, where, command="models list-folder", host=host, port=port)
# Percent-encoded for the same reason `_local_folder_matches` does it: the
# relaxed validation above admits spaces, `?`/`#`, and non-ASCII, none of
# which may be allowed to alter the request. Error payloads below carry the
Expand Down Expand Up @@ -740,11 +846,19 @@ def search_cmd(
str | None,
typer.Option("--where", show_default=False, help="Override the resolved routing mode."),
] = None,
host: Annotated[
str | None,
typer.Option(help="Server host (defaults to COMFY_LOCAL_URL or 127.0.0.1). Local targets only."),
] = None,
port: Annotated[
int | None,
typer.Option(help="Server port (defaults to COMFY_LOCAL_URL or 8188). Local targets only."),
] = None,
):
renderer = get_renderer()
if type_ is not None:
_reject_unsafe_path_segment(type_, kind="type", renderer=renderer)
target = _resolve_and_stamp(renderer, where)
target = _resolve_and_stamp(renderer, where, command="models search", host=host, port=port)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

try:
if target.is_cloud:
Expand Down Expand Up @@ -826,9 +940,23 @@ def show_cmd(
str | None,
typer.Option("--where", show_default=False, help="Override the resolved routing mode."),
] = None,
host: Annotated[
Comment thread
mattmillerai marked this conversation as resolved.
Resolved
str | None,
typer.Option(
help="Server host, for parity with the other `models` verbs. `show` needs the cloud asset "
"catalog, so a local target (including one named here) is reported as unsupported."
),
] = None,
port: Annotated[
int | None,
typer.Option(
help="Server port, for parity with the other `models` verbs. `show` needs the cloud asset "
"catalog, so a local target (including one named here) is reported as unsupported."
),
] = None,
):
renderer = get_renderer()
target = _resolve_and_stamp(renderer, where)
target = _resolve_and_stamp(renderer, where, command="models show", host=host, port=port)

if not target.is_cloud:
# On local there's no asset catalog. We can confirm the file exists by
Expand Down
36 changes: 36 additions & 0 deletions comfy_cli/host_port.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,45 @@ def validate_host(host: str) -> str:
if any(c.isspace() or ord(c) < 0x20 or ord(c) == 0x7F for c in candidate):
raise typer.BadParameter(f"invalid host: {host!r} (contains whitespace or control characters)")
_reject_embedded_port(host)
_reject_stray_brackets(host)
# The URL layer IDNA-encodes the host before connecting; a value it can't
# encode (an empty or over-long label, say) would otherwise escape as a
# raw ``UnicodeError`` traceback rather than a usage error.
try:
host.encode("idna")
Comment thread
mattmillerai marked this conversation as resolved.
Resolved
except UnicodeError:
raise typer.BadParameter(f"invalid host: {host!r} (not a valid hostname)") from None
# IDNA encoding is not a URL-parser pass: ``urlsplit`` NFKC-normalizes the
# netloc and rejects a fullwidth ``/`` (it folds to ``/``) that IDNA lets
# through, so check the URL the callers will build as well.
from comfy_cli.env_checker import _bracket_host

try:
urllib.parse.urlsplit(f"http://{_bracket_host(host)}:{DEFAULT_PORT}/")
except ValueError:
raise typer.BadParameter(f"invalid host: {host!r} (not a valid hostname)") from None
return host


def _reject_stray_brackets(host: str) -> None:
"""Reject ``[``/``]`` anywhere but around a genuine IPv6 literal.

``_reject_embedded_port`` only inspects colon-bearing hosts, so a
colon-free ``'[localhost]'`` or ``'a]b'`` slipped through and then made
``urllib.parse.urlsplit`` raise ``ValueError("Invalid IPv6 URL")`` — an
uncaught traceback instead of a usage error.
"""
if "[" not in host and "]" not in host:
return
if host.startswith("[") and host.endswith("]"):
try:
ipaddress.IPv6Address(host[1:-1])
return
except ValueError:
pass
raise typer.BadParameter(f"invalid host: {host!r} (brackets are only valid around an IPv6 literal)")


def _reject_embedded_port(host: str) -> None:
"""Reject a colon in a host unless it's a genuine IPv6 literal.

Expand Down
Loading
Loading