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.

Studio: the Images pill makes images and videos in chat with the loaded local models (#14110)

Etherl56d1204955cf
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index f56b0f79fdc..ed000e9ecaa 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -11552,6 +11552,9 @@ class DiffusionBackend:
# Per-generation cancel Event that unload()/a superseding load set (under _lock) to abort just this denoise.
cancel = threading.Event()
+ from core.inference.generation_ticket import bind_generation_cancel
+
+ bind_generation_cancel(cancel)
with self._generation_slot(cancel):
# Never render beside a background compile; wait outside the state lock so status polls keep answering.
pending_bg = getattr(self._state, "bg_compile", None)
diff --git a/studio/backend/core/inference/generate_image_tool.py b/studio/backend/core/inference/generate_image_tool.py
new file mode 100644
index 00000000000..85f2c0926c3
--- /dev/null
+++ b/studio/backend/core/inference/generate_image_tool.py
@@ -0,0 +1,291 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The ``generate_image`` chat tool: one image on the image model already loaded in Unsloth Studio.
+
+The tool runs on a chat worker thread. It hands the Images route's core to the server loop,
+bound to the calling account, so the image lands in that account's gallery and goes through
+the same access checks. It never loads or unloads a model.
+"""
+
+from __future__ import annotations
+
+import concurrent.futures
+import json
+import logging
+import os
+import shutil
+import time
+from typing import Any, Optional
+
+logger = logging.getLogger(__name__)
+
+GENERATE_IMAGE_TOOL_NAME = "generate_image"
+
+ERR_NO_PROMPT = "Error: generate_image needs a prompt."
+ERR_NOT_LOADED = "Error: no image model is loaded in Unsloth Studio. Load one on the Images page, then try again."
+ERR_EDIT_ONLY = (
+ "Error: the image model loaded in Unsloth Studio only edits images. "
+ "Load a text-to-image model on the Images page."
+)
+ERR_BUSY = "Error: another image is generating in Unsloth Studio. Try again when it finishes."
+ERR_STOPPED = "Error: image generation was stopped."
+ERR_TIMEOUT = "Error: image generation took too long and was stopped."
+ERR_OTHER_ACCOUNT = (
+ "Error: another account is generating on the image model. Try again when it finishes."
+)
+ERR_NO_LOOP = "Error: Unsloth Studio could not reach its server loop to run this tool. Try again."
+
+_DESCRIPTION = (
+ "Generate one image with the image model loaded in Unsloth Studio. Write the full prompt "
+ "yourself from the user's request: subject, setting, style, lighting and composition. Steps "
+ "and guidance follow the loaded model's own defaults; the size defaults to 1024x1024. It "
+ "never loads or unloads a model."
+)
+
+# A chat with no tool timeout ("no limit") still gets a ceiling, so a stuck render can't hold
+# the turn forever.
+_MAX_WAIT_S = 900.0
+_STOP_WAIT_S = 30.0
+_POLL_S = 0.25
+_PROMPT_ECHO_CHARS = 300
+_MIN_SIDE = 256
+# DiffusionGenerateRequest's own ceiling.
+_TRANSPORT_MAX_SIDE = 2752
+
+
+def _size_limits(status: dict) -> tuple[int, int, int, int]:
+ """(multiple, min side, max side, max pixels) of the loaded family, as the route enforces them."""
+ cond = status.get("conditioning") or {}
+ multiple = max(1, int(cond.get("dimension_multiple") or 16))
+ max_side = min(_TRANSPORT_MAX_SIDE, int(cond.get("max_output_side") or 2048))
+ max_side = max_side // multiple * multiple
+ max_pixels = int(cond.get("max_output_pixels") or 2048 * 2048)
+ min_side = -(-_MIN_SIDE // multiple) * multiple
+ return multiple, min_side, max_side, max_pixels
+
+
+def generate_image_schema(status: dict) -> dict:
+ """The OpenAI function tool for the loaded image model; negative_prompt only when it has one."""
+ multiple, min_side, max_side, max_pixels = _size_limits(status)
+ bounds = f"{min_side} to {max_side}, a multiple of {multiple}"
+ if max_pixels < max_side * max_side:
+ bounds += f", at most {max_pixels:,} pixels in total"
+ properties: dict[str, Any] = {
+ "prompt": {"type": "string", "description": "The full image prompt."},
+ "width": {
+ "type": "integer",
+ "description": f"Width in pixels, {bounds}. Default 1024.",
+ },
+ "height": {
+ "type": "integer",
+ "description": f"Height in pixels, {bounds}. Default 1024.",
+ },
+ "seed": {
+ "type": "integer",
+ "description": "Seed for a repeatable image. Random when omitted.",
+ },
+ }
+ if status.get("supports_negative_prompt"):
+ properties["negative_prompt"] = {
+ "type": "string",
+ "description": "What the image should not show.",
+ }
+ description = _DESCRIPTION
+ hint = status.get("prompt_hint")
+ if hint:
+ description += " " + str(hint)
+ return {
+ "type": "function",
+ "function": {
+ "name": GENERATE_IMAGE_TOOL_NAME,
+ "description": description,
+ "parameters": {"type": "object", "properties": properties, "required": ["prompt"]},
+ },
+ }
+
+
+def offers_txt2img(status: dict) -> bool:
+ """False for an edit-only model, the same rule /v1/images/generations refuses on."""
+ workflows = status.get("workflows")
+ return not workflows or "txt2img" in workflows
+
+
+def _snap_size(arguments: dict, status: dict) -> tuple[int, int]:
+ """Width and height on the loaded family's grid and inside its bounds (the route refuses, never snaps)."""
+ multiple, min_side, max_side, max_pixels = _size_limits(status)
+
+ def snap(value: Any) -> int:
+ return min(max_side, max(min_side, int(round(int(value) / multiple)) * multiple))
+
+ w = snap(arguments.get("width") if arguments.get("width") is not None else 1024)
+ h = snap(arguments.get("height") if arguments.get("height") is not None else 1024)
+ while w * h > max_pixels and max(w, h) > min_side:
+ if w >= h:
+ w -= multiple
+ else:
+ h -= multiple
+ return w, h
+
+
+def _build_request(arguments: dict, prompt: str, status: dict):
+ from models.inference import DiffusionGenerateRequest
+
+ # Only what the model supplied: an omitted steps/guidance must stay unset so the core
+ # resolves the loaded model's own defaults.
+ fields: dict[str, Any] = {"prompt": prompt}
+ if arguments.get("width") is not None or arguments.get("height") is not None:
+ fields["width"], fields["height"] = _snap_size(arguments, status)
+ if arguments.get("seed") is not None:
+ fields["seed"] = int(arguments["seed"])
+ negative = arguments.get("negative_prompt")
+ if status.get("supports_negative_prompt") and isinstance(negative, str) and negative.strip():
+ fields["negative_prompt"] = negative.strip()
+ return DiffusionGenerateRequest(**fields)
+
+
+async def _generate(request, ticket):
+ from core.inference import media_keepwarm
+ from core.inference.generation_ticket import generation_ticket
+ from core.inference.gpu_arbiter import DIFFUSION
+ from routes.inference import _generate_diffusion_image_core
+
+ # The HTTP route is counted by the keep-warm middleware; this path never goes through it.
+ await media_keepwarm.begin_request(DIFFUSION)
+ try:
+ with generation_ticket(ticket):
+ return await _generate_diffusion_image_core(request)
+ finally:
+ media_keepwarm.end_request(DIFFUSION)
+
+
+def _stop(future, ticket) -> None:
+ """Stop this call's render on the GPU too, queued or running. Never the account-wide cancel:
+ that reaches whichever render is active, possibly another chat's or the Images page's."""
+ ticket.stop()
+ concurrent.futures.wait([future], timeout = _STOP_WAIT_S)
+ future.cancel()
+
+
+def _http_error(exc) -> str:
+ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG, DIFFUSION_NOT_LOADED_MSG
+
+ detail = exc.detail
+ if isinstance(detail, dict):
+ if detail.get("error") == "gpu_busy":
+ return ERR_OTHER_ACCOUNT
+ error = detail.get("error")
+ text = detail.get("message") or (error.get("message") if isinstance(error, dict) else error)
+ else:
+ text = detail
+ text = str(text or "image generation failed.")
+ if text == DIFFUSION_CANCELLED_MSG:
+ return ERR_STOPPED
+ if text == DIFFUSION_NOT_LOADED_MSG:
+ return ERR_NOT_LOADED
+ return "Error: " + text
+
+
+def _save_to_workdir(image, workdir: str, account) -> dict:
+ from core.inference import image_gallery
+ from utils.account_context import run_as
+
+ source = run_as(account, image_gallery.image_path, image.id)
+ if source is None:
+ raise RuntimeError("the generated image is missing from the gallery.")
+ name = f"generated-image-{image.id[:8]}.png"
+ os.makedirs(workdir, exist_ok = True)
+ target = os.path.join(workdir, name)
+ shutil.copyfile(source, target)
+ return {"name": name, "size": os.path.getsize(target)}
+
+
+def _run(arguments: dict, workdir: str, cancel_event, timeout: Optional[float]) -> str:
+ import asyncio
+
+ from fastapi import HTTPException
+
+ from core.inference.generation_ticket import GenerationTicket
+ from core.inference.gpu_arbiter import DIFFUSION, GpuBusyForAnotherAccountError
+ from core.inference.media_chat_tools import media_chat_status, server_loop
+ from core.inference.media_keepwarm import engine_if_imported
+ from utils.account_context import arun_as, current_account
+
+ prompt = str(arguments.get("prompt") or "").strip()
+ if not prompt:
+ return ERR_NO_PROMPT
+ account = current_account()
+ loop = server_loop()
+ if loop is None:
+ return ERR_NO_LOOP
+ status = media_chat_status("text-to-image")
+ if status is None:
+ return ERR_NOT_LOADED
+ if not offers_txt2img(status):
+ return ERR_EDIT_ONLY
+ engine = engine_if_imported(DIFFUSION)
+ progress = getattr(engine, "generate_progress", None)
+ # Never queue: the engine cancel only reaches the active run, so a queued one could not stop.
+ if progress is not None and progress().get("active"):
+ return ERR_BUSY
+ try:
+ request = _build_request(arguments, prompt, status)
+ except (TypeError, ValueError) as exc:
+ errors = getattr(exc, "errors", None)
+ message = errors()[0].get("msg") if callable(errors) and errors() else str(exc)
+ return f"Error: invalid generate_image arguments: {message}"
+
+ ticket = GenerationTicket()
+ future = asyncio.run_coroutine_threadsafe(arun_as(account, _generate(request, ticket)), loop)
+ limit = _MAX_WAIT_S if timeout is None or timeout >= 9999 else max(1.0, float(timeout))
+ deadline = time.monotonic() + limit
+ stopped = None
+ while not future.done():
+ if cancel_event is not None and cancel_event.is_set():
+ stopped = ERR_STOPPED
+ elif time.monotonic() >= deadline:
+ stopped = ERR_TIMEOUT
+ if stopped:
+ _stop(future, ticket)
+ break
+ concurrent.futures.wait([future], timeout = _POLL_S)
+ # A render that finished inside the stop window is still a saved image: hand it over.
+ if stopped and (not future.done() or future.cancelled() or future.exception() is not None):
+ return stopped
+ try:
+ response = future.result()
+ except concurrent.futures.CancelledError:
+ return ERR_STOPPED
+ except GpuBusyForAnotherAccountError:
+ return ERR_OTHER_ACCOUNT
+ except HTTPException as exc:
+ return _http_error(exc)
+ if not response.images:
+ return "Error: the image model returned no image."
+ image = response.images[0]
+ saved = _save_to_workdir(image, workdir, account)
+ shown = " ".join(prompt.split())[:_PROMPT_ECHO_CHARS]
+ text = (
+ f"Generated a {image.width}x{image.height} image (seed {image.seed}) and saved it as "
+ f"{saved['name']}. Prompt used: {shown}"
+ )
+ return (
+ text + "\n__FILES__:" + json.dumps([saved]) + "\n__IMAGES__:" + json.dumps([saved["name"]])
+ )
+
+
+def run_generate_image(
+ arguments: Any,
+ *,
+ workdir: str,
+ cancel_event = None,
+ timeout: Optional[float] = None,
+) -> str:
+ """Generate one image into ``workdir``; always a string, an ``Error: ...`` one on failure."""
+ try:
+ return _run(
+ arguments if isinstance(arguments, dict) else {}, workdir, cancel_event, timeout
+ )
+ except Exception as exc: # noqa: BLE001 - a tool result, never a crashed turn
+ logger.warning("generate_image failed: %s", exc, exc_info = True)
+ return f"Error: image generation failed: {exc}"
diff --git a/studio/backend/core/inference/generate_video_tool.py b/studio/backend/core/inference/generate_video_tool.py
new file mode 100644
index 00000000000..81a53ee7c62
--- /dev/null
+++ b/studio/backend/core/inference/generate_video_tool.py
@@ -0,0 +1,276 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The ``generate_video`` chat tool: one clip on the video model already loaded in Unsloth Studio.
+
+It goes through the same job path as ``POST /v1/videos`` (``_create_openai_video``) with no
+model named, so it never loads, switches or unloads a model. The job runs on the video
+backend's own thread; the tool polls it and copies the finished MP4 into the chat workdir.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import concurrent.futures
+import json
+import os
+import shutil
+import threading
+import time
+from typing import Any, Optional
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+NOT_LOADED_MSG = (
+ "Error: no video model is loaded in Unsloth Studio. "
+ "Load one on the Video page, then try again."
+)
+BUSY_MSG = "Error: another video is rendering in Unsloth Studio; try again when it finishes."
+STOPPED_MSG = "Error: video generation was stopped."
+STILL_RENDERING_MSG = (
+ "Error: the video is still rendering; find it on the Video page when it finishes."
+)
+OTHER_ACCOUNT_MSG = (
+ "Error: another account is generating on the video model. Try again when it finishes."
+)
+NO_LOOP_MSG = "Error: Unsloth Studio could not reach its server loop to run this tool. Try again."
+NO_PROMPT_MSG = "Error: generate_video needs a prompt."
+
+_DEFAULT_TIMEOUT_S = 900.0
+_CREATE_TIMEOUT_S = 60.0
+_STOP_WAIT_S = 30.0
+_POLL_S = 1.0
+
+_DESCRIPTION = (
+ "Generate one short video clip with the video model loaded in Unsloth Studio. Write the full "
+ "prompt yourself from the user's request: subject, motion, setting, style and camera. Length "
+ "and size default to the loaded model's own settings. It never loads or unloads a model."
+)
+
+
+def _seed_supported() -> bool:
+ from models.inference import VideoJobCreateRequest
+ return "seed" in VideoJobCreateRequest.model_fields
+
+
+def _number_text(value: Any) -> str:
+ if isinstance(value, float) and value.is_integer():
+ value = int(value)
+ return str(value)
+
+
+def generate_video_schema(status: dict) -> dict:
+ description = _DESCRIPTION
+ defaults = (status or {}).get("defaults") or {}
+ durations = [_number_text(d) for d in defaults.get("duration_presets") or []]
+ sizes = [f"{p[0]}x{p[1]}" for p in defaults.get("resolution_presets") or [] if len(p) == 2]
+ if durations:
+ description += f" This model offers clips of {', '.join(durations)} seconds."
+ if sizes:
+ description += f" Its sizes include {', '.join(sizes[:4])}."
+ if (status or {}).get("prompt_hint"):
+ description += " " + str(status["prompt_hint"])
+ properties: dict = {
+ "prompt": {"type": "string", "description": "Full description of the clip to render"},
+ "seconds": {"type": "number", "description": "Clip length in seconds (optional)"},
+ "width": {"type": "integer", "description": "Width in pixels (optional, with height)"},
+ "height": {"type": "integer", "description": "Height in pixels (optional, with width)"},
+ }
+ if _seed_supported():
+ properties["seed"] = {"type": "integer", "description": "Seed to repeat a clip (optional)"}
+ return {
+ "type": "function",
+ "function": {
+ "name": "generate_video",
+ "description": description,
+ "parameters": {"type": "object", "properties": properties, "required": ["prompt"]},
+ },
+ }
+
+
+def _http_message(exc) -> str:
+ detail = getattr(exc, "detail", None)
+ if isinstance(detail, dict):
+ inner = detail.get("error")
+ if isinstance(inner, dict) and inner.get("message"):
+ return str(inner["message"])
+ if detail.get("message"):
+ return str(detail["message"])
+ return str(detail or exc)
+
+
+def run_generate_video(
+ arguments: dict,
+ *,
+ workdir: str,
+ cancel_event = None,
+ timeout: Optional[float] = None,
+) -> str:
+ """Render one clip; always returns the tool result text, never raises."""
+ try:
+ return _run(
+ arguments if isinstance(arguments, dict) else {}, workdir, cancel_event, timeout
+ )
+ except Exception as exc: # noqa: BLE001 - a tool result, never a crashed tool loop
+ logger.warning("generate_video failed: %s", exc, exc_info = True)
+ return f"Error: video generation failed: {exc}"
+
+
+def _run(arguments: dict, workdir: str, cancel_event, timeout: Optional[float]) -> str:
+ from fastapi import HTTPException
+
+ from core.inference import media_keepwarm
+ from core.inference.gpu_arbiter import VIDEO, GpuBusyForAnotherAccountError
+ from core.inference.media_chat_tools import media_chat_status, server_loop
+ from core.inference.video_families import VIDEO_GENERATION_BUSY_MSG
+ from models.inference import VideoJobCreateRequest
+ from utils.account_context import arun_as, current_account, run_as
+
+ prompt = str(arguments.get("prompt") or "").strip()
+ if not prompt:
+ return NO_PROMPT_MSG
+ acct = current_account()
+ loop = server_loop()
+ if loop is None:
+ return NO_LOOP_MSG
+ if run_as(acct, media_chat_status, "text-to-video") is None:
+ return NOT_LOADED_MSG
+
+ fields: dict = {"prompt": prompt}
+ if arguments.get("seconds") is not None:
+ fields["seconds"] = _number_text(arguments["seconds"])
+ width, height = arguments.get("width"), arguments.get("height")
+ if width is not None and height is not None:
+ fields["size"] = f"{_number_text(width)}x{_number_text(height)}"
+ seed = arguments.get("seed")
+ if seed is not None and _seed_supported():
+ fields["seed"] = int(seed)
+ else:
+ seed = None
+ body = VideoJobCreateRequest(**fields)
+
+ cap = _DEFAULT_TIMEOUT_S if timeout is None or timeout >= 9999 else float(timeout)
+ deadline = time.monotonic() + cap
+
+ async def _create():
+ from routes.video import _create_openai_video
+
+ await media_keepwarm.begin_request(VIDEO)
+ created = False
+ try:
+ # No model named: the auto-switch returns at once, so the subject is never consulted.
+ job = await _create_openai_video(body, None, acct.username or "", None)
+ created = True
+ return job
+ finally:
+ media_keepwarm.end_request(VIDEO, counted = created)
+
+ future = asyncio.run_coroutine_threadsafe(arun_as(acct, _create()), loop)
+ # Never cancel a create in flight: past the backend's begin_generate the job already runs,
+ # and a cancel there would leave it rendering with no record on the Video page.
+ create_by = time.monotonic() + min(_CREATE_TIMEOUT_S, max(cap, 1.0))
+ while not future.done():
+ if cancel_event is not None and cancel_event.is_set():
+ concurrent.futures.wait([future], timeout = _STOP_WAIT_S)
+ if not future.done():
+ # Stop the job as soon as the create hands one back.
+ future.add_done_callback(lambda f: _cancel_created_job(acct, f))
+ return STOPPED_MSG
+ break
+ if time.monotonic() >= create_by:
+ return STILL_RENDERING_MSG
+ concurrent.futures.wait([future], timeout = 0.25)
+ try:
+ job = future.result()
+ except concurrent.futures.CancelledError:
+ return STOPPED_MSG
+ except GpuBusyForAnotherAccountError:
+ return OTHER_ACCOUNT_MSG
+ except HTTPException as exc:
+ message = _http_message(exc)
+ if exc.status_code == 409 and message == VIDEO_GENERATION_BUSY_MSG:
+ return BUSY_MSG
+ if exc.status_code == 503:
+ return NOT_LOADED_MSG
+ return f"Error: {message}"
+
+ return _await_job(acct, job.id, workdir, prompt, seed, cancel_event, deadline)
+
+
+def _cancel_created_job(acct, future) -> None:
+ """Done-callback (server loop): stop the job a create finished after the user pressed Stop."""
+ if future.cancelled() or future.exception() is not None:
+ return
+
+ def _cancel(video_id: str) -> None:
+ from core.inference.video import get_video_backend
+ from utils.account_context import run_as
+ try:
+ run_as(
+ acct,
+ get_video_backend().cancel_generate,
+ expected_video_id = video_id,
+ expected_account = acct.account_id,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning("generate_video: stopping job %s failed: %s", video_id, exc)
+
+ # Off the loop thread: the backend cancel takes its lock.
+ threading.Thread(target = _cancel, args = (future.result().id,), daemon = True).start()
+
+
+def _await_job(acct, video_id: str, workdir: str, prompt: str, seed, cancel_event, deadline) -> str:
+ from core.inference import video_gallery
+ from core.inference.video import get_video_backend
+ from routes.video import _lookup_video
+ from utils.account_context import run_as
+
+ while True:
+ view = run_as(acct, _lookup_video, video_id)
+ if view is None:
+ return "Error: the video was removed before it finished."
+ if view.status == "completed":
+ break
+ if view.status == "failed":
+ message = view.error.message if view.error else "video generation failed."
+ return f"Error: {message}"
+ if cancel_event is not None and cancel_event.is_set():
+ run_as(
+ acct,
+ get_video_backend().cancel_generate,
+ expected_video_id = video_id,
+ expected_account = acct.account_id,
+ )
+ stop_by = time.monotonic() + _STOP_WAIT_S
+ while time.monotonic() < stop_by:
+ view = run_as(acct, _lookup_video, video_id)
+ if view is None or view.status in ("completed", "failed"):
+ break
+ time.sleep(min(_POLL_S, 0.25))
+ # A clip that finished inside the stop window is still a saved clip: hand it over.
+ if view is None or view.status != "completed":
+ return STOPPED_MSG
+ break
+ if time.monotonic() >= deadline:
+ return STILL_RENDERING_MSG
+ if cancel_event is not None:
+ cancel_event.wait(_POLL_S)
+ else:
+ time.sleep(_POLL_S)
+
+ source = run_as(acct, video_gallery.owned_video_path, video_id)
+ if source is None:
+ return "Error: the finished video is missing from the Video page."
+ root = os.path.realpath(workdir)
+ os.makedirs(root, exist_ok = True)
+ name = f"generated-video-{video_id.removeprefix('video_')[:8]}.mp4"
+ target = os.path.join(root, name)
+ shutil.copyfile(source, target)
+ shown = " ".join(prompt.split())
+ if len(shown) > 300:
+ shown = shown[:299].rstrip() + "…"
+ parts = [f"{view.seconds}s", view.size] + ([f"seed {seed}"] if seed is not None else [])
+ text = f"Generated a video ({', '.join(parts)}) saved as {name}. Prompt: {shown}"
+ return text + "\n__FILES__:" + json.dumps([{"name": name, "size": os.path.getsize(target)}])
diff --git a/studio/backend/core/inference/generation_ticket.py b/studio/backend/core/inference/generation_ticket.py
new file mode 100644
index 00000000000..54d9d6c3b43
--- /dev/null
+++ b/studio/backend/core/inference/generation_ticket.py
@@ -0,0 +1,58 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Stop one image generation without touching any other run of the same account.
+
+A caller binds a ticket in its context; ``asyncio.to_thread`` copies the context into the engine
+thread, where the engine hands the ticket its per-generation cancel event. Stopping the ticket
+sets only that event, whether the run is still queued or already denoising.
+"""
+
+from __future__ import annotations
+
+import contextvars
+import threading
+from contextlib import contextmanager
+from typing import Iterator, Optional
+
+
+class GenerationTicket:
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._events: list[threading.Event] = []
+ self._stopped = False
+
+ def bind(self, event: threading.Event) -> None:
+ with self._lock:
+ self._events.append(event)
+ stopped = self._stopped
+ if stopped:
+ event.set()
+
+ def stop(self) -> None:
+ with self._lock:
+ self._stopped = True
+ events = list(self._events)
+ for event in events:
+ event.set()
+
+
+_ticket: contextvars.ContextVar[Optional[GenerationTicket]] = contextvars.ContextVar(
+ "generation_ticket", default = None
+)
+
+
+def bind_generation_cancel(event: threading.Event) -> None:
+ """Called by an engine with the cancel event of the generation it is about to run."""
+ ticket = _ticket.get()
+ if ticket is not None:
+ ticket.bind(event)
+
+
+@contextmanager
+def generation_ticket(ticket: GenerationTicket) -> Iterator[GenerationTicket]:
+ token = _ticket.set(ticket)
+ try:
+ yield ticket
+ finally:
+ _ticket.reset(token)
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index ddf33f05f99..4ba8089d0e2 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -523,6 +523,7 @@ from core.inference.mcp_images import (
from core.inference.tool_loop_controller import (
_WORKSPACE_READ_TOOLS,
BROWSER_TOOL_NAMES,
+ REPEATABLE_TOOL_NAMES,
ToolLoopController,
_reruns_after_new_work,
append_deferred_nudges,
@@ -41480,7 +41481,8 @@ class LlamaCppBackend:
_novel_at_last_keep[_key] = _novel_kept
_last_workspace_key = _key
# A browser call acts on the page as it is then: two scrolls are two scrolls.
- elif _key in _seen_keys and _fn.get("name") not in BROWSER_TOOL_NAMES:
+ # Two identical generate_image calls are two images.
+ elif _key in _seen_keys and _fn.get("name") not in REPEATABLE_TOOL_NAMES:
continue
_seen_keys.add(_key)
if len(_deduped) < _MAX_TOOL_CALLS_PER_TURN:
diff --git a/studio/backend/core/inference/media_chat_tools.py b/studio/backend/core/inference/media_chat_tools.py
new file mode 100644
index 00000000000..bda6d582660
--- /dev/null
+++ b/studio/backend/core/inference/media_chat_tools.py
@@ -0,0 +1,72 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Chat tools that render on the image or video model already loaded in Unsloth Studio.
+
+Every registry that needs to know these tools (sentinel stripping, always-safe, dedupe
+exemptions, the Anthropic allow-list) reads ``MEDIA_CHAT_TOOLS`` so the lists can't drift.
+The module has no heavy imports at load time; the status helpers import lazily.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Optional
+
+MEDIA_CHAT_TOOLS = frozenset({"generate_image", "generate_video"})
+
+_TOOL_TASKS = (("generate_image", "text-to-image"), ("generate_video", "text-to-video"))
+
+# The server's event loop. The tools run on a worker thread inside the chat tool loop and
+# hand the generation coroutine to this loop, never to a loop of their own.
+_server_loop: Optional[asyncio.AbstractEventLoop] = None
+
+
+def remember_server_loop(loop: asyncio.AbstractEventLoop) -> None:
+ global _server_loop
+ _server_loop = loop
+
+
+def server_loop() -> Optional[asyncio.AbstractEventLoop]:
+ loop = _server_loop
+ if loop is None or loop.is_closed():
+ return None
+ return loop
+
+
+def media_chat_status(task: str) -> Optional[dict]:
+ """The resident image or video model's status, or None when there is none this account may use."""
+ from hub.services.models import account_access
+ from routes.inference import _resident_media_status
+
+ status = _resident_media_status(task)
+ if status is None:
+ return None
+ if account_access.managed_account():
+ modality = "diffusion" if task == "text-to-image" else "video"
+ try:
+ account_access.require_media_generation_access(status, modality)
+ except Exception: # noqa: BLE001 - a refused account is simply not offered the tool
+ return None
+ return status
+
+
+def offered_media_chat_tools(enabled_tools) -> list[dict]:
+ """Schemas for the media tools the caller asked for whose model is loaded and visible."""
+ from core.inference.generate_image_tool import generate_image_schema, offers_txt2img
+ from core.inference.generate_video_tool import generate_video_schema
+
+ tools: list[dict] = []
+ for name, task in _TOOL_TASKS:
+ if name not in enabled_tools:
+ continue
+ status = media_chat_status(task)
+ if status is None:
+ continue
+ if name == "generate_image":
+ if offers_txt2img(status):
+ tools.append(generate_image_schema(status))
+ elif status.get("h3_task") != "ref2va":
+ # The Ref2VA partition needs a reference image or video, which this text-only tool never sends.
+ tools.append(generate_video_schema(status))
+ return tools
diff --git a/studio/backend/core/inference/mlx_diffusion_backend.py b/studio/backend/core/inference/mlx_diffusion_backend.py
index aa04763b9ca..91f793e7e1b 100644
--- a/studio/backend/core/inference/mlx_diffusion_backend.py
+++ b/studio/backend/core/inference/mlx_diffusion_backend.py
@@ -1032,6 +1032,9 @@ class MlxDiffusionBackend:
check_output_size(family, w, h)
cancel = threading.Event()
+ from core.inference.generation_ticket import bind_generation_cancel
+
+ bind_generation_cancel(cancel)
from hub.services.models.account_access import media_generation_slot
with self._generate_lock, media_generation_slot("diffusion"):
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index 7e0ba0108de..9a66272311c 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -64,6 +64,7 @@ from core.inference.mcp_images import (
from core.inference.tool_loop_controller import (
_WORKSPACE_READ_TOOLS,
BROWSER_TOOL_NAMES,
+ REPEATABLE_TOOL_NAMES,
ToolLoopController,
_reruns_after_new_work,
append_deferred_nudges,
@@ -1483,7 +1484,8 @@ def run_safetensors_tool_loop(
novel_at_last_keep[_key] = novel_kept
last_workspace_key = _key
# A browser call acts on the page as it is then: two scrolls are two scrolls.
- elif _key in seen_keys and _fn.get("name") not in BROWSER_TOOL_NAMES:
+ # Two identical generate_image calls are two images.
+ elif _key in seen_keys and _fn.get("name") not in REPEATABLE_TOOL_NAMES:
continue
seen_keys.add(_key)
if len(deduped) < _MAX_TOOL_CALLS_PER_TURN:
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 3ec085751b8..99d7a28c140 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -4226,6 +4226,9 @@ class SdCppDiffusionBackend:
)
cancel = threading.Event()
+ from core.inference.generation_ticket import bind_generation_cancel
+
+ bind_generation_cancel(cancel)
from hub.services.models.account_access import media_generation_slot
with self._generate_lock, media_generation_slot("diffusion"):
diff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.py
index 38d081c3c92..e81c24e18d8 100644
--- a/studio/backend/core/inference/tool_loop_controller.py
+++ b/studio/backend/core/inference/tool_loop_controller.py
@@ -23,6 +23,7 @@ from urllib.parse import urlparse
from core.inference.browser_agent import BROWSER_TOOL_NAMES
from core.inference.llama_tool_schema import unrelaxed
from core.inference.mcp_images import is_image_tool, split_images as split_mcp_images
+from core.inference.media_chat_tools import MEDIA_CHAT_TOOLS
# Stamped by mcp_client on every tool it registers; the provenance the envelope
# is trusted on.
@@ -31,6 +32,9 @@ MCP_TOOL_PREFIX = "mcp__"
MCP_TOOL_SEARCH_NAME = "mcp_tool_search"
from core.inference.tool_call_parser import TOOL_ERROR_NUDGE, TOOL_ERROR_PREFIXES
+# Never deduplicated: an identical call is new work (the page as it is now, another render).
+REPEATABLE_TOOL_NAMES = BROWSER_TOOL_NAMES | MEDIA_CHAT_TOOLS
+
_CANONICAL_HEAL_ARG = {
"python": "code",
@@ -843,6 +847,9 @@ def status_for_tool(tool_name: str, arguments: Mapping[str, Any]) -> str:
return f"Running: {preview}" if preview else "Running command..."
if tool_name == "view_image":
return "Viewing image: " + str(arguments.get("path") or "")[:80]
+ if tool_name in MEDIA_CHAT_TOOLS:
+ kind = "image" if tool_name == "generate_image" else "video"
+ return f"Generating {kind}: " + str(arguments.get("prompt") or "")[:60]
if tool_name == "edit_file":
# The name, not the patch: the tool card below already shows the edit.
path = str(arguments.get("path") or "").strip()
@@ -1042,8 +1049,8 @@ def _strip_rag_sources_sentinel(result: str) -> str:
# Only these emit the file envelope, and only their output is defused first. An MCP tool or a fetched page ending in a
# well-formed __FILES__ line is content, not an envelope, and stripping it would take that line away from the model.
_SANDBOX_TOOLS = frozenset({"python", "terminal"})
-# edit_file emits it too, for a file it created.
-_FILE_SENTINEL_TOOLS = _SANDBOX_TOOLS | {"edit_file"}
+# edit_file emits it too, for a file it created, and the media tools for the file they rendered.
+_FILE_SENTINEL_TOOLS = _SANDBOX_TOOLS | {"edit_file"} | MEDIA_CHAT_TOOLS
# Only an MCP result can carry the UI envelope; mcp_client defuses tool-written ones.
_MCP_TOOL_PREFIX = "mcp__"
@@ -1054,7 +1061,7 @@ _MCP_TOOL_PREFIX = "mcp__"
# document an MCP tool read, or a page that was fetched, ending in a well-formed one of
# either is content the model needs, and cutting it leaves the model reasoning over less
# than the card the user is looking at.
-_IMAGE_SENTINEL_TOOLS = _SANDBOX_TOOLS | {"code_execution"}
+_IMAGE_SENTINEL_TOOLS = _SANDBOX_TOOLS | {"code_execution", "generate_image"}
_SOURCE_MAP_TOOLS = frozenset({"search_knowledge_base", "search_conversation"})
# Invalidated by workspace writes, but reading an image is not new work that licenses a rerun.
_WORKSPACE_READ_TOOLS = frozenset({"view_image"})
@@ -1332,11 +1339,12 @@ class ToolLoopController:
elif (
self._deduplicate_tool_calls
and key in self._successful_keys
- and tool_name not in BROWSER_TOOL_NAMES
+ and tool_name not in REPEATABLE_TOOL_NAMES
and tool_name != MCP_TOOL_SEARCH_NAME
):
# Not the browser tools: each acts on or reads the page as it is now, so a second
# scroll down or a snapshot after a click is new work, and two such no-ops ended the turn.
+ # Nor the media tools: the same prompt again is another image with a fresh seed.
# Nor mcp_tool_search: a repeat restores tools a later load evicted.
action = "duplicate"
noop = _noop_result("duplicate", tool_name)
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 8a70af1b08b..6b3b59cc7ad 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -45,6 +45,7 @@ from contextvars import ContextVar
# What a truncated result costs besides its body, charged where the cut is decided rather than held back in advance.
from .context_window import _RESULT_NOTICE_RESERVE, compaction_receipt_field
from .browser_agent import BROWSER_TOOL_NAMES, execute_browser_tool, is_browser_tool
+from .media_chat_tools import MEDIA_CHAT_TOOLS
from . import file_history
# The window of the model THIS request is served by, set by execute_tool for the call's duration. Left unset it falls
@@ -7288,6 +7289,8 @@ _ALWAYS_SAFE_TOOLS = frozenset(
# Gated in the chat tab instead, which knows what each ref on the live page is: submits,
# purchases, sign-ins and new sites ask there, in every permission mode.
*BROWSER_TOOL_NAMES,
+ # Render on the resident image/video model; never load/unload a model or reach the network.
+ *MEDIA_CHAT_TOOLS,
}
)
@@ -14742,6 +14745,21 @@ def execute_tool(
),
name,
)
+ if name in MEDIA_CHAT_TOOLS:
+ if name == "generate_image":
+ from .generate_image_tool import run_generate_image as run_media_tool
+ else:
+ from .generate_video_tool import run_generate_video as run_media_tool
+ with _session_in_flight(session_id):
+ return _fit_result_to_room(
+ run_media_tool(
+ arguments,
+ workdir = _get_workdir(session_id),
+ cancel_event = cancel_event,
+ timeout = effective_timeout,
+ ),
+ name,
+ )
return f"Unknown tool: {name}"
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 1f603bcb89a..146cfb9b169 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -6689,6 +6689,14 @@ async def _select_request_tools(
if tool["function"]["name"] in payload.enabled_tools
and (supports_vision or tool["function"]["name"] != BROWSER_SCREENSHOT)
]
+ if tools_on and payload.enabled_tools is not None:
+ # Opt-in by name too, and only while an image or video model this account may use is loaded.
+ from core.inference.media_chat_tools import offered_media_chat_tools, remember_server_loop
+ media_tools = offered_media_chat_tools(payload.enabled_tools)
+ if media_tools:
+ # The tools run on a worker thread and hand the render back to this loop.
+ remember_server_loop(asyncio.get_running_loop())
+ tools += media_tools
tools = [
tool
for tool in tools
@@ -42618,8 +42626,14 @@ _STUDIO_ANTHROPIC_TOOL_ALIASES = {
# this channel has no way to present, so an omitted permission_mode ("ask") only
# asks then. render_html is excluded because a networked canvas prompts in auto,
# and this channel invokes the loop without confirm; auto/ask reject, off/full run.
-_ANTHROPIC_UNPROMPTED_SAFE_TOOLS = frozenset(
- {"web_search", "search_knowledge_base", "search_conversation", "read_skill", "view_image"}
+from core.inference.media_chat_tools import MEDIA_CHAT_TOOLS as _MEDIA_CHAT_TOOLS
+
+# The media tools are always-safe too, though this channel never selects them (ALL_TOOLS only).
+_ANTHROPIC_UNPROMPTED_SAFE_TOOLS = (
+ frozenset(
+ {"web_search", "search_knowledge_base", "search_conversation", "read_skill", "view_image"}
+ )
+ | _MEDIA_CHAT_TOOLS
)
@@ -50955,7 +50969,13 @@ async def generate_diffusion_image(
):
if request.provider_id:
return await _external_image_generation(request, http_request)
+ return await _generate_diffusion_image_core(request)
+
+async def _generate_diffusion_image_core(
+ request: DiffusionGenerateRequest,
+) -> DiffusionGenerateResponse:
+ """The local-engine image run, shared by the route and the chat generate_image tool."""
from core.inference import image_gallery
from core.inference.diffusion_engine_router import get_active_diffusion_engine
from core.inference.diffusion_families import (
diff --git a/studio/backend/tests/test_generate_image_tool.py b/studio/backend/tests/test_generate_image_tool.py
new file mode 100644
index 00000000000..58eabc9cc4a
--- /dev/null
+++ b/studio/backend/tests/test_generate_image_tool.py
@@ -0,0 +1,583 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The generate_image chat tool renders on the loaded image model, as the calling account."""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import threading
+from types import SimpleNamespace
+
+import pytest
+from fastapi import HTTPException
+from PIL import Image
+
+from auth import policy
+from core.inference import (
+ diffusion_engine_router,
+ generate_image_tool as tool,
+ gpu_arbiter,
+ media_chat_tools,
+ media_keepwarm,
+ tools,
+)
+from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG
+from core.inference.generation_ticket import bind_generation_cancel
+from core.inference.tool_loop_controller import (
+ ToolLoopController,
+ status_for_tool,
+ strip_result_for_model,
+)
+from hub.services.models import account_access as access
+from models.inference import DiffusionGenerateRequest, DiffusionGenerateResponse, GalleryImage
+from routes import inference
+from state import active_generations
+from utils.account_context import OWNER, AccountContext, run_as
+
+ALICE = AccountContext("a" * 32, "alice")
+STATUS = {"loaded": True, "repo_id": "org/public-model", "family": "z-image", "base_repo": None}
+
+
+class FakeEngine:
+ def __init__(self, status = None):
+ self.status_dict = dict(STATUS if status is None else status)
+ self.calls: list[dict] = []
+ self.release = threading.Event()
+ self.started = threading.Event()
+ self.block = False
+ self.active = False
+ self.cancels: list[str] = []
+
+ def status(self):
+ return dict(self.status_dict)
+
+ def generate_progress(self):
+ return {"active": self.active}
+
+ def cancel_generate(self, expected_account = None):
+ self.release.set()
+ return True
+
+ def generate(self, **kwargs):
+ # Like the real engines: the per-generation event goes to the caller's ticket.
+ cancel = threading.Event()
+ bind_generation_cancel(cancel)
+ self.calls.append(kwargs)
+ self.started.set()
+ if self.block:
+ cancel.wait(20)
+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)
+ size = (kwargs.get("width") or 1024, kwargs.get("height") or 1024)
+ return {
+ "images": [Image.new("RGB", size, "blue")],
+ "seed": 7,
+ "repo_id": "org/public-model",
+ }
+
+
[email protected](autouse = True)
+def isolated(monkeypatch, tmp_path):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)
+ monkeypatch.setattr(access, "_resident_accounts", {})
+ monkeypatch.setattr(access, "_generation_accounts", {})
+ monkeypatch.setattr(access, "repo_is_public", lambda *a, **k: True)
+ monkeypatch.setattr(gpu_arbiter, "_owner", None)
+ monkeypatch.setattr(gpu_arbiter, "_owner_account", None)
+ monkeypatch.setattr(tool, "_STOP_WAIT_S", 5.0)
+ monkeypatch.setattr(inference, "_enabled_agent_skills", lambda: [])
+ monkeypatch.setattr(inference, "_thread_has_conversation_archive", lambda _: False)
+ active_generations.reset_for_tests()
+ yield
+ active_generations.reset_for_tests()
+
+
+def engine(monkeypatch):
+ fake = FakeEngine()
+ monkeypatch.setitem(media_keepwarm._ENGINES, gpu_arbiter.DIFFUSION, lambda: fake)
+ monkeypatch.setitem(media_keepwarm._ENGINES, gpu_arbiter.VIDEO, lambda: None)
+ monkeypatch.setattr(diffusion_engine_router, "get_active_diffusion_engine", lambda: fake)
+ return fake
+
+
+def server_loop(monkeypatch):
+ loop = asyncio.new_event_loop()
+ thread = threading.Thread(target = loop.run_forever, daemon = True)
+ thread.start()
+ monkeypatch.setattr(media_chat_tools, "_server_loop", loop)
+ yield loop
+ loop.call_soon_threadsafe(loop.stop)
+ thread.join(5)
+ loop.close()
+
+
+def keepwarm(monkeypatch):
+ counts = {"begin": 0, "end": 0}
+
+ async def begin(owner):
+ assert owner == gpu_arbiter.DIFFUSION
+ counts["begin"] += 1
+
+ def end(owner, *, counted = True):
+ counts["end"] += 1
+
+ monkeypatch.setattr(media_keepwarm, "begin_request", begin)
+ monkeypatch.setattr(media_keepwarm, "end_request", end)
+ return counts
+
+
+def _alice_loaded(monkeypatch):
+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.DIFFUSION)
+ monkeypatch.setattr(gpu_arbiter, "_owner_account", ALICE.account_id)
+
+
+def _in_thread(account, fn, *args, **kwargs):
+ """Run like the chat tool loop does: on a worker thread bound to the caller's account."""
+ out = {}
+ thread = threading.Thread(target = lambda: out.update(r = run_as(account, fn, *args, **kwargs)))
+ thread.start()
+ thread.join(60)
+ return out["r"]
+
+
+def _select(enabled, *, tools_on = True):
+ payload = SimpleNamespace(enabled_tools = enabled, rag_scope = None, bypass_permissions = False)
+
+ async def go():
+ selected = await inference._select_request_tools(
+ payload, tools_on = tools_on, mcp_allowed = False, supports_vision = True
+ )
+ return selected, asyncio.get_running_loop()
+
+ selected, loop = asyncio.run(go())
+ return {t["function"]["name"]: t for t in selected}, loop
+
+
+def test_offered_only_while_a_usable_text_to_image_model_is_loaded(engine, monkeypatch):
+ media_chat_tools._server_loop = None
+ names, loop = _select(["generate_image"])
+ assert "generate_image" in names and media_chat_tools._server_loop is loop
+ assert "generate_image" not in _select(["web_search"])[0]
+ assert "generate_image" not in _select(None)[0]
+ assert "generate_image" not in _select(["generate_image"], tools_on = False)[0]
+ # A video model isn't loaded, so its tool isn't offered alongside.
+ assert "generate_video" not in _select(["generate_image", "generate_video"])[0]
+
+ engine.status_dict["workflows"] = ["edit"]
+ assert "generate_image" not in _select(["generate_image"])[0]
+ engine.status_dict["workflows"] = ["txt2img", "edit"]
+ assert "generate_image" in _select(["generate_image"])[0]
+
+ engine.status_dict["loaded"] = False
+ assert "generate_image" not in _select(["generate_image"])[0]
+ engine.status_dict["loaded"] = True
+
+ monkeypatch.setattr(access, "resident_hidden", lambda *a, **k: True)
+ assert "generate_image" not in _select(["generate_image"])[0]
+
+
+def test_a_managed_account_refused_the_model_is_not_offered_it(engine, monkeypatch):
+ def refuse(status, modality):
+ raise HTTPException(status_code = 403, detail = "not allowed")
+
+ _alice_loaded(monkeypatch)
+ assert "generate_image" in run_as(ALICE, _select, ["generate_image"])[0]
+ monkeypatch.setattr(access, "require_media_generation_access", refuse)
+ assert "generate_image" in _select(["generate_image"])[0] # the owner is never refused
+ assert "generate_image" not in run_as(ALICE, _select, ["generate_image"])[0]
+
+
+def test_unselected_loop_is_not_remembered(engine):
+ media_chat_tools._server_loop = None
+ _select(["web_search"])
+ assert media_chat_tools._server_loop is None
+
+
[email protected]("supports", [True, False])
+def test_negative_prompt_follows_the_model_family(supports):
+ status = {**STATUS, "supports_negative_prompt": supports, "prompt_hint": "Use tags."}
+ schema = tool.generate_image_schema(status)["function"]
+ assert ("negative_prompt" in schema["parameters"]["properties"]) is supports
+ assert schema["parameters"]["required"] == ["prompt"]
+ assert schema["description"].endswith(" Use tags.")
+ assert "Unsloth Studio" in schema["description"]
+
+
+def test_managed_account_run_lands_in_its_own_gallery(
+ engine, server_loop, keepwarm, monkeypatch, tmp_path
+):
+ _alice_loaded(monkeypatch)
+ checked = []
+ real_check = access.require_media_generation_access
+ monkeypatch.setattr(
+ access,
+ "require_media_generation_access",
+ lambda status, modality: (checked.append(modality), real_check(status, modality))[1],
+ )
+ workdir = tmp_path / "work"
+ monkeypatch.setattr(tools, "_get_workdir", lambda session_id = None: str(workdir))
+ result = _in_thread(
+ ALICE,
+ tools.execute_tool,
+ "generate_image",
+ {"prompt": "a sloth\n on a branch", "width": 512, "height": 512},
+ session_id = "s",
+ )
+ assert result.startswith("Generated a 512x512 image (seed 7)"), result
+ assert "Prompt used: a sloth on a branch" in result
+ assert checked and set(checked) == {"diffusion"}
+ from core.inference import image_gallery
+
+ alice_ids = run_as(ALICE, lambda: [p.stem for p in image_gallery.gallery_dir().glob("*.png")])
+ owner_dir = run_as(OWNER, image_gallery.gallery_dir)
+ assert len(alice_ids) == 1 and not list(owner_dir.glob("*.png"))
+ saved = workdir / f"generated-image-{alice_ids[0][:8]}.png"
+ assert saved.is_file() and Image.open(saved).size == (512, 512)
+ assert keepwarm == {"begin": 1, "end": 1}
+
+
+ "status, expected",
+ [
+ ({"generation_defaults": {"steps": 28, "guidance": 3.5}}, (28, 3.5)),
+ # sd.cpp and MLX report no recipe; the family table decides from the base repo.
+ ({"repo_id": "/models/my-flux", "base_repo": "black-forest-labs/FLUX.1-dev"}, (20, 3.5)),
+ ],
+)
+def test_omitted_steps_and_guidance_follow_the_loaded_model(
+ engine, server_loop, keepwarm, monkeypatch, tmp_path, status, expected
+):
+ engine.status_dict.update(status)
+ monkeypatch.setattr(tools, "_get_workdir", lambda session_id = None: str(tmp_path / "w"))
+ result = _in_thread(
+ OWNER, tools.execute_tool, "generate_image", {"prompt": "p"}, session_id = "s"
+ )
+ assert result.startswith("Generated a 1024x1024 image"), result
+ assert (engine.calls[0]["steps"], engine.calls[0]["guidance"]) == expected
+
+
+def test_the_core_runs_under_the_account_bound_in_the_coroutine(
+ engine, server_loop, keepwarm, monkeypatch, tmp_path
+):
+ import utils.account_context as account_context
+
+ bound = []
+ real = account_context.arun_as
+
+ def spy(account, awaitable):
+ bound.append(account)
+ return real(account, awaitable)
+
+ monkeypatch.setattr(account_context, "arun_as", spy)
+ _alice_loaded(monkeypatch)
+ result = _in_thread(
+ ALICE, tool.run_generate_image, {"prompt": "x"}, workdir = str(tmp_path), timeout = 30
+ )
+ assert result.startswith("Generated"), result
+ assert bound == [ALICE]
+
+
+def _fake_core(monkeypatch, behaviour):
+ seen = []
+
+ async def core(request):
+ seen.append(request)
+ return await behaviour(request)
+
+ monkeypatch.setattr(inference, "_generate_diffusion_image_core", core)
+ return seen
+
+
+def _response(tmp_path, monkeypatch):
+ from core.inference import image_gallery
+
+ png = tmp_path / "abcdef0123456789.png"
+ Image.new("RGB", (1024, 768)).save(png)
+ monkeypatch.setattr(image_gallery, "image_path", lambda image_id: png)
+ record = {
+ "id": "abcdef0123456789",
+ "url": "/x",
+ "prompt": "p",
+ "width": 1024,
+ "height": 768,
+ "steps": 9,
+ "guidance": 0.0,
+ "seed": 3,
+ "created_at": 0.0,
+ }
+ return DiffusionGenerateResponse(images = [GalleryImage(**record)])
+
+
+def test_omitted_settings_are_not_sent_and_sizes_snap(engine, server_loop, monkeypatch, tmp_path):
+ response = _response(tmp_path, monkeypatch)
+
+ async def ok(request):
+ return response
+
+ seen = _fake_core(monkeypatch, ok)
+ work = tmp_path / "w"
+ tool.run_generate_image({"prompt": "x", "width": 1030, "height": 100}, workdir = str(work))
+ tool.run_generate_image({"prompt": "x", "negative_prompt": "blur"}, workdir = str(work))
+ first, second = seen
+ assert "steps" not in first.model_fields_set and "guidance" not in first.model_fields_set
+ assert (first.width, first.height) == (1024, 256)
+ assert first.model_fields_set == {"prompt", "width", "height"}
+ assert second.negative_prompt is None # the family has no negative prompt
+ engine.status_dict["supports_negative_prompt"] = True
+ tool.run_generate_image({"prompt": "x", "negative_prompt": "blur"}, workdir = str(work))
+ assert seen[-1].negative_prompt == "blur"
+
+
+def test_sentinels_stay_out_of_the_model_text(engine, server_loop, monkeypatch, tmp_path):
+ response = _response(tmp_path, monkeypatch)
+
+ async def ok(request):
+ return response
+
+ _fake_core(monkeypatch, ok)
+ result = tool.run_generate_image({"prompt": "x"}, workdir = str(tmp_path / "w"))
+ assert '\n__FILES__:[{"name": "generated-image-abcdef01.png"' in result
+ assert result.endswith('\n__IMAGES__:["generated-image-abcdef01.png"]')
+ assert (tmp_path / "w" / "generated-image-abcdef01.png").is_file()
+ stripped = strip_result_for_model(result, "generate_image")
+ assert "__FILES__" not in stripped and "__IMAGES__" not in stripped
+ assert stripped.startswith("Generated a 1024x768 image (seed 3)")
+
+
+ "error, expected",
+ [
+ (gpu_arbiter.GpuBusyForAnotherAccountError("chat", 1), tool.ERR_OTHER_ACCOUNT),
+ (
+ HTTPException(409, detail = {"error": "gpu_busy", "message": "busy"}),
+ tool.ERR_OTHER_ACCOUNT,
+ ),
+ (HTTPException(400, detail = "Width too large for this model."), "Error: Width too large"),
+ (HTTPException(409, detail = "Model was replaced."), "Error: Model was replaced."),
+ (HTTPException(500, detail = "Image generation failed: OOM"), "Error: Image generation"),
+ (HTTPException(404, detail = {"error": {"message": "Model not found"}}), "Error: Model not"),
+ (HTTPException(409, detail = DIFFUSION_CANCELLED_MSG), tool.ERR_STOPPED),
+ (RuntimeError("boom"), "Error: image generation failed: boom"),
+ ],
+)
+def test_failures_become_error_strings(engine, server_loop, monkeypatch, tmp_path, error, expected):
+ async def fail(request):
+ raise error
+
+ _fake_core(monkeypatch, fail)
+ assert tool.run_generate_image({"prompt": "x"}, workdir = str(tmp_path)).startswith(expected)
+
+
+def test_refusals_before_any_render(engine, server_loop, monkeypatch, tmp_path):
+ run = lambda args: tool.run_generate_image(args, workdir = str(tmp_path)) # noqa: E731
+ assert run({"prompt": " "}) == tool.ERR_NO_PROMPT
+ assert run("not a dict") == tool.ERR_NO_PROMPT
+ engine.active = True
+ assert run({"prompt": "x"}) == tool.ERR_BUSY
+ engine.active = False
+ engine.status_dict["workflows"] = ["edit"]
+ assert run({"prompt": "x"}) == tool.ERR_EDIT_ONLY
+ engine.status_dict["loaded"] = False
+ assert run({"prompt": "x"}) == tool.ERR_NOT_LOADED
+ monkeypatch.setattr(media_chat_tools, "_server_loop", None)
+ assert run({"prompt": "x"}) == tool.ERR_NO_LOOP
+ assert not engine.calls
+
+
[email protected]("how", ["cancel", "timeout"])
+def test_stop_and_timeout_stop_the_engine_too(
+ engine, server_loop, keepwarm, monkeypatch, tmp_path, how
+):
+ _alice_loaded(monkeypatch)
+ engine.block = True
+ cancel = threading.Event()
+ if how == "cancel":
+ threading.Thread(target = lambda: engine.started.wait(20) and cancel.set()).start()
+ result = _in_thread(
+ ALICE,
+ tool.run_generate_image,
+ {"prompt": "x"},
+ workdir = str(tmp_path),
+ cancel_event = cancel,
+ timeout = 2 if how == "timeout" else 60,
+ )
+ assert result == (tool.ERR_STOPPED if how == "cancel" else tool.ERR_TIMEOUT)
+ # The run unwound before the tool returned: the keep-warm count is already closed.
+ assert keepwarm == {"begin": 1, "end": 1}
+ assert not os.listdir(tmp_path)
+
+
+def test_a_render_that_finishes_inside_the_stop_window_is_still_returned(
+ engine, server_loop, keepwarm, monkeypatch, tmp_path
+):
+ # The timeout lands at the last step: the engine finishes the image instead of cancelling.
+ _alice_loaded(monkeypatch)
+ finish = engine.generate
+
+ def generate(**kwargs):
+ cancel = threading.Event()
+ bind_generation_cancel(cancel)
+ engine.started.set()
+ cancel.wait(20)
+ return finish(**kwargs)
+
+ monkeypatch.setattr(engine, "generate", generate)
+ result = _in_thread(
+ ALICE, tool.run_generate_image, {"prompt": "x"}, workdir = str(tmp_path), timeout = 1
+ )
+ assert result.startswith("Generated a 1024x1024 image"), result
+ assert [n for n in os.listdir(tmp_path) if n.startswith("generated-image-")]
+
+
+def test_keepwarm_counts_once_per_tool_call_and_never_in_the_core(
+ engine, server_loop, keepwarm, tmp_path
+):
+ assert media_keepwarm.owner_for_path("/api/inference/images/generate") == gpu_arbiter.DIFFUSION
+ asyncio.run(inference._generate_diffusion_image_core(DiffusionGenerateRequest(prompt = "x")))
+ assert keepwarm == {"begin": 0, "end": 0}
+ for _ in range(2):
+ tool.run_generate_image({"prompt": "x"}, workdir = str(tmp_path))
+ assert keepwarm == {"begin": 2, "end": 2}
+
+
+def test_registries_treat_both_media_tools_alike():
+ from core.inference.tool_loop_controller import (
+ _FILE_SENTINEL_TOOLS,
+ _IMAGE_SENTINEL_TOOLS,
+ REPEATABLE_TOOL_NAMES,
+ )
+
+ for name in ("generate_image", "generate_video"):
+ assert not tools.is_potentially_unsafe_tool_call(name, {"prompt": "x"})
+ assert name in _FILE_SENTINEL_TOOLS and name in REPEATABLE_TOOL_NAMES
+ assert name in inference._ANTHROPIC_UNPROMPTED_SAFE_TOOLS
+ assert "generate_image" in _IMAGE_SENTINEL_TOOLS
+ assert "generate_video" not in _IMAGE_SENTINEL_TOOLS
+ assert (
+ status_for_tool("generate_image", {"prompt": "p" * 99}) == "Generating image: " + "p" * 60
+ )
+ assert status_for_tool("generate_video", {"prompt": "dog"}) == "Generating video: dog"
+
+
+def test_anthropic_never_selects_media_tools(engine):
+ picked = inference._select_anthropic_server_tools(
+ tools.ALL_TOOLS, {"generate_image", "generate_video"}, ["generate_image", "web_search"]
+ )
+ assert [t["function"]["name"] for t in picked] == ["web_search"]
+ assert not {t["function"]["name"] for t in tools.ALL_TOOLS} & media_chat_tools.MEDIA_CHAT_TOOLS
+
+
+def test_the_same_prompt_twice_is_two_renders():
+ controller = ToolLoopController(tools = [tool.generate_image_schema(STATUS)])
+ call = {"id": "g", "function": {"name": "generate_image", "arguments": '{"prompt":"x"}'}}
+ first = controller.prepare_call(call)
+ controller.record_result(first, "Generated a 1024x1024 image.")
+ assert controller.prepare_call(call).action == "execute"
+
+
+def test_stopping_a_queued_call_never_cancels_the_render_ahead_of_it(
+ engine, server_loop, keepwarm, monkeypatch, tmp_path
+):
+ # Same account, two surfaces: a render already holds the engine (still before step 0, so
+ # progress reads idle) when the chat call arrives and queues behind it. Stop on the chat must
+ # leave that render alone and drop only its own queued run.
+ _alice_loaded(monkeypatch)
+ lock = threading.Lock()
+ other_cancel = threading.Event()
+ other_done = threading.Event()
+ account_wide = []
+ ran = []
+
+ def cancel_generate(expected_account = None):
+ account_wide.append(expected_account)
+ other_cancel.set()
+ return True
+
+ def generate(**kwargs):
+ cancel = threading.Event()
+ bind_generation_cancel(cancel)
+ engine.started.set()
+ while not lock.acquire(timeout = 0.05):
+ if cancel.is_set():
+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)
+ try:
+ ran.append(kwargs)
+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)
+ finally:
+ lock.release()
+
+ holding = threading.Event()
+
+ def other_render():
+ with lock:
+ holding.set()
+ other_cancel.wait(3)
+ other_done.set()
+
+ monkeypatch.setattr(engine, "cancel_generate", cancel_generate)
+ monkeypatch.setattr(engine, "generate", generate)
+ # What the router does for a real engine: cancel whatever render the account has active.
+ monkeypatch.setattr(
+ diffusion_engine_router,
+ "cancel_generation_for_account",
+ lambda account_id: engine.cancel_generate(expected_account = account_id),
+ )
+ holder = threading.Thread(target = other_render)
+ holder.start()
+ assert holding.wait(10)
+ stop = threading.Event()
+ threading.Thread(target = lambda: engine.started.wait(20) and stop.set()).start()
+ result = _in_thread(
+ ALICE,
+ tool.run_generate_image,
+ {"prompt": "x"},
+ workdir = str(tmp_path),
+ cancel_event = stop,
+ timeout = 60,
+ )
+ holder.join(10)
+ assert result == tool.ERR_STOPPED
+ assert not other_cancel.is_set() and not account_wide
+ assert other_done.is_set() and not ran
+
+
+def test_sizes_follow_the_loaded_family_grid_and_bounds(engine, server_loop, monkeypatch, tmp_path):
+ response = _response(tmp_path, monkeypatch)
+
+ async def ok(request):
+ return response
+
+ seen = _fake_core(monkeypatch, ok)
+ engine.status_dict["conditioning"] = {
+ "dimension_multiple": 32,
+ "max_output_side": 2752,
+ "max_output_pixels": 2400 * 1792,
+ }
+ schema = tool.generate_image_schema(engine.status_dict)
+ width_doc = schema["function"]["parameters"]["properties"]["width"]["description"]
+ assert "multiple of 32" in width_doc and "2752" in width_doc
+ work = str(tmp_path / "w")
+ tool.run_generate_image({"prompt": "x", "width": 1280, "height": 720}, workdir = work)
+ tool.run_generate_image({"prompt": "x", "width": 2752, "height": 2752}, workdir = work)
+ engine.status_dict["conditioning"] = {
+ "dimension_multiple": 16,
+ "max_output_side": 2048,
+ "max_output_pixels": 2048 * 2048,
+ }
+ tool.run_generate_image({"prompt": "x", "width": 2752}, workdir = work)
+ from core.inference.diffusion_conditioning import check_output_size
+
+ fams = [
+ SimpleNamespace(dimension_multiple = 32, max_output_side = 2752, max_output_pixels = 2400 * 1792),
+ ] * 2 + [
+ SimpleNamespace(dimension_multiple = 16, max_output_side = 2048, max_output_pixels = 2048 * 2048)
+ ]
+ for fam, request in zip(fams, seen):
+ check_output_size(fam, request.width, request.height) # the route's own check accepts it
+ assert (seen[0].width, seen[0].height) == (1280, 704)
+ assert (seen[2].width, seen[2].height) == (2048, 1024)
diff --git a/studio/backend/tests/test_generate_video_tool.py b/studio/backend/tests/test_generate_video_tool.py
new file mode 100644
index 00000000000..ad9eec5d8a3
--- /dev/null
+++ b/studio/backend/tests/test_generate_video_tool.py
@@ -0,0 +1,335 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The generate_video chat tool, driven through the real job path on a fake video backend."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import sys
+import threading
+import time
+from pathlib import Path
+from typing import Optional
+
+import pytest
+
+import core.inference.gpu_arbiter as gpu_arbiter
+import core.inference.media_chat_tools as media_chat_tools
+import core.inference.media_keepwarm as media_keepwarm
+import core.inference.video as video_module
+import core.inference.video_gallery as gallery_module
+import routes.video as video_routes
+from core.inference import generate_video_tool as tool
+from models.inference import VideoJobCreateRequest
+from utils.account_context import AccountContext, run_as
+
+_TESTS_DIR = Path(__file__).resolve().parent
+if str(_TESTS_DIR) not in sys.path:
+ sys.path.insert(0, str(_TESTS_DIR))
+
+from test_openai_videos_route import _GatedBackend # noqa: E402
+
+ALICE = AccountContext("a" * 32, "alice")
+
+
[email protected](autouse = True)
+def _healthy_diffusers(healthy_diffusers):
+ pass
+
+
+def server_loop():
+ loop = asyncio.new_event_loop()
+ thread = threading.Thread(target = loop.run_forever, daemon = True)
+ thread.start()
+ media_chat_tools.remember_server_loop(loop)
+ yield loop
+ media_chat_tools.remember_server_loop(None)
+ loop.call_soon_threadsafe(loop.stop)
+ thread.join(5)
+ loop.close()
+
+
+def backend(monkeypatch, tmp_path, server_loop):
+ backend = _GatedBackend()
+ backend.loaded = True
+ monkeypatch.setattr(video_module, "get_video_backend", lambda: backend)
+ monkeypatch.setattr(gpu_arbiter, "_owner", None)
+ monkeypatch.setitem(gpu_arbiter._EVICTORS, gpu_arbiter.VIDEO, lambda: None)
+ (tmp_path / "gallery").mkdir()
+ monkeypatch.setattr(gallery_module, "gallery_dir", lambda: tmp_path / "gallery")
+ monkeypatch.setattr(video_routes, "_jobs", {})
+ monkeypatch.setattr(video_routes, "_managed_jobs", {})
+ monkeypatch.setattr(media_chat_tools, "media_chat_status", lambda task: backend.status())
+ monkeypatch.setattr(tool, "_POLL_S", 0.02)
+ yield backend
+ backend.gate.set()
+
+
+def keepwarm(monkeypatch):
+ calls: list = []
+
+ async def _begin(owner):
+ calls.append(("begin", owner))
+
+ def _end(owner, *, counted = True):
+ calls.append(("end", owner, counted))
+
+ monkeypatch.setattr(media_keepwarm, "begin_request", _begin)
+ monkeypatch.setattr(media_keepwarm, "end_request", _end)
+ return calls
+
+
+def _run(tmp_path, args, **kwargs):
+ return tool.run_generate_video(args, workdir = str(tmp_path / "work"), **kwargs)
+
+
+def _only_job() -> str:
+ jobs = list(video_routes._jobs) or [
+ i for jobs in video_routes._managed_jobs.values() for i in jobs
+ ]
+ assert len(jobs) == 1, jobs
+ return jobs[0]
+
+
+def _wait_phase(
+ backend,
+ *phases,
+ timeout = 5.0,
+):
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if backend.generate_progress().get("phase") in phases:
+ return
+ time.sleep(0.01)
+ raise AssertionError(backend.generate_progress())
+
+
+def test_completed_clip_is_copied_into_the_workdir_with_a_files_row(tmp_path, backend, keepwarm):
+ out = _run(tmp_path, {"prompt": " a fox\n runs ", "seconds": 2, "width": 768, "height": 512})
+ text, files = out.split("\n__FILES__:")
+ assert "__IMAGES__" not in out
+ assert text.startswith("Generated a video (") and text.endswith("Prompt: a fox runs")
+ video_id = _only_job()
+ name = f"generated-video-{video_id.removeprefix('video_')[:8]}.mp4"
+ copied = tmp_path / "work" / name
+ assert copied.read_bytes() == gallery_module.owned_video_path(video_id).read_bytes()
+ assert json.loads(files) == [{"name": name, "size": copied.stat().st_size}]
+ sent = backend.last_generate_kwargs
+ assert (sent["prompt"], sent["width"], sent["height"]) == ("a fox\n runs", 768, 512)
+ assert keepwarm == [("begin", gpu_arbiter.VIDEO), ("end", gpu_arbiter.VIDEO, True)]
+
+
+def test_model_none_never_reaches_the_auto_switch_or_a_load(
+ tmp_path, backend, keepwarm, monkeypatch
+):
+ import core.inference.media_auto_switch as mas
+ import utils.openai_auto_switch_settings as switch_settings
+
+ requested: list = []
+ real_switch = mas.maybe_auto_switch_media_model
+
+ async def _spy(model, **kwargs):
+ requested.append(model)
+ return await real_switch(model, **kwargs)
+
+ def _setting_read():
+ raise AssertionError("the auto-switch went past its model=None early return")
+
+ def _no_acquire(*args, **kwargs):
+ raise AssertionError("the GPU arbiter was asked for the video slot")
+
+ monkeypatch.setattr(mas, "maybe_auto_switch_media_model", _spy)
+ monkeypatch.setattr(switch_settings, "get_media_auto_switch_enabled", _setting_read)
+ for name in ("acquire", "acquire_async", "acquire_for_load"):
+ if hasattr(gpu_arbiter, name):
+ monkeypatch.setattr(gpu_arbiter, name, _no_acquire)
+ assert "\n__FILES__:" in _run(tmp_path, {"prompt": "x", "model": "other/model"})
+ assert requested == [None]
+ assert backend.last_load_kwargs == {}
+
+
+def test_a_running_job_maps_the_busy_409(tmp_path, backend, keepwarm):
+ backend.gate.clear()
+ assert _run(tmp_path, {"prompt": "first"}, timeout = 0.2) == tool.STILL_RENDERING_MSG
+ assert _run(tmp_path, {"prompt": "second"}, timeout = 0.2) == tool.BUSY_MSG
+ assert keepwarm[-1] == ("end", gpu_arbiter.VIDEO, False)
+
+
+def test_timeout_leaves_the_job_running(tmp_path, backend, keepwarm, monkeypatch):
+ backend.gate.clear()
+ cancels: list = []
+ monkeypatch.setattr(backend, "cancel_generate", lambda **kw: cancels.append(kw))
+ assert _run(tmp_path, {"prompt": "slow"}, timeout = 0.2) == tool.STILL_RENDERING_MSG
+ assert video_routes._lookup_video(_only_job()).status in ("queued", "in_progress")
+ assert cancels == []
+ assert keepwarm == [("begin", gpu_arbiter.VIDEO), ("end", gpu_arbiter.VIDEO, True)]
+
+
+def test_the_cancel_event_stops_the_job(tmp_path, backend, keepwarm):
+ backend.gate.clear()
+ stop = threading.Event()
+ threading.Timer(0.2, stop.set).start()
+ assert _run(tmp_path, {"prompt": "stop me"}, cancel_event = stop) == tool.STOPPED_MSG
+ _wait_phase(backend, "failed")
+ job = video_routes._lookup_video(_only_job())
+ assert job.status == "failed" and job.error.code == "cancelled"
+ assert not (tmp_path / "work").exists()
+
+
+def test_a_clip_that_completes_inside_the_stop_window_is_still_returned(
+ tmp_path, backend, keepwarm, monkeypatch
+):
+ # Stop lands at the last step: the backend finishes the clip instead of cancelling.
+ backend.gate.clear()
+ monkeypatch.setattr(backend, "cancel_generate", lambda **kw: backend.gate.set())
+ stop = threading.Event()
+ threading.Timer(0.2, stop.set).start()
+ result = _run(tmp_path, {"prompt": "last step"}, cancel_event = stop)
+ assert result.startswith("Generated a video"), result
+ assert [p.name for p in (tmp_path / "work").iterdir() if p.suffix == ".mp4"]
+
+
+def _slow_create(monkeypatch, keepwarm, delay):
+ async def _begin(owner):
+ keepwarm.append(("begin", owner))
+ await asyncio.sleep(delay)
+
+ monkeypatch.setattr(media_keepwarm, "begin_request", _begin)
+
+
+def test_a_slow_create_is_never_cancelled_so_its_job_stays_tracked(
+ tmp_path, backend, keepwarm, monkeypatch
+):
+ backend.gate.clear()
+ _slow_create(monkeypatch, keepwarm, 0.6)
+ monkeypatch.setattr(tool, "_CREATE_TIMEOUT_S", 0.1)
+ assert _run(tmp_path, {"prompt": "slow create"}, timeout = 30) == tool.STILL_RENDERING_MSG
+ deadline = time.monotonic() + 5
+ while not (video_routes._jobs or video_routes._managed_jobs) and time.monotonic() < deadline:
+ time.sleep(0.02)
+ # The create finished after the tool answered, and the job is on record.
+ assert video_routes._lookup_video(_only_job()).status in ("queued", "in_progress")
+
+
+def test_stop_during_a_slow_create_stops_the_job_it_starts(
+ tmp_path, backend, keepwarm, monkeypatch
+):
+ backend.gate.clear()
+ _slow_create(monkeypatch, keepwarm, 0.6)
+ monkeypatch.setattr(tool, "_STOP_WAIT_S", 0.05)
+ stop = threading.Event()
+ stop.set()
+ assert _run(tmp_path, {"prompt": "stop early"}, cancel_event = stop) == tool.STOPPED_MSG
+ deadline = time.monotonic() + 5
+ while not (video_routes._jobs or video_routes._managed_jobs) and time.monotonic() < deadline:
+ time.sleep(0.02)
+ _wait_phase(backend, "failed")
+ job = video_routes._lookup_video(_only_job())
+ assert job.status == "failed" and job.error.code == "cancelled"
+
+
+def test_a_failed_job_reports_its_error(tmp_path, backend, keepwarm):
+ backend.fail_with = "the sampler blew up"
+ assert _run(tmp_path, {"prompt": "x"}).startswith("Error: ")
+ assert video_routes._lookup_video(_only_job()).status == "failed"
+
+
+def test_not_loaded_and_bad_input_are_error_strings(tmp_path, backend, keepwarm, monkeypatch):
+ assert _run(tmp_path, {"prompt": " "}) == tool.NO_PROMPT_MSG
+ backend.loaded = False
+ assert _run(tmp_path, {"prompt": "x"}) == tool.NOT_LOADED_MSG
+ monkeypatch.setattr(media_chat_tools, "media_chat_status", lambda task: None)
+ assert _run(tmp_path, {"prompt": "x"}) == tool.NOT_LOADED_MSG
+ backend.loaded = True
+ monkeypatch.setattr(media_chat_tools, "media_chat_status", lambda task: backend.status())
+ assert _run(tmp_path, {"prompt": "x", "width": 8, "height": 8}).startswith("Error: ")
+ media_chat_tools.remember_server_loop(None)
+ assert _run(tmp_path, {"prompt": "x"}) == tool.NO_LOOP_MSG
+ assert keepwarm == [("begin", gpu_arbiter.VIDEO), ("end", gpu_arbiter.VIDEO, False)] * 2
+
+
+def test_another_accounts_generation_maps_to_its_own_error(
+ tmp_path, backend, keepwarm, monkeypatch
+):
+ async def _busy(*args, **kwargs):
+ raise gpu_arbiter.GpuBusyForAnotherAccountError(gpu_arbiter.VIDEO, 1)
+
+ monkeypatch.setattr(video_routes, "_create_openai_video", _busy)
+ assert _run(tmp_path, {"prompt": "x"}) == tool.OTHER_ACCOUNT_MSG
+
+
[email protected]("has_seed", [False, True])
+def test_seed_is_offered_and_forwarded_only_when_the_request_has_the_field(
+ tmp_path, backend, keepwarm, monkeypatch, has_seed
+):
+ import models.inference as models_inference
+
+ class _Seeded(VideoJobCreateRequest):
+ seed: Optional[int] = None
+
+ class _Plain(VideoJobCreateRequest):
+ pass
+
+ _Plain.model_fields.pop("seed", None)
+ monkeypatch.setattr(models_inference, "VideoJobCreateRequest", _Seeded if has_seed else _Plain)
+ seen: list = []
+
+ async def _capture(body, reference, subject, hf_token):
+ seen.append(body.model_dump(exclude_none = True))
+ raise video_routes.HTTPException(status_code = 400, detail = {"error": {"message": "stop"}})
+
+ monkeypatch.setattr(video_routes, "_create_openai_video", _capture)
+ schema = tool.generate_video_schema(backend.status())
+ assert ("seed" in schema["function"]["parameters"]["properties"]) is has_seed
+ assert _run(tmp_path, {"prompt": "x", "seed": 7}) == "Error: stop"
+ assert seen == [{"prompt": "x", **({"seed": 7} if has_seed else {})}]
+
+
+def test_the_schema_names_the_tool_and_appends_the_prompt_hint(backend):
+ schema = tool.generate_video_schema({**backend.status(), "prompt_hint": "Say the camera move."})
+ fn = schema["function"]
+ assert fn["name"] == "generate_video" and fn["parameters"]["required"] == ["prompt"]
+ assert fn["description"].startswith("Generate one short video clip with the video model")
+ assert fn["description"].endswith(" Say the camera move.")
+ assert "Studio" not in fn["description"].replace("Unsloth Studio", "")
+
+
+def test_a_managed_accounts_job_resolves_under_that_account(
+ tmp_path, backend, keepwarm, monkeypatch, server_loop
+):
+ import contextvars
+
+ from hub.services.models import account_access
+
+ monkeypatch.setattr(account_access, "require_media_generation_access", lambda *a, **k: None)
+ # The coroutine must bind the account itself, not lean on the caller's context leaking over.
+ schedule = server_loop.call_soon_threadsafe
+ monkeypatch.setattr(
+ server_loop,
+ "call_soon_threadsafe",
+ lambda cb, *args, context = None: schedule(cb, *args, context = contextvars.Context()),
+ )
+ out = run_as(ALICE, _run, tmp_path, {"prompt": "private"})
+ assert "\n__FILES__:" in out
+ assert video_routes._jobs == {}
+ assert list(video_routes._managed_jobs) == [ALICE.account_id]
+ video_id = _only_job()
+ assert run_as(ALICE, video_routes._lookup_video, video_id).status == "completed"
+ assert backend._generate_job_account == ALICE.account_id
+
+
+def test_a_ref2va_video_model_is_not_offered_to_chat(monkeypatch):
+ from core.inference import media_chat_tools
+
+ statuses = {"text-to-video": {"loaded": True, "h3_task": "ref2va"}}
+ monkeypatch.setattr(media_chat_tools, "media_chat_status", lambda task: statuses.get(task))
+ assert media_chat_tools.offered_media_chat_tools({"generate_video"}) == []
+ statuses["text-to-video"]["h3_task"] = "fl2va"
+ assert [
+ t["function"]["name"] for t in media_chat_tools.offered_media_chat_tools({"generate_video"})
+ ] == ["generate_video"]
diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.py
index f54c59c239b..876b826d477 100644
--- a/studio/backend/tests/test_llama_cpp_tool_loop.py
+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py
@@ -5580,9 +5580,14 @@ def test_gguf_textual_fallback_keeps_identical_calls_when_deduplication_is_off(
assert len(calls) == (1 if deduplicate else 3), [c[0] for c in calls]
-def test_gguf_identical_browser_calls_in_one_batch_all_run(monkeypatch):
- # Each acts on the page as it is then, so the second scroll is not a repeat of the first.
- blocks = '<tool_call>{"name":"browser_scroll","arguments":{"direction":"down"}}</tool_call>' * 2
+ "name, arguments",
+ [("browser_scroll", '{"direction":"down"}'), ("generate_image", '{"prompt":"a sloth"}')],
+)
+def test_gguf_identical_browser_calls_in_one_batch_all_run(monkeypatch, name, arguments):
+ # Each acts on the page as it is then, so the second scroll is not a repeat of the first;
+ # a second identical generate_image is a second image.
+ blocks = f'<tool_call>{{"name":"{name}","arguments":{arguments}}}</tool_call>' * 2
first_stream = [_sse({"content": blocks}), _done()]
final_stream = [_sse({"content": "done"}), _done()]
backend, _payloads = _backend_and_payloads(monkeypatch, [first_stream, final_stream])
@@ -5596,12 +5601,12 @@ def test_gguf_identical_browser_calls_in_one_batch_all_run(monkeypatch):
list(
backend.generate_chat_completion_with_tools(
messages = [{"role": "user", "content": "scroll"}],
- tools = [{"type": "function", "function": {"name": "browser_scroll"}}],
+ tools = [{"type": "function", "function": {"name": name}}],
max_tool_iterations = 1,
)
)
- assert [name for name, _ in calls] == ["browser_scroll", "browser_scroll"]
+ assert [called for called, _ in calls] == [name, name]
def test_gguf_drain_truncated_enabled_name_json_preserved_when_auto_heal_disabled(monkeypatch):
diff --git a/studio/backend/tests/test_nudge_tool_calls_wiring.py b/studio/backend/tests/test_nudge_tool_calls_wiring.py
index 30d8a68a3ee..b2c3e963b7f 100644
--- a/studio/backend/tests/test_nudge_tool_calls_wiring.py
+++ b/studio/backend/tests/test_nudge_tool_calls_wiring.py
@@ -148,3 +148,35 @@ def test_studio_external_adapter_disables_the_nudge_on_the_external_loop():
local_src = src.replace(external_body, "")
assert "nudge_tool_calls: runtime.nudgeToolCalls" in local_src
assert "run_tools_locally: true" not in local_src
+
+
+def test_safetensors_loop_runs_identical_generate_image_calls_in_one_turn():
+ # Two identical renders are two images; an identical web_search is still deduplicated.
+ ran = []
+ turns = iter(
+ [
+ '<tool_call>{"name": "generate_image", "arguments": {"prompt": "x"}}</tool_call>' * 2
+ + '<tool_call>{"name": "web_search", "arguments": {"query": "q"}}</tool_call>' * 2,
+ "done",
+ ]
+ )
+
+ def single_turn(_messages):
+ for turn in turns:
+ yield turn
+ return
+
+ list(
+ run_safetensors_tool_loop(
+ single_turn = single_turn,
+ messages = [{"role": "user", "content": "two images"}],
+ tools = [
+ {"type": "function", "function": {"name": "generate_image"}},
+ {"type": "function", "function": {"name": "web_search"}},
+ ],
+ execute_tool = lambda name, arguments, **_k: ran.append(name) or "OK",
+ session_id = "s",
+ confirm_tool_calls = False,
+ )
+ )
+ assert ran == ["generate_image", "generate_image", "web_search"]
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index 91f0b94e65e..b5d97b258f1 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -217,8 +217,12 @@ export const BUDGET = {
// Audio failure actions, seeds and the single voice picker (#14075) add 492 B raw / 134 B transfer (6,812,691 ->
// 6,813,183 B raw, 2,050,209 -> 2,050,343 B transfer against 4bed2fa246, one machine and build, Node 24, chunk count
// unchanged at 95): the shared audio failure and seed helpers are imported by startup chunks. Raised by that growth.
- transferBytes: 2_048_653,
- rawBytes: 6_809_138,
+ // The Images pill making images and videos with the loaded local models (#14110) adds 5,425 B raw / 1,442 B
+ // transfer (6,814,532 -> 6,819,957 B raw, 2,050,886 -> 2,052,328 B transfer against 82523339bd, one machine and build,
+ // Node 24, chunk count unchanged at 95): the local image and video cards in the eager tool UI registry and the
+ // composer and adapter gates in the eager chat chunk. Raised by that growth.
+ transferBytes: 2_050_095,
+ rawBytes: 6_814_563,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx b/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx
index 6f3e2706a03..7da51f63911 100644
--- a/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx
+++ b/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx
@@ -109,6 +109,8 @@ const TOOL_CALL_LABELS: Record<string, string> = {
terminal: "Terminal",
edit_file: "Edit",
image_generation: "Images",
+ generate_image: "Images",
+ generate_video: "Video",
search_knowledge_base: "Docs",
render_html: "Canvas",
};
@@ -129,7 +131,13 @@ function toolCategoryFromCall(toolName: string): string | null {
) {
return "code";
}
- if (normalized === "image_generation") return "images";
+ if (
+ normalized === "image_generation" ||
+ normalized === "generate_image" ||
+ normalized === "generate_video"
+ ) {
+ return "images";
+ }
if (normalized === "search_knowledge_base") return "docs";
if (normalized === "render_html") return "artifacts";
if (normalized.startsWith("mcp__")) return "mcp";
diff --git a/studio/frontend/src/components/assistant-ui/sandbox-files.ts b/studio/frontend/src/components/assistant-ui/sandbox-files.ts
index a48605fad72..3012a4fba25 100644
--- a/studio/frontend/src/components/assistant-ui/sandbox-files.ts
+++ b/studio/frontend/src/components/assistant-ui/sandbox-files.ts
@@ -12,8 +12,19 @@ const FILES_MARKER = "\n__FILES__:";
/** The tools that run code in the sandbox. Their result is always wrapped: the session is the only record of where it ran. */
export const SANDBOX_RUN_TOOLS = new Set(["python", "terminal"]);
+/**
+ * The chat tools that render on the image or video model loaded in Unsloth. They
+ * write their output into the sandbox and answer with the file envelope. Keep in step
+ * with MEDIA_CHAT_TOOLS in studio/backend/core/inference/media_chat_tools.py.
+ */
+export const MEDIA_CHAT_TOOLS: ReadonlySet<string> = new Set(["generate_image", "generate_video"]);
+
/** The tools that emit the file envelope; edit_file only for a file it created. Nothing else's output is an envelope. */
-export const SANDBOX_FILE_TOOLS = new Set([...SANDBOX_RUN_TOOLS, "edit_file"]);
+export const SANDBOX_FILE_TOOLS = new Set([
+ ...SANDBOX_RUN_TOOLS,
+ "edit_file",
+ ...MEDIA_CHAT_TOOLS,
+]);
/**
* The tools that emit the image envelope: the sandbox ones, and the provider's hosted
@@ -21,7 +32,11 @@ export const SANDBOX_FILE_TOOLS = new Set([...SANDBOX_RUN_TOOLS, "edit_file"]);
* well-formed `__IMAGES__` line from any other tool as content the model reads, so
* the card has to keep it too, or the user sees less than the model was given.
*/
-export const IMAGE_SENTINEL_TOOLS = new Set([...SANDBOX_RUN_TOOLS, "code_execution"]);
+export const IMAGE_SENTINEL_TOOLS = new Set([
+ ...SANDBOX_RUN_TOOLS,
+ "code_execution",
+ "generate_image",
+]);
function isSandboxFile(entry: unknown): entry is SandboxFile {
if (typeof entry !== "object" || entry === null) return false;
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 4783cb30465..f6e1caf582a 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -77,7 +77,10 @@ import { withToolConfirmation } from "@/components/assistant-ui/tool-confirmatio
import { ToolFallback } from "@/components/assistant-ui/tool-fallback";
import { ToolGroup } from "@/components/assistant-ui/tool-group";
import { CodeExecutionToolUI } from "@/components/assistant-ui/tool-ui-code-execution";
-import { ImageGenerationToolUI } from "@/components/assistant-ui/tool-ui-image-generation";
+import {
+ ImageGenerationToolUI,
+ VideoGenerationToolUI,
+} from "@/components/assistant-ui/tool-ui-image-generation";
import { KnowledgeBaseToolUI } from "@/components/assistant-ui/tool-ui-knowledge-base";
import { ReadSkillToolUI } from "@/components/assistant-ui/tool-ui-read-skill";
import { SkillMentionPopover } from "@/components/assistant-ui/skill-mentions";
@@ -262,6 +265,8 @@ import { BypassPermissionsMenuItem } from "@/features/chat/bypass-permissions-me
import { PermissionModeComposerPill } from "@/features/chat/permission-mode-select";
import {
codeToolsOn,
+ imageToolAvailable,
+ localImagePillCount,
settleThreadScopedSettingsForCopy,
useChatRuntimeStore,
} from "@/features/chat/stores/chat-runtime-store";
@@ -2901,6 +2906,8 @@ const Composer: FC<{
const supportsBuiltinImageGeneration = useChatRuntimeStore(
(s) => s.supportsBuiltinImageGeneration,
);
+ // The local Images pill counts only while it is on, like RAG.
+ const localImagePills = useChatRuntimeStore(localImagePillCount);
const mcpEnabledForChat = useChatRuntimeStore((s) => s.mcpEnabledForChat);
const ragEnabled = useChatRuntimeStore((s) => s.ragEnabled);
const deepResearchEnabled = useChatRuntimeStore(
@@ -2949,6 +2956,7 @@ const Composer: FC<{
3 +
(ragEnabled ? 1 : 0) +
(supportsBuiltinImageGeneration ? 1 : 0) +
+ localImagePills +
(mcpEnabledForChat ? 1 : 0) +
(effectiveDeepResearchEnabled ? 1 : 0);
// Under the count threshold the row still overflows on long labels ("Run
@@ -6725,17 +6733,15 @@ const ImagesToggle: FC = () => {
const modelLoaded = useChatRuntimeStore(
(s) => !!s.params.checkpoint && !s.modelLoading,
);
- // OpenAI cloud Responses-API models advertise image_generation as a
- // server-side tool; no local runtime fallback. Mirror of shared-composer's
- // imageDisabled / showImagePill so this composer matches the empty state.
- const supportsBuiltinImageGeneration = useChatRuntimeStore(
- (s) => s.supportsBuiltinImageGeneration,
- );
+ // The provider's own image_generation, or the image or video model loaded in
+ // Unsloth for a model that calls Unsloth tools. Mirror of
+ // shared-composer's imageDisabled / showImagePill so this composer matches the empty state.
+ const imageToolShown = useChatRuntimeStore(imageToolAvailable);
const imageToolsEnabled = useChatRuntimeStore((s) => s.imageToolsEnabled);
const setImageToolsEnabled = useChatRuntimeStore(
(s) => s.setImageToolsEnabled,
);
- if (!supportsBuiltinImageGeneration) {
+ if (!imageToolShown) {
return null;
}
const disabled = !modelLoaded;
@@ -6929,9 +6935,7 @@ const ComposerToolsMenu: FC<{
const supportsBuiltinCodeExecution = useChatRuntimeStore(
(s) => s.supportsBuiltinCodeExecution,
);
- const supportsBuiltinImageGeneration = useChatRuntimeStore(
- (s) => s.supportsBuiltinImageGeneration,
- );
+ const imageToolShown = useChatRuntimeStore(imageToolAvailable);
const imageToolsEnabled = useChatRuntimeStore((s) => s.imageToolsEnabled);
const setImageToolsEnabled = useChatRuntimeStore(
(s) => s.setImageToolsEnabled,
@@ -7401,7 +7405,7 @@ const ComposerToolsMenu: FC<{
) : null}
</DropdownMenuItem>
{deepResearchWithTools ? plusMenuNodes.deepResearch : null}
- {supportsBuiltinImageGeneration && (
+ {imageToolShown && (
<DropdownMenuItem
disabled={imageDisabled}
className={
@@ -8215,6 +8219,9 @@ const CodeExecutionToolUIConfirmable =
const ImageGenerationToolUIConfirmable = withToolConfirmation(
ImageGenerationToolUI,
);
+const VideoGenerationToolUIConfirmable = withToolConfirmation(
+ VideoGenerationToolUI,
+);
const RenderHtmlToolUIConfirmable = withToolConfirmation(RenderHtmlToolUI);
// Read at render time, not module scope: the skill modules reach the chat barrel.
const ReadSkillToolUIConfirmable = withToolConfirmation((props) => (
@@ -8247,6 +8254,8 @@ const ASSISTANT_PART_COMPONENTS = {
terminal: TerminalToolUIConfirmable,
code_execution: CodeExecutionToolUIConfirmable,
image_generation: ImageGenerationToolUIConfirmable,
+ generate_image: ImageGenerationToolUIConfirmable,
+ generate_video: VideoGenerationToolUIConfirmable,
render_html: RenderHtmlToolUIConfirmable,
},
Fallback: ToolFallbackConfirmable,
diff --git a/studio/frontend/src/components/assistant-ui/tool-fold-exemptions.ts b/studio/frontend/src/components/assistant-ui/tool-fold-exemptions.ts
index a15b9fa037d..6f7d7884d98 100644
--- a/studio/frontend/src/components/assistant-ui/tool-fold-exemptions.ts
+++ b/studio/frontend/src/components/assistant-ui/tool-fold-exemptions.ts
@@ -4,7 +4,7 @@
// Which tool calls stay visible whatever the fold and collapse preferences say. One place for the
// rule, so the tool group that shows the run and the Thinking header that counts it agree.
-import { hasCreatedFiles } from "./sandbox-files.ts";
+import { MEDIA_CHAT_TOOLS, hasCreatedFiles } from "./sandbox-files.ts";
export interface ToolPartLike {
readonly type: string;
@@ -33,7 +33,7 @@ export function carriesImages(result: unknown): boolean {
);
}
-/** Canvases, Python, generated images, results that carry images and anything that wrote a
+/** Canvases, Python, generated images and videos, results that carry images and anything that wrote a
* file: their output lives only in the card, so it is never tucked away. */
export function holdsOwnOutput(part: ToolPartLike): boolean {
return (
@@ -41,6 +41,7 @@ export function holdsOwnOutput(part: ToolPartLike): boolean {
(part.toolName === "render_html" ||
part.toolName === "python" ||
part.toolName === "image_generation" ||
+ MEDIA_CHAT_TOOLS.has(part.toolName ?? "") ||
carriesImages(part.result) ||
hasCreatedFiles(part.toolName, part.result))
);
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-image-generation.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-image-generation.tsx
index 9a74ed6a503..2598a5c3ea5 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-image-generation.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-image-generation.tsx
@@ -9,17 +9,25 @@ import { cn } from "@/lib/utils";
import type { ToolCallMessagePartComponent } from "@assistant-ui/react";
import { Download01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { ImageIcon, PencilIcon } from "lucide-react";
+import { downloadUrl, isDownloadCancelled } from "@/lib/native-files";
+import { toast } from "@/lib/toast";
+import { ImageIcon, PencilIcon, VideoIcon } from "lucide-react";
import type { CSSProperties, MouseEvent } from "react";
import { memo, useCallback, useEffect, useRef, useState } from "react";
import { useGeneratedImageOverlay } from "./generated-image-overlay-context";
import { downloadImagePart } from "./image";
+import {
+ isSandboxToolResult,
+ type SandboxFile,
+ sandboxFilePath,
+} from "./sandbox-files";
import { isToolCallRunning, toolArgText } from "./tool-arg-text";
import {
ToolFallbackContent,
ToolFallbackRoot,
ToolFallbackTrigger,
} from "./tool-fallback";
+import { useSandboxImage } from "./use-sandbox-image";
/**
* Renders the synthetic `_toolEvent` chunks emitted by
@@ -31,6 +39,10 @@ import {
* The `tool_start` carries the revised prompt as `args.prompt` plus
* `args.kind: "image"`. Without this, ToolFallback would print the prompt as
* JSON with an empty Result block (the "no image" symptom).
+ *
+ * `generate_image` (the image model loaded in Unsloth) shares this card. Its result is the
+ * sandbox wrapper, so the image is fetched from the chat's sandbox, and it has no Edit: that needs
+ * an OpenAI image-generation call id. A failed call answers with an "Error: ..." string.
*/
interface ImageGenerationArgs {
// Straight off the wire; the provider decides the JSON type, not this file.
@@ -62,6 +74,28 @@ type GeneratedImagePart = {
filename?: string;
};
+type SandboxMediaResult = {
+ text: string;
+ sessionId: string;
+ images: unknown[];
+ files?: SandboxFile[];
+};
+
+const sandboxMediaResult = (result: unknown): SandboxMediaResult | null =>
+ isSandboxToolResult(result) ? (result as SandboxMediaResult) : null;
+
+// Success is always an object (the sandbox wrapper or the hosted image); a plain string is an
+// "Error: ..." from the tool, or the loop's own text for a stopped or skipped call.
+const toolErrorText = (result: unknown): string =>
+ typeof result === "string" ? result.trim() : "";
+
+const notGeneratedLabel = (kind: "Image" | "Video", text: string): string =>
+ text.startsWith("Error:")
+ ? `${kind} generation failed`
+ : `${kind} not generated`;
+
+const baseName = (name: string): string => name.split("/").pop() || name;
+
const CAPTION_COLLAPSED_LINES = 4;
const INLINE_IMAGE_MAX_WIDTH = 520;
const INLINE_IMAGE_MAX_HEIGHT = 620;
@@ -144,6 +178,98 @@ const loadingDots = Array.from({ length: 64 }, (_, index) => {
);
});
+/**
+ * A generate_image or generate_video result: the file in the chat's sandbox, fetched with auth,
+ * with Download and no Edit. The ref sits on the frame so the lazy fetch starts near the viewport.
+ */
+function SandboxMediaFigure({
+ kind,
+ url,
+ filename,
+ title,
+ caption,
+}: {
+ kind: "image" | "video";
+ url: string;
+ filename: string;
+ title: string;
+ caption: string;
+}) {
+ const { ref, state } = useSandboxImage<HTMLDivElement>(url);
+ const loaded = state.status === "loaded" ? state.url : null;
+ const handleDownload = () => {
+ if (!loaded) return;
+ if (kind === "image") {
+ downloadImagePart({ image: loaded, filename });
+ return;
+ }
+ void downloadUrl(loaded, filename).catch((error) => {
+ if (!isDownloadCancelled(error)) toast.error("Could not save video.");
+ });
+ };
+ return (
+ <figure
+ className="m-0 flex max-w-full flex-col items-start gap-2 align-top"
+ style={{ width: INLINE_IMAGE_MAX_WIDTH, maxWidth: "100%" }}
+ >
+ <div
+ ref={ref}
+ className="group/generated-image relative w-full overflow-hidden rounded-2xl align-top"
+ >
+ {state.status === "failed" ? (
+ <p className="text-xs leading-5 text-muted-foreground">
+ {kind === "image" ? "Image not available" : "Video not available"}
+ </p>
+ ) : !loaded ? (
+ <div
+ role="status"
+ aria-busy="true"
+ aria-label={kind === "image" ? "Loading image…" : "Loading video…"}
+ className="aspect-square w-full rounded-2xl bg-muted/20"
+ />
+ ) : kind === "image" ? (
+ <img
+ src={loaded}
+ alt={title}
+ className="block h-auto max-h-[min(70dvh,620px)] max-w-full rounded-2xl object-contain"
+ />
+ ) : (
+ <video
+ src={loaded}
+ controls={true}
+ playsInline={true}
+ preload="metadata"
+ aria-label={title}
+ className="block h-auto max-h-[min(70dvh,620px)] w-full rounded-2xl"
+ />
+ )}
+ {loaded ? (
+ <div
+ {...{ [FIND_SKIP_ATTRIBUTE]: "" }}
+ className="pointer-events-none absolute top-0 right-0 z-20 p-3 opacity-100 transition-opacity sm:opacity-0 sm:group-hover/generated-image:opacity-100 sm:group-focus-within/generated-image:opacity-100"
+ >
+ <Button
+ type="button"
+ variant="dark"
+ size="icon-sm"
+ className="pointer-events-auto rounded-full bg-black/70 text-white hover:bg-black/85"
+ onClick={handleDownload}
+ aria-label={`Download generated ${kind}`}
+ >
+ <HugeiconsIcon icon={Download01Icon} className="size-4" />
+ </Button>
+ </div>
+ ) : null}
+ </div>
+ {caption ? (
+ <figcaption className="line-clamp-4 w-full whitespace-pre-wrap break-words text-xs leading-5 text-muted-foreground">
+ {caption}
+ </figcaption>
+ ) : null}
+ </figure>
+ );
+}
+
function GeneratedImagePlaceholder({ label }: { label: string }) {
return (
<div
@@ -177,6 +303,11 @@ const ImageGenerationToolUIImpl: ToolCallMessagePartComponent = ({
typeof result === "object" &&
typeof (result as ImageGenerationResult).image_b64 === "string";
const imageResult = isImageResult ? (result as ImageGenerationResult) : null;
+ const localResult = isImageResult ? null : sandboxMediaResult(result);
+ const localImageName = localResult?.images.find(
+ (name): name is string => typeof name === "string" && name.length > 0,
+ );
+ const errorText = toolErrorText(result);
// Coerced for the same reason `prompt` is: these reach `.match`,
// `.toLowerCase` and `Array.join`, all of which throw on a non-string.
const size = toolArgText(imageResult?.size);
@@ -225,7 +356,7 @@ const ImageGenerationToolUIImpl: ToolCallMessagePartComponent = ({
canExpand: boolean;
} | null>(null);
const captionRef = useRef<HTMLDivElement | null>(null);
- const isPendingImage = !imagePart && isRunning;
+ const isPendingImage = !imagePart && !localImageName && isRunning;
const promptOverflowMeasured = promptOverflow?.prompt === captionPrompt;
const promptCanExpand = promptOverflowMeasured
@@ -274,7 +405,9 @@ const ImageGenerationToolUIImpl: ToolCallMessagePartComponent = ({
!promptExpanded;
const runningLabel = "Generating image…";
- const completedLabel = formatGeneratedImageLabel(prompt);
+ const completedLabel = errorText
+ ? notGeneratedLabel("Image", errorText)
+ : formatGeneratedImageLabel(prompt);
const showPreview = () => {
if (!imagePart) {
@@ -326,6 +459,18 @@ const ImageGenerationToolUIImpl: ToolCallMessagePartComponent = ({
icon={ImageIcon}
/>
<ToolFallbackContent>
+ {errorText ? (
+ <p className="text-xs leading-5 text-muted-foreground">{errorText}</p>
+ ) : null}
+ {localResult && localImageName ? (
+ <SandboxMediaFigure
+ kind="image"
+ url={sandboxFilePath(localResult.sessionId, localImageName)}
+ filename={baseName(localImageName)}
+ title={imageTitle}
+ caption={captionPrompt}
+ />
+ ) : null}
{imagePart ? (
<figure
className="m-0 flex max-w-full flex-col items-start gap-2 align-top"
@@ -426,3 +571,64 @@ export const ImageGenerationToolUI = memo(
ImageGenerationToolUIImpl,
) as unknown as ToolCallMessagePartComponent;
ImageGenerationToolUI.displayName = "ImageGenerationToolUI";
+
+const VIDEO_FILE = /\.(mp4|webm|mov)$/i;
+
+/** `generate_video`: the .mp4 the video model loaded in Unsloth wrote into the chat's sandbox. */
+const VideoGenerationToolUIImpl: ToolCallMessagePartComponent = ({
+ args,
+ result,
+ status,
+}) => {
+ const prompt = toolArgText((args as { prompt?: unknown })?.prompt).trim();
+ const isRunning = isToolCallRunning(status);
+ const localResult = sandboxMediaResult(result);
+ const videoFile = localResult?.files?.find((file) =>
+ VIDEO_FILE.test(file.name),
+ );
+ const [open, setOpen] = useState(true);
+ const errorText = toolErrorText(result);
+ const runningLabel = "Generating video…";
+
+ if (!videoFile && isRunning) {
+ return (
+ <div className="aui-tool-fallback-root w-full py-1">
+ <GeneratedImagePlaceholder label={runningLabel} />
+ </div>
+ );
+ }
+ const completedLabel = errorText
+ ? notGeneratedLabel("Video", errorText)
+ : prompt
+ ? `Generated video: ${prompt.length > 80 ? `${prompt.slice(0, 80)}…` : prompt}`
+ : "Generated video";
+
+ return (
+ <ToolFallbackRoot open={open} onOpenChange={setOpen}>
+ <ToolFallbackTrigger
+ toolName={isRunning ? runningLabel : completedLabel}
+ status={status}
+ icon={VideoIcon}
+ />
+ <ToolFallbackContent>
+ {errorText ? (
+ <p className="text-xs leading-5 text-muted-foreground">{errorText}</p>
+ ) : null}
+ {localResult && videoFile ? (
+ <SandboxMediaFigure
+ kind="video"
+ url={sandboxFilePath(localResult.sessionId, videoFile.name)}
+ filename={baseName(videoFile.name)}
+ title={prompt || "Generated video"}
+ caption={prompt}
+ />
+ ) : null}
+ </ToolFallbackContent>
+ </ToolFallbackRoot>
+ );
+};
+
+export const VideoGenerationToolUI = memo(
+ VideoGenerationToolUIImpl,
+) as unknown as ToolCallMessagePartComponent;
+VideoGenerationToolUI.displayName = "VideoGenerationToolUI";
diff --git a/studio/frontend/src/components/assistant-ui/use-sandbox-image.ts b/studio/frontend/src/components/assistant-ui/use-sandbox-image.ts
index 892e393503f..03c161faf39 100644
--- a/studio/frontend/src/components/assistant-ui/use-sandbox-image.ts
+++ b/studio/frontend/src/components/assistant-ui/use-sandbox-image.ts
@@ -20,14 +20,18 @@ const IDLE: SandboxImageState = { status: "idle" };
* `<img src>` hitting it straight gets a 401 and the renderer's "Image not available" placeholder.
* Pass the URL from `sandboxFilePath()`/`markdownSandboxImageSrc()` and render what comes back.
*
+ * Any element can hold the ref (a `<video>` for a generated clip); it only marks where the file shows.
+ *
* Keyed by url: an element that moves to another file reads idle rather than showing the previous
* file's blob, and a stale response can never write state for a url it was not fetched for.
*/
-export function useSandboxImage(url: string | null): {
- ref: RefObject<HTMLImageElement | null>;
+export function useSandboxImage<T extends Element = HTMLImageElement>(
+ url: string | null,
+): {
+ ref: RefObject<T | null>;
state: SandboxImageState;
} {
- const ref = useRef<HTMLImageElement>(null);
+ const ref = useRef<T>(null);
const [state, setState] = useState<{
url: string | null;
load: SandboxImageState;
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index e14a3b233d2..f3c73bb6ef3 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -285,6 +285,7 @@ import {
awaitPendingQwenDefaultsMigration,
flushPendingChatSettings,
codeToolsOn,
+ localMediaToolsForTurn,
useChatRuntimeStore,
} from "../stores/chat-runtime-store";
import {
@@ -2314,6 +2315,7 @@ export async function buildLocalTokenCountExtras(
userTexts(messages),
);
const browserTools = browserAgentToolsForTurn();
+ const localMediaTools = localMediaToolsForTurn(state);
if (
!toolsEnabled &&
!codeToolsEnabled &&
@@ -2321,6 +2323,7 @@ export async function buildLocalTokenCountExtras(
!ragOn &&
!deepResearchEnabled &&
browserTools.length === 0 &&
+ localMediaTools.length === 0 &&
skillTools.length === 0
) {
// Explicit false, not omission: the server defaults tools on. The permission level rides
@@ -2353,6 +2356,7 @@ export async function buildLocalTokenCountExtras(
// match the request gate so token pricing includes only sent skill tools.
...skillTools,
...browserTools,
+ ...localMediaTools,
],
mcp_enabled: mcpEnabledForChat,
// Top level, not inside rag_scope: an archived thread puts search_conversation and its
@@ -5220,10 +5224,9 @@ export function createOpenAIStreamAdapter(
externalRouting.kind === "external" ? externalRouting.modelId : "";
// Image-generation flag; computed first so Gemini image mode can suppress Search/Code.
- const imageGenerationEnabledForThisTurn = Boolean(
+ const hostedImageGenerationForThisTurn = Boolean(
externalProvider &&
externalSelection &&
- imageToolsEnabled &&
providerSupportsBuiltinImageGeneration(
externalProvider.providerType,
externalSelection.modelId,
@@ -5231,6 +5234,16 @@ export function createOpenAIStreamAdapter(
externalProvider.apiType,
),
);
+ const imageGenerationEnabledForThisTurn =
+ imageToolsEnabled && hostedImageGenerationForThisTurn;
+ // Otherwise the Images pill renders on the image or video model loaded in Unsloth.
+ const localMediaTools = localMediaToolsForTurn({
+ imageToolsEnabled,
+ supportsBuiltinImageGeneration: hostedImageGenerationForThisTurn,
+ supportsTools: supportsStudioToolsForThisTurn,
+ localImageModelReady: runtime.localImageModelReady,
+ localVideoModelReady: runtime.localVideoModelReady,
+ });
// Per-model Search/Code allowances live in providerSupportsBuiltin*; this flag only signals image-mode.
const geminiImageModeForThisTurn =
externalProvider?.providerType === "gemini" &&
@@ -6669,7 +6682,8 @@ export function createOpenAIStreamAdapter(
hostedCodeToolsForThisTurn.length > 0 ||
(supportsStudioToolsForThisTurn &&
studioLocalCodeTools.length > 0),
- images: imageGenerationEnabledForThisTurn,
+ images:
+ imageGenerationEnabledForThisTurn || localMediaTools.length > 0,
mcp: supportsStudioToolsForThisTurn && mcpEnabledForChat,
docs:
supportsStudioToolsForThisTurn &&
@@ -6858,6 +6872,7 @@ export function createOpenAIStreamAdapter(
projectRagEnabled ||
skillTools.length > 0 ||
browserTools.length > 0 ||
+ localMediaTools.length > 0 ||
// Armed research needs Studio's loop: deep_research is appended past every tool filter, but
// only for a request that asked for the loop at all.
deepResearchArmed)
@@ -6871,6 +6886,7 @@ export function createOpenAIStreamAdapter(
...skillTools,
...studioLocalCodeTools,
...browserTools,
+ ...localMediaTools,
// Hosted tools with no local stand-in; their pills stay lit regardless, so listing only local
// names dropped Images/Fetch whenever another tool selected this branch. Search is excluded
// (Unsloth runs it above); Code rides along only when it resolved to the provider's sandbox.
@@ -7093,6 +7109,7 @@ export function createOpenAIStreamAdapter(
projectRagEnabled ||
skillTools.length > 0 ||
browserTools.length > 0 ||
+ localMediaTools.length > 0 ||
deepResearchArmed)
? {
enable_tools: true,
@@ -7107,6 +7124,7 @@ export function createOpenAIStreamAdapter(
? ["python", "terminal", "edit_file", "view_image"]
: []),
...browserTools,
+ ...localMediaTools,
],
mcp_enabled: mcpEnabledForChat,
// Scope: thread_id = this thread's docs, kb_id = a KB, project_id = the thread's project
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 6c218be88b1..2fd304c3374 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -85,6 +85,15 @@ import {
import { isNpuModelId } from "@/features/npu";
import { GuidedTour, useGuidedTourController } from "@/features/tour";
import { isTauri } from "@/lib/api-base";
+// The images and video barrels export only their pages; the status calls alone keep those pages out of the chat chunk.
+// eslint-disable-next-line no-restricted-imports
+import { getDiffusionStatus } from "@/features/images/api";
+// eslint-disable-next-line no-restricted-imports
+import { getVideoStatus } from "@/features/video/api";
+import {
+ subscribeModelEjected,
+ subscribeModelLifecycle,
+} from "@/lib/model-lifecycle-events";
import { useDocumentFlag } from "@/lib/document-flag";
import { chatModelLoaded } from "./lib/chat-model-loaded";
import { hasKnownContextWindow } from "./lib/context-window-known";
@@ -254,6 +263,7 @@ import {
CHAT_WEB_FETCH_TOOLS_ENABLED_KEY,
PENDING_CHAT_ATTACHMENT_KEY,
loadOptionalBool,
+ localMediaReadyFromStatus,
noteEffortDisplacedByPin,
pinHoldsLiveEffort,
readPendingAttachmentTargetClaim,
@@ -3202,9 +3212,11 @@ export function ChatPage({
supportsBuiltinWebFetch,
toolsEnabled: nextToolsEnabled,
codeToolsEnabled: canRunCode ? (storedCodeToolsEnabled ?? false) : false,
- imageToolsEnabled: supportsBuiltinImageGeneration
- ? (storedImageToolsEnabled ?? false)
- : false,
+ // Unsloth-tools models can render on the loaded image model; readiness gates the pill, not this.
+ imageToolsEnabled:
+ supportsBuiltinImageGeneration || supportsStudioToolsHere
+ ? (storedImageToolsEnabled ?? false)
+ : false,
// Default Fetch off (Anthropic bills per fetch); deliberate opt-in.
webFetchToolsEnabled: supportsBuiltinWebFetch
? (storedWebFetchToolsEnabled ?? false)
@@ -3213,6 +3225,47 @@ export function ChatPage({
// Reruns once settings hydrate: this normalization reads the stored pills and clamps them to the
// model, and hydration refreshes what it reads, so it has to be applied last.
}, [externalProvidersForChat, inferenceCheckpoint, settingsHydrated]);
+ // The Images pill can use the image or video model loaded in Unsloth. Re-read on mount,
+ // when any load settles (a chat load can evict them), when either is ejected, and on focus.
+ useEffect(() => {
+ let disposed = false;
+ let controller: AbortController | null = null;
+ const refresh = () => {
+ controller?.abort();
+ const current = new AbortController();
+ controller = current;
+ void Promise.allSettled([
+ getDiffusionStatus(current.signal),
+ getVideoStatus(current.signal),
+ ]).then(([image, video]) => {
+ if (disposed || current.signal.aborted) return;
+ useChatRuntimeStore
+ .getState()
+ .setLocalMediaModelsReady(
+ localMediaReadyFromStatus(
+ image.status === "fulfilled" ? image.value : null,
+ video.status === "fulfilled" ? video.value : null,
+ ),
+ );
+ });
+ };
+ refresh();
+ const unsubscribers = [
+ subscribeModelLifecycle(({ loading }) => {
+ if (!loading) refresh();
+ }),
+ subscribeModelEjected("image", refresh),
+ subscribeModelEjected("video", refresh),
+ ];
+ // An idle unload, another tab or an MCP client changes them with no event in this tab.
+ window.addEventListener("focus", refresh);
+ unsubscribers.push(() => window.removeEventListener("focus", refresh));
+ return () => {
+ disposed = true;
+ controller?.abort();
+ for (const unsubscribe of unsubscribers) unsubscribe();
+ };
+ }, []);
// Another tab can change the active model's pin (the pin store listens for the storage event),
// and the normalization above reads the pin through a getState helper without subscribing, so
// the composer kept the old level until a switch. Only the effort here: the pills and the rest
@@ -4009,9 +4062,10 @@ export function ChatPage({
codeToolsEnabled: canRunCode
? (storedCodeToolsEnabled ?? false)
: false,
- imageToolsEnabled: supportsBuiltinImageGeneration
- ? (storedImageToolsEnabled ?? false)
- : false,
+ imageToolsEnabled:
+ supportsBuiltinImageGeneration || supportsStudioToolsHere
+ ? (storedImageToolsEnabled ?? false)
+ : false,
webFetchToolsEnabled: supportsBuiltinWebFetch
? (storedWebFetchToolsEnabled ?? false)
: false,
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index bb056cb2641..0195793318d 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -230,6 +230,8 @@ import {
resolveSpeculativeSettingsForLoad,
saveSpeculativeType,
codeToolsOn,
+ localImagePillCount,
+ localImageTool,
useChatRuntimeStore,
} from "./stores/chat-runtime-store";
import {
@@ -1012,9 +1014,20 @@ export function SharedComposer({
// Gemini rejects codeExecution alongside image modalities. Search is blocked on older Gemini image
// ids but allowed on Gemini 3 image models, so only Code is disabled unconditionally there.
const isExternalGemini = selectedExternalProvider?.providerType === "gemini";
- const imageDisabled = !modelLoaded || !supportsBuiltinImageGeneration;
+ // The image or video model loaded in Unsloth, reached through generate_image / generate_video.
+ const localImageToolHere = useChatRuntimeStore((s) =>
+ localImageTool({ ...s, supportsBuiltinImageGeneration }),
+ );
+ const localImagePills = useChatRuntimeStore((s) =>
+ localImagePillCount({ ...s, supportsBuiltinImageGeneration }),
+ );
+ const imageDisabled =
+ !modelLoaded || !(supportsBuiltinImageGeneration || localImageToolHere);
const imageModeDisablesCode =
- isExternalGemini && imageToolsEnabled && !imageDisabled;
+ isExternalGemini &&
+ imageToolsEnabled &&
+ modelLoaded &&
+ supportsBuiltinImageGeneration;
// Image-tier Gemini models always reject codeExecution and reject web_search on older ids, so gate
// strictly on provider builtin support: local `supportsTools` must not re-enable a pill the
// Gemini backend silently drops.
@@ -1046,9 +1059,10 @@ export function SharedComposer({
const codeDisabled =
(modelLoaded && (isGeminiImageTier || !canRunCode)) ||
imageModeDisablesCode;
- // Images pill lights only on OpenAI cloud Responses-API models and the Gemini Nano Banana
- // family. No local tool runtime fallback.
- const showImagePill = supportsBuiltinImageGeneration;
+ // Images pill: the provider's own image generation on OpenAI cloud Responses-API models and the
+ // Gemini Nano Banana family, else the image or video model loaded in Unsloth when the chat
+ // model calls Unsloth tools.
+ const showImagePill = supportsBuiltinImageGeneration || localImageToolHere;
// Fetch pill: Anthropic-only (web_fetch_20250910 / web_fetch_20260209).
const webFetchDisabled = !modelLoaded || !supportsBuiltinWebFetch;
const showWebFetchPill = supportsBuiltinWebFetch;
@@ -1060,7 +1074,8 @@ export function SharedComposer({
const isMobile = useIsMobile();
const pillCount =
4 +
- (showImagePill ? 1 : 0) +
+ (supportsBuiltinImageGeneration ? 1 : 0) +
+ localImagePills +
(showRagPill && ragEnabled ? 1 : 0) +
(showWebFetchPill ? 1 : 0) +
(mcpEnabledForChat ? 1 : 0);
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index 27989e01014..8798026e46c 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -1083,12 +1083,88 @@ function isPillClampedOff(
> = {
toolsEnabled: state.supportsTools || state.supportsBuiltinWebSearch,
codeToolsEnabled: state.supportsTools || state.supportsBuiltinCodeExecution,
- imageToolsEnabled: state.supportsBuiltinImageGeneration,
+ // Capability, not readiness: the image model coming and going must not drop a chat's Images pref.
+ imageToolsEnabled:
+ state.supportsBuiltinImageGeneration || state.supportsTools,
webFetchToolsEnabled: state.supportsBuiltinWebFetch,
};
return !capable[key];
}
+type LocalMediaToolState = Pick<
+ ChatRuntimeStore,
+ | "supportsTools"
+ | "supportsBuiltinImageGeneration"
+ | "localImageModelReady"
+ | "localVideoModelReady"
+>;
+
+/**
+ * The Images pill runs on the image or video model loaded in Unsloth: the chat
+ * model calls Unsloth tools and one of them is resident. A hosted image model
+ * keeps its own image_generation, so it wins.
+ */
+export function localImageTool(s: LocalMediaToolState): boolean {
+ return (
+ !s.supportsBuiltinImageGeneration &&
+ s.supportsTools &&
+ (s.localImageModelReady || s.localVideoModelReady)
+ );
+}
+
+/** Whether the Images pill and + menu item show for this model. */
+export function imageToolAvailable(s: LocalMediaToolState): boolean {
+ return s.supportsBuiltinImageGeneration || localImageTool(s);
+}
+
+/** The local pill takes composer room only while it is on, like RAG; the hosted pill counts as before. */
+export function localImagePillCount(
+ s: LocalMediaToolState & Pick<ChatRuntimeStore, "imageToolsEnabled">,
+): number {
+ return localImageTool(s) && s.imageToolsEnabled ? 1 : 0;
+}
+
+/** The local media tools a turn sends in enabled_tools; never the hosted "image_generation". */
+export function localMediaToolsForTurn(
+ s: LocalMediaToolState & Pick<ChatRuntimeStore, "imageToolsEnabled">,
+): string[] {
+ if (!s.imageToolsEnabled || !localImageTool(s)) return [];
+ return [
+ ...(s.localImageModelReady ? ["generate_image"] : []),
+ ...(s.localVideoModelReady ? ["generate_video"] : []),
+ ];
+}
+
+type MediaStatusSnapshot = {
+ loaded?: boolean;
+ /** False when the resident model belongs to another account this one may not use. */
+ yours?: boolean;
+ workflows?: string[] | null;
+ h3_task?: string | null;
+} | null;
+
+/**
+ * Whether the image and video status responses leave a model this account can render on.
+ * A hidden resident answers `{loaded: true, yours: false}`; the backend never offers the
+ * tool for it, so it is not ready here either. An edit-only image model is not ready.
+ */
+export function localMediaReadyFromStatus(
+ image: MediaStatusSnapshot,
+ video: MediaStatusSnapshot,
+): { image: boolean; video: boolean } {
+ return {
+ image: Boolean(
+ image?.loaded &&
+ image.yours !== false &&
+ (!image.workflows || image.workflows.includes("txt2img")),
+ ),
+ // Ref2VA needs reference media the chat tool never sends.
+ video: Boolean(
+ video?.loaded && video.yours !== false && video.h3_task !== "ref2va",
+ ),
+ };
+}
+
/** Sampling keys share `params` with the model's recommendation, so a load in this window
* would pin the model's value onto the chat. Captured at the edit; last entry wins. */
function heldThreadScopedParamValue(key: string): unknown {
@@ -2459,6 +2535,10 @@ type ChatRuntimeStore = {
supportsBuiltinWebFetch: boolean;
/** mirrors the backend Settings switch "Keep multiple models loaded". */
keepModelsLoaded: boolean;
+ /** A text-to-image model is loaded in Unsloth, so the Images pill can offer generate_image. Not persisted. */
+ localImageModelReady: boolean;
+ /** A video model is loaded in Unsloth, so the Images pill can offer generate_video. Not persisted. */
+ localVideoModelReady: boolean;
toolsEnabled: boolean;
/** persisted Code preference; codeToolsOn() gives the effective value. */
codeToolsEnabled: boolean;
@@ -2770,6 +2850,7 @@ type ChatRuntimeStore = {
setPreserveThinking: (value: boolean) => void;
setToolsEnabled: (enabled: boolean, options?: { persist?: boolean }) => void;
setKeepModelsLoaded: (keep: boolean) => void;
+ setLocalMediaModelsReady: (ready: { image: boolean; video: boolean }) => void;
setCodeToolsEnabled: (enabled: boolean) => void;
setImageToolsEnabled: (enabled: boolean) => void;
setDeepResearchEnabled: (enabled: boolean) => void;
@@ -4348,6 +4429,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
supportsBuiltinWebFetch: false,
toolsEnabled: loadBool(CHAT_TOOLS_ENABLED_KEY, false),
keepModelsLoaded: false,
+ localImageModelReady: false,
+ localVideoModelReady: false,
codeToolsEnabled: loadBool(CHAT_CODE_TOOLS_ENABLED_KEY, false),
codeToolsDeclinedUnderFullAccess: false,
imageToolsEnabled: loadBool(CHAT_IMAGE_TOOLS_ENABLED_KEY, false),
@@ -5571,6 +5654,12 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
};
}),
setKeepModelsLoaded: (keepModelsLoaded) => set({ keepModelsLoaded }),
+ setLocalMediaModelsReady: ({ image, video }) =>
+ set((state) =>
+ state.localImageModelReady === image && state.localVideoModelReady === video
+ ? state
+ : { localImageModelReady: image, localVideoModelReady: video },
+ ),
setCodeToolsEnabled: (codeToolsEnabled) =>
set((state) => {
saveBool(CHAT_CODE_TOOLS_ENABLED_KEY, codeToolsEnabled);
diff --git a/studio/frontend/tests/chat-barrel-module-scope-reads.test.ts b/studio/frontend/tests/chat-barrel-module-scope-reads.test.ts
index 6b2c753669e..57164292bf2 100644
--- a/studio/frontend/tests/chat-barrel-module-scope-reads.test.ts
+++ b/studio/frontend/tests/chat-barrel-module-scope-reads.test.ts
@@ -1523,6 +1523,7 @@ const KNOWN_DEEP_CYCLE_READS = new Map<string, number>([
["components/assistant-ui/thread.tsx: RenderHtmlToolUI", 1],
["components/assistant-ui/thread.tsx: Sources", 1],
["components/assistant-ui/thread.tsx: TerminalToolUI", 1],
+ ["components/assistant-ui/thread.tsx: VideoGenerationToolUI", 1],
["components/assistant-ui/thread.tsx: ToolFallback", 1],
["components/assistant-ui/thread.tsx: WebSearchToolUI", 1],
["components/ui/sidebar.tsx: SIDEBAR_WIDTH_DEFAULT", 1],
diff --git a/studio/frontend/tests/chat-images-local-tool.test.ts b/studio/frontend/tests/chat-images-local-tool.test.ts
new file mode 100644
index 00000000000..177bdb90eea
--- /dev/null
+++ b/studio/frontend/tests/chat-images-local-tool.test.ts
@@ -0,0 +1,207 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The Images pill on a local or Unsloth Studio-tools model renders on the image or video
+// model loaded in Unsloth Studio (generate_image / generate_video); a hosted image model
+// keeps the provider's own image_generation.
+
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+import { installLocalStorageFake, readSrc } from "./helpers/kit.ts";
+
+const { store: localStorageFake } = installLocalStorageFake();
+localStorageFake.set("unsloth_chat_settings_imported_to_studio_db", "true");
+register("./thread-sampling-resolver.mjs", import.meta.url);
+await import("./helpers/store-stubs/settings-http.ts");
+await import("./helpers/store-stubs/chat-history-storage.ts");
+
+type MediaState = {
+ supportsTools: boolean;
+ supportsBuiltinImageGeneration: boolean;
+ localImageModelReady: boolean;
+ localVideoModelReady: boolean;
+ imageToolsEnabled: boolean;
+};
+
+const store = await import("../src/features/chat/stores/chat-runtime-store.ts");
+const { localImageTool, imageToolAvailable, localImagePillCount, localMediaToolsForTurn } =
+ store as unknown as {
+ localImageTool: (s: MediaState) => boolean;
+ imageToolAvailable: (s: MediaState) => boolean;
+ localImagePillCount: (s: MediaState) => number;
+ localMediaToolsForTurn: (s: MediaState) => string[];
+ };
+const runtime = store.useChatRuntimeStore as unknown as {
+ getState: () => MediaState & {
+ setImageToolsEnabled: (on: boolean) => void;
+ setLocalMediaModelsReady: (ready: { image: boolean; video: boolean }) => void;
+ };
+ setState: (patch: Record<string, unknown>) => void;
+};
+
+const LOCAL: MediaState = {
+ supportsTools: true,
+ supportsBuiltinImageGeneration: false,
+ localImageModelReady: true,
+ localVideoModelReady: false,
+ imageToolsEnabled: true,
+};
+const HOSTED: MediaState = { ...LOCAL, supportsBuiltinImageGeneration: true };
+
+test("a hosted image model keeps its builtin; a local turn sends the loaded media models' tools", () => {
+ assert.deepEqual(localMediaToolsForTurn(HOSTED), []);
+ assert.deepEqual(localMediaToolsForTurn({ ...HOSTED, localVideoModelReady: true }), []);
+ assert.deepEqual(localMediaToolsForTurn(LOCAL), ["generate_image"]);
+ assert.deepEqual(localMediaToolsForTurn({ ...LOCAL, localVideoModelReady: true }), [
+ "generate_image",
+ "generate_video",
+ ]);
+ assert.deepEqual(
+ localMediaToolsForTurn({ ...LOCAL, localImageModelReady: false, localVideoModelReady: true }),
+ ["generate_video"],
+ );
+ // Off, no Unsloth Studio tools, or nothing loaded: nothing is sent.
+ assert.deepEqual(localMediaToolsForTurn({ ...LOCAL, imageToolsEnabled: false }), []);
+ assert.deepEqual(localMediaToolsForTurn({ ...LOCAL, supportsTools: false }), []);
+ assert.deepEqual(localMediaToolsForTurn({ ...LOCAL, localImageModelReady: false }), []);
+ for (const state of [LOCAL, HOSTED, { ...LOCAL, localVideoModelReady: true }]) {
+ assert.ok(!localMediaToolsForTurn(state).includes("image_generation"));
+ }
+});
+
+test("the pill shows for a hosted image model or a tools model with a media model loaded", () => {
+ assert.equal(imageToolAvailable(HOSTED), true);
+ assert.equal(imageToolAvailable({ ...HOSTED, supportsTools: false }), true);
+ assert.equal(imageToolAvailable(LOCAL), true);
+ assert.equal(imageToolAvailable({ ...LOCAL, imageToolsEnabled: false }), true);
+ assert.equal(imageToolAvailable({ ...LOCAL, supportsTools: false }), false);
+ assert.equal(imageToolAvailable({ ...LOCAL, localImageModelReady: false }), false);
+ assert.equal(localImageTool(HOSTED), false, "hosted wins over the local tool");
+});
+
+test("the local pill takes composer room only while on; the hosted pill is counted apart", () => {
+ assert.equal(localImagePillCount({ ...LOCAL, imageToolsEnabled: false }), 0);
+ assert.equal(localImagePillCount(LOCAL), 1);
+ assert.equal(localImagePillCount(HOSTED), 0);
+ // Loading an image model with the pill off keeps the shared composer at 4 pills (labels stay).
+ const sharedComposer = readSrc("features/chat/shared-composer.tsx");
+ assert.match(
+ sharedComposer,
+ /4 \+\s*\(supportsBuiltinImageGeneration \? 1 : 0\) \+\s*localImagePills \+/,
+ );
+ const thread = readSrc("components/assistant-ui/thread.tsx");
+ assert.match(thread, /\(supportsBuiltinImageGeneration \? 1 : 0\) \+\s*localImagePills \+/);
+ assert.ok(thread.includes("useChatRuntimeStore(localImagePillCount)"));
+});
+
+test("both composers show the pill through the shared selector", () => {
+ const sharedComposer = readSrc("features/chat/shared-composer.tsx");
+ assert.ok(
+ sharedComposer.includes(
+ "const showImagePill = supportsBuiltinImageGeneration || localImageToolHere;",
+ ),
+ );
+ assert.match(sharedComposer, /localImageTool\(\{ \.\.\.s, supportsBuiltinImageGeneration \}\)/);
+ assert.ok(!sharedComposer.includes("No local tool runtime fallback"));
+ // Gemini's image mode stays hosted-only.
+ assert.match(
+ sharedComposer,
+ /imageModeDisablesCode =\s*isExternalGemini &&\s*imageToolsEnabled &&\s*modelLoaded &&\s*supportsBuiltinImageGeneration;/,
+ );
+ const thread = readSrc("components/assistant-ui/thread.tsx");
+ // ImagesToggle and the + menu.
+ assert.equal(thread.split("useChatRuntimeStore(imageToolAvailable)").length - 1, 2);
+ assert.ok(thread.includes("if (!imageToolShown) {"));
+ assert.ok(thread.includes("{imageToolShown && ("));
+});
+
+test("readiness changes never clear the stored Images preference (D3)", () => {
+ const state = () => runtime.getState();
+ runtime.setState({ supportsTools: true, supportsBuiltinImageGeneration: false });
+ state().setLocalMediaModelsReady({ image: true, video: false });
+ state().setImageToolsEnabled(true);
+ state().setLocalMediaModelsReady({ image: false, video: false });
+ assert.equal(state().imageToolsEnabled, true);
+ assert.equal(state().localImageModelReady, false);
+ state().setLocalMediaModelsReady({ image: true, video: true });
+ assert.equal(state().imageToolsEnabled, true);
+ assert.deepEqual(localMediaToolsForTurn(state()), ["generate_image", "generate_video"]);
+
+ // The clamps key on capability (hosted builtin or Unsloth Studio tools), never on readiness.
+ const storeSource = readSrc("features/chat/stores/chat-runtime-store.ts");
+ assert.match(
+ storeSource,
+ /imageToolsEnabled:\s*state\.supportsBuiltinImageGeneration \|\| state\.supportsTools,/,
+ );
+ const chatPage = readSrc("features/chat/chat-page.tsx");
+ const clamps = chatPage.match(
+ /imageToolsEnabled:\s*supportsBuiltinImageGeneration \|\| supportsStudioToolsHere\s*\?/g,
+ );
+ assert.equal(clamps?.length, 2);
+ assert.ok(!/imageToolsEnabled:[^,]*localImageModelReady/.test(storeSource + chatPage));
+});
+
+test("chat-page refreshes readiness from both status routes and the lifecycle events", () => {
+ const chatPage = readSrc("features/chat/chat-page.tsx");
+ for (const needle of [
+ "getDiffusionStatus(current.signal)",
+ "getVideoStatus(current.signal)",
+ "Promise.allSettled(",
+ "localMediaReadyFromStatus(",
+ "subscribeModelLifecycle(",
+ 'subscribeModelEjected("image", refresh)',
+ 'subscribeModelEjected("video", refresh)',
+ 'window.addEventListener("focus", refresh)',
+ ]) {
+ assert.ok(chatPage.includes(needle), needle);
+ }
+});
+
+test("every adapter tool gate opens for, and every tool list carries, the local media tools", () => {
+ const adapter = readSrc("features/chat/api/chat-adapter.ts");
+ assert.equal(adapter.split("...localMediaTools,").length - 1, 3, "token count, external, local lists");
+ assert.equal(adapter.split("localMediaTools.length > 0 ||").length - 1, 2, "external and local gates");
+ assert.ok(adapter.includes("localMediaTools.length === 0"), "token-count early exit");
+ assert.match(adapter, /images:\s*imageGenerationEnabledForThisTurn \|\| localMediaTools\.length > 0,/);
+ // The hosted name only ever follows the hosted flag.
+ assert.match(
+ adapter,
+ /\.\.\.\(imageGenerationEnabledForThisTurn\s*\?\s*\["image_generation"\]\s*:\s*\[\]\)/,
+ );
+});
+
+test("a hidden or edit-only resident is not ready; one this account may use is", () => {
+ const { localMediaReadyFromStatus } = store as unknown as {
+ localMediaReadyFromStatus: (
+ image: Record<string, unknown> | null,
+ video: Record<string, unknown> | null,
+ ) => { image: boolean; video: boolean };
+ };
+ // Another account's resident, as the status routes answer a managed caller.
+ assert.deepEqual(
+ localMediaReadyFromStatus({ loaded: true, yours: false }, { loaded: true, yours: false }),
+ { image: false, video: false },
+ );
+ assert.deepEqual(
+ localMediaReadyFromStatus(
+ { loaded: true, workflows: ["txt2img", "img2img"] },
+ { loaded: true },
+ ),
+ { image: true, video: true },
+ );
+ // MiniMax-H3 Ref2VA needs reference media the chat tool never sends.
+ assert.deepEqual(
+ localMediaReadyFromStatus(null, { loaded: true, h3_task: "ref2va" }),
+ { image: false, video: false },
+ );
+ assert.deepEqual(
+ localMediaReadyFromStatus({ loaded: true, workflows: ["edit"] }, null),
+ { image: false, video: false },
+ );
+ assert.deepEqual(localMediaReadyFromStatus(null, { loaded: false }), {
+ image: false,
+ video: false,
+ });
+});
diff --git a/studio/frontend/tests/image-sentinel-tools.test.ts b/studio/frontend/tests/image-sentinel-tools.test.ts
index 51b421bb9bb..705cf0fd357 100644
--- a/studio/frontend/tests/image-sentinel-tools.test.ts
+++ b/studio/frontend/tests/image-sentinel-tools.test.ts
@@ -4,10 +4,15 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { readSrc } from "./helpers/kit.ts";
+import { readSrc, readText } from "./helpers/kit.ts";
-const { IMAGE_SENTINEL_TOOLS, SANDBOX_FILE_TOOLS, SANDBOX_RUN_TOOLS, hasCreatedFiles } =
- await import("../src/components/assistant-ui/sandbox-files.ts");
+const {
+ IMAGE_SENTINEL_TOOLS,
+ MEDIA_CHAT_TOOLS,
+ SANDBOX_FILE_TOOLS,
+ SANDBOX_RUN_TOOLS,
+ hasCreatedFiles,
+} = await import("../src/components/assistant-ui/sandbox-files.ts");
test("only the tools that emit the image envelope are in the set", () => {
for (const emitter of ["python", "terminal", "code_execution"]) {
@@ -55,3 +60,44 @@ test("the adapter slices the image envelope only for the tools that emit it", ()
"a second, ungated __IMAGES__ slice appeared",
);
});
+
+test("the media chat tools emit the file envelope, and generate_image the image one", () => {
+ assert.deepEqual([...MEDIA_CHAT_TOOLS].sort(), ["generate_image", "generate_video"]);
+ for (const tool of MEDIA_CHAT_TOOLS) {
+ assert.ok(SANDBOX_FILE_TOOLS.has(tool), `${tool} replays as its text, not the wrapper`);
+ assert.ok(!SANDBOX_RUN_TOOLS.has(tool), `${tool} runs no code`);
+ }
+ assert.ok(IMAGE_SENTINEL_TOOLS.has("generate_image"));
+ // The video is a file, never an __IMAGES__ entry.
+ assert.ok(!IMAGE_SENTINEL_TOOLS.has("generate_video"));
+ assert.ok(
+ hasCreatedFiles("generate_video", {
+ text: "Generated a 4 s video.",
+ images: [],
+ sessionId: "chat-1",
+ files: [{ name: "generated-video-1a2b3c4d.mp4", size: 1024 }],
+ }),
+ );
+});
+
+test("the frontend media tool set matches the backend's", () => {
+ const backend = readText("../../backend/core/inference/media_chat_tools.py");
+ const match = backend.match(/^MEDIA_CHAT_TOOLS = frozenset\(\{([^}]*)\}\)/m);
+ assert.ok(match, "media_chat_tools.py no longer declares MEDIA_CHAT_TOOLS as a frozenset literal");
+ const names = [...match[1].matchAll(/"([^"]+)"/g)].map((m) => m[1]).sort();
+ assert.deepEqual(names, [...MEDIA_CHAT_TOOLS].sort());
+});
+
+test("the hosted image tool name is never stripped as a local media tool, nor the reverse", () => {
+ // SERVER_SIDE_BUILTIN_TOOL_NAMES drops a part from outbound history; the local tools' results
+ // are real tool messages the model must see again.
+ for (const path of ["features/chat/utils/provider-compaction.ts", "features/chat/api/chat-adapter.ts"]) {
+ const source = readSrc(path);
+ const start = source.indexOf("const SERVER_SIDE_BUILTIN_TOOL_NAMES");
+ assert.ok(start >= 0, path);
+ const block = source.slice(start, source.indexOf("]);", start));
+ assert.ok(block.includes('"image_generation"'), path);
+ for (const tool of MEDIA_CHAT_TOOLS) assert.ok(!block.includes(tool), `${path}: ${tool}`);
+ }
+ assert.ok(!MEDIA_CHAT_TOOLS.has("image_generation"));
+});
diff --git a/tests/studio/test_generate_image_frontend_contract.py b/tests/studio/test_generate_image_frontend_contract.py
new file mode 100644
index 00000000000..82684579e7a
--- /dev/null
+++ b/tests/studio/test_generate_image_frontend_contract.py
@@ -0,0 +1,81 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The chat Images pill reaches generate_image / generate_video on the models loaded in Unsloth Studio."""
+
+import re
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+FRONTEND = ROOT / "studio" / "frontend" / "src"
+BACKEND = ROOT / "studio" / "backend"
+
+
+def source(path: str) -> str:
+ return (FRONTEND / path).read_text(encoding = "utf-8")
+
+
+def _names(literal: str) -> set[str]:
+ return set(re.findall(r'"([^"]+)"', literal))
+
+
+def test_media_chat_tools_match_backend() -> None:
+ backend = (BACKEND / "core" / "inference" / "media_chat_tools.py").read_text(encoding = "utf-8")
+ frontend = source("components/assistant-ui/sandbox-files.ts")
+ backend_set = re.search(r"^MEDIA_CHAT_TOOLS = frozenset\(\{([^}]*)\}\)", backend, re.M)
+ frontend_set = re.search(
+ r"export const MEDIA_CHAT_TOOLS[^=]*= new Set\(\[([^\]]*)\]\)", frontend
+ )
+ assert backend_set and frontend_set
+ assert (
+ _names(backend_set.group(1))
+ == _names(frontend_set.group(1))
+ == {
+ "generate_image",
+ "generate_video",
+ }
+ )
+ assert "...MEDIA_CHAT_TOOLS," in frontend
+ # The fold exemption reads the same set.
+ assert "MEDIA_CHAT_TOOLS.has(" in source("components/assistant-ui/tool-fold-exemptions.ts")
+
+
+def test_thread_registers_both_media_cards() -> None:
+ thread = source("components/assistant-ui/thread.tsx")
+ assert "generate_image: ImageGenerationToolUIConfirmable," in thread
+ assert "generate_video: VideoGenerationToolUIConfirmable," in thread
+ assert "const VideoGenerationToolUIConfirmable = withToolConfirmation(" in thread
+ assert "image_generation: ImageGenerationToolUIConfirmable," in thread
+
+
+def test_adapter_sends_local_media_tools_on_every_path() -> None:
+ adapter = source("features/chat/api/chat-adapter.ts")
+ assert adapter.count("...localMediaTools,") == 3
+ assert adapter.count("localMediaTools.length > 0 ||") == 2
+ assert "localMediaTools.length === 0" in adapter
+
+
+def test_local_results_have_no_edit_and_video_plays_from_the_sandbox() -> None:
+ card = source("components/assistant-ui/tool-ui-image-generation.tsx")
+ # Edit stays on the hosted figure only; the sandbox figure has Download alone.
+ sandbox_figure = card[
+ card.index("function SandboxMediaFigure(") : card.index(
+ "function GeneratedImagePlaceholder"
+ )
+ ]
+ assert "Edit" not in sandbox_figure and "openOverlay" not in sandbox_figure
+ assert "useSandboxImage<HTMLDivElement>(url)" in sandbox_figure
+ assert "<video" in sandbox_figure and 'preload="metadata"' in sandbox_figure
+ video = card[card.index("const VideoGenerationToolUIImpl") :]
+ assert 'kind="video"' in video and "sandboxFilePath(" in video
+ assert "export function useSandboxImage<T extends Element = HTMLImageElement>(" in source(
+ "components/assistant-ui/use-sandbox-image.ts"
+ )
+
+
+def test_details_sheet_labels_media_tools() -> None:
+ sheet = source("components/assistant-ui/message-response-details-sheet.tsx")
+ assert 'generate_image: "Images",' in sheet
+ assert 'generate_video: "Video",' in sheet
+ assert 'normalized === "generate_video"' in sheet