diff --git a/comfy_api_nodes/apis/comfy_cloud.py b/comfy_api_nodes/apis/comfy_cloud.py new file mode 100644 index 00000000000..083f0e9875b --- /dev/null +++ b/comfy_api_nodes/apis/comfy_cloud.py @@ -0,0 +1,107 @@ +from typing import Literal + +from pydantic import BaseModel, Field, field_validator + + +# Only the workflows this build ships. The backend serves more. +ComfyCloudWorkflow = Literal[ + "z-image-turbo/text-to-image", + "flux-2/text-to-image", + "minimax-h3/text-to-video", + "minimax-h3/first-last-frame-to-video", + "minimax-h3/reference-to-video", + "minimax-h3/image-to-video", + "mage-flow/text-to-image", + "mage-flow-turbo/text-to-image", + "minimax-music-3/text-to-audio", +] + + +# Only the inputs the shipped nodes send. The manifests accept more. +class ComfyCloudWorkflowInputs(BaseModel): + prompt: str | None = Field(None) + image_url: str | None = Field(None) + assets: dict[str, "ComfyCloudAssetInput"] | None = Field(None) + audio_url: str | None = Field(None) + first_frame_url: str | None = Field(None) + last_frame_url: str | None = Field(None) + instruction: str | None = Field(None) + prompt_enhance: bool | None = Field(None) + enhance_prompt: bool | None = Field(None) + negative_prompt: str | None = Field(None) + aspect_ratio: str | None = Field(None) + duration_seconds: float | None = Field(None) + quality_mode: str | None = Field(None) + seed: int | None = Field(None, ge=0, le=0xFFFFFFFFFFFFFFFF) + scale: str | None = Field(None) + width: int | None = Field(None, ge=256, le=2048) + height: int | None = Field(None, ge=256, le=2048) + resolution: str | None = Field(None) + rendering_speed: str | None = Field(None) + color_correction: str | None = Field(None) + turbo: bool | None = Field(None) + style_lora: bool | None = Field(None) + model: str | None = Field(None) + lora: str | None = Field(None) + steps: int | None = Field(None, ge=1) + turbo_steps: int | None = Field(None, ge=1) + fast_steps: int | None = Field(None, ge=1) + cfg: float | None = Field(None, ge=0) + guidance: float | None = Field(None, ge=0) + shift: float | None = Field(None, ge=0) + turbo_strength: float | None = Field(None, ge=0) + style_strength: float | None = Field(None, ge=0) + megapixels: float | None = Field(None, gt=0) + size_multiple: int | None = Field(None, ge=1) + sampler: str | None = Field(None) + scheduler: str | None = Field(None) + denoise: float | None = Field(None, ge=0, le=1) + text_encoder: str | None = Field(None) + ref_image_size: str | None = Field(None) + lyrics: str | None = Field(None) + max_duration: float | None = Field(None, gt=0) + caption_cfg: float | None = Field(None, ge=0) + top_k: int | None = Field(None, ge=1) + tiled_decode: bool | None = Field(None) + tile_size: int | None = Field(None, ge=1) + tile_overlap: int | None = Field(None, ge=0) + audio_quality: str | None = Field(None) + + +class ComfyCloudAssetInput(BaseModel): + type: Literal["IMAGE", "VIDEO", "AUDIO"] = Field(...) + url: str = Field(...) + + +class ComfyCloudGenerateRequest(BaseModel): + workflow: ComfyCloudWorkflow = Field(...) + inputs: ComfyCloudWorkflowInputs = Field(...) + + +class ComfyCloudGenerateResponse(BaseModel): + task_id: str = Field(..., min_length=1) + status: str = Field(...) + polling_url: str | None = Field(None) + cancel_url: str | None = Field(None) + + @field_validator("task_id") + @classmethod + def task_id_must_not_be_blank(cls, value: str) -> str: + if not value.strip(): + raise ValueError("task_id must not be blank") + return value + + +class ComfyCloudStatusResponse(BaseModel): + task_id: str = Field(..., min_length=1) + status: str = Field(...) + progress: float | None = Field(None) + output_url: str | None = Field(None) + error: str | None = Field(None) + + @field_validator("task_id") + @classmethod + def task_id_must_not_be_blank(cls, value: str) -> str: + if not value.strip(): + raise ValueError("task_id must not be blank") + return value diff --git a/comfy_api_nodes/nodes_comfy_cloud.py b/comfy_api_nodes/nodes_comfy_cloud.py new file mode 100644 index 00000000000..2abc18daa3e --- /dev/null +++ b/comfy_api_nodes/nodes_comfy_cloud.py @@ -0,0 +1,858 @@ +import contextlib +import math +import posixpath +from io import BytesIO +from typing import ClassVar +from urllib.parse import quote, unquote, urlsplit + +import torch + +from typing_extensions import override + +from comfy_api.latest import IO, ComfyExtension, Input +from comfy_api_nodes.apis.comfy_cloud import ( + ComfyCloudAssetInput, + ComfyCloudGenerateRequest, + ComfyCloudGenerateResponse, + ComfyCloudStatusResponse, + ComfyCloudWorkflow, + ComfyCloudWorkflowInputs, +) +from comfy_api_nodes.util import ( + ApiEndpoint, + audio_bytes_to_audio_input, + download_url_to_bytesio, + download_url_to_image_tensor, + download_url_to_video_output, + get_number_of_images, + poll_op, + sync_op, + sync_op_raw, + upload_audio_to_comfyapi, + upload_image_to_comfyapi, + upload_video_to_comfyapi, + validate_string, +) + + +# Must stay in step with comfyCloudOutputBuckets in cloud's services/comfy-api/config/config.go. +_OUTPUT_BUCKETS = frozenset( + { + "comfy-cloud-assets", + "comfy-cloud-assets-stg", + "comfy-cloud-assets-test", + "partner-nodes-assets", + "partner-nodes-assets-staging", + } +) +_GENERATE_ENDPOINT = ApiEndpoint(path="/proxy/comfy-cloud/workflow/generate", method="POST") +_RUN_TIMEOUT_SECONDS = 2100 +_POLL_INTERVAL_SECONDS = 5.0 +_POLL_MAX_ATTEMPTS = int(_RUN_TIMEOUT_SECONDS / _POLL_INTERVAL_SECONDS) + 24 # +2 min of slack +_OUTPUT_DOWNLOAD_TIMEOUT = 30 * 60 +_MAX_UPLOAD_IMAGE_PIXELS = 32_000_000 +_MAX_UPLOAD_IMAGE_DIMENSION = 8192 +_MAX_DECODED_AUDIO_BYTES = 256 * 1024 * 1024 +# Hardcoded mirror of Metronome's GPU rate. Nothing links the two, so it must be +# changed by hand when the rate card moves. +# +# VERIFY AGAINST A REAL CHARGE, not the rate card. This was briefly set to +# 0.00185, read off rtx_pro_6000's card entry, which over-quoted every run by +# ~43%. Dividing an actual billed event gives the truth: +# credits_used 1.98 / gpu_seconds 7.244173 / 211 credits-per-USD = 0.0012954 +# +# THIS IS THE LIST PRICE. Never put a promotional or time-boxed rate here. +# ComfyUI is pulled, not pushed, so a user keeps whatever value they last pulled +# for as long as they like. A promo rate shipped here does not expire when the +# promotion does: the rate card returns to list, that user's node still quotes +# the discount, and they are charged MORE than they were shown, indefinitely and +# invisibly to us. A promo belongs in Metronome alone, where ending it actually +# ends it, and in the launch copy. Quoting above the charged rate is the safe +# direction; quoting below it is not. +# +# The same asymmetry applies to any list-price INCREASE, which is why a +# server-supplied per-run estimate (BE-9841) is the only way to change this +# number safely rather than a nicety. +COMFY_CLOUD_GPU_SECOND_USD = 0.001295 +COMFY_CLOUD_CREDITS_PER_USD = 211 +COMFY_CLOUD_GPU_SECOND_CREDITS = COMFY_CLOUD_GPU_SECOND_USD * COMFY_CLOUD_CREDITS_PER_USD +_COMFY_CLOUD_PRICE_BADGE = IO.PriceBadge( + expr=( + f'{{"type":"usd","usd":{COMFY_CLOUD_GPU_SECOND_USD:.6f},' + '"format":{"suffix":"/GPU-second","approximate":true}}' + ) +) +_COMFY_CLOUD_RATE_DESCRIPTION = ( + f" Runs on a Comfy Cloud GPU, billed by how long it runs at " + f"${COMFY_CLOUD_GPU_SECOND_USD:.6f}/GPU-second " + f"({COMFY_CLOUD_GPU_SECOND_CREDITS:.2f} credits). Paid in credits, no Cloud " + "subscription required." +) + + +# Marked beta on purpose: the workflow set is curated by hand and expected to +# change, so a node can gain or lose options, and a workflow can be retired. +# display_name is not stored in a saved graph, so this is free to remove later; +# node_id and the input names are the parts that are permanent. +_COMFY_CLOUD_BETA_SUFFIX = " [BETA]" +_COMFY_CLOUD_BETA_DESCRIPTION = ( + "BETA. The Comfy Cloud node set is still changing: options may be added or " + "removed, and a workflow may be retired. " +) + + +def _comfy_cloud_display_name(display_name: str) -> str: + """A SUFFIX, not a prefix: the menu and node search sort alphabetically, so a + leading marker would file all of these under "[" instead of their model.""" + return display_name + _COMFY_CLOUD_BETA_SUFFIX + + +def _comfy_cloud_description(summary: str) -> str: + """Node descriptions carry the beta notice and the rate. The beta notice leads + because it is the caveat to read first; the rate is here because the price + badge only renders on Nodes 2.0, and a plain local install still defaults to + the classic canvas.""" + return _COMFY_CLOUD_BETA_DESCRIPTION + summary + _COMFY_CLOUD_RATE_DESCRIPTION + + +_TEXT_LIMITS = { + "prompt": (1, 4096), + "instruction": (1, 4096), + "negative_prompt": (0, 2048), + "lyrics": (0, 4096), +} + + +def _task_endpoints(task_id: str) -> tuple[ApiEndpoint, ApiEndpoint]: + if not task_id.strip(): + raise ValueError("Comfy Cloud returned an empty task ID.") + task_path = f"/proxy/comfy-cloud/workflow/tasks/{quote(task_id, safe='')}" + return ApiEndpoint(path=task_path), ApiEndpoint(path=f"{task_path}/cancel", method="POST") + + +def _with_input_sockets(inputs: list[IO.Input]) -> list[IO.Input]: + for input_spec in inputs: + if isinstance(input_spec, IO.WidgetInput): + input_spec.socketless = False + return inputs + + +def _cloud_schema( + node_id: str, + display_name: str, + summary: str, + category: str, + inputs: list[IO.Input], + output: IO.Output, +) -> IO.Schema: + """Every Comfy Cloud node is the same schema but for its id, name, blurb, category, + inputs and output type, so they are all built here.""" + return IO.Schema( + node_id=node_id, + display_name=_comfy_cloud_display_name(display_name), + category=category, + description=_comfy_cloud_description(summary), + inputs=_with_input_sockets(inputs), + outputs=[output], + hidden=[ + IO.Hidden.auth_token_comfy_org, + IO.Hidden.api_key_comfy_org, + IO.Hidden.unique_id, + ], + is_api_node=True, + price_badge=_COMFY_CLOUD_PRICE_BADGE, + ) + + +def _validated_output_url(url: str) -> str: + parsed = urlsplit(url) + decoded_path = unquote(parsed.path) + is_proxy_path = ( + not parsed.scheme + and not parsed.netloc + and decoded_path.startswith("/proxy/comfy-cloud/") + and posixpath.normpath(decoded_path) == decoded_path + ) + # normpath first: a client resolves dot segments before sending, so + # ".../comfy-cloud-assets/../other/x.png" would advertise an allowed bucket here + # and fetch from another one on the wire. + bucket = decoded_path.lstrip("/").split("/", 1)[0] + is_signed_https_url = ( + parsed.scheme == "https" + and parsed.hostname == "storage.googleapis.com" + and parsed.port is None + and parsed.username is None + and parsed.password is None + and posixpath.normpath(decoded_path) == decoded_path + and bucket in _OUTPUT_BUCKETS + ) + if not is_proxy_path and not is_signed_https_url: + raise RuntimeError("Comfy Cloud returned an invalid output URL.") + return url + + +def _validate_image_upload(image: Input.Image) -> None: + if not isinstance(image, torch.Tensor): + return + if image.ndim not in (3, 4): + raise ValueError("Invalid input image shape.") + height, width = image.shape[-3:-1] + if max(height, width) > _MAX_UPLOAD_IMAGE_DIMENSION or height * width > _MAX_UPLOAD_IMAGE_PIXELS: + raise ValueError("Input image exceeds the 8192px or 32-megapixel Comfy Cloud limit.") + + +def _progress(response: ComfyCloudStatusResponse) -> float | None: + if response.progress is None or not math.isfinite(response.progress): + return None + return min(100.0, max(0.0, response.progress)) + + +async def _poll_task(cls: type[IO.ComfyNode], task_id: str) -> ComfyCloudStatusResponse: + polling_endpoint, cancel_endpoint = _task_endpoints(task_id) + try: + return await poll_op( + cls, + polling_endpoint, + response_model=ComfyCloudStatusResponse, + status_extractor=lambda response: response.status, + progress_extractor=_progress, + cancel_endpoint=cancel_endpoint, + poll_interval=_POLL_INTERVAL_SECONDS, + max_poll_attempts=_POLL_MAX_ATTEMPTS, + ) + except Exception: + with contextlib.suppress(Exception): + await sync_op_raw(cls, cancel_endpoint, max_retries=0) + raise + + +def _validate_node_inputs(cls: type[IO.ComfyNode], values: dict) -> dict: + validated = dict(values) + for input_spec in cls.define_schema().inputs: + if not isinstance(input_spec, IO.WidgetInput) or input_spec.id not in values: + continue + value = values[input_spec.id] + io_type = input_spec.get_io_type() + if io_type == "STRING": + if not isinstance(value, str): + raise ValueError(f"{input_spec.id} must be a string.") + value = value.strip() + minimum, maximum = _TEXT_LIMITS.get(input_spec.id, (0, None)) + validate_string( + value, + min_length=minimum, + max_length=maximum, + field_name=input_spec.id, + ) + validated[input_spec.id] = value + elif io_type == "COMBO" and value not in input_spec.options: + raise ValueError(f"Invalid {input_spec.id}: {value!r}.") + elif io_type == "BOOLEAN" and not isinstance(value, bool): + raise ValueError(f"{input_spec.id} must be a boolean.") + elif io_type == "INT": + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"{input_spec.id} must be an integer.") + if input_spec.min is not None and value < input_spec.min: + raise ValueError(f"{input_spec.id} must be at least {input_spec.min}.") + if input_spec.max is not None and value > input_spec.max: + raise ValueError(f"{input_spec.id} must be at most {input_spec.max}.") + elif io_type == "FLOAT": + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise ValueError(f"{input_spec.id} must be a finite number.") + if input_spec.min is not None and value < input_spec.min: + raise ValueError(f"{input_spec.id} must be at least {input_spec.min}.") + if input_spec.max is not None and value > input_spec.max: + raise ValueError(f"{input_spec.id} must be at most {input_spec.max}.") + if input_spec.step: + origin = input_spec.min or 0 + steps = (value - origin) / input_spec.step + if not math.isclose(steps, round(steps), abs_tol=1e-7): + raise ValueError(f"{input_spec.id} must use increments of {input_spec.step}.") + return validated + + +_ASPECT_RATIOS = ["1:1", "3:4", "2:3", "3:2", "4:3", "16:9", "9:16", "21:9"] +_VIDEO_RESOLUTIONS = ["480p", "720p"] +_MINIMAX_MUSIC3_QUALITIES = ["V0", "128k", "320k"] +_UINT64_MAX = 0xFFFFFFFFFFFFFFFF +_NEGATIVE_PROMPT_TOOLTIP = "Leave empty to keep the negative prompt this pipeline was tuned with." + + +def _prompt_input(name: str = "prompt") -> IO.String.Input: + return IO.String.Input(name, multiline=True, default="") + + +def _negative_prompt_input() -> IO.String.Input: + return IO.String.Input( + "negative_prompt", multiline=True, default="", tooltip=_NEGATIVE_PROMPT_TOOLTIP + ) + + +def _aspect_ratio_input(default: str = "1:1") -> IO.Combo.Input: + return IO.Combo.Input("aspect_ratio", options=_ASPECT_RATIOS, default=default) + + +def _megapixels_input() -> IO.Float.Input: + # Resolution Selector graphs take a ratio and pixel budget rather than raw dimensions. + return IO.Float.Input( + "megapixels", default=1.0, min=0.1, max=16.0, step=0.1, + tooltip="Total pixel budget. 1.0 is about 1024x1024 at a square ratio.", + ) + + +def _seed_input(maximum: int = _UINT64_MAX) -> IO.Int.Input: + return IO.Int.Input("seed", default=42, min=0, max=maximum, control_after_generate=True) + + +def _video_resolution_input(advanced: bool = True) -> IO.Combo.Input: + return IO.Combo.Input( + "resolution", + options=_VIDEO_RESOLUTIONS, + default="480p", + advanced=advanced, + tooltip="Frame size budget. 720p costs roughly twice the GPU-seconds of 480p.", + ) + + +async def _submit_workflow( + cls: type[IO.ComfyNode], workflow: ComfyCloudWorkflow, inputs: ComfyCloudWorkflowInputs +) -> str: + task = await sync_op( + cls, + _GENERATE_ENDPOINT, + response_model=ComfyCloudGenerateResponse, + data=ComfyCloudGenerateRequest(workflow=workflow, inputs=inputs), + ) + result = await _poll_task(cls, task.task_id) + if not result.output_url: + raise RuntimeError("Comfy Cloud task completed without an output URL.") + return _validated_output_url(result.output_url) + + +async def _run_image_workflow( + cls: type[IO.ComfyNode], workflow: ComfyCloudWorkflow, inputs: ComfyCloudWorkflowInputs +) -> IO.NodeOutput: + url = await _submit_workflow(cls, workflow, inputs) + return IO.NodeOutput( + await download_url_to_image_tensor( + url, timeout=_OUTPUT_DOWNLOAD_TIMEOUT, cls=cls, allow_redirects=False + ) + ) + + +async def _run_video_workflow( + cls: type[IO.ComfyNode], workflow: ComfyCloudWorkflow, inputs: ComfyCloudWorkflowInputs +) -> IO.NodeOutput: + url = await _submit_workflow(cls, workflow, inputs) + return IO.NodeOutput( + await download_url_to_video_output( + url, timeout=_OUTPUT_DOWNLOAD_TIMEOUT, cls=cls, allow_redirects=False + ) + ) + + +async def _run_audio_workflow( + cls: type[IO.ComfyNode], workflow: ComfyCloudWorkflow, inputs: ComfyCloudWorkflowInputs +) -> IO.NodeOutput: + url = await _submit_workflow(cls, workflow, inputs) + buffer = BytesIO() + await download_url_to_bytesio( + url, buffer, timeout=_OUTPUT_DOWNLOAD_TIMEOUT, cls=cls, allow_redirects=False + ) + return IO.NodeOutput(audio_bytes_to_audio_input(buffer.getvalue())) + + +async def _upload_workflow_image(cls: type[IO.ComfyNode], image: Input.Image, **options) -> str: + if get_number_of_images(image) != 1: + raise ValueError("Exactly one input image is required.") + _validate_image_upload(image) + return await upload_image_to_comfyapi(cls, image, **options) + + +def _image_schema(cls: type[IO.ComfyNode], inputs: list[IO.Input]) -> IO.Schema: + return _cloud_schema( + cls.node_id, cls.display_name, cls.summary, "comfy cloud/image", inputs, IO.Image.Output() + ) + + +class ComfyCloudFlux2TextToImageNode(IO.ComfyNode): + node_id = "ComfyCloudFlux2TextToImageNode" + display_name = "Comfy Cloud Flux 2 Text to Image" + summary = ( + "Generates an image from a text prompt with Flux 2 dev. Turbo swaps in the chosen LoRA " + "and a short schedule, trading a little fidelity for a much quicker run; switch it off " + "for the full-length dev pass with no LoRA." + ) + + @classmethod + def define_schema(cls) -> IO.Schema: + return _image_schema( + cls, + [ + _prompt_input(), + _seed_input(), + _aspect_ratio_input(), + _megapixels_input(), + IO.Boolean.Input( + "turbo", + default=True, + tooltip="Run the Turbo LoRA on a short schedule, trading a little fidelity " + "for a much quicker run. Off runs the full dev pass with no LoRA.", + ), + ], + ) + + @classmethod + async def execute( + cls, + prompt: str, + seed: int = 42, + aspect_ratio: str = "1:1", + megapixels: float = 1.0, + turbo: bool = True, + ) -> IO.NodeOutput: + prompt = _validate_node_inputs(cls, locals())["prompt"] + return await _run_image_workflow( + cls, + "flux-2/text-to-image", + ComfyCloudWorkflowInputs( + prompt=prompt, aspect_ratio=aspect_ratio, megapixels=megapixels, turbo=turbo, seed=seed, + ), + ) + + +class ComfyCloudZImageTurboNode(IO.ComfyNode): + node_id = "ComfyCloudZImageTurboNode" + display_name = "Comfy Cloud Z-Image Turbo Text to Image" + summary = ( + "Generates an image from a text prompt with Z-Image Turbo in 8 steps. One of the " + "quickest and cheapest nodes here, which makes it the one to iterate on." + ) + + @classmethod + def define_schema(cls) -> IO.Schema: + return _image_schema( + cls, + [ + _prompt_input(), + _seed_input(), + _aspect_ratio_input(), + _megapixels_input(), + ], + ) + + @classmethod + async def execute( + cls, + prompt: str, + seed: int = 42, + aspect_ratio: str = "1:1", + megapixels: float = 1.0, + ) -> IO.NodeOutput: + prompt = _validate_node_inputs(cls, locals())["prompt"] + return await _run_image_workflow( + cls, + "z-image-turbo/text-to-image", + ComfyCloudWorkflowInputs( + prompt=prompt, aspect_ratio=aspect_ratio, megapixels=megapixels, seed=seed, + ), + ) + + +class _ComfyCloudMageFlowNode(IO.ComfyNode): + """Mage-Flow text to image. The base and turbo graphs are the same pipeline at + two schedule lengths, so they differ only in their step and cfg defaults and + which checkpoints load.""" + + workflow: ClassVar[ComfyCloudWorkflow] + node_id: ClassVar[str] + display_name: ClassVar[str] + summary: ClassVar[str] + + @classmethod + def define_schema(cls) -> IO.Schema: + return _image_schema( + cls, + [ + _prompt_input(), + _negative_prompt_input(), + _seed_input(), + _aspect_ratio_input(), + _megapixels_input(), + ], + ) + + @classmethod + async def execute( + cls, + prompt: str, + negative_prompt: str = "", + seed: int = 42, + aspect_ratio: str = "1:1", + megapixels: float = 1.0, + ) -> IO.NodeOutput: + validated = _validate_node_inputs(cls, locals()) + return await _run_image_workflow( + cls, + cls.workflow, + ComfyCloudWorkflowInputs( + prompt=validated["prompt"], negative_prompt=validated["negative_prompt"], + aspect_ratio=aspect_ratio, megapixels=megapixels, seed=seed, + ), + ) + + +class ComfyCloudMageFlowTextToImageNode(_ComfyCloudMageFlowNode): + workflow = "mage-flow/text-to-image" + node_id = "ComfyCloudMageFlowTextToImageNode" + display_name = "Comfy Cloud Mage Flow Text to Image" + summary = ( + "Generates an image from a text prompt with Mage-Flow over a full 30-step pass. " + "It takes a negative prompt, which the distilled turbo variant cannot use well." + ) + + +class ComfyCloudMageFlowTurboTextToImageNode(_ComfyCloudMageFlowNode): + workflow = "mage-flow-turbo/text-to-image" + node_id = "ComfyCloudMageFlowTurboTextToImageNode" + display_name = "Comfy Cloud Mage Flow Turbo Text to Image" + summary = ( + "Generates an image from a text prompt with distilled Mage-Flow in 4 steps at cfg 1. " + "Roughly a seventh of the GPU time of the full pass, which makes it the one to iterate on." + ) + + +class ComfyCloudMiniMaxMusic3TextToAudioNode(IO.ComfyNode): + @classmethod + def define_schema(cls) -> IO.Schema: + return _cloud_schema( + "ComfyCloudMiniMaxMusic3TextToAudioNode", + "Comfy Cloud MiniMax Music 3 Text to Audio", + ( + "Generates a full song from a description with MiniMax Music 3. The prompt " + "carries the style, instrumentation and mood; lyrics are sung rather than " + "described, and an empty lyric leaves the track instrumental." + ), + "comfy cloud/audio", + [ + _prompt_input(), + IO.String.Input( + "lyrics", multiline=True, default="", + tooltip="Words to sing. Leave empty for an instrumental.", + ), + # SeedNode caps at int64, below the uint64 the other graphs take. + _seed_input(0x7FFFFFFFFFFFFFFF), + IO.Float.Input( + "max_duration", default=120.0, min=0.04, max=360.0, step=0.04, + tooltip="Longest the track may run. The model can end the song earlier.", + ), + IO.Combo.Input( + "audio_quality", + options=_MINIMAX_MUSIC3_QUALITIES, + default=_MINIMAX_MUSIC3_QUALITIES[0], + tooltip="mp3 bitrate. V0 is variable and the highest quality of the three.", + ), + ], + IO.Audio.Output(), + ) + + @classmethod + async def execute( + cls, + prompt: str, + lyrics: str = "", + seed: int = 42, + max_duration: float = 120.0, + audio_quality: str = "V0", + ) -> IO.NodeOutput: + validated = _validate_node_inputs(cls, locals()) + return await _run_audio_workflow( + cls, + "minimax-music-3/text-to-audio", + ComfyCloudWorkflowInputs( + prompt=validated["prompt"], lyrics=validated["lyrics"], seed=seed, + max_duration=max_duration, caption_cfg=1.5, + audio_quality=audio_quality, + ), + ) + + +def _video_schema(node_id: str, display_name: str, summary: str, inputs: list[IO.Input]) -> IO.Schema: + return _cloud_schema( + node_id, display_name, summary, "comfy cloud/video", inputs, IO.Video.Output() + ) + + +_MINIMAX_H3_MAX_REFERENCES = 4 +_MINIMAX_H3_MAX_AUDIO_REFERENCES = 3 + + +def _minimax_h3_inputs(default_ratio: str, plain: list[IO.Input] | None = None) -> list[IO.Input]: + """Everything the three fl2va/ref2va graphs expose past their media inputs. + + The turbo LoRA branch those templates carry is not here: its weights have + catalog entries but no bytes in the mirror, so cloud's frozen graphs leave + the branch out until they are uploaded. + """ + return [ + _prompt_input(), + _seed_input(), + _aspect_ratio_input(default_ratio), + _video_resolution_input(advanced=False), + IO.Int.Input( + "duration_seconds", + default=5, + min=5, + max=15, + display_mode=IO.NumberDisplay.slider, + tooltip=( + "Length in seconds. The pipeline quantises to 17-frame steps at 24fps, " + "so the clip lands within about two thirds of a second of this." + ), + ), + *(plain or []), + ] + + +async def _minimax_h3_asset(cls: type[IO.ComfyNode], image: Input.Image) -> ComfyCloudAssetInput: + return ComfyCloudAssetInput( + type="IMAGE", url=await _upload_workflow_image(cls, image, total_pixels=2048 * 2048) + ) + + +async def _minimax_h3_video_asset(cls: type[IO.ComfyNode], video: Input.Video) -> ComfyCloudAssetInput: + return ComfyCloudAssetInput(type="VIDEO", url=await upload_video_to_comfyapi(cls, video)) + + +async def _minimax_h3_audio_asset(cls: type[IO.ComfyNode], audio: Input.Audio) -> ComfyCloudAssetInput: + return ComfyCloudAssetInput(type="AUDIO", url=await upload_audio_to_comfyapi(cls, audio)) + + +class ComfyCloudMiniMaxH3TextToVideoNode(IO.ComfyNode): + @classmethod + def define_schema(cls) -> IO.Schema: + return _video_schema( + "ComfyCloudMiniMaxH3TextToVideoNode", + "Comfy Cloud MiniMax H3 Text to Video", + ( + "Generates a video with a matching soundtrack from a text prompt, using MiniMax " + "H3. Picture and audio come out of the same pass rather than being dubbed on " + "afterwards." + ), + _minimax_h3_inputs("16:9"), + ) + + @classmethod + async def execute( + cls, + prompt: str, + seed: int = 42, + aspect_ratio: str = "16:9", + resolution: str = "480p", + duration_seconds: int = 5 + ) -> IO.NodeOutput: + prompt = _validate_node_inputs(cls, locals())["prompt"] + inputs = ComfyCloudWorkflowInputs( + prompt=prompt, aspect_ratio=aspect_ratio, duration_seconds=duration_seconds, + seed=seed, resolution=resolution + ) + return await _run_video_workflow(cls, "minimax-h3/text-to-video", inputs) + + +# MiniMax H3's two Qwen3-VL encoder precisions. Keys, not filenames: cloud holds +# the file each one maps to. +class ComfyCloudMiniMaxH3FirstLastFrameToVideoNode(IO.ComfyNode): + @classmethod + def define_schema(cls) -> IO.Schema: + return _video_schema( + "ComfyCloudMiniMaxH3FirstLastFrameToVideoNode", + "Comfy Cloud MiniMax H3 First-Last Frame to Video", + ( + "Generates the motion between two keyframes, with a matching soundtrack, using " + "MiniMax H3. Give it the opening and closing frames and the model fills in the " + "shot between them. The last frame is optional: leave it out and the motion runs " + "away from the first frame instead." + ), + [ + IO.Image.Input("first_frame"), + IO.Image.Input("last_frame", optional=True), + *_minimax_h3_inputs("1:1"), + ], + ) + + @classmethod + async def execute( + cls, + first_frame: Input.Image, + prompt: str, + seed: int = 42, + aspect_ratio: str = "1:1", + resolution: str = "480p", + duration_seconds: int = 5, + last_frame: Input.Image | None = None, + ) -> IO.NodeOutput: + prompt = _validate_node_inputs(cls, locals())["prompt"] + assets = {"first_frame": await _minimax_h3_asset(cls, first_frame)} + if last_frame is not None: + assets["last_frame"] = await _minimax_h3_asset(cls, last_frame) + return await _run_video_workflow( + cls, + "minimax-h3/first-last-frame-to-video", + ComfyCloudWorkflowInputs( + prompt=prompt, aspect_ratio=aspect_ratio, resolution=resolution, + duration_seconds=duration_seconds, seed=seed, assets=assets + ), + ) + + +class ComfyCloudMiniMaxH3ImageToVideoNode(IO.ComfyNode): + @classmethod + def define_schema(cls) -> IO.Schema: + return _video_schema( + "ComfyCloudMiniMaxH3ImageToVideoNode", + "Comfy Cloud MiniMax H3 Image to Video", + ( + "Animates a still into a video with a matching soundtrack, using MiniMax H3. " + "Feed it a clip's closing frame and it continues the sequence, so chaining " + "several builds a longer shot." + ), + [IO.Image.Input("first_frame"), *_minimax_h3_inputs("1:1")], + ) + + @classmethod + async def execute( + cls, + first_frame: Input.Image, + prompt: str, + seed: int = 42, + aspect_ratio: str = "1:1", + resolution: str = "480p", + duration_seconds: int = 5 + ) -> IO.NodeOutput: + prompt = _validate_node_inputs(cls, locals())["prompt"] + return await _run_video_workflow( + cls, + "minimax-h3/image-to-video", + ComfyCloudWorkflowInputs( + prompt=prompt, aspect_ratio=aspect_ratio, resolution=resolution, + duration_seconds=duration_seconds, seed=seed, + assets={"first_frame": await _minimax_h3_asset(cls, first_frame)}, + ), + ) + + +class ComfyCloudMiniMaxH3ReferenceToVideoNode(IO.ComfyNode): + @classmethod + def define_schema(cls) -> IO.Schema: + return _video_schema( + "ComfyCloudMiniMaxH3ReferenceToVideoNode", + "Comfy Cloud MiniMax H3 Reference to Video", + ( + "Generates a video with a matching soundtrack from optional image, video, and " + "audio references, using MiniMax H3. The references carry subject and style " + "across the shot, and the prompt addresses images by connection order." + ), + [ + IO.Autogrow.Input( + "reference_images", + template=IO.Autogrow.TemplatePrefix( + input=IO.Image.Input("reference_image"), + prefix="reference_image_", + min=0, + max=_MINIMAX_H3_MAX_REFERENCES, + ), + tooltip=( + "Up to four references, addressed in the prompt as upwards " + "in connection order." + ), + ), + IO.Video.Input("ref_video", optional=True), + IO.Autogrow.Input( + "ref_audio", + template=IO.Autogrow.TemplatePrefix( + input=IO.Audio.Input("ref_audio"), + prefix="ref_audio_", + min=0, + max=_MINIMAX_H3_MAX_AUDIO_REFERENCES, + ), + ), + *_minimax_h3_inputs( + "16:9", + plain=[ + IO.Combo.Input( + "ref_image_size", + options=["match", "max"], + default="match", + tooltip=( + "'match' scales each reference to the output's pixel area; 'max' " + "sends it at the 2048px short edge for the closest likeness. " + "Reference tokens ride through every sampling step, so 'max' " + "costs several times the GPU-seconds." + ), + ) + ], + ), + ], + ) + + @classmethod + async def execute( + cls, + prompt: str, + reference_images: dict[str, Input.Image] | None = None, + ref_video: Input.Video | None = None, + ref_audio: dict[str, Input.Audio] | None = None, + seed: int = 42, + aspect_ratio: str = "16:9", + resolution: str = "480p", + duration_seconds: int = 5, + ref_image_size: str = "match" + ) -> IO.NodeOutput: + prompt = _validate_node_inputs(cls, locals())["prompt"] + images = [image for image in (reference_images or {}).values() if image is not None] + if len(images) > _MINIMAX_H3_MAX_REFERENCES: + raise ValueError(f"At most {_MINIMAX_H3_MAX_REFERENCES} reference images are supported.") + audios = [audio for audio in (ref_audio or {}).values() if audio is not None] + if len(audios) > _MINIMAX_H3_MAX_AUDIO_REFERENCES: + raise ValueError(f"At most {_MINIMAX_H3_MAX_AUDIO_REFERENCES} reference audio inputs are supported.") + # Numbered by connection order, which is the order the prompt's + # tags refer to them in. + assets = { + f"reference_image_{index}": await _minimax_h3_asset(cls, image) + for index, image in enumerate(images, 1) + } + if ref_video is not None: + assets["ref_video"] = await _minimax_h3_video_asset(cls, ref_video) + assets.update({ + f"ref_audio_{index}": await _minimax_h3_audio_asset(cls, audio) + for index, audio in enumerate(audios, 1) + }) + return await _run_video_workflow( + cls, + "minimax-h3/reference-to-video", + ComfyCloudWorkflowInputs( + prompt=prompt, aspect_ratio=aspect_ratio, resolution=resolution, + duration_seconds=duration_seconds, seed=seed, ref_image_size=ref_image_size, + assets=assets, + ), + ) + + +class ComfyCloudExtension(ComfyExtension): + @override + async def get_node_list(self) -> list[type[IO.ComfyNode]]: + return [ + ComfyCloudMiniMaxH3TextToVideoNode, + ComfyCloudMiniMaxH3FirstLastFrameToVideoNode, + # ComfyCloudMiniMaxH3ReferenceToVideoNode, # Disabled until the server-side issue is fixed. + ComfyCloudMiniMaxH3ImageToVideoNode, + ComfyCloudMiniMaxMusic3TextToAudioNode, + ComfyCloudFlux2TextToImageNode, + ComfyCloudZImageTurboNode, + ComfyCloudMageFlowTextToImageNode, + ComfyCloudMageFlowTurboTextToImageNode, + ] + + +async def comfy_entrypoint() -> ComfyCloudExtension: + return ComfyCloudExtension() diff --git a/comfy_api_nodes/util/client.py b/comfy_api_nodes/util/client.py index 039e97d587a..a896027c970 100644 --- a/comfy_api_nodes/util/client.py +++ b/comfy_api_nodes/util/client.py @@ -574,6 +574,15 @@ def _merge_params(endpoint_params: dict[str, Any], method: str, data: dict[str, return params +# 5xx codes that mean "switched off", not "try again": retrying only makes the +# user wait through the backoff for the same answer. +_TERMINAL_SERVICE_REFUSALS = frozenset({"comfy_cloud_provider_disabled"}) + + +def _is_terminal_service_refusal(body: Any) -> bool: + return isinstance(body, dict) and body.get("error") in _TERMINAL_SERVICE_REFUSALS + + def _friendly_http_message(status: int, body: Any) -> str: if status == 401: return "Unauthorized: Please login first to use this node." @@ -586,6 +595,11 @@ def _friendly_http_message(status: int, body: Any) -> str: try: if isinstance(body, dict): err = body.get("error") + # comfy-api's envelope is flat: {"error": code, "message": text}. + if isinstance(err, str): + msg = body.get("message") + if isinstance(msg, str) and msg: + return msg if isinstance(err, dict): msg = err.get("message") typ = err.get("type") @@ -776,7 +790,11 @@ async def _monitor(stop_evt: asyncio.Event, start_ts: float): rate_limit_delay *= cfg.retry_backoff retry_label = f"rate-limit retry {rate_limit_attempts} of {cfg.max_retries_on_rate_limit}" should_retry = True - elif resp.status in _RETRY_STATUS and (attempt - rate_limit_attempts) <= cfg.max_retries: + elif ( + resp.status in _RETRY_STATUS + and not _is_terminal_service_refusal(body) + and (attempt - rate_limit_attempts) <= cfg.max_retries + ): wait_time = delay delay *= cfg.retry_backoff retry_label = f"retry {attempt - rate_limit_attempts} of {cfg.max_retries}" diff --git a/comfy_api_nodes/util/download_helpers.py b/comfy_api_nodes/util/download_helpers.py index 0ec3c6e6648..4344bf7dc52 100644 --- a/comfy_api_nodes/util/download_helpers.py +++ b/comfy_api_nodes/util/download_helpers.py @@ -38,6 +38,7 @@ async def download_url_to_bytesio( retry_delay: float = 1.0, retry_backoff: float = 2.0, cls: type[COMFY_IO.ComfyNode] = None, + allow_redirects: bool = True, ) -> None: """Stream-download a URL to `dest`. @@ -49,6 +50,10 @@ async def download_url_to_bytesio( If `url` starts with `/proxy/`, `cls` must be provided so the URL can be expanded to an absolute URL and authentication headers can be applied. + Pass `allow_redirects=False` when the caller has already vetted `url` and a + redirect would move the download somewhere it did not vet. The default keeps + aiohttp's redirect following. + Raises: ProcessingInterrupted, LocalNetworkError, ApiServerError, Exception (HTTP and other errors) """ @@ -68,6 +73,11 @@ async def download_url_to_bytesio( while True: attempt += 1 + # A retry re-reads from byte zero, so a part-filled BytesIO must be emptied + # or the two bodies concatenate. + if isinstance(dest, BytesIO): + dest.seek(0) + dest.truncate(0) op_id = _generate_operation_id("GET", url, attempt) timeout_cfg = aiohttp.ClientTimeout(total=timeout) @@ -96,7 +106,9 @@ async def _monitor(): monitor_task = asyncio.create_task(_monitor()) - req_task = asyncio.create_task(session.get(to_aiohttp_url(url), headers=headers)) + req_task = asyncio.create_task( + session.get(to_aiohttp_url(url), headers=headers, allow_redirects=allow_redirects) + ) done, pending = await asyncio.wait({req_task, monitor_task}, return_when=asyncio.FIRST_COMPLETED) if monitor_task in done and req_task in pending: @@ -111,7 +123,9 @@ async def _monitor(): raise ProcessingInterrupted("Task cancelled") from None async with resp: - if resp.status >= 400: + # Under allow_redirects=False a redirect lands here unfollowed, and its + # body is not the file that was asked for. + if resp.status >= 300: with contextlib.suppress(Exception): try: body = await resp.json() @@ -221,10 +235,11 @@ async def download_url_to_image_tensor( *, timeout: float = None, cls: type[COMFY_IO.ComfyNode] = None, + allow_redirects: bool = True, ) -> torch.Tensor: """Downloads an image from a URL and returns a [B, H, W, C] tensor.""" result = BytesIO() - await download_url_to_bytesio(url, result, timeout=timeout, cls=cls) + await download_url_to_bytesio(url, result, timeout=timeout, cls=cls, allow_redirects=allow_redirects) return bytesio_to_image_tensor(result) @@ -234,10 +249,18 @@ async def download_url_to_video_output( timeout: float = None, max_retries: int = 5, cls: type[COMFY_IO.ComfyNode] = None, + allow_redirects: bool = True, ) -> InputImpl.VideoFromFile: """Downloads a video from a URL and returns a `VIDEO` output.""" result = BytesIO() - await download_url_to_bytesio(video_url, result, timeout=timeout, max_retries=max_retries, cls=cls) + await download_url_to_bytesio( + video_url, + result, + timeout=timeout, + max_retries=max_retries, + cls=cls, + allow_redirects=allow_redirects, + ) return InputImpl.VideoFromFile(result) @@ -270,6 +293,7 @@ async def download_url_to_file_3d( timeout: float | None = None, max_retries: int = 5, cls: type[COMFY_IO.ComfyNode] = None, + allow_redirects: bool = True, ) -> Types.File3D: """Downloads a 3D model file from a URL into memory as BytesIO. @@ -284,6 +308,7 @@ async def download_url_to_file_3d( timeout=timeout, max_retries=max_retries, cls=cls, + allow_redirects=allow_redirects, ) if task_id is not None: diff --git a/tests-unit/comfy_api_nodes_test/comfy_cloud_test.py b/tests-unit/comfy_api_nodes_test/comfy_cloud_test.py new file mode 100644 index 00000000000..78ab160ea52 --- /dev/null +++ b/tests-unit/comfy_api_nodes_test/comfy_cloud_test.py @@ -0,0 +1,881 @@ +import ast +import asyncio +import re +from pathlib import Path +from io import BytesIO +from typing import get_args +from unittest.mock import AsyncMock + +import aiohttp +import pytest +import torch + +from comfy.cli_args import args + +if not torch.cuda.is_available(): + args.cpu = True + +from comfy_api_nodes.apis.comfy_cloud import ( + ComfyCloudGenerateRequest, + ComfyCloudGenerateResponse, + ComfyCloudStatusResponse, + ComfyCloudWorkflow, + ComfyCloudWorkflowInputs, +) +from comfy_api_nodes import nodes_comfy_cloud +from comfy_api_nodes.util import download_helpers + + + +def _execute_with_defaults(node, prompt, **overrides): + """Call a node with its own schema defaults, so a test does not have to track + each workflow's argument list.""" + kwargs = {} + for spec in node.define_schema().inputs: + default = getattr(spec, "default", None) + if default is not None: + kwargs[spec.id] = default + elif getattr(spec, "options", None): + kwargs[spec.id] = spec.options[0] + kwargs["prompt"] = prompt + kwargs.update(overrides) + return asyncio.run(node.execute(**kwargs)) + +@pytest.mark.parametrize( + ("node", "workflow", "returns_video", "requires_image", "controls"), + [ + ( + nodes_comfy_cloud.ComfyCloudZImageTurboNode, "z-image-turbo/text-to-image", False, False, + {"aspect_ratio": "1:1", "megapixels": 1.0}, + ), + ( + nodes_comfy_cloud.ComfyCloudMiniMaxH3TextToVideoNode, "minimax-h3/text-to-video", True, False, + { + "aspect_ratio": "16:9", "duration_seconds": 5.0, "resolution": "480p", + }, + ), + ], +) +def test_workflow_submission_polling_and_download( + monkeypatch, node, workflow, returns_video, requires_image, controls +): + sync = AsyncMock( + return_value=ComfyCloudGenerateResponse( + task_id="task-1", + status="queued", + polling_url="/proxy/comfy-cloud/workflow/tasks/task-1", + cancel_url="/proxy/comfy-cloud/workflow/tasks/task-1/cancel", + ) + ) + poll = AsyncMock( + return_value=ComfyCloudStatusResponse( + task_id="task-1", + status="completed", + progress=100, + output_url="/proxy/comfy-cloud/results/task-1/output", + ) + ) + upload = AsyncMock(return_value="https://example.com/input.png") + image_download = AsyncMock(return_value="image-output") + video_download = AsyncMock(return_value="video-output") + monkeypatch.setattr(nodes_comfy_cloud, "sync_op", sync) + monkeypatch.setattr(nodes_comfy_cloud, "poll_op", poll) + monkeypatch.setattr(nodes_comfy_cloud, "upload_image_to_comfyapi", upload) + monkeypatch.setattr(nodes_comfy_cloud, "download_url_to_image_tensor", image_download) + monkeypatch.setattr(nodes_comfy_cloud, "download_url_to_video_output", video_download) + monkeypatch.setattr(nodes_comfy_cloud, "get_number_of_images", lambda image: 1) + + output = _execute_with_defaults(node, "A tiny fennec fox") + + endpoint = sync.call_args.args[1] + request = sync.call_args.kwargs["data"] + assert endpoint.path == "/proxy/comfy-cloud/workflow/generate" + assert endpoint.method == "POST" + assert request == ComfyCloudGenerateRequest( + workflow=workflow, + inputs=ComfyCloudWorkflowInputs( + prompt="A tiny fennec fox", + image_url="https://example.com/input.png" if requires_image else None, + seed=42, + **controls, + ), + ) + assert upload.await_count == int(requires_image) + + poll_endpoint = poll.call_args.args[1] + cancel_endpoint = poll.call_args.kwargs["cancel_endpoint"] + assert poll_endpoint.path == "/proxy/comfy-cloud/workflow/tasks/task-1" + assert cancel_endpoint.path == "/proxy/comfy-cloud/workflow/tasks/task-1/cancel" + assert cancel_endpoint.method == "POST" + assert output[0] == ("video-output" if returns_video else "image-output") + + +def test_contract_omits_optional_status_fields(): + request = ComfyCloudGenerateRequest( + workflow="z-image-turbo/text-to-image", + inputs=ComfyCloudWorkflowInputs(prompt="A lighthouse"), + ) + status = ComfyCloudStatusResponse(task_id="task-1", status="queued") + + assert request.model_dump(exclude_none=True) == { + "workflow": "z-image-turbo/text-to-image", + "inputs": {"prompt": "A lighthouse"}, + } + assert status.model_dump(exclude_none=True) == {"task_id": "task-1", "status": "queued"} + + +def test_status_progress_is_clamped_for_display(): + assert nodes_comfy_cloud._progress(ComfyCloudStatusResponse(task_id="task-1", status="running", progress=100.5)) == 100 + assert nodes_comfy_cloud._progress(ComfyCloudStatusResponse(task_id="task-1", status="running", progress=-1)) == 0 + + +def test_poll_failure_cancels_submitted_task(monkeypatch): + poll = AsyncMock(side_effect=ValueError("invalid status response")) + cancel = AsyncMock(return_value={"status": "cancellation_requested"}) + monkeypatch.setattr(nodes_comfy_cloud, "poll_op", poll) + monkeypatch.setattr(nodes_comfy_cloud, "sync_op_raw", cancel) + + with pytest.raises(ValueError, match="invalid status response"): + asyncio.run(nodes_comfy_cloud._poll_task(nodes_comfy_cloud.ComfyCloudZImageTurboNode, "task/1")) + + cancel.assert_awaited_once() + assert cancel.call_args.args[1].path == "/proxy/comfy-cloud/workflow/tasks/task%2F1/cancel" + assert cancel.call_args.kwargs["max_retries"] == 0 + + +@pytest.mark.parametrize("response_model", [ComfyCloudGenerateResponse, ComfyCloudStatusResponse]) +@pytest.mark.parametrize("task_id", ["", " "]) +def test_contract_rejects_empty_task_ids(response_model, task_id): + values = {"task_id": task_id, "status": "queued"} + if response_model is ComfyCloudGenerateResponse: + values.update(polling_url="/poll", cancel_url="/cancel") + + with pytest.raises(ValueError, match="task_id"): + response_model(**values) + + +@pytest.mark.parametrize( + "url", + [ + "http://example.com/output.png", + "http://127.0.0.1/output.png", + "//169.254.169.254/latest/meta-data", + "/unrelated/path/output.png", + "https://user@example.com/output.png", + "/proxy/comfy-cloud/../../v1/users/me", + "/proxy/comfy-cloud/%2e%2e/%2e%2e/v1/users/me", + "https://127.0.0.1/output.png", + "https://169.254.169.254/latest/meta-data", + "https://attacker.example/output.png", + ], +) +def test_cloud_workflows_reject_untrusted_output_urls(monkeypatch, url): + sync = AsyncMock( + return_value=ComfyCloudGenerateResponse( + task_id="task-1", + status="queued", + polling_url="/poll", + cancel_url="/cancel", + ) + ) + poll = AsyncMock( + return_value=ComfyCloudStatusResponse(task_id="task-1", status="completed", output_url=url) + ) + download = AsyncMock() + monkeypatch.setattr(nodes_comfy_cloud, "sync_op", sync) + monkeypatch.setattr(nodes_comfy_cloud, "poll_op", poll) + monkeypatch.setattr(nodes_comfy_cloud, "download_url_to_image_tensor", download) + + with pytest.raises(RuntimeError, match="invalid output URL"): + asyncio.run(nodes_comfy_cloud.ComfyCloudZImageTurboNode.execute("prompt")) + download.assert_not_awaited() + + +def test_cloud_workflows_accept_signed_https_output_urls(monkeypatch): + sync = AsyncMock( + return_value=ComfyCloudGenerateResponse( + task_id="task-1", + status="queued", + polling_url="/poll", + cancel_url="/cancel", + ) + ) + poll = AsyncMock( + return_value=ComfyCloudStatusResponse( + task_id="task-1", + status="completed", + output_url="https://storage.googleapis.com/comfy-cloud-assets/output.png?signature=example", + ) + ) + download = AsyncMock(return_value="image-output") + monkeypatch.setattr(nodes_comfy_cloud, "sync_op", sync) + monkeypatch.setattr(nodes_comfy_cloud, "poll_op", poll) + monkeypatch.setattr(nodes_comfy_cloud, "download_url_to_image_tensor", download) + + output = asyncio.run(nodes_comfy_cloud.ComfyCloudZImageTurboNode.execute("prompt")) + + assert output[0] == "image-output" + download.assert_awaited_once_with( + "https://storage.googleapis.com/comfy-cloud-assets/output.png?signature=example", + timeout=nodes_comfy_cloud._OUTPUT_DOWNLOAD_TIMEOUT, + cls=nodes_comfy_cloud.ComfyCloudZImageTurboNode, + allow_redirects=False, + ) + + +@pytest.mark.parametrize( + "node", + [ + nodes_comfy_cloud.ComfyCloudZImageTurboNode, + nodes_comfy_cloud.ComfyCloudFlux2TextToImageNode, + nodes_comfy_cloud.ComfyCloudMiniMaxH3TextToVideoNode, + ], +) +def test_capability_nodes_reject_oversized_prompts(monkeypatch, node): + sync = AsyncMock() + monkeypatch.setattr(nodes_comfy_cloud, "sync_op", sync) + + with pytest.raises(Exception, match="4096"): + asyncio.run(node.execute("x" * 4097, object())) + sync.assert_not_awaited() + + +def test_capability_nodes_strip_prompts_before_submission(monkeypatch): + values = nodes_comfy_cloud._validate_node_inputs( + nodes_comfy_cloud.ComfyCloudZImageTurboNode, {"prompt": " prompt "} + ) + + assert values["prompt"] == "prompt" + + +def test_task_routes_ignore_response_urls_and_errors_hide_task_token(monkeypatch): + sync = AsyncMock( + return_value=ComfyCloudGenerateResponse( + task_id="secret/task-token", + status="queued", + polling_url="https://attacker.example/poll", + cancel_url="https://attacker.example/cancel", + ) + ) + poll = AsyncMock( + return_value=ComfyCloudStatusResponse( + task_id="secret/task-token", + status="completed", + error="provider details with secret/task-token", + ) + ) + monkeypatch.setattr(nodes_comfy_cloud, "sync_op", sync) + monkeypatch.setattr(nodes_comfy_cloud, "poll_op", poll) + + with pytest.raises(RuntimeError) as error: + _execute_with_defaults(nodes_comfy_cloud.ComfyCloudMiniMaxH3TextToVideoNode, "A prompt") + + assert poll.call_args.args[1].path == "/proxy/comfy-cloud/workflow/tasks/secret%2Ftask-token" + assert poll.call_args.kwargs["cancel_endpoint"].path == "/proxy/comfy-cloud/workflow/tasks/secret%2Ftask-token/cancel" + assert "task-token" not in str(error.value) + assert "provider details" not in str(error.value) + + +CONTROLLED_IMAGE_NODES = [ + ( + nodes_comfy_cloud.ComfyCloudZImageTurboNode, + "z-image-turbo/text-to-image", + ["prompt", "seed", "aspect_ratio", "megapixels"], + {"prompt": "A glass forest", "seed": 9, "aspect_ratio": "16:9", "megapixels": 1.5}, + {"prompt": "A glass forest", "aspect_ratio": "16:9", "megapixels": 1.5, "seed": 9}, + ), + ( + nodes_comfy_cloud.ComfyCloudFlux2TextToImageNode, + "flux-2/text-to-image", + ["prompt", "seed", "aspect_ratio", "megapixels", "turbo"], + {"prompt": "A glass forest", "seed": 9, "aspect_ratio": "3:2", "megapixels": 2.0, "turbo": False}, + {"prompt": "A glass forest", "aspect_ratio": "3:2", "megapixels": 2.0, "turbo": False, "seed": 9}, + ), +] + + +@pytest.mark.parametrize(("node", "workflow", "input_names", "arguments", "expected_inputs"), CONTROLLED_IMAGE_NODES) +def test_controlled_image_node_schema_and_request_mapping( + monkeypatch, node, workflow, input_names, arguments, expected_inputs +): + sync = AsyncMock( + return_value=ComfyCloudGenerateResponse( + task_id="task-2", + status="queued", + polling_url="/tasks/task-2", + cancel_url="/tasks/task-2/cancel", + ) + ) + poll = AsyncMock( + return_value=ComfyCloudStatusResponse( + task_id="task-2", + status="completed", + output_url="/proxy/comfy-cloud/results/task-2/image.png", + ) + ) + upload = AsyncMock(return_value="/uploads/input.png") + download = AsyncMock(return_value="image-output") + monkeypatch.setattr(nodes_comfy_cloud, "sync_op", sync) + monkeypatch.setattr(nodes_comfy_cloud, "poll_op", poll) + monkeypatch.setattr(nodes_comfy_cloud, "upload_image_to_comfyapi", upload) + monkeypatch.setattr(nodes_comfy_cloud, "download_url_to_image_tensor", download) + monkeypatch.setattr(nodes_comfy_cloud, "get_number_of_images", lambda image: 1) + + schema = node.define_schema() + assert schema.node_id == node.node_id + # The schema decorates the class attribute with the beta marker. + assert schema.display_name == f"{node.display_name} [BETA]" + assert schema.is_api_node is True + assert [input.id for input in schema.inputs] == input_names + assert len(schema.outputs) == 1 + assert schema.outputs[0].get_io_type() == "IMAGE" + + output = asyncio.run(node.execute(**arguments)) + request = sync.call_args.kwargs["data"] + + assert request.workflow == workflow + assert request.inputs.model_dump(exclude_none=True) == expected_inputs + assert "asset_id" not in request.model_dump_json() + assert '"id"' not in request.model_dump_json() + assert upload.await_count == int("image" in arguments) + if "image" in arguments: + assert upload.call_args.kwargs == {"total_pixels": None} + download.assert_awaited_once_with( + "/proxy/comfy-cloud/results/task-2/image.png", + timeout=30 * 60, + cls=node, + allow_redirects=False, + ) + assert output[0] == "image-output" + + +def test_controlled_image_nodes_are_declared_and_registered(): + workflows = {workflow for _, workflow, _, _, _ in CONTROLLED_IMAGE_NODES} + registered = set(asyncio.run(nodes_comfy_cloud.ComfyCloudExtension().get_node_list())) + + assert workflows <= set(get_args(ComfyCloudWorkflow)) + assert {node for node, _, _, _, _ in CONTROLLED_IMAGE_NODES} <= registered + + +def test_music_node_sends_its_hidden_caption_cfg(monkeypatch): + run = AsyncMock(return_value="audio-output") + monkeypatch.setattr(nodes_comfy_cloud, "_run_audio_workflow", run) + + output = _execute_with_defaults( + nodes_comfy_cloud.ComfyCloudMiniMaxMusic3TextToAudioNode, + "A dreamy instrumental", + ) + + inputs = run.call_args.args[2] + assert inputs.caption_cfg == 1.5 + assert output == "audio-output" + + +@pytest.mark.skip(reason="Disabled until the server-side issue is fixed") +def test_reference_video_exposes_and_sends_multimodal_references(monkeypatch): + node = nodes_comfy_cloud.ComfyCloudMiniMaxH3ReferenceToVideoNode + run = AsyncMock(return_value="video-output") + asset = AsyncMock( + return_value=nodes_comfy_cloud.ComfyCloudAssetInput(type="IMAGE", url="/uploads/reference.png") + ) + video_asset = AsyncMock( + return_value=nodes_comfy_cloud.ComfyCloudAssetInput(type="VIDEO", url="/uploads/reference.mp4") + ) + audio_asset = AsyncMock( + side_effect=[ + nodes_comfy_cloud.ComfyCloudAssetInput(type="AUDIO", url="/uploads/reference-1.m4a"), + nodes_comfy_cloud.ComfyCloudAssetInput(type="AUDIO", url="/uploads/reference-2.m4a"), + ] + ) + monkeypatch.setattr(nodes_comfy_cloud, "_run_video_workflow", run) + monkeypatch.setattr(nodes_comfy_cloud, "_minimax_h3_asset", asset) + monkeypatch.setattr(nodes_comfy_cloud, "_minimax_h3_video_asset", video_asset) + monkeypatch.setattr(nodes_comfy_cloud, "_minimax_h3_audio_asset", audio_asset) + + schema = node.define_schema() + input_names = [input_spec.id for input_spec in schema.inputs] + assert input_names == [ + "reference_images", "ref_video", "ref_audio", "prompt", "seed", + "aspect_ratio", "resolution", "duration_seconds", "ref_image_size", + ] + assert next(input_spec for input_spec in schema.inputs if input_spec.id == "ref_video").optional is True + image_template = next(input_spec for input_spec in schema.inputs if input_spec.id == "reference_images").template + assert (image_template.min, image_template.max) == (0, 4) + audio_template = next(input_spec for input_spec in schema.inputs if input_spec.id == "ref_audio").template + assert (audio_template.min, audio_template.max) == (0, 3) + + asyncio.run( + node.execute( + prompt="A glass forest", + reference_images={"reference_image_1": "image"}, + ref_video="video", + ref_audio={"ref_audio_1": "audio-1", "ref_audio_2": "audio-2"}, + ref_image_size="max", + ) + ) + + inputs = run.call_args.args[2] + assert inputs.ref_image_size == "max" + assert inputs.assets == { + "reference_image_1": nodes_comfy_cloud.ComfyCloudAssetInput(type="IMAGE", url="/uploads/reference.png"), + "ref_video": nodes_comfy_cloud.ComfyCloudAssetInput(type="VIDEO", url="/uploads/reference.mp4"), + "ref_audio_1": nodes_comfy_cloud.ComfyCloudAssetInput(type="AUDIO", url="/uploads/reference-1.m4a"), + "ref_audio_2": nodes_comfy_cloud.ComfyCloudAssetInput(type="AUDIO", url="/uploads/reference-2.m4a"), + } + video_asset.assert_awaited_once_with(node, "video") + assert audio_asset.await_count == 2 + + +@pytest.mark.skip(reason="Disabled until the server-side issue is fixed") +def test_reference_video_accepts_no_references(monkeypatch): + run = AsyncMock(return_value="video-output") + monkeypatch.setattr(nodes_comfy_cloud, "_run_video_workflow", run) + + output = _execute_with_defaults( + nodes_comfy_cloud.ComfyCloudMiniMaxH3ReferenceToVideoNode, + "An empty desert", + ) + + assert run.call_args.args[2].assets == {} + assert output == "video-output" + + +def _workflow_ids_submitted_by_the_nodes() -> set[str]: + """Every workflow id the module names, read off the source. + + Matched by shape rather than by call site: most nodes pass a literal to their + runner, while Mage Flow passes a `workflow` ClassVar. Categories do not collide + with the shape ("comfy cloud/image" has a space). + """ + tree = ast.parse(Path(nodes_comfy_cloud.__file__).read_text()) + shape = re.compile(r"^[a-z0-9][a-z0-9.-]*/[a-z0-9][a-z0-9.-]*$") + return { + node.value + for node in ast.walk(tree) + if isinstance(node, ast.Constant) and isinstance(node.value, str) and shape.match(node.value) + } + + +def test_every_submitted_workflow_id_is_accepted_by_the_request_model(): + """BE-12049. The union is what pydantic validates the outgoing request + against, so an id a node submits but the union does not name is a + ValidationError on Run, for that node only, and no test caught it: the + check above covers the image nodes alone and only as a subset, so a video + id could drift and a stale union entry naming no node stayed invisible. + + Exact equality in both directions, deliberately. + """ + submitted = _workflow_ids_submitted_by_the_nodes() + declared = set(get_args(ComfyCloudWorkflow)) + + assert submitted, "found no workflow ids; the AST scan above has broken" + assert submitted - declared == set(), f"submitted but not in the union: {sorted(submitted - declared)}" + assert declared - submitted == set(), f"in the union but submitted by nothing: {sorted(declared - submitted)}" + + +# The controls a first-time user is shown before expanding anything. Everything +# outside this set has to be advanced, or the node opens on a wall of dials. +PLAIN_CONTROLS = { + "prompt", "instruction", "image", "audio", "first_frame", "last_frame", + "aspect_ratio", "duration_seconds", "seed", "scale", "quality_mode", + "prompt_enhance", "enhance_prompt", "turbo", "rendering_speed", + # Music: lyrics are sung rather than described, so they are a second prompt + # rather than a tuning dial; max_duration is that graph's length control and + # tiled_decode its one quality-against-speed switch. + "lyrics", "max_duration", "audio_quality", + # Video: the frame-size budget is a headline choice rather than a dial, and + # reference-to-video's slots are its media inputs. ref_image_size is that + # graph's one quality-against-speed switch. + "resolution", "reference_images", "ref_video", "ref_audio", "ref_image_size", + # Mage Flow: a negative prompt is a second prompt rather than a dial, and the + # pixel budget is how that graph is sized at all, so neither is "advanced". + "negative_prompt", "megapixels", +} + + +def test_tuning_controls_are_hidden_behind_the_advanced_flag(): + for node in asyncio.run(nodes_comfy_cloud.ComfyCloudExtension().get_node_list()): + plain = [ + input_spec.id + for input_spec in node.define_schema().inputs + if not getattr(input_spec, "advanced", None) + ] + assert set(plain) <= PLAIN_CONTROLS, f"{node.__name__} shows {sorted(set(plain) - PLAIN_CONTROLS)}" + # The headline set is prompt, the media inputs, aspect ratio, resolution, + # duration, seed and one quality-against-speed switch. The multimodal + # reference node also exposes its video and audio reference groups. + assert len(plain) <= 9, f"{node.__name__} opens with {len(plain)} controls" + + +def test_pointer_node_pickers_name_the_trade_off_rather_than_the_model(): + """A default/* id is a pointer: the model behind it is re-pointed over time and + the id does not change. A saved graph stores the KEY, so a key naming a model + would stop resolving the day the pointer moved.""" + tiers = {"fast", "balanced", "quality"} + for node in asyncio.run(nodes_comfy_cloud.ComfyCloudExtension().get_node_list()): + if not getattr(node, "workflow", "").startswith("default/"): + continue + for options in (node.model_options, node.lora_options): + assert set(options) <= tiers, f"{node.__name__}: {sorted(set(options) - tiers)}" + + +def test_every_seed_starts_at_42_and_advances_after_a_run(): + for node in asyncio.run(nodes_comfy_cloud.ComfyCloudExtension().get_node_list()): + seed = next((i for i in node.define_schema().inputs if i.id == "seed"), None) + assert seed is not None, f"{node.__name__} has no seed" + assert seed.default == 42, f"{node.__name__} seeds at {seed.default}" + assert seed.control_after_generate is True + + +def test_cloud_workflow_controls_have_connection_sockets(): + nodes = asyncio.run(nodes_comfy_cloud.ComfyCloudExtension().get_node_list()) + + for node in nodes: + for input_spec in node.define_schema().inputs: + if isinstance(input_spec, nodes_comfy_cloud.IO.WidgetInput): + assert input_spec.socketless is False, f"{node.__name__}.{input_spec.id}" + + +def test_cloud_workflow_schemas_have_descriptions(): + nodes = asyncio.run(nodes_comfy_cloud.ComfyCloudExtension().get_node_list()) + + for node in nodes: + assert node.define_schema().description.strip(), node.__name__ + + +def test_cloud_workflow_schemas_share_exact_estimated_rate_metadata(): + nodes = asyncio.run(nodes_comfy_cloud.ComfyCloudExtension().get_node_list()) + + assert nodes_comfy_cloud.COMFY_CLOUD_GPU_SECOND_USD == 0.001295 + assert nodes_comfy_cloud.COMFY_CLOUD_CREDITS_PER_USD == 211 + assert nodes_comfy_cloud.COMFY_CLOUD_GPU_SECOND_CREDITS == pytest.approx(0.273245) + for node in nodes: + schema = node.define_schema() + badge = schema.price_badge.as_dict(schema.inputs) + assert badge["expr"] == ( + '{"type":"usd","usd":0.001295,"format":{"suffix":"/GPU-second","approximate":true}}' + ) + assert schema.description.endswith( + "Runs on a Comfy Cloud GPU, billed by how long it runs at " + "$0.001295/GPU-second (0.27 credits). Paid in credits, no Cloud " + "subscription required." + ), node.__name__ + + +def test_every_node_describes_what_it_actually_does(): + """These descriptions used to be three generic bodies shared across sixteen + nodes, which left the tooltip saying nothing about which model runs or why + you would pick this node over the one beside it.""" + nodes = asyncio.run(nodes_comfy_cloud.ComfyCloudExtension().get_node_list()) + summaries = {} + + for node in nodes: + schema = node.define_schema() + summary = schema.description.split(" Runs on a Comfy Cloud GPU")[0] + assert len(summary) > 60, f"{node.__name__} says too little: {summary!r}" + summaries.setdefault(summary, []).append(node.__name__) + + shared = {s: n for s, n in summaries.items() if len(n) > 1} + # The four capability nodes deliberately share wording per output type. + assert all(len(n) <= 2 for n in shared.values()), shared + + +def test_all_linkable_widget_constraints_are_validated(): + nodes = asyncio.run(nodes_comfy_cloud.ComfyCloudExtension().get_node_list()) + + for node in nodes: + for input_spec in node.define_schema().inputs: + if not isinstance(input_spec, nodes_comfy_cloud.IO.WidgetInput): + continue + io_type = input_spec.get_io_type() + if io_type == "COMBO": + invalid = "not-an-option" + elif io_type == "BOOLEAN": + invalid = "true" + elif io_type == "INT": + invalid = (input_spec.min - 1) if input_spec.min is not None else 1.5 + elif io_type == "FLOAT": + invalid = float("nan") + elif io_type == "STRING" and nodes_comfy_cloud._TEXT_LIMITS.get(input_spec.id, (0,))[0]: + invalid = " " + else: + continue + with pytest.raises((ValueError, Exception), match=input_spec.id): + nodes_comfy_cloud._validate_node_inputs(node, {input_spec.id: invalid}) + + +def test_text_inputs_name_the_field_when_a_linked_value_is_not_a_string(): + """_with_input_sockets clears socketless on every widget, so a graph can link an INT + output into a text input. That must name the field, not raise AttributeError.""" + with pytest.raises(ValueError, match="prompt"): + nodes_comfy_cloud._validate_node_inputs( + nodes_comfy_cloud.ComfyCloudZImageTurboNode, {"prompt": 7} + ) + + +def test_uploaded_images_have_decoded_resource_limits(): + oversized_image = torch.empty((1, 8193, 1, 3), device="meta") + # The only case that reaches the pixel-count branch rather than the dimension one. + oversized_pixels = torch.empty((1, 8000, 5000, 3), device="meta") + + with pytest.raises(ValueError, match="32-megapixel"): + nodes_comfy_cloud._validate_image_upload(oversized_image) + with pytest.raises(ValueError, match="32-megapixel"): + nodes_comfy_cloud._validate_image_upload(oversized_pixels) + + +def _stub_download_session(monkeypatch, responses): + """Point download_url_to_bytesio at a scripted list of responses, one per attempt. + + Returns the list that records the `allow_redirects` each attempt asked aiohttp for. + """ + seen_allow_redirects = [] + + class Session: + def __init__(self, timeout): + pass + + async def get(self, url, headers, allow_redirects=True): + seen_allow_redirects.append(allow_redirects) + return responses.pop(0) + + async def close(self): + pass + + monkeypatch.setattr(download_helpers.aiohttp, "ClientSession", Session) + monkeypatch.setattr(download_helpers, "sleep_with_interrupt", AsyncMock()) + return seen_allow_redirects + + +class _StubContent: + def __init__(self, chunks): + self.chunks = iter(chunks) + self.finished = False + + async def read(self, size): + chunk = next(self.chunks) + if isinstance(chunk, Exception): + raise chunk + if not chunk: + self.finished = True + return chunk + + def at_eof(self): + return self.finished + + +class _StubResponse: + headers = {} + content_length = None + + def __init__(self, chunks, status=200): + self.content = _StubContent(chunks) + self.status = status + + async def json(self): + return {} + + async def text(self): + return "" + + async def __aenter__(self): + return self + + async def __aexit__(self, *args): + return False + + +def test_in_memory_download_empties_its_sink_before_retrying(monkeypatch): + """A retry re-reads the body from byte zero. Without the reset the caller gets + the partial first attempt concatenated with the whole second one.""" + _stub_download_session( + monkeypatch, + [ + _StubResponse([b"partial", aiohttp.ClientPayloadError("retry")]), + _StubResponse([b"final", b""]), + ], + ) + destination = BytesIO() + + asyncio.run(download_helpers.download_url_to_bytesio("https://example.com/result", destination)) + + assert destination.read() == b"final" + + +def test_redirects_are_refused_rather_than_followed_when_disallowed(monkeypatch): + """Comfy Cloud vets the output URL's bucket before downloading, so a redirect has to + fail rather than quietly fetch the body from somewhere that was never vetted.""" + seen = _stub_download_session(monkeypatch, [_StubResponse([], status=302)]) + + with pytest.raises(Exception, match="HTTP 302"): + asyncio.run( + download_helpers.download_url_to_bytesio( + "https://example.com/result", BytesIO(), allow_redirects=False, max_retries=0 + ) + ) + + assert seen == [False] + + +def test_extension_registers_exactly_the_shipped_set(): + """The shipped surface is deliberate: four capability nodes whose model the backend + chooses, plus the named workflows that expose control a generic shape cannot.""" + capability_nodes = { + nodes_comfy_cloud.ComfyCloudZImageTurboNode, + nodes_comfy_cloud.ComfyCloudFlux2TextToImageNode, + nodes_comfy_cloud.ComfyCloudMiniMaxH3TextToVideoNode, + } + named_nodes = { + nodes_comfy_cloud.ComfyCloudMiniMaxH3TextToVideoNode, + nodes_comfy_cloud.ComfyCloudZImageTurboNode, + nodes_comfy_cloud.ComfyCloudFlux2TextToImageNode, + nodes_comfy_cloud.ComfyCloudMageFlowTextToImageNode, + nodes_comfy_cloud.ComfyCloudMageFlowTurboTextToImageNode, + nodes_comfy_cloud.ComfyCloudMiniMaxMusic3TextToAudioNode, + nodes_comfy_cloud.ComfyCloudMiniMaxH3FirstLastFrameToVideoNode, + nodes_comfy_cloud.ComfyCloudMiniMaxH3ImageToVideoNode, + } + registered = set(asyncio.run(nodes_comfy_cloud.ComfyCloudExtension().get_node_list())) + + assert registered == capability_nodes | named_nodes + + +def test_every_node_is_named_for_its_provider(): + """A user searching "flux" sees our paid cloud node beside the free local one. + The provider prefix is the only thing on the name that tells them apart.""" + for node in asyncio.run(nodes_comfy_cloud.ComfyCloudExtension().get_node_list()): + name = node.define_schema().display_name + assert name.startswith("Comfy Cloud "), f"{node.__name__} is named {name!r}" + # Beta marker is a SUFFIX so the menu still sorts these by model rather + # than filing all of them under "[". + assert name.endswith(" [BETA]"), f"{node.__name__} is named {name!r}" + + +@pytest.mark.parametrize( + "bucket", + ["comfy-cloud", "comfy-cloud-assets-evil", "example", "comfy-cloud-assets.evil.com", + "partner-nodes-assets-evil", "partner-nodes", + # Advertises an allowed bucket in the first segment and resolves to another one. + "comfy-cloud-assets/../other-bucket", "comfy-cloud-assets/%2e%2e/other-bucket"], +) +def test_output_urls_outside_the_backend_bucket_allowlist_are_rejected(bucket): + """The output URL is backend-supplied, so this is defence in depth -- but the host check + alone would accept any bucket on storage.googleapis.com. Pinned to the same set the Go + side enforces (comfyCloudOutputBuckets).""" + with pytest.raises(RuntimeError): + nodes_comfy_cloud._validated_output_url( + f"https://storage.googleapis.com/{bucket}/output.png?signature=example" + ) + + +@pytest.mark.parametrize( + "bucket", ["comfy-cloud-assets", "comfy-cloud-assets-stg", "comfy-cloud-assets-test"] +) +def test_output_urls_in_the_backend_bucket_allowlist_are_accepted(bucket): + url = f"https://storage.googleapis.com/{bucket}/output.png?signature=example" + assert nodes_comfy_cloud._validated_output_url(url) == url + + +def test_poll_budget_covers_the_platform_run_ceiling(): + """The poll budget must sit just above the platform's own max_runtime, so a job that is + still legitimately running is ended by its own timeout rather than abandoned by the node.""" + budget = nodes_comfy_cloud._POLL_MAX_ATTEMPTS * nodes_comfy_cloud._POLL_INTERVAL_SECONDS + assert budget > nodes_comfy_cloud._RUN_TIMEOUT_SECONDS + assert budget - nodes_comfy_cloud._RUN_TIMEOUT_SECONDS <= 300 + + +def test_output_buckets_match_the_server_allowlist(): + """Pins the bucket set so a change here is deliberate and paired. + + The same list lives in cloud at services/comfy-api/config/config.go + (comfyCloudOutputBuckets). Widening one side only is not a benign skew: the + job runs on the GPU, the caller is billed per GPU-second, and the output is + then rejected on the user's machine. The node half also ships on the ComfyUI + release train, so a mismatch persists until the next release. + """ + assert nodes_comfy_cloud._OUTPUT_BUCKETS == frozenset( + { + "comfy-cloud-assets", + "comfy-cloud-assets-stg", + "comfy-cloud-assets-test", + "partner-nodes-assets", + "partner-nodes-assets-staging", + } + ) + + +def test_disabled_provider_message_reaches_the_user_verbatim(): + """comfy-api's error envelope is flat, and the message is what a user reads. + + Before this, _friendly_http_message only unwrapped a NESTED error object, so + a flat {"error": code, "message": text} body fell through to the raw-JSON + branch and the user was shown the whole payload. + """ + from comfy_api_nodes.util import client + + body = { + "error": "comfy_cloud_provider_disabled", + "message": "Comfy Cloud is currently unavailable. Please try again later.", + } + assert client._friendly_http_message(503, body) == body["message"] + + +def test_disabled_provider_is_not_retried(): + """A switched-off provider is a terminal answer, not a transient blip. + + 503 is in _RETRY_STATUS, so without this the user waits through three + backoff rounds only to be told the same thing. + """ + from comfy_api_nodes.util import client + + assert client._is_terminal_service_refusal( + {"error": "comfy_cloud_provider_disabled", "message": "x"} + ) + # A genuine transient 503 carries no such code and must still be retried. + assert not client._is_terminal_service_refusal({"error": "upstream_timeout"}) + assert not client._is_terminal_service_refusal({}) + assert not client._is_terminal_service_refusal("bad gateway") + + +@pytest.mark.parametrize( + ("node", "io_type"), + [ + (nodes_comfy_cloud.ComfyCloudZImageTurboNode, "IMAGE"), + (nodes_comfy_cloud.ComfyCloudMiniMaxH3TextToVideoNode, "VIDEO"), + (nodes_comfy_cloud.ComfyCloudMiniMaxMusic3TextToAudioNode, "AUDIO"), + ], +) +def test_nodes_declare_their_output_io_type(node, io_type): + assert node.define_schema().outputs[0].get_io_type() == io_type + + +@pytest.mark.parametrize("kind", ["image", "video", "audio"]) +def test_every_output_kind_refuses_a_redirect_off_the_vetted_url(monkeypatch, kind): + """The bucket pin decides where the bytes may come from. Following a redirect + would hand that decision back to the server we just checked.""" + seen = {} + + async def fake(url, *args, **kwargs): + seen.update(kwargs) + return "output" + + async def fake_bytesio(url, dest, *args, **kwargs): + seen.update(kwargs) + + monkeypatch.setattr(nodes_comfy_cloud, "download_url_to_image_tensor", fake) + monkeypatch.setattr(nodes_comfy_cloud, "download_url_to_video_output", fake) + monkeypatch.setattr(nodes_comfy_cloud, "download_url_to_bytesio", fake_bytesio) + monkeypatch.setattr(nodes_comfy_cloud, "audio_bytes_to_audio_input", lambda data: "audio") + monkeypatch.setattr( + nodes_comfy_cloud, "_submit_workflow", + AsyncMock(return_value="https://storage.googleapis.com/comfy-cloud-assets/o.bin?X-Goog-Signature=x"), + ) + + run = { + "image": nodes_comfy_cloud._run_image_workflow, + "video": nodes_comfy_cloud._run_video_workflow, + "audio": nodes_comfy_cloud._run_audio_workflow, + }[kind] + asyncio.run(run(nodes_comfy_cloud.ComfyCloudZImageTurboNode, "z-image-turbo/text-to-image", None)) + + assert seen["allow_redirects"] is False