Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

9.6 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

import base64
import json

import pytest

from fastapi.responses import Response

from studio_mcp.media import INLINE_CAP

from .mcp_harness import (
    JPEG,
    PNG,
    PNG_URL,
    REMOTE,
    WEBP,
    bodies,
    call_with_progress,
    data_url,
    fake_studio,
    fast_polls,  # noqa: F401  (fixture)
    queries,
    run_tool,
    slow,
)


def _image(image_id, side, seed):
    return {
        "id": image_id,
        "url": f"/api/inference/images/gallery/{image_id}/file",
        "prompt": "a red fox",
        "width": side,
        "height": side,
        "steps": 4,
        "guidance": 0.0,
        "seed": seed,
        "model": "black-forest-labs/FLUX.1-schnell",
    }


GENERATED = {"images": [_image("img-small", 512, 1), _image("img-large", 1024, 2)]}


def _png(request, body):
    return Response(PNG, media_type = "image/png")


def _webp(request, body):
    assert request.query_params.get("thumb") == "1024"
    return Response(WEBP, media_type = "image/webp")


PAYLOADS = {
    ("POST", "/api/inference/images/generate"): GENERATED,
    ("GET", "/api/inference/images/generate-progress"): {
        "active": True,
        "step": 2,
        "total_steps": 4,
        "fraction": 0.5,
    },
}


GALLERY = "/api/inference/images/gallery"
GENERATE = ("POST", "/api/inference/images/generate")


def _studio(overrides = None):
    return fake_studio(
        {
            **PAYLOADS,
            ("GET", f"{GALLERY}/img-small/file"): _png,
            ("GET", f"{GALLERY}/img-large/file"): _webp,
            **{
                ("GET", f"{GALLERY}/{i}/signed-url"): {
                    "url": f"{GALLERY}/{i}/file-signed?token=t.{i}"
                }
                for i in ("img-small", "img-large")
            },
            **(overrides or {}),
        }
    )


def _generate(
    monkeypatch,
    args,
    overrides = None,
    **client,
):
    return run_tool(monkeypatch, _studio(overrides), "generate_image", args, **client)


def test_txt2img_returns_ids_urls_and_inline_images(monkeypatch):
    result, studio = _generate(
        monkeypatch, {"prompt": "a red fox", "width": 512, "steps": 4}, **REMOTE
    )
    remote = "http://192.168.1.20:8888" + GALLERY
    assert result["structuredContent"] == {
        "images": [
            {
                "id": i,
                "url": f"{remote}/{i}/file",
                "download_url": f"{remote}/{i}/file-signed?token=t.{i}",
                "width": side,
                "height": side,
                "seed": seed,
                "batch_seed": None,
                "batch_index": None,
            }
            for i, side, seed in (("img-small", 512, 1), ("img-large", 1024, 2))
        ]
    }
    content = result["content"]
    assert json.loads(content[0]["text"]) == result["structuredContent"]
    assert [c["type"] for c in content[1:]] == ["image", "image", "resource_link"]
    assert base64.b64decode(content[1]["data"]) == PNG
    assert content[1]["mimeType"] == "image/png"
    assert base64.b64decode(content[2]["data"]) == WEBP
    assert content[2]["mimeType"] == "image/webp"
    assert content[3]["uri"] == f"{remote}/img-large/file-signed?token=t.img-large"
    assert bodies(studio, "/api/inference/images/generate") == [
        {"prompt": "a red fox", "width": 512, "steps": 4}
    ]
    # A large image is never fetched in full; gallery files are fetched as the caller.
    assert queries(studio, f"{GALLERY}/img-large/file") == [{"thumb": "1024"}]
    fetches = [c[2] for c in studio.state.calls if "/gallery/" in c[1]]
    assert len(fetches) == 4
    for headers in fetches:
        assert headers["authorization"] == "Bearer sk-unsloth-test"
        assert headers["host"] == "unsloth-mcp.invalid"


REFUSALS = {
    "R1": "Reference needs init_image: pass the hero as init_image plus reference_images.",
    "R2": 'workflow="edit" needs init_image: it is the image the instruction changes.',
    "R3": 'workflow="outpaint" needs init_image: it is the image to extend.',
    "R4": 'workflow="outpaint" needs mask_image: white marks the padded border to fill.',
    "R5": "upscale must be above 1 (up to 4); for a same-size redraw leave upscale out and set strength.",
}


@pytest.mark.parametrize(
    "refusal,args",
    [
        ("R1", {"reference_images": [PNG_URL]}),
        ("R1", {"reference_images": [{"gallery_id": "ref-1"}]}),
        ("R1", {"workflow": "reference"}),
        ("R1", {"workflow": "reference", "reference_images": [{"gallery_id": "ref-1"}]}),
        ("R2", {"workflow": "edit"}),
        ("R3", {"workflow": "outpaint"}),
        ("R4", {"workflow": "outpaint", "init_image": PNG_URL}),
        ("R4", {"workflow": "outpaint", "init_image": {"gallery_id": "src-1"}}),
        ("R5", {"init_image": PNG_URL, "upscale": 1}),
        ("R5", {"init_image": {"gallery_id": "src-1"}, "upscale": 0.5}),
    ],
)
def test_a_workflow_missing_its_images_is_refused_before_any_call(monkeypatch, refusal, args):
    result, studio = _generate(monkeypatch, {"prompt": "the same knight", **args})
    assert result["isError"] is True
    assert REFUSALS[refusal] in result["content"][0]["text"]
    # Refused before resolve_image, so a gallery_id input is never fetched.
    assert studio.state.calls == []


def test_upscale_without_init_image_keeps_its_own_refusal(monkeypatch):
    result, studio = _generate(monkeypatch, {"prompt": "x", "upscale": 1})
    assert result["isError"] is True
    assert result["content"][0]["text"].startswith("upscale needs init_image")
    assert studio.state.calls == []


@pytest.mark.parametrize(
    "args",
    [
        {"workflow": "reference", "init_image": PNG_URL, "reference_images": [PNG_URL]},
        {"init_image": PNG_URL, "reference_images": [PNG_URL, PNG_URL]},
        {"workflow": "outpaint", "init_image": PNG_URL, "mask_image": PNG_URL},
        {"init_image": PNG_URL, "mask_image": PNG_URL},
        {"workflow": "edit", "init_image": PNG_URL},
        {"init_image": PNG_URL, "upscale": 2},
    ],
)
def test_workflows_with_their_images_send_the_same_body(monkeypatch, args):
    result, studio = _generate(monkeypatch, {"prompt": "x", **args})
    assert result["isError"] is False
    png = data_url(PNG, "image/png")
    images = {
        key: [png] * len(value) if isinstance(value, list) else png
        for key, value in args.items()
        if key in ("init_image", "mask_image", "reference_images")
    }
    assert bodies(studio, "/api/inference/images/generate") == [{"prompt": "x", **args, **images}]


def test_seeds_and_prompts_make_a_batch_and_rows_carry_their_batch_fields(monkeypatch):
    rows = [
        {**_image("img-small", 512, 11), "batch_seed": 11, "batch_index": 0},
        {**_image("img-large", 1024, 12), "batch_seed": 12, "batch_index": 1},
    ]
    args = {"prompt": "a fox", "seeds": [11, 12], "prompts": ["a fox", "a fox at night"]}
    result, studio = _generate(monkeypatch, args, {GENERATE: {"images": rows}})
    assert result["isError"] is False
    assert bodies(studio, "/api/inference/images/generate") == [args]
    images = result["structuredContent"]["images"]
    assert [(i["batch_seed"], i["batch_index"]) for i in images] == [(11, 0), (12, 1)]


def test_a_thumbnail_studio_could_not_make_keeps_its_png_type(monkeypatch):
    # The gallery route answers a failed thumbnail with the original PNG.
    result, _studio = _generate(
        monkeypatch, {"prompt": "x"}, {("GET", f"{GALLERY}/img-large/file"): _png}
    )
    previews = [c for c in result["content"] if c["type"] == "image"]
    assert previews[-1]["mimeType"] == "image/png"


def test_a_full_image_over_the_cap_falls_back_to_the_thumbnail(monkeypatch):
    def huge(request, body):
        if request.query_params.get("thumb"):
            return Response(WEBP, media_type = "image/webp")
        return Response(PNG + b"\x00" * INLINE_CAP, media_type = "image/png")

    overrides = {
        GENERATE: {"images": [_image("img-small", 512, 7)]},
        ("GET", f"{GALLERY}/img-small/file"): huge,
    }
    result, _studio = _generate(monkeypatch, {"prompt": "x"}, overrides)
    assert [c["type"] for c in result["content"][1:]] == ["image", "resource_link"]
    assert result["content"][1]["mimeType"] == "image/webp"


def test_progress_is_reported_while_generating(monkeypatch, fast_polls):
    studio = _studio({GENERATE: slow(GENERATED, 0.2)})
    progress, _result = call_with_progress(
        monkeypatch, studio, "generate_image", {"prompt": "x"}, "g"
    )
    assert progress and progress[0]["progress"] == 0.5
    assert progress[0]["message"] == "Step 2 of 4"


PNG_DATA = data_url(PNG, "image/png")


@pytest.mark.parametrize(
    "args,expected",
    [
        (
            {
                "prompt": "make it night",
                "init_image": {"gallery_id": "src-1"},
                "mask_image": PNG_URL,
                "reference_images": [{"data_url": data_url(JPEG, "image/jpeg")}],
                "workflow": "edit",
                "strength": 0.6,
                "allow_oversized": True,
            },
            {
                "init_image": PNG_DATA,
                "mask_image": PNG_DATA,
                "reference_images": [data_url(JPEG, "image/jpeg")],
            },
        ),
        ({"prompt": "sharper", "init_image": PNG_URL, "upscale": 2}, {"init_image": PNG_DATA}),
    ],
)
def test_edit_and_upscale_inputs_land_in_their_body_fields(monkeypatch, args, expected):
    result, studio = _generate(monkeypatch, args, {("GET", f"{GALLERY}/src-1/file"): _png})
    assert result["isError"] is False
    assert bodies(studio, "/api/inference/images/generate") == [{**args, **expected}]