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.

Revert 11 PRs merged before review converged (#12569)

Etherlb1da4866a051
diff --git a/studio/backend/core/inference/chat_generation_runs.py b/studio/backend/core/inference/chat_generation_runs.py
index c01a48bfbd1..953de0a5f28 100644
--- a/studio/backend/core/inference/chat_generation_runs.py
+++ b/studio/backend/core/inference/chat_generation_runs.py
@@ -36,10 +36,9 @@ _SHUTDOWN_CANCEL_SECONDS = 5.0
# force-kills the backend after five seconds.
_SWEEP_SHUTDOWN_SECONDS = 0.5
# A durable run sets cancel_on_disconnect=False, so reaping is keyed on progress rather than on connectedness. The
-# default matches llama_cpp._DEFAULT_FIRST_TOKEN_TIMEOUT_S: that path renews on advancing ``prompt_progress``, and this
-# lease renews on the ``: prefill-progress`` stand-in the routes emit when those frames are dropped for the UI. Slow
-# decode is safe at any speed via streamed chunks. A century: clear of any real lease, far below where integer
-# milliseconds overflow.
+# default matches llama_cpp._DEFAULT_FIRST_TOKEN_TIMEOUT_S, the request path's own first-token budget: a lease older
+# than that cannot be legitimate prefill, and slow decode is safe at any speed. A century: clear of any real lease, far
+# below where integer milliseconds overflow.
_MAX_ENV_SECONDS = 100.0 * 365.0 * 24.0 * 60.0 * 60.0
# The longest admission keep-alive cadence worth deriving a lease from. A day already means the queue never reports,
# and tripling it stays far inside _MAX_ENV_SECONDS.
@@ -403,9 +402,6 @@ _ADMISSION_WAIT_MARKER = ": admission-wait"
_ADMISSION_DONE_MARKER = ": admission-done"
# A server-side tool still running. Rate limited like the wait marker.
_TOOL_HEARTBEAT_MARKER = ": tool-heartbeat"
-# Prefill still advancing while prompt_progress frames are dropped for the UI. Same lease
-# contract as the tool heartbeat; not a stall keep-alive.
-_PREFILL_PROGRESS_MARKER = ": prefill-progress"
def _minimum_lease_seconds() -> float:
@@ -808,22 +804,15 @@ class ChatGenerationSupervisor:
break
next_raw_task = asyncio.create_task(iterator.__anext__())
text = raw.decode("utf-8", "replace") if isinstance(raw, bytes) else str(raw)
- # Admission / tool / prefill comments are progress; plain keep-alives are not. A
- # queued run only emits `: admission-wait`, which _SSEDecoder drops, so nothing
- # renewed the lease and a healthy queue reaped its own runs. `: keep-alive` is the
- # opposite signal, emitted when the generator has produced NOTHING, so renewing on
- # any byte would keep a wedged run alive forever. Prefill drops ``prompt_progress``
- # for clients that did not ask for it and stands in with `: prefill-progress`
- # (same idea as `: tool-heartbeat`). Rate limited because chunk traffic already
+ # Admission comments are progress; plain keep-alives are not. A queued run only emits `:
+ # admission-wait`, which _SSEDecoder drops, so nothing renewed the lease and a healthy queue reaped its
+ # own runs. `: keep-alive` is the opposite signal, emitted when the generator has produced NOTHING, so
+ # renewing on any byte would keep a wedged run alive forever. Rate limited because chunk traffic already
# renews through append_events.
if _ADMISSION_DONE_MARKER in text:
last_keepalive = time.monotonic()
await self._try_touch_progress(run_id)
- elif (
- _ADMISSION_WAIT_MARKER in text
- or _TOOL_HEARTBEAT_MARKER in text
- or _PREFILL_PROGRESS_MARKER in text
- ):
+ elif _ADMISSION_WAIT_MARKER in text or _TOOL_HEARTBEAT_MARKER in text:
now_s = time.monotonic()
if now_s - last_keepalive >= _renew_interval_seconds():
last_keepalive = now_s
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 0def3f744e2..3921b44d057 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -240,15 +240,6 @@ from .diffusion_precision import (
torchao_quantize_importable,
)
from .diffusion_te_prequant import te_prequant_pipe_kwargs
-from .diffusion_flow_shift import apply_comfy_flow_shift
-from .diffusion_text_length import (
- IDEOGRAM4_COMFY_GUIDANCE,
- IDEOGRAM4_COMFY_MU,
- IDEOGRAM4_COMFY_STD,
- ideogram4_comfy_guidance_schedule,
- flux_t5_kwarg,
- true_cfg_needs_empty_negative,
-)
from .diffusion_denoiser_prequant import (
DENOISER_COMPONENT,
PIPELINE_SEED_DECLINED,
@@ -6996,8 +6987,6 @@ class DiffusionBackend:
)
self._raise_if_load_cancelled(_load_token)
- # Sample at ComfyUI's static sigma shift where the shipped scheduler differs (before from_pipe copies it).
- apply_comfy_flow_shift(pipe, getattr(fam, "comfy_flow_shift", None), logger)
# Before the speed optims so their decode compile lands inside the non-finite check; `off` keeps fp32.
vae_fp16 = str(
speed_mode or ""
@@ -9416,20 +9405,7 @@ class DiffusionBackend:
if steps == 48 and abs(float(guidance) - 7.0) < 1e-6:
kwargs.pop(state.family.cfg_kwarg, None)
else:
- # Otherwise ComfyUI's template: its "Default" schedule (mu 0.0, std 1.75; the card taper above
- # keeps the pipeline's mu 0 / std 1.5) and, at the default guidance 7, its CFG override to 3
- # over the last 30% of sampling, as a per-step schedule. Any other guidance stays constant.
- if "mu" in call_params:
- kwargs["mu"] = IDEOGRAM4_COMFY_MU
- if "std" in call_params:
- kwargs["std"] = IDEOGRAM4_COMFY_STD
- if abs(float(guidance) - IDEOGRAM4_COMFY_GUIDANCE) < 1e-6:
- kwargs.pop(state.family.cfg_kwarg, None)
- kwargs["guidance_schedule"] = ideogram4_comfy_guidance_schedule(
- steps, width, height
- )
- else:
- kwargs["guidance_schedule"] = None
+ kwargs["guidance_schedule"] = None
if state.family.name == LUMINA2_FAMILY_NAME and "cfg_trunc_ratio" in call_params:
# Lumina 2's card recipe truncates the CFG double-forward to the first quarter
# (cfg_trunc_ratio=0.25); the 1.0 default oversaturates.
@@ -9461,13 +9437,6 @@ class DiffusionBackend:
kwargs["height"] = ih
if negative_prompt and "negative_prompt" in call_params:
kwargs["negative_prompt"] = negative_prompt
- elif "negative_prompt" in call_params and true_cfg_needs_empty_negative(
- state.family.cfg_kwarg, guidance
- ):
- # Qwen-Image style pipelines run true CFG only when a negative is PRESENT, so a blank negative
- # silently dropped CFG while the UI showed guidance 4. ComfyUI encodes an empty negative and
- # applies CFG; do the same.
- kwargs["negative_prompt"] = ""
if workflow == "controlnet" and control_pil is not None:
# CN pipeline takes the control map + scale; guidance start/end bound its step range. Every kwarg
# is signature-gated.
@@ -9666,11 +9635,6 @@ class DiffusionBackend:
chunk_kwargs["negative_prompt"] = [
chunk_kwargs["negative_prompt"]
] * len(chunk)
- # FLUX.1 T5 length as ComfyUI pads it: 256 for prompts up to 256 tokens (diffusers pads every
- # prompt to 512); longer prompts keep the 512 bucket. Per chunk, since a prompts list varies.
- t5_len = flux_t5_kwarg(state.family.name, pipe, call_params, chunk_kwargs)
- if t5_len is not None:
- chunk_kwargs["max_sequence_length"] = t5_len
# A step cache keys residuals on the cond/uncond context, which a graph key
# cannot see. Per chunk because an AUTO decision is re-taken per generation.
if state.cuda_graphs:
diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.py
index 21bc614705e..8889e1158e0 100644
--- a/studio/backend/core/inference/diffusion_families.py
+++ b/studio/backend/core/inference/diffusion_families.py
@@ -113,9 +113,6 @@ class DiffusionFamily:
max_output_pixels: int = 2048 * 2048
# Accepted condition-image preprocessing resolutions (square side, by area); empty = no such control.
reference_resolutions: tuple[int, ...] = field(default_factory = tuple)
- # Static sigma shift ComfyUI samples this family with; the loader rebuilds the scheduler at it. None = keep the
- # shipped scheduler.
- comfy_flow_shift: Optional[float] = None
# Activation-guard cost of one condition pixel relative to one output pixel.
condition_pixel_weight: float = 1.0
# Extra lowercased substrings (besides ``name``) that map a repo id here.
@@ -328,7 +325,6 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
# Qwen instruction editing: the 2511 checkpoint ships as QwenImageEditPlusPipeline. Specific aliases first so
# detect_family prefers this over "qwen-image".
name = "qwen-image-edit",
- comfy_flow_shift = 3.1, # ComfyUI ModelSamplingAuraFlow 3.1 (Qwen-Image-Edit 2511 template)
pipeline_class = "QwenImageEditPlusPipeline",
transformer_class = "QwenImageTransformer2DModel",
base_repo = "Qwen/Qwen-Image-Edit-2511",
@@ -346,7 +342,6 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
),
DiffusionFamily(
name = "qwen-image",
- comfy_flow_shift = 3.1, # ComfyUI ModelSamplingAuraFlow 3.1 (Qwen-Image templates)
pipeline_class = "QwenImagePipeline",
transformer_class = "QwenImageTransformer2DModel",
base_repo = "Qwen/Qwen-Image",
@@ -493,7 +488,6 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
),
DiffusionFamily(
name = "z-image",
- comfy_flow_shift = 3.0, # ComfyUI shift 3 for Turbo and base (Turbo already ships 3.0)
pipeline_class = "ZImagePipeline",
transformer_class = "ZImageTransformer2DModel",
base_repo = "Tongyi-MAI/Z-Image-Turbo",
@@ -1138,37 +1132,29 @@ def prefer_ungated_mirror(
# Default (steps, guidance) per model for callers that cannot pass them. Matched by substring, most specific first;
# same values as the UI MODEL_DEFAULTS table, keep in sync.
_GENERATION_DEFAULTS: tuple[tuple[str, int, float], ...] = (
- # Values follow ComfyUI's official templates for the same model (our baseline).
- # Z-Image-Turbo: 8 steps (ComfyUI runs 8 sampler steps; diffusers runs one forward per step).
- ("z-image-turbo", 8, 0.0),
- # FLUX.1 Krea dev is a FLUX.1-dev finetune, NOT a Krea-2: 20 steps at the FLUX guidance default 3.5, as ComfyUI.
- # Must precede the generic "krea" key.
- ("flux.1-krea", 20, 3.5),
+ ("z-image-turbo", 9, 0.0),
+ # FLUX.1 Krea dev is a FLUX.1-dev finetune, NOT a Krea-2: 28 steps at guidance 4.5. Must precede the generic
+ # "krea" key.
+ ("flux.1-krea", 28, 4.5),
# Krea 2 Raw (undistilled): 52 steps / guidance 3.5. Must precede the generic "krea" key.
("krea-2-raw", 52, 3.5),
# Krea 2 Turbo (distilled): 8 steps, no CFG. "krea" then covers Turbo and other krea ids but Raw.
("krea", 8, 0.0),
("flux.1-schnell", 4, 0.0),
- ("kontext", 20, 2.5), # editing: before the generic flux.1
- ("flux.1", 20, 3.5),
- # The undistilled base variants run real CFG: 20 steps at CFG 5, as ComfyUI. Keep this before the generic
- # distilled key, which covers both 4B and 9B 4-step checkpoints.
- ("flux.2-klein-base", 20, 5.0),
+ ("kontext", 28, 2.5), # editing: before the generic flux.1
+ ("flux.1", 28, 3.5),
+ # The undistilled base variants need their model-card 50-step CFG recipe. Keep this before the generic distilled
+ # key, which covers both 4B and 9B 4-step checkpoints.
+ ("flux.2-klein-base", 50, 4.0),
("flux.2-klein", 4, 1.0),
- ("flux.2-dev", 20, 4.0), # full (non-distilled)
- # Qwen-Image-2.1: 25 steps, no guidance. Before the generic qwen-image key.
- ("qwen-image-2.1", 25, 1.0),
- ("qwen-image-21", 25, 1.0),
- ("qwen_image_21", 25, 1.0),
- ("qwenimage21", 25, 1.0),
- # Qwen-Image-Edit 2511: 40 steps at CFG 4. Before the generic qwen-image key.
- ("qwen-image-edit", 40, 4.0),
- # Qwen-Image-2512: 50 steps at CFG 4 (its own ComfyUI template; the original Qwen-Image runs 20).
- ("qwen-image-2512", 50, 4.0),
+ ("flux.2-dev", 28, 4.0), # full (non-distilled)
+ # Qwen-Image-2.1: 40 steps, no guidance. Before the generic qwen-image key.
+ ("qwen-image-2.1", 40, 1.0),
+ ("qwen-image-21", 40, 1.0),
+ ("qwen_image_21", 40, 1.0),
+ ("qwenimage21", 40, 1.0),
("qwen-image", 20, 4.0),
- # Z-Image base: 25 steps at ComfyUI CFG 4. diffusers Z-Image computes pos + g * (pos - neg), so its g is
- # ComfyUI's cfg - 1.
- ("z-image", 25, 3.0),
+ ("z-image", 20, 4.0),
# Lumina Image 2.0 card: 50 steps, guidance 4 (plus cfg_trunc_ratio 0.25, which the loader passes itself).
("lumina", 50, 4.0),
# HunyuanImage 2.1 card: 50 steps; guidance feeds distilled_guidance_scale, while real CFG runs inside the
@@ -1178,13 +1164,13 @@ _GENERATION_DEFAULTS: tuple[tuple[str, int, float], ...] = (
("hidream-i1-dev", 28, 0.0),
("hidream-i1-fast", 16, 0.0),
("hidream", 50, 5.0),
- # Ideogram 4: ComfyUI's Default preset, 20 steps at guidance 7 (3 once sigma <= 0.3), logit-normal mu 0.0 / std 1.75.
- # An explicit 48 steps at 7 still runs the card's tapered schedule.
- ("ideogram", 20, 7.0),
+ # Ideogram 4 card: 48 steps, guidance 7 (its schedule tapers the last 3 steps; the loader keeps that taper at
+ # these defaults).
+ ("ideogram", 48, 7.0),
# SDXL: Turbo distilled; base wants ~30 steps + CFG ~7. "sdxl-turbo" precedes "sdxl".
("sdxl-turbo", 3, 0.0),
- ("stable-diffusion-xl", 25, 7.0),
- ("sdxl", 25, 7.0),
+ ("stable-diffusion-xl", 30, 7.0),
+ ("sdxl", 30, 7.0),
)
# Unrecognised model: distilled few-step / no-CFG shape, matching the UI fallback.
_GENERATION_DEFAULT_FALLBACK = (9, 0.0)
diff --git a/studio/backend/core/inference/diffusion_flow_shift.py b/studio/backend/core/inference/diffusion_flow_shift.py
deleted file mode 100644
index e12d3cb0c2b..00000000000
--- a/studio/backend/core/inference/diffusion_flow_shift.py
+++ /dev/null
@@ -1,64 +0,0 @@
-# SPDX-License-Identifier: AGPL-3.0-only
-# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-
-"""Static sigma shift a family samples with in ComfyUI, applied to the loaded scheduler. No
-torch/diffusers imports: it only rebuilds ``pipe.scheduler`` from its own config.
-
-Several shipped schedulers shift sigmas differently from ComfyUI's defaults for the same model:
-Qwen-Image resolves a resolution-dependent exponential shift (about 2.0 at 1024 px) and stretches
-the tail to 0.02 where ComfyUI samples a constant 3.1, Z-Image base ships 6.0 against 3.0, Wan2.2
-ships 5.0 / 3.0 against 8 / 5 and HunyuanVideo-1.5 5.0 / 9.0 against 7. A flow-matching shift ``s``
-maps sigma to ``s * sigma / (1 + (s - 1) * sigma)`` in both, so setting the static shift (and
-dropping the dynamic shift and terminal stretch) reproduces ComfyUI's schedule.
-"""
-
-from __future__ import annotations
-
-from typing import Any, Optional
-
-
-def flow_shift_overrides(config: Any, shift: float) -> Optional[dict]:
- """Scheduler config overrides that sample at static ``shift``, or None when the scheduler has
- no flow shift Studio knows how to set."""
- try:
- keys = set(config.keys())
- except Exception: # noqa: BLE001 - an exotic config just keeps its scheduler
- return None
- if "flow_shift" in keys and config.get("use_flow_sigmas", True):
- # UniPC / DPM-Solver in flow mode (Wan).
- return {"flow_shift": float(shift)}
- if "shift" in keys and "use_dynamic_shifting" in keys:
- # FlowMatchEulerDiscrete: static shift, no resolution-dependent mu, no terminal stretch.
- overrides = {"shift": float(shift), "use_dynamic_shifting": False}
- if "shift_terminal" in keys:
- overrides["shift_terminal"] = None
- return overrides
- return None
-
-
-def apply_comfy_flow_shift(
- pipe: Any,
- shift: Optional[float],
- logger: Any = None,
-) -> bool:
- """Rebuild ``pipe.scheduler`` at ComfyUI's static ``shift``. True when it changed."""
- if shift is None:
- return False
- scheduler = getattr(pipe, "scheduler", None)
- config = getattr(scheduler, "config", None)
- if scheduler is None or config is None:
- return False
- overrides = flow_shift_overrides(config, shift)
- if not overrides:
- return False
- if all(config.get(k) == v for k, v in overrides.items()):
- return False
- try:
- pipe.scheduler = type(scheduler).from_config(config, **overrides)
- except Exception as exc: # noqa: BLE001 - keep the shipped schedule rather than fail the load
- if logger is not None:
- logger.warning("flow shift %s not applied: %s", shift, exc)
- return False
- if logger is not None:
- logger.info("scheduler flow shift set to %s (ComfyUI default)", shift)
- return True
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.py
index c8e54161f31..1641a775d17 100644
--- a/studio/backend/core/inference/diffusion_memory.py
+++ b/studio/backend/core/inference/diffusion_memory.py
@@ -2397,19 +2397,6 @@ def refine_plan_from_loaded_weights(
return plan
-def _placed_on(tensor: Any, device_type: str, is_torchao: Callable[[Any], bool]) -> bool:
- """Whether ``tensor``'s storage is on ``device_type``. A torchao subclass is judged by its inner tensors: after a
- streamed offload its wrapper can still report the onload device while its data and scales sit on the host."""
- if is_torchao(tensor):
- try:
- names, _ = tensor.__tensor_flatten__()
- inner = [getattr(tensor, n) for n in names]
- return all(getattr(t, "device", tensor.device).type == device_type for t in inner)
- except Exception: # noqa: BLE001 - unflattenable: move it, the swap is idempotent
- return False
- return tensor.device.type == device_type
-
-
def _keep_groups_resident(
module: Any,
room_mib: int,
@@ -2490,7 +2477,7 @@ def _keep_groups_resident(
continue
cpu = getattr(group, "cpu_param_dict", None) or {}
for t in tensors:
- if _placed_on(t, onload.type, is_torchao):
+ if t.device.type == onload.type:
continue
moved = cpu.get(t, t).to(onload)
if is_torchao(t):
diff --git a/studio/backend/core/inference/diffusion_text_length.py b/studio/backend/core/inference/diffusion_text_length.py
deleted file mode 100644
index 0ece9c90116..00000000000
--- a/studio/backend/core/inference/diffusion_text_length.py
+++ /dev/null
@@ -1,147 +0,0 @@
-# SPDX-License-Identifier: AGPL-3.0-only
-# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-
-"""Text-conditioning defaults that follow ComfyUI. No torch/diffusers imports.
-
-FLUX.1 T5 sequence length:
-
-diffusers pads (and truncates) the FLUX.1 T5 prompt to ``max_sequence_length=512`` and runs T5
-without an attention mask, so every pad token takes part in the encoder's self-attention. ComfyUI,
-our baseline, pads the same T5 prompt only up to 256 tokens and otherwise uses its real length
-(again with no mask). Both the embeddings and the text tokens the DiT attends over therefore differ,
-and 512 costs 256 extra joint-attention tokens per step for a short prompt.
-
-``flux_t5_sequence_length`` reproduces the ComfyUI length (256) for every prompt of at most 256 T5
-tokens (EOS included). Longer prompts pad to 512 as before (bucketed, see the function), and a prompt
-past 512 tokens truncates exactly as before.
-"""
-
-from __future__ import annotations
-
-import math
-from typing import Any, Iterable, Optional
-
-# ComfyUI's Ideogram 4 template ("Default" preset): 20 steps, logit-normal mean 0.0 and spread 1.75 before the
-# resolution term (both implementations add it the same way), and guidance 7 overridden to 3 over the last 30% of
-# sampling (CFG override, start 0.7 / end 1.0). Ideogram 4 samples a plain flow model (shift 1), so that range is
-# sigma <= 0.3.
-IDEOGRAM4_COMFY_STEPS = 20
-IDEOGRAM4_COMFY_MU = 0.0
-IDEOGRAM4_COMFY_STD = 1.75
-IDEOGRAM4_COMFY_GUIDANCE = 7.0
-IDEOGRAM4_COMFY_TAIL_GUIDANCE = 3.0
-IDEOGRAM4_COMFY_TAIL_SIGMA = 0.3
-_IDEOGRAM4_LOGSNR_MIN = -15.0
-_IDEOGRAM4_LOGSNR_MAX = 18.0
-
-
-def ideogram4_sigmas(steps: int, width: int, height: int, mu: float, std: float) -> list[float]:
- """The ``steps`` sigmas the Ideogram 4 logit-normal schedule visits (terminal 0 excluded), highest first."""
- from statistics import NormalDist
-
- mean = float(mu) + 0.5 * math.log((int(width) * int(height)) / (512 * 512))
- t_min = 1.0 / (1.0 + math.exp(0.5 * _IDEOGRAM4_LOGSNR_MAX))
- t_max = 1.0 / (1.0 + math.exp(0.5 * _IDEOGRAM4_LOGSNR_MIN))
- out = []
- for i in range(int(steps)):
- u = 1.0 - i / int(steps) # the schedule is built on linspace(0, 1) and flipped
- if u >= 1.0:
- t = 0.0
- else:
- y = mean + float(std) * NormalDist().inv_cdf(u)
- t = 1.0 - 1.0 / (1.0 + math.exp(-y))
- out.append(1.0 - min(max(t, t_min), t_max))
- return out
-
-
-def ideogram4_comfy_guidance_schedule(steps: int, width: int, height: int) -> list[float]:
- """Per-step guidance ComfyUI's template applies: 7, then 3 on every step whose sigma is <= 0.3."""
- return [
- IDEOGRAM4_COMFY_TAIL_GUIDANCE
- if sigma <= IDEOGRAM4_COMFY_TAIL_SIGMA
- else IDEOGRAM4_COMFY_GUIDANCE
- for sigma in ideogram4_sigmas(steps, width, height, IDEOGRAM4_COMFY_MU, IDEOGRAM4_COMFY_STD)
- ]
-
-
-# FLUX.1 families on a FluxPipeline-style ``max_sequence_length`` whose ComfyUI tokenizer is the FLUX T5 one.
-FLUX_T5_FAMILIES = frozenset({"flux.1", "flux.1-kontext"})
-FLUX_T5_MIN_TOKENS = 256
-FLUX_T5_MAX_TOKENS = 512
-
-
-def _texts(value: Any) -> list[str]:
- if value is None:
- return []
- if isinstance(value, str):
- return [value]
- if isinstance(value, (list, tuple)):
- return [v for v in value if isinstance(v, str)]
- return []
-
-
-def t5_token_count(tokenizer: Any, text: str) -> int:
- """T5 tokens for ``text`` including the EOS the tokenizer appends."""
- ids = tokenizer(text, add_special_tokens = True)["input_ids"]
- return len(ids)
-
-
-def flux_t5_sequence_length(
- tokenizer: Any,
- prompts: Iterable[Any],
- *,
- floor: int = FLUX_T5_MIN_TOKENS,
- cap: int = FLUX_T5_MAX_TOKENS,
-) -> Optional[int]:
- """``max_sequence_length`` for one FLUX.1 call, or None when it cannot be measured (keep the
- pipeline default). ``prompts`` holds each str / list-of-str the call encodes with T5."""
- if tokenizer is None or not callable(tokenizer):
- return None
- texts: list[str] = []
- for value in prompts:
- texts.extend(_texts(value))
- if not texts:
- return None
- try:
- longest = max(t5_token_count(tokenizer, t) for t in texts)
- except Exception: # noqa: BLE001 - an odd tokenizer only keeps the pipeline default
- return None
- # Bucketed, a deliberate deviation from ComfyUI's exact length: every distinct text length is a new denoiser shape,
- # and on the compiled default path the first one past 256 measured a 14 s recompile, each further one a CUDA graph
- # recapture (0.4 to 1 s) until the 4-graph cap made later shapes run eager. So a prompt past 256 tokens pads to the
- # cap (exactly the old behaviour); T5 runs unmasked, so that padding shifts the embeddings of those prompts only.
- return int(floor) if longest <= int(floor) else int(cap)
-
-
-def flux_t5_kwarg(
- family_name: str, pipe: Any, call_params: Any, chunk_kwargs: dict
-) -> Optional[int]:
- """The ``max_sequence_length`` to pass for this chunk, or None to leave the kwarg alone.
-
- Only FLUX.1 families, only when the pipeline accepts the kwarg, and never over a value the
- caller already set. The negative prompt counts only when true CFG actually encodes it."""
- if family_name not in FLUX_T5_FAMILIES:
- return None
- if "max_sequence_length" not in call_params or "max_sequence_length" in chunk_kwargs:
- return None
- prompts: list[Any] = [chunk_kwargs.get("prompt_2") or chunk_kwargs.get("prompt")]
- negative = chunk_kwargs.get("negative_prompt_2") or chunk_kwargs.get("negative_prompt")
- try:
- true_cfg = float(chunk_kwargs.get("true_cfg_scale", 1.0) or 1.0)
- except (TypeError, ValueError):
- true_cfg = 1.0
- if negative and true_cfg > 1.0:
- prompts.append(negative)
- return flux_t5_sequence_length(getattr(pipe, "tokenizer_2", None), prompts)
-
-
-def true_cfg_needs_empty_negative(cfg_kwarg: str, guidance: Any) -> bool:
- """True when a ``true_cfg_scale`` pipeline (Qwen-Image family) would skip CFG for want of a
- negative prompt. diffusers enables true CFG only when ``true_cfg_scale > 1`` AND a negative is
- given; ComfyUI always encodes the (possibly empty) negative and applies CFG above 1."""
- if cfg_kwarg != "true_cfg_scale":
- return False
- try:
- return float(guidance) > 1.0
- except (TypeError, ValueError):
- return False
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 2e6fdec3813..f7d0183458e 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -6343,7 +6343,7 @@ def _widen_pin_ids_for_companion_devices(
pin_ids: list[int],
inherited_ids: Optional[list[int]],
*,
- allowed_ids: Optional[Iterable[int]] = None,
+ may_widen: bool = True,
) -> tuple[list[int], str]:
"""Fit a pinned GPU mask to the companion devices the argv names (#11810).
@@ -6351,14 +6351,12 @@ def _widen_pin_ids_for_companion_devices(
``inherited_ids``, else the physical index). Cards they name are appended after the
pinned ones, the winning flag is renumbered to the child's mask, and a main
``--device`` is added so ``-ngl -1`` does not spread over the extra cards. Tokens
- the parent cannot see are left alone. With ``allowed_ids`` (explicit gpu_ids) the
- mask only widens onto those cards. Returns the mask and a log note, empty when
- unchanged.
+ the parent cannot see are left alone. ``may_widen`` False (explicit gpu_ids) only
+ renumbers within the pin. Returns the mask and a log note, empty when unchanged.
"""
if not pin_ids:
return list(pin_ids), ""
main_ids = [int(i) for i in pin_ids]
- allowed = None if allowed_ids is None else {int(i) for i in allowed_ids}
# A main --device past the pinned positions would resolve to a widened companion card.
for token in str(_extra_args_main_device(cmd) or "").split(","):
match = _GPU_DEVICE_TOKEN_RE.match(token.strip())
@@ -6392,7 +6390,7 @@ def _widen_pin_ids_for_companion_devices(
physical = n
elif n < len(inherited_ids):
physical = int(inherited_ids[n])
- if allowed is not None and physical not in main_ids and physical not in allowed:
+ if not may_widen and physical not in main_ids:
physical = None
tokens.append((token, physical))
if any(physical is not None for _, physical in tokens):
@@ -6981,11 +6979,6 @@ def _llama_chunk_has_generated_output(data: dict) -> bool:
return False
-def _perf_callback_wants_timings(callback) -> bool:
- """A callback that only tracks prefill progress opts out of per-token timings."""
- return callback is not None and getattr(callback, "wants_timings", True)
-
-
def _report_live_llama_timings(callback, chunk) -> None:
"""Report request-scoped llama.cpp progress without altering the public stream."""
if callback is None or not isinstance(chunk, dict):
@@ -8575,17 +8568,6 @@ class LlamaCppBackend:
effective = self._gpu_ids or None
return requested == raw or requested == effective
- def _adopt_widened_pin(self, pin_ids: List[int]) -> None:
- """Record a companion-widened explicit pin as the effective one (#12467).
-
- The effective pin is recorded before the mask widens. /status echoes it and
- dedupe adopts a request carrying it, so the narrower pin would come back as
- the stored intent and reload without the companion card. Only an already
- recorded pin is replaced: a launch that recorded none (forced CPU) stays None.
- """
- if self._gpu_ids is not None:
- self._gpu_ids = [int(i) for i in pin_ids]
-
def _record_matching_gpu_request(self, gpu_ids: Optional[List[int]]) -> None:
"""Adopt the caller's explicit pool after a full already-loaded match.
@@ -29771,14 +29753,12 @@ class LlamaCppBackend:
cmd,
_pin_ids,
self._resolve_visible_physical_ids(),
- allowed_ids = gpu_ids or None,
+ may_widen = not gpu_ids,
)
if _companion_widen:
_companion_fit_mask = list(_pin_ids)
if not _had_main_device and _extra_args_main_device(cmd) is not None:
_companion_added_device = list(cmd[-2:])
- if gpu_ids:
- self._adopt_widened_pin(_pin_ids)
if _companion_widen:
logger.info(
"Companion device flags name GPUs by their unpinned "
@@ -31037,7 +31017,7 @@ class LlamaCppBackend:
cmd,
list(_remaining),
list(_companion_fit_mask),
- allowed_ids = gpu_ids or None,
+ may_widen = not gpu_ids,
)
_companion_added_device = (
list(cmd[-2:])
@@ -35937,7 +35917,7 @@ class LlamaCppBackend:
retry_preflight_context_length = None
# Progress events let advancing prefills renew the first-token deadline.
payload["return_progress"] = True
- if _perf_callback_wants_timings(perf_callback):
+ if perf_callback is not None:
payload["timings_per_token"] = True
if logit_bias:
payload["logit_bias"] = logit_bias
@@ -37072,7 +37052,7 @@ class LlamaCppBackend:
if on_decode_slot is not None:
payload["verbose"] = True
payload["response_fields"] = ["id_slot"]
- if _perf_callback_wants_timings(perf_callback):
+ if perf_callback is not None:
payload["timings_per_token"] = True
if logit_bias:
payload["logit_bias"] = logit_bias
@@ -39806,7 +39786,7 @@ class LlamaCppBackend:
# Progress events feed the first-token deadline; timings stay opt-in.
stream_payload["return_progress"] = True
- if _perf_callback_wants_timings(perf_callback):
+ if perf_callback is not None:
stream_payload["timings_per_token"] = True
_final_respawn_truncations: list[dict] = []
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 7cf0df65f55..e94b068d6ad 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -2175,9 +2175,6 @@ def _map_guidance(
``--cfg-scale``. A distilled 0/1 means CFG off (sd-cli's 1.0); a value > 1 is real CFG."""
if fam.name in ("flux.1", "flux.2-klein", "flux.2-dev"):
return None, (float(guidance) if guidance is not None else None)
- if fam.name == "z-image":
- # diffusers Z-Image computes pos + g * (pos - neg), so its g is standard CFG minus 1 (sd.cpp's cfg 4 == g 3).
- return (float(guidance) + 1.0 if guidance is not None and guidance > 0.0 else 1.0), None
cfg = float(guidance) if (guidance is not None and guidance > 1.0) else 1.0
return cfg, None
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 388f4977765..44b1ec385a2 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -55,7 +55,6 @@ from .diffusion_attention import (
sdpa_math_only,
select_attention_backend,
)
-from .diffusion_flow_shift import apply_comfy_flow_shift
from .diffusion_cache import (
FBCACHE_MIN_STEPS,
TC_AUTO,
@@ -6533,8 +6532,6 @@ class VideoBackend:
}
)
- # Sample at ComfyUI's static sigma shift where the shipped scheduler differs.
- apply_comfy_flow_shift(pipe, getattr(fam, "comfy_flow_shift", None), logger)
from . import diffusion_prompt_cache
diffusion_prompt_cache.install(
@@ -7502,8 +7499,6 @@ class VideoBackend:
),
}
)
- # Sample at ComfyUI's static sigma shift where the shipped scheduler differs.
- apply_comfy_flow_shift(pipe, getattr(fam, "comfy_flow_shift", None), logger)
from . import diffusion_prompt_cache
diffusion_prompt_cache.install(
diff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.py
index a3d5bad2f7d..0739f3c2e61 100644
--- a/studio/backend/core/inference/video_families.py
+++ b/studio/backend/core/inference/video_families.py
@@ -130,9 +130,6 @@ class VideoFamily:
modular_workflow: Optional[str] = None
# Released video and audio sigma shifts, when configurable.
default_flow_shift: Optional[float] = None
- # Static sigma shift ComfyUI samples this family with by default; the loader rebuilds the scheduler at it. None =
- # keep the shipped scheduler. Distinct from default_flow_shift, which also exposes a user control.
- comfy_flow_shift: Optional[float] = None
default_audio_flow_shift: Optional[float] = None
# First/last-frame conditioning: the request may carry keyframe images.
supports_keyframes: bool = False
@@ -266,10 +263,9 @@ _FAMILIES: tuple[VideoFamily, ...] = (
prequant_variant_repos = (("lightricks/ltx-2.3", "fp8", "unsloth/LTX-2.3-FP8"),),
),
# Wan2.2-TI2V-5B (diffusers >= 0.35, verified on 0.39): ~5B single-stream DiT (UMT5 encoder), no audio. Its VAE's
- # temporal compression 4 gives valid frame counts 4k+1. Defaults 20 steps / CFG 5 (ComfyUI's template).
+ # temporal compression 4 gives valid frame counts 4k+1. Defaults 50 steps / CFG 5.
VideoFamily(
name = "wan2.2-ti2v-5b",
- comfy_flow_shift = 8.0, # ComfyUI ModelSamplingSD3 8 (TI2V-5B template)
pipeline_class = "WanPipeline",
transformer_class = "WanTransformer3DModel",
base_repo = "Wan-AI/Wan2.2-TI2V-5B-Diffusers",
@@ -279,7 +275,7 @@ _FAMILIES: tuple[VideoFamily, ...] = (
# "wan2.2-5b"/"wan-ti2v" are the picker/GGUF short ids; "wan2.2-ti2v" catches the repo stem
aliases = ("wan2.2-5b", "wan-ti2v", "wan2.2-ti2v", "wan-ti2v-5b"),
has_audio = False,
- default_steps = 20,
+ default_steps = 50,
default_guidance = 5.0,
default_num_frames = 121,
default_fps = 24,
@@ -302,7 +298,6 @@ _FAMILIES: tuple[VideoFamily, ...] = (
# transformer_2, so cfg2_kwarg is threaded only here.
VideoFamily(
name = "wan2.2-t2v-a14b",
- comfy_flow_shift = 5.0, # ComfyUI ModelSamplingSD3 5 (T2V-A14B template)
pipeline_class = "WanPipeline",
transformer_class = "WanTransformer3DModel",
base_repo = "Wan-AI/Wan2.2-T2V-A14B-Diffusers",
@@ -320,9 +315,8 @@ _FAMILIES: tuple[VideoFamily, ...] = (
transformer2_class = "WanTransformer3DModel",
is_moe = True,
cfg2_kwarg = "guidance_scale_2",
- # ComfyUI's A14B template without the Lightning LoRA: 20 steps at CFG 3.5 on both experts.
- default_steps = 20,
- default_guidance = 3.5,
+ default_steps = 50,
+ default_guidance = 5.0,
# 81 frames at 16 fps ~5s (81 = 4*20 + 1), the A14B card's default clip.
default_num_frames = 81,
default_fps = 16, # A14B runs at 16 fps (vs TI2V-5B's 24)
@@ -341,7 +335,6 @@ _FAMILIES: tuple[VideoFamily, ...] = (
# so only the community repacks load.
VideoFamily(
name = "hunyuanvideo-1.5",
- comfy_flow_shift = 7.0, # ComfyUI model default and template shift 7
pipeline_class = "HunyuanVideo15Pipeline",
transformer_class = "HunyuanVideo15Transformer3DModel",
base_repo = "hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_t2v",
@@ -352,7 +345,7 @@ _FAMILIES: tuple[VideoFamily, ...] = (
aliases = ("hunyuanvideo-1-5", "hunyuanvideo1.5", "hunyuanvideo1-5", "hv15"),
has_audio = False,
guidance_via_guider = True,
- default_steps = 20,
+ default_steps = 50,
default_guidance = 6.0,
default_num_frames = 121,
default_fps = 24,
@@ -371,7 +364,6 @@ _FAMILIES: tuple[VideoFamily, ...] = (
# own family so a 720p load defaults to 720p sizes; the full-path alias outranks the generic token.
VideoFamily(
name = "hunyuanvideo-1.5-720p",
- comfy_flow_shift = 7.0, # ComfyUI model default and template shift 7
pipeline_class = "HunyuanVideo15Pipeline",
transformer_class = "HunyuanVideo15Transformer3DModel",
base_repo = "hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-720p_t2v",
@@ -382,7 +374,7 @@ _FAMILIES: tuple[VideoFamily, ...] = (
aliases = ("hunyuanvideo-1.5-diffusers-720p_t2v", "hv15-720p"),
has_audio = False,
guidance_via_guider = True,
- default_steps = 20,
+ default_steps = 50,
default_guidance = 6.0,
default_num_frames = 121,
default_fps = 24,
@@ -817,14 +809,10 @@ def validate_video_reference_conditioning(
_VIDEO_GENERATION_DEFAULTS: tuple[tuple[str, int, float], ...] = (
("distilled", 8, 1.0),
("ltx", 40, 4.0),
- # ComfyUI's templates for the same models (our baseline). Wan2.2-T2V-A14B: 20 steps at CFG 3.5 (Lightning LoRA
- # off); before the generic Wan key.
- ("a14b", 20, 3.5),
- ("wan2.2-14b", 20, 3.5),
- # Wan2.2-TI2V-5B: 20 steps at CFG 5.
- ("wan", 20, 5.0),
- # HunyuanVideo-1.5: 20 steps with the guider's shipped CFG 6.0.
- ("hunyuanvideo", 20, 6.0),
+ # Wan2.2 pipelines default to 50 steps / CFG 5.0; both TI2V-5B and A14B share these.
+ ("wan", 50, 5.0),
+ # HunyuanVideo-1.5: 50 steps with the guider's shipped CFG 6.0.
+ ("hunyuanvideo", 50, 6.0),
)
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 04d66c1c97b..5dd1cc7992b 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -870,9 +870,7 @@ def _is_prefill_progress_only(data) -> bool:
class _ProgressKeepalive:
- """Dropped ``prompt_progress`` still needs a stand-in frame: the relay's idle timer, and the
- durable-run lease (which ignores plain ``: keep-alive``). Emit ``: prefill-progress`` on the
- same cadence."""
+ """Dropped progress still resets the relay's idle timer, so stand in for the keepalive it starved."""
def __init__(self, interval_s: Optional[float]):
self._interval_s = interval_s
@@ -1909,10 +1907,6 @@ _OPENAI_ADMISSION_SSE_WAIT = ": admission-wait\n\n"
_OPENAI_ADMISSION_SSE_DONE = ": admission-done\n\n"
# A server-side tool still running, unlike a stall keep-alive: durable runs renew their lease on it.
_OPENAI_TOOL_HEARTBEAT_SSE = ": tool-heartbeat\n\n"
-# Prefill still advancing with nothing to stream: ``prompt_progress`` dropped for a client that did
-# not ask for it, or a native GGUF generator still in prefill. Same lease contract as the tool
-# heartbeat: not a stall keep-alive.
-_OPENAI_PREFILL_PROGRESS_SSE = ": prefill-progress\n\n"
_OPENAI_LLAMA_ADMISSION_POLL_S = 0.25
# Cap on waiting for a cancelled teardown task. Request.is_disconnected() can swallow
# cancel() (#7617), so teardown abandons the task rather than hold the response, and
@@ -7090,45 +7084,6 @@ def _monitor_perf_callback(monitor_id: Optional[str], context_length):
return _callback
-class _PrefillProgressSignal:
- """Wrap a GGUF perf callback to count advancing ``prompt_progress`` from the backend thread.
-
- The native GGUF generators consume progress themselves and yield nothing until the first
- token, so the route's stall loop would only ever send ``: keep-alive``, which the durable
- lease ignores. The stall loop polls ``advanced()`` to send ``: prefill-progress`` instead."""
-
- def __init__(self, inner):
- self._inner = inner
- self._last_processed = None
- self._advances = 0
- self._seen = 0
- # Only ask llama-server for per-token timings when a monitor actually consumes them.
- self.wants_timings = inner is not None
-
- @property
- def needs_phase(self) -> bool:
- return self._inner is not None and getattr(self._inner, "needs_phase", True)
-
- def __call__(self, sample: dict) -> None:
- progress = sample.get("prompt_progress")
- if isinstance(progress, dict):
- processed = progress.get("processed")
- # Any change counts, so a new prefill round (lower count) renews too; a repeat does not.
- if processed is not None and processed != self._last_processed:
- self._last_processed = processed
- self._advances += 1
- if self._inner is not None:
- self._inner(sample)
-
- def advanced(self) -> bool:
- """True once per stall tick when prefill moved since the previous call."""
- advances = self._advances
- if advances == self._seen:
- return False
- self._seen = advances
- return True
-
-
def _monitor_call_text(name: Any, arguments: Any = None) -> str:
call_name = str(name or "tool")
if arguments is None or arguments == "":
@@ -28331,14 +28286,11 @@ async def produce_openai_chat_completions(
)
)
- _gguf_monitor_callback = (
+ _gguf_perf_callback = (
_monitor_perf_callback(monitor_id, llama_backend.context_length)
if not _wants_multiple_choices(payload)
else None
)
- # Only a stream has a stall loop to feed; elsewhere the monitor callback (or None) stands.
- _gguf_prefill_signal = _PrefillProgressSignal(_gguf_monitor_callback)
- _gguf_perf_callback = _gguf_prefill_signal if payload.stream else _gguf_monitor_callback
def _gguf_chat_delta_line(delta: ChoiceDelta, finish_reason = None) -> str:
if delta.reasoning_content is not None and delta.content is None:
@@ -28827,12 +28779,7 @@ async def produce_openai_chat_completions(
)
if done_tasks:
break
- # Advancing prefill renews the durable lease; a bare keep-alive does not.
- yield (
- _OPENAI_PREFILL_PROGRESS_SSE
- if _gguf_prefill_signal.advanced()
- else _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
- )
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
approval_flush_pending = False
wait_timeout = _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S
event = next_task.result()
@@ -29527,12 +29474,7 @@ async def produce_openai_chat_completions(
)
if done_tasks:
break
- # Advancing prefill renews the durable lease; a bare keep-alive does not.
- yield (
- _OPENAI_PREFILL_PROGRESS_SSE
- if _gguf_prefill_signal.advanced()
- else _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
- )
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
cumulative = next_task.result()
finally:
if next_task.done():
@@ -33441,8 +33383,7 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge
)
):
if progress_keepalive.due():
- # Distinct from stall keep-alive: durable runs renew their lease on it.
- yield _OPENAI_PREFILL_PROGRESS_SSE.encode()
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE.encode()
continue
out = _cmpl_stream_event_out(event, _include_usage)
if out is not None:
@@ -41869,8 +41810,7 @@ async def _openai_passthrough_stream_admitted(
if not client_wants_progress and _is_prefill_progress_only(chunk_data):
_monitor_openai_sse_line(monitor_id, raw_line, llama_backend.context_length)
if progress_keepalive.due():
- # Distinct from stall keep-alive: durable runs renew their lease on it.
- yield _OPENAI_PREFILL_PROGRESS_SSE
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
continue
# With healing active, a content-bearing line may be replaced by
# held/promoted chunks; otherwise the single (already
diff --git a/studio/backend/run.py b/studio/backend/run.py
index 0d25bd0ddf5..f9b8b1b66da 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -348,16 +348,11 @@ def _print_localhost_ipv6_mismatch_warning(local_url: str, port: int) -> None:
)
-def _verify_global_reachability(
- display_host: str,
- port: int,
- wsl_nat: bool = False,
-) -> None:
+def _verify_global_reachability(display_host: str, port: int) -> None:
"""Probe check-host.net to confirm display_host:port is reachable from the public internet. Synchronous so
output lands between the banner URLs and the stop hint. Bounded at ~15s; failures swallowed (verifier
failing is not Unsloth failing). Only meaningful for a wildcard bind, and skipped entirely by
- UNSLOTH_STUDIO_DISABLE_PUBLIC_CHECK. ``wsl_nat``: the private address is WSL's NAT side, not a LAN
- one, and the WSL note already printed says so."""
+ UNSLOTH_STUDIO_DISABLE_PUBLIC_CHECK."""
global _public_reachable
# Reset to "unknown" each run; set True/False only when the probe decides.
_public_reachable = None
@@ -386,8 +381,6 @@ def _verify_global_reachability(
addr = ipaddress.ip_address(display_host)
if addr.is_loopback or addr.is_private or addr.is_link_local:
_public_reachable = False
- if wsl_nat:
- return
print(
f"{dim} Note: {display_host} is a private/LAN address -- "
f"reachable on this network only, not from the public internet."
@@ -543,32 +536,6 @@ def _network_share_host_for_bind(host: str) -> str:
return host
-def _is_wsl_nat() -> bool:
- from lan_access import _wsl_networking_mode
-
- # "unknown" = WSL too old for wslinfo, which is NAT; "none" has no network at all.
- if _wsl_networking_mode() not in ("nat", "unknown"):
- return False
- # Imported only on WSL: every wildcard bind reaches here. A container on Docker Desktop's WSL2
- # kernel also reads "unknown", but its host port is whatever -p published.
- from utils.paths.file_manager import _in_container
-
- return not _in_container()
-
-
-def _print_wsl_windows_hint(port: int) -> None:
- """WSL2 NAT has no LAN URL to print, but Windows reaches a wildcard bind through localhost
- forwarding (#11187). Printed where the reachability note goes, which it stands in for."""
- dim = "\033[38;5;245m" if _stdout_color_ok() else ""
- reset = "\033[0m" if dim else ""
- print(
- f"{dim} WSL2: open http://localhost:{port} in a Windows browser. Other devices on your "
- f"network can't reach WSL's NAT address; set networkingMode=mirrored in "
- f"%UserProfile%\\.wslconfig for LAN access.{reset}",
- flush = True,
- )
-
-
def _loopback_bind_host_for(host: str) -> str:
return wildcard_loopback_host(host) or "127.0.0.1"
@@ -661,10 +628,7 @@ def _emit_startup_output(
if localhost_mismatch_url:
_print_localhost_ipv6_mismatch_warning(localhost_mismatch_url, port)
elif wildcard_bind:
- wsl_nat = _is_wsl_nat()
- if wsl_nat:
- _print_wsl_windows_hint(port)
- _verify_global_reachability(display_host, port, wsl_nat = wsl_nat)
+ _verify_global_reachability(display_host, port)
_print_cloudflare_line(loopback_host = _loopback_bind_host_for(host))
_emit_tool_policy_notice(lan_addresses[0] if lan_addresses else host, False, enable_tools)
print_studio_stop_hint()
diff --git a/studio/backend/tests/test_chat_generation_lease_compat.py b/studio/backend/tests/test_chat_generation_lease_compat.py
index bd5b6f2e1a2..be82ee93011 100644
--- a/studio/backend/tests/test_chat_generation_lease_compat.py
+++ b/studio/backend/tests/test_chat_generation_lease_compat.py
@@ -705,15 +705,11 @@ def test_the_admission_marker_matches_the_route_that_emits_it():
assert inference_route._OPENAI_ADMISSION_SSE_WAIT.startswith(runs_mod._ADMISSION_WAIT_MARKER)
assert inference_route._OPENAI_ADMISSION_SSE_DONE.startswith(runs_mod._ADMISSION_DONE_MARKER)
assert inference_route._OPENAI_TOOL_HEARTBEAT_SSE.startswith(runs_mod._TOOL_HEARTBEAT_MARKER)
- assert inference_route._OPENAI_PREFILL_PROGRESS_SSE.startswith(
- runs_mod._PREFILL_PROGRESS_MARKER
- )
# And none may match the stall keep-alive, which is the opposite signal.
for marker in (
runs_mod._ADMISSION_WAIT_MARKER,
runs_mod._ADMISSION_DONE_MARKER,
runs_mod._TOOL_HEARTBEAT_MARKER,
- runs_mod._PREFILL_PROGRESS_MARKER,
):
assert not inference_route._OPENAI_PASSTHROUGH_SSE_KEEPALIVE.startswith(marker)
# The two must stay distinct, or the done branch would swallow every wait.
diff --git a/studio/backend/tests/test_chat_generation_supervisor.py b/studio/backend/tests/test_chat_generation_supervisor.py
index 4c4321f098d..2829e533a3e 100644
--- a/studio/backend/tests/test_chat_generation_supervisor.py
+++ b/studio/backend/tests/test_chat_generation_supervisor.py
@@ -445,13 +445,9 @@ async def test_a_prefill_reporting_only_progress_renews_the_lease(durable_run, m
@pytest.mark.asyncio
@pytest.mark.parametrize(
"comment, reaped",
- [
- ("_OPENAI_TOOL_HEARTBEAT_SSE", []),
- ("_OPENAI_PREFILL_PROGRESS_SSE", []),
- ("_OPENAI_PASSTHROUGH_SSE_KEEPALIVE", ["run-1"]),
- ],
+ [("_OPENAI_TOOL_HEARTBEAT_SSE", []), ("_OPENAI_PASSTHROUGH_SSE_KEEPALIVE", ["run-1"])],
)
-async def test_progress_comments_hold_the_lease_but_a_stalled_stream_does_not(
+async def test_a_silent_tool_holds_the_lease_but_a_stalled_stream_does_not(
durable_run, monkeypatch, comment, reaped
):
comment = getattr(inference, comment)
@@ -478,144 +474,6 @@ async def test_progress_comments_hold_the_lease_but_a_stalled_stream_does_not(
assert sampled["reaped"] == reaped
[email protected]("tools", [False, True], ids = ["chat", "tool-loop"])
[email protected]("reports_progress, reaped", [(True, []), (False, ["run-1"])])
-async def test_native_gguf_prefill_progress_holds_the_lease(
- durable_run, monkeypatch, tools, reports_progress, reaped
-):
- """The Studio UI never takes the passthrough: its GGUF chat and tool loop run the native
- generators, which consume prompt_progress and stay silent until the first token. Advancing
- progress must still renew the lease through the stall loop; a silent generator must not."""
- from core.inference.llama_cpp import _report_live_llama_timings
-
- entered, release = threading.Event(), threading.Event()
-
- def _prefill(perf_callback):
- entered.set()
- processed = 0
- while not release.wait(0.005):
- if reports_progress:
- processed += 512
- # The same hook the real generators feed from each llama-server progress frame.
- _report_live_llama_timings(
- perf_callback,
- {"choices": [], "prompt_progress": {"total": 10**6, "processed": processed}},
- )
-
- def generate(*, perf_callback = None, **_kwargs):
- _prefill(perf_callback)
- yield "Hi"
- yield {"type": "metadata", "finish_reason": "stop"}
-
- def generate_with_tools(*, perf_callback = None, **_kwargs):
- _prefill(perf_callback)
- yield {"type": "content", "text": "Hi"}
- yield {"type": "metadata", "finish_reason": "stop"}
-
- llama = SimpleNamespace(
- is_loaded = True,
- model_identifier = "local.gguf",
- base_url = "http://llama.test",
- effective_parallel_slots = 1,
- supports_tools = tools,
- supports_tool_passthrough = tools,
- is_vision = False,
- _is_audio = False,
- context_length = None,
- generate_chat_completion = generate,
- generate_chat_completion_with_tools = generate_with_tools,
- release_idle_chat_slot = lambda *_a, **_k: False,
- count_chat_tokens = lambda *_a, **_k: 16,
- _request_reasoning_kwargs = lambda *_a, **_k: None,
- )
- monkeypatch.setattr(inference, "get_llama_cpp_backend", lambda: llama)
- monkeypatch.setattr(inference, "_automatic_model_load_may_run", lambda: False)
-
- async def no_switch(*_a, **_k):
- return None
-
- monkeypatch.setattr(inference, "_maybe_auto_switch_model", no_switch)
- monkeypatch.setattr(inference, "_LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S", 0.02)
- if not tools:
- monkeypatch.setattr(inference, "_effective_enable_tools", lambda _payload: False)
- now = {"ms": runs_db.now_ms()}
- monkeypatch.setattr(runs_db, "now_ms", lambda: now["ms"])
- real_produce = inference.produce_openai_chat_completions
- sampled = {"comments": set()}
-
- async def wrapped(payload, request, subject, *, cancel_on_disconnect):
- if tools:
- # What the UI sends with the web-search pill lit: server-side tools, no client tools.
- payload.enable_tools = True
- payload.enabled_tools = ["web_search"]
- response = await real_produce(
- payload, request, subject, cancel_on_disconnect = cancel_on_disconnect
- )
- inner = response.body_iterator
- # Preparation has already read its own interval; only the stream's rate limit is lifted.
- monkeypatch.setattr(chat_generation_runs, "_renew_interval_seconds", lambda: 0.0)
-
- async def body():
- comments = 0
- async for raw in inner:
- text = raw.decode() if isinstance(raw, bytes) else str(raw)
- if text.startswith(":") and entered.is_set():
- comments += 1
- sampled["comments"].add(text.strip())
- if comments == 2:
- now["ms"] += 21 * 60_000
- elif comments == 5 and "reaped" not in sampled:
- sampled["reaped"] = runs_db.reconcile_runs(stale_after_ms = 1_200_000)
- release.set()
- yield raw
-
- response.body_iterator = body()
- return response
-
- monkeypatch.setattr(inference, "produce_openai_chat_completions", wrapped)
- try:
- supervisor = ChatGenerationSupervisor(SimpleNamespace(state = SimpleNamespace()))
- await asyncio.wait_for(supervisor._produce("run-1"), 30)
- finally:
- release.set()
- assert sampled["reaped"] == reaped
- expected = ": prefill-progress" if reports_progress else ": keep-alive"
- assert expected in sampled["comments"], sampled["comments"]
- if not reports_progress:
- assert ": prefill-progress" not in sampled["comments"]
-
-
-def test_prefill_signal_counts_only_moving_progress():
- from core.inference.llama_cpp import _perf_callback_wants_timings
-
- forwarded = []
- bare = inference._PrefillProgressSignal(None)
- # Without a monitor the wrapper must not switch llama-server to per-token timings.
- assert _perf_callback_wants_timings(bare) is False
- assert bare.needs_phase is False
- assert bare.advanced() is False
- bare({"prompt_progress": {"processed": 10}})
- bare({"prompt_progress": {"processed": 10}})
- assert bare.advanced() is True
- assert bare.advanced() is False
- # A new prefill round restarts the count lower; that is still movement.
- bare({"prompt_progress": {"processed": 2}})
- assert bare.advanced() is True
- bare({"timings": {"predicted_n": 1}})
- assert bare.advanced() is False
-
- def monitor(sample):
- forwarded.append(sample)
-
- monitor.needs_phase = False
- wrapped = inference._PrefillProgressSignal(monitor)
- assert _perf_callback_wants_timings(wrapped) is True
- assert wrapped.needs_phase is False
- wrapped({"prompt_progress": {"processed": 1}})
- assert forwarded == [{"prompt_progress": {"processed": 1}}]
-
-
async def _subscriber_sequences(after = 0):
response = await run_routes.chat_generation_events(
"run-1",
diff --git a/studio/backend/tests/test_companion_device_widening.py b/studio/backend/tests/test_companion_device_widening.py
index e75ba525a66..51e554cbaeb 100644
--- a/studio/backend/tests/test_companion_device_widening.py
+++ b/studio/backend/tests/test_companion_device_widening.py
@@ -13,11 +13,11 @@ def _widen(
pin_ids,
cmd,
inherited = None,
- allowed_ids = None,
+ may_widen = True,
):
cmd = list(cmd)
widened, note = llama_cpp._widen_pin_ids_for_companion_devices(
- cmd, pin_ids, inherited, allowed_ids = allowed_ids
+ cmd, pin_ids, inherited, may_widen = may_widen
)
return cmd, widened, note
@@ -141,54 +141,18 @@ def test_load_model_uses_the_argv_and_skips_an_unmappable_mask():
window = src[at - 400 : at + 200]
assert "_visibility_mask_is_unmappable()" in window
assert 'env.get("LLAMA_ARG_DEVICE", "")' in window
- assert "allowed_ids = gpu_ids or None" in src[at : at + 300]
+ assert "may_widen = not gpu_ids" in src[at : at + 300]
-def test_a_widened_explicit_pin_is_what_status_and_dedupe_see():
- # #12467: gpu_ids [0, 1] fitted to [0] then widened for the projector. The effective
- # pin was recorded before widening, so /status echoed [0]; a client re-sending that
- # matched, became the stored intent, and the replayed load lost GPU 1 again.
- import inspect
-
- src = inspect.getsource(llama_cpp.LlamaCppBackend.load_model)
- at = src.index("_widen_pin_ids_for_companion_devices(")
- window = src[at : at + 900]
- assert "if gpu_ids:" in window
- assert "self._adopt_widened_pin(_pin_ids)" in window
-
- backend = llama_cpp.LlamaCppBackend.__new__(llama_cpp.LlamaCppBackend)
- backend._is_diffusion = False
- backend._requested_gpu_ids, backend._gpu_ids = [0, 1], [0]
- backend._adopt_widened_pin([0, 1])
- assert backend._gpu_ids == [0, 1]
- assert backend.matches_gpu_ids([0, 1]) is True
- # Dropping the projector's card is a real placement change, so it reloads.
- assert backend.matches_gpu_ids([0]) is False
-
- # A launch that recorded no effective pin (forced CPU) keeps recording none.
- backend._gpu_ids = None
- backend._adopt_widened_pin([0, 1])
- assert backend._gpu_ids is None
-
-
-def test_explicit_gpu_ids_never_widen_onto_an_unselected_card():
- cmd, pin, note = _widen([0], ["--mmproj-device", "CUDA1"], allowed_ids = [0])
+def test_an_explicit_gpu_ids_pin_is_never_widened_onto_another_card():
+ cmd, pin, note = _widen([0], ["--mmproj-device", "CUDA1"], may_widen = False)
assert pin == [0]
assert cmd == ["--mmproj-device", "CUDA1"]
assert note == ""
-def test_explicit_gpu_ids_widen_onto_a_selected_card_the_fit_left_out():
- # #12467: gpu_ids [0, 1] saved, the fit chose [0], the projector names GPU 1
- cmd, pin, note = _widen([0], ["--mmproj-device", "CUDA1"], allowed_ids = [0, 1])
- assert pin == [0, 1]
- assert _value(cmd, "--mmproj-device") == "CUDA1"
- assert cmd[-2:] == ["--device", "CUDA0"]
- assert note
-
-
def test_an_explicit_pin_still_renumbers_a_companion_on_one_of_its_cards():
- cmd, pin, _ = _widen([2, 3], ["--mmproj-device", "CUDA3"], allowed_ids = [2, 3])
+ cmd, pin, _ = _widen([2, 3], ["--mmproj-device", "CUDA3"], may_widen = False)
assert pin == [2, 3]
assert _value(cmd, "--mmproj-device") == "CUDA1"
assert "--device" not in cmd
diff --git a/studio/backend/tests/test_dataset_system_column.py b/studio/backend/tests/test_dataset_system_column.py
deleted file mode 100644
index f4dce0b60c6..00000000000
--- a/studio/backend/tests/test_dataset_system_column.py
+++ /dev/null
@@ -1,89 +0,0 @@
-# SPDX-License-Identifier: AGPL-3.0-only
-# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-
-import pytest
-from datasets import Dataset
-
-from utils.datasets import format_and_template_dataset
-
-
-class _TurnTokenizer:
- chat_template = "{{ messages }}"
- eos_token = "</s>"
-
- def apply_chat_template(self, conversation, **_kwargs):
- return "".join(f"<{turn['role']}>{turn['content']}" for turn in conversation)
-
-
-def _sharegpt(turns):
- return "conversations", [{"from": role, "value": content} for role, content in turns]
-
-
-def _chatml(turns):
- return "messages", [{"role": role, "content": content} for role, content in turns]
-
-
-def _format(rows):
- result = format_and_template_dataset(
- Dataset.from_list(rows), model_name = "stub-model", tokenizer = _TurnTokenizer()
- )
- assert result["success"], result["errors"]
- return list(result["dataset"]["text"])
-
-
[email protected]("shape", [_sharegpt, _chatml], ids = ["sharegpt", "chatml"])
-def test_system_column_is_trained_as_the_system_turn(shape):
- column, convo = shape([("user", "q"), ("assistant", "a")])
-
- texts = _format([{"system": "Here is a list of functions", column: convo}])
-
- assert texts == ["<system>Here is a list of functions<user>q<assistant>a"]
-
-
[email protected]("shape", [_sharegpt, _chatml], ids = ["sharegpt", "chatml"])
-def test_system_column_does_not_override_a_leading_system_turn_or_add_a_blank_one(shape):
- column, with_system = shape([("system", "inline"), ("user", "q"), ("assistant", "a")])
- _, without_system = shape([("user", "q"), ("assistant", "a")])
-
- texts = _format(
- [
- {"system": "column", column: with_system},
- {"system": " ", column: without_system},
- ]
- )
-
- assert texts == ["<system>inline<user>q<assistant>a", "<user>q<assistant>a"]
-
-
-class _NoSystemTokenizer(_TurnTokenizer):
- def apply_chat_template(self, conversation, **kwargs):
- if any(turn["role"] == "system" for turn in conversation):
- raise ValueError("System role not supported")
- return super().apply_chat_template(conversation, **kwargs)
-
-
[email protected]("shape", [_sharegpt, _chatml], ids = ["sharegpt", "chatml"])
-def test_system_column_falls_back_when_the_template_rejects_a_system_turn(shape):
- column, convo = shape([("user", "q"), ("assistant", "a")])
-
- result = format_and_template_dataset(
- Dataset.from_list([{"system": "Here is a list of functions", column: convo}]),
- model_name = "stub-model",
- tokenizer = _NoSystemTokenizer(),
- )
-
- assert result["success"], result["errors"]
- assert list(result["dataset"]["text"]) == ["<user>q<assistant>a"]
-
-
-def test_a_malformed_row_is_dropped_on_its_own_when_a_system_column_is_present():
- _, convo = _chatml([("user", "q"), ("assistant", "a")])
-
- texts = _format(
- [
- {"system": "column", "messages": convo},
- {"system": "column", "messages": [None, *convo]},
- ]
- )
-
- assert texts == ["<system>column<user>q<assistant>a"]
diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.py
index ba78ff05810..2d41b06e38e 100644
--- a/studio/backend/tests/test_diffusion_backend.py
+++ b/studio/backend/tests/test_diffusion_backend.py
@@ -14420,148 +14420,3 @@ def test_diffusion_status_response_keeps_the_gguf_a_swap_replaced():
]
assert dumped["replaced"] == "gguf:m-Q4_K_M.gguf"
assert dumped["artifact"] == "prequant:o/r/f.safetensors"
-
-
-# FLUX.1 T5 length (ComfyUI parity): real prompt length floored at 256, capped at 512.
-class _T5WordTokenizer:
- """One id per whitespace word plus EOS, like T5TokenizerFast on plain words."""
-
- def __call__(
- self,
- text,
- add_special_tokens = True,
- **_,
- ):
- return {"input_ids": [5] * len(text.split()) + ([1] if add_special_tokens else [])}
-
-
-class _FluxFakePipe(_FakePipe):
- def __init__(self):
- super().__init__()
- self.tokenizer_2 = _T5WordTokenizer()
-
- def __call__(
- self,
- *,
- prompt = None,
- max_sequence_length = 512,
- **kwargs,
- ):
- return super().__call__(prompt = prompt, max_sequence_length = max_sequence_length, **kwargs)
-
-
-def test_generate_passes_flux1_t5_length_like_comfy(fake_runtime, tmp_path, monkeypatch):
- diffusers = sys.modules["diffusers"]
- monkeypatch.setattr(diffusers, "FluxPipeline", _FakePipeline, raising = False)
- monkeypatch.setattr(diffusers, "FluxTransformer2DModel", _FakeTransformer, raising = False)
- _no_cache(monkeypatch)
- backend = _loaded_backend(tmp_path, family_override = "flux.1")
- pipe = _FluxFakePipe()
- object.__setattr__(backend._state, "pipe", pipe)
- backend.generate(prompt = "a sloth on a branch", steps = 4, guidance = 0.0)
- assert pipe.last_kwargs["max_sequence_length"] == 256
- backend.generate(prompt = " ".join(["w"] * 320), steps = 4, guidance = 0.0)
- assert pipe.last_kwargs["max_sequence_length"] == 512 # past 256 tokens: the 512 bucket
-
-
-def test_generate_leaves_t5_length_alone_off_flux1(fake_runtime, tmp_path):
- backend = _loaded_backend(tmp_path, family_override = "z-image")
- pipe = _FluxFakePipe()
- object.__setattr__(backend._state, "pipe", pipe)
- backend.generate(prompt = "a sloth", steps = 4, guidance = 0.0)
- assert pipe.last_kwargs["max_sequence_length"] == 512 # pipeline default, nothing passed
-
-
-def test_qwen_true_cfg_gets_an_empty_negative_like_comfy(fake_runtime, tmp_path, monkeypatch):
- """diffusers runs Qwen-Image true CFG only when a negative is present; ComfyUI always encodes the
- empty negative and applies CFG. A blank negative must not silently turn CFG off."""
- diffusers = sys.modules["diffusers"]
- monkeypatch.setattr(diffusers, "QwenImagePipeline", _FakePipeline, raising = False)
- monkeypatch.setattr(diffusers, "QwenImageTransformer2DModel", _FakeTransformer, raising = False)
- _no_cache(monkeypatch)
- backend = _loaded_backend(tmp_path, family_override = "qwen-image")
- backend.generate(prompt = "a sloth", steps = 4, guidance = 4.0)
- call = backend._state.pipe.last_kwargs
- assert call["true_cfg_scale"] == 4.0 and call["negative_prompt"] == ""
- # An explicit negative is kept; guidance <= 1 never asks for CFG.
- backend.generate(prompt = "a sloth", negative_prompt = "blurry", steps = 4, guidance = 4.0)
- assert backend._state.pipe.last_kwargs["negative_prompt"] == "blurry"
- backend.generate(prompt = "a sloth", steps = 4, guidance = 1.0)
- assert backend._state.pipe.last_kwargs["negative_prompt"] is None
-
-
-def test_guidance_scale_families_get_no_injected_negative(fake_runtime, tmp_path):
- backend = _loaded_backend(tmp_path) # z-image: guidance_scale, its own CFG handling
- backend.generate(prompt = "a sloth", steps = 4, guidance = 4.0)
- assert backend._state.pipe.last_kwargs["negative_prompt"] is None
-
-
-class _IdeogramScheduleFakePipe(_FakePipe):
- def __call__(
- self,
- *,
- prompt = None,
- mu = 0.0,
- std = 1.5,
- guidance_schedule = "card",
- **kwargs,
- ):
- return super().__call__(
- prompt = prompt, mu = mu, std = std, guidance_schedule = guidance_schedule, **kwargs
- )
-
-
-def test_generate_ideogram_defaults_follow_comfy_template(fake_runtime, tmp_path):
- """ComfyUI's Ideogram 4 template: 20 steps, mu 0.0 / std 1.75, guidance 7 overridden to 3 where sigma <= 0.3
- (the last 3 of 20 steps at 1024^2). Another guidance stays constant; an explicit 48 / 7 keeps the card taper."""
- backend = DiffusionBackend()
- _load_ideogram(backend, tmp_path)
- pipe = _IdeogramScheduleFakePipe()
- object.__setattr__(backend._state, "pipe", pipe)
- backend.generate(prompt = "a sloth", width = 1024, height = 1024, steps = 20, guidance = 7.0)
- call = pipe.last_kwargs
- assert call["guidance_scale"] is None
- assert call["guidance_schedule"] == [7.0] * 17 + [3.0] * 3
- assert (call["mu"], call["std"]) == (0.0, 1.75)
- backend.generate(prompt = "a sloth", width = 512, height = 512, steps = 20, guidance = 7.0)
- assert pipe.last_kwargs["guidance_schedule"] == [7.0] * 14 + [3.0] * 6
- backend.generate(prompt = "a sloth", width = 1024, height = 1024, steps = 20, guidance = 5.0)
- call = pipe.last_kwargs
- assert call["guidance_scale"] == 5.0 and call["guidance_schedule"] is None
- assert (call["mu"], call["std"]) == (0.0, 1.75)
- backend.generate(prompt = "a sloth", steps = 48, guidance = 7.0)
- call = pipe.last_kwargs
- assert call["guidance_schedule"] == "card" and (call["mu"], call["std"]) == (0.0, 1.5)
-
-
-class _ShiftSchedulerConfig(dict):
- pass
-
-
-class _ShiftFakeScheduler:
- def __init__(self, **config):
- self.config = _ShiftSchedulerConfig(config)
-
- @classmethod
- def from_config(cls, config, **overrides):
- return cls(**{**config, **overrides})
-
-
-class _QwenShiftFakePipeline(_FakePipeline):
- @classmethod
- def from_pretrained(cls, base, **kwargs):
- pipe = super().from_pretrained(base, **kwargs)
- pipe.scheduler = _ShiftFakeScheduler(
- shift = 1.0, use_dynamic_shifting = True, shift_terminal = 0.02
- )
- return pipe
-
-
-def test_qwen_load_samples_at_comfy_static_shift(fake_runtime, tmp_path, monkeypatch):
- diffusers = sys.modules["diffusers"]
- monkeypatch.setattr(diffusers, "QwenImagePipeline", _QwenShiftFakePipeline, raising = False)
- monkeypatch.setattr(diffusers, "QwenImageTransformer2DModel", _FakeTransformer, raising = False)
- _no_cache(monkeypatch)
- backend = _loaded_backend(tmp_path, family_override = "qwen-image")
- cfg = backend._state.pipe.scheduler.config
- assert (cfg["shift"], cfg["use_dynamic_shifting"], cfg["shift_terminal"]) == (3.1, False, None)
diff --git a/studio/backend/tests/test_diffusion_flow_shift.py b/studio/backend/tests/test_diffusion_flow_shift.py
deleted file mode 100644
index a50392db789..00000000000
--- a/studio/backend/tests/test_diffusion_flow_shift.py
+++ /dev/null
@@ -1,73 +0,0 @@
-# SPDX-License-Identifier: AGPL-3.0-only
-# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-
-"""Families sample at ComfyUI's static sigma shift: the loader rebuilds the shipped scheduler."""
-
-from __future__ import annotations
-
-import types
-
-from core.inference.diffusion_families import detect_family
-from core.inference.diffusion_flow_shift import apply_comfy_flow_shift, flow_shift_overrides
-from core.inference.video_families import detect_video_family
-
-
-class _Config(dict):
- pass
-
-
-class _FakeScheduler:
- def __init__(self, **config):
- self.config = _Config(config)
-
- @classmethod
- def from_config(cls, config, **overrides):
- return cls(**{**config, **overrides})
-
-
-# Shipped configs (the fields that matter) of the Qwen-Image, Wan2.2-TI2V-5B and HunyuanVideo-1.5 720p repos.
-_QWEN = dict(
- shift = 1.0, use_dynamic_shifting = True, shift_terminal = 0.02, time_shift_type = "exponential"
-)
-_WAN = dict(flow_shift = 5.0, use_flow_sigmas = True, solver_order = 2)
-_HV15 = dict(shift = 9.0, use_dynamic_shifting = False, shift_terminal = None)
-
-
-def test_flow_match_gets_a_static_shift_without_terminal_stretch():
- pipe = types.SimpleNamespace(scheduler = _FakeScheduler(**_QWEN))
- assert apply_comfy_flow_shift(pipe, 3.1) is True
- cfg = pipe.scheduler.config
- assert (cfg["shift"], cfg["use_dynamic_shifting"], cfg["shift_terminal"]) == (3.1, False, None)
- assert cfg["time_shift_type"] == "exponential" # untouched keys survive
- assert apply_comfy_flow_shift(pipe, 3.1) is False # idempotent
-
-
-def test_unipc_flow_shift_and_static_euler():
- wan = types.SimpleNamespace(scheduler = _FakeScheduler(**_WAN))
- assert apply_comfy_flow_shift(wan, 8.0) and wan.scheduler.config["flow_shift"] == 8.0
- hv = types.SimpleNamespace(scheduler = _FakeScheduler(**_HV15))
- assert apply_comfy_flow_shift(hv, 7.0) and hv.scheduler.config["shift"] == 7.0
-
-
-def test_no_shift_or_unknown_scheduler_is_a_no_op():
- pipe = types.SimpleNamespace(scheduler = _FakeScheduler(**_QWEN))
- assert apply_comfy_flow_shift(pipe, None) is False
- other = types.SimpleNamespace(scheduler = _FakeScheduler(beta_schedule = "scaled_linear"))
- assert apply_comfy_flow_shift(other, 3.0) is False
- assert flow_shift_overrides(_Config(beta_schedule = "x"), 3.0) is None
- assert apply_comfy_flow_shift(types.SimpleNamespace(), 3.0) is False
-
-
-def test_family_shifts_match_comfy_defaults():
- assert detect_family("Qwen/Qwen-Image").comfy_flow_shift == 3.1
- assert detect_family("Qwen/Qwen-Image-Edit-2511").comfy_flow_shift == 3.1
- assert detect_family("Tongyi-MAI/Z-Image").comfy_flow_shift == 3.0
- # Families whose shipped schedule already matches keep it.
- assert detect_family("black-forest-labs/FLUX.1-schnell").comfy_flow_shift is None
- assert detect_video_family("Wan-AI/Wan2.2-TI2V-5B-Diffusers").comfy_flow_shift == 8.0
- assert detect_video_family("Wan-AI/Wan2.2-T2V-A14B-Diffusers").comfy_flow_shift == 5.0
- for repo in (
- "hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_t2v",
- "hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-720p_t2v",
- ):
- assert detect_video_family(repo).comfy_flow_shift == 7.0
diff --git a/studio/backend/tests/test_diffusion_flux_t5_length.py b/studio/backend/tests/test_diffusion_flux_t5_length.py
deleted file mode 100644
index 993b7ea29d0..00000000000
--- a/studio/backend/tests/test_diffusion_flux_t5_length.py
+++ /dev/null
@@ -1,84 +0,0 @@
-# SPDX-License-Identifier: AGPL-3.0-only
-# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-
-"""FLUX.1 T5 sequence length follows ComfyUI: the prompt's real T5 length (EOS included), floored
-at 256 and capped at the pipeline's 512, instead of diffusers' fixed 512."""
-
-from __future__ import annotations
-
-import types
-
-import pytest
-
-from core.inference.diffusion_text_length import (
- flux_t5_kwarg,
- flux_t5_sequence_length,
-)
-
-
-class _WordTokenizer:
- """One id per whitespace word plus EOS, like T5TokenizerFast on plain words."""
-
- def __call__(
- self,
- text,
- add_special_tokens = True,
- **_,
- ):
- ids = [5] * len(text.split())
- return {"input_ids": ids + ([1] if add_special_tokens else [])}
-
-
-def _words(n):
- return " ".join(["w"] * n)
-
-
- "words, expected",
- [(3, 256), (255, 256), (256, 512), (300, 512), (511, 512), (700, 512)],
-)
-def test_length_is_256_up_to_256_tokens_else_the_512_bucket(words, expected):
- assert flux_t5_sequence_length(_WordTokenizer(), [_words(words)]) == expected
-
-
-def test_longest_prompt_of_a_list_sets_the_length():
- assert flux_t5_sequence_length(_WordTokenizer(), [["a", _words(200)]]) == 256
- assert flux_t5_sequence_length(_WordTokenizer(), [["a", _words(400)]]) == 512
-
-
-def test_no_tokenizer_keeps_the_pipeline_default():
- assert flux_t5_sequence_length(None, ["a"]) is None
-
-
-def test_only_flux1_families_and_only_when_accepted():
- pipe = types.SimpleNamespace(tokenizer_2 = _WordTokenizer())
- params = {"max_sequence_length": None}
- assert flux_t5_kwarg("flux.1", pipe, params, {"prompt": "a"}) == 256
- assert flux_t5_kwarg("flux.1-kontext", pipe, params, {"prompt": "a"}) == 256
- assert flux_t5_kwarg("flux.2-klein", pipe, params, {"prompt": "a"}) is None
- assert flux_t5_kwarg("flux.1", pipe, {}, {"prompt": "a"}) is None
- # An explicit value is never overridden.
- assert flux_t5_kwarg("flux.1", pipe, params, {"prompt": "a", "max_sequence_length": 77}) is None
-
-
-def test_negative_counts_only_under_true_cfg():
- pipe = types.SimpleNamespace(tokenizer_2 = _WordTokenizer())
- params = {"max_sequence_length": None}
- kw = {"prompt": "a", "negative_prompt": _words(300)}
- assert flux_t5_kwarg("flux.1", pipe, params, kw) == 256
- assert flux_t5_kwarg("flux.1", pipe, params, {**kw, "true_cfg_scale": 4.0}) == 512
- # prompt_2 is what FLUX.1 feeds T5 when given.
- assert flux_t5_kwarg("flux.1", pipe, params, {"prompt": "a", "prompt_2": _words(280)}) == 512
-
-
-def test_ideogram4_comfy_guidance_switches_where_sigma_falls_to_0_3():
- from core.inference.diffusion_text_length import (
- ideogram4_comfy_guidance_schedule,
- ideogram4_sigmas,
- )
-
- sigmas = ideogram4_sigmas(20, 1024, 1024, 0.0, 1.75)
- assert sigmas == sorted(sigmas, reverse = True) and sigmas[0] > 0.999 # clamped at logSNR -15
- schedule = ideogram4_comfy_guidance_schedule(20, 1024, 1024)
- assert schedule == [7.0] * 17 + [3.0] * 3
- assert sigmas[16] > 0.3 >= sigmas[17]
diff --git a/studio/backend/tests/test_diffusion_measured_placement.py b/studio/backend/tests/test_diffusion_measured_placement.py
index 905bce43a5d..734c2b070e6 100644
--- a/studio/backend/tests/test_diffusion_measured_placement.py
+++ b/studio/backend/tests/test_diffusion_measured_placement.py
@@ -496,70 +496,6 @@ def test_generate_releases_and_restores_resident_groups():
assert "pipe._unsloth_measured_reserve = (" in src
-def test_torchao_groups_stay_on_device_after_release_and_restore(monkeypatch):
- """An oversized request streams the pinned groups of a torchao int8 DiT, then restore pins them again. The int8
- wrapper can still report the onload device after a streamed offload while its data and scales sit on the host;
- restore must judge it by the inner tensors, else the next request computes on a host weight."""
- torch, _ = _cuda_offload_model()
- pytest.importorskip("torchao")
- from diffusers.hooks import apply_group_offloading
- from torchao.quantization import Int8DynamicActivationInt8WeightConfig, quantize_
-
- monkeypatch.delenv("UNSLOTH_DIFFUSION_PARTIAL_RESIDENT", raising = False)
- cfg = Int8DynamicActivationInt8WeightConfig(set_inductor_config = False)
- if not hasattr(cfg, "version"):
- pytest.skip("torchao without config versions")
- cfg.version = 2
- torch.manual_seed(0)
- net = (
- torch.nn.Sequential(
- torch.nn.Linear(256, 512),
- torch.nn.Sequential(*[torch.nn.Linear(512, 512) for _ in range(3)]),
- )
- .cuda()
- .to(torch.bfloat16)
- )
- quantize_(net[1], cfg)
- x = torch.randn(64, 256, device = "cuda", dtype = torch.bfloat16)
- with torch.no_grad():
- ref = net(x)
- net.to("cpu")
- kwargs = dict(
- onload_device = torch.device("cuda"),
- offload_device = torch.device("cpu"),
- offload_type = "block_level",
- num_blocks_per_group = 1,
- use_stream = True,
- record_stream = True,
- non_blocking = True,
- )
- apply_group_offloading(net, **dm._torchao_group_offload_kwargs(net, kwargs, [0]))
- pipe = types.SimpleNamespace(transformer = net, components = {"transformer": net})
- assert dm._keep_groups_resident(net, 1024, "cuda") > 0
- with torch.no_grad():
- assert torch.equal(net(x), ref)
- restore = dm.release_resident_groups(pipe, 1024)
- assert restore is not None
- for _ in range(2):
- assert torch.equal(net(x), ref)
- restore()
- for lin in net[1]:
- # torchao 0.14 (torch <= 2.9) keeps the v1 layout, nesting its int8 data one subclass deeper
- assert set(_inner_devices(lin.weight)) == {"cuda"}
- assert torch.equal(net(x), ref)
-
-
-def _inner_devices(tensor):
- names, _ = tensor.__tensor_flatten__()
- out = []
- for name in names:
- inner = getattr(tensor, name)
- out += (
- _inner_devices(inner) if hasattr(inner, "__tensor_flatten__") else [inner.device.type]
- )
- return out
-
-
def test_eager_offload_hooks_install_is_idempotent():
go = pytest.importorskip("diffusers.hooks.group_offloading")
dm.install_group_offload_hooks_eager()
diff --git a/studio/backend/tests/test_diffusion_more_families.py b/studio/backend/tests/test_diffusion_more_families.py
index 286049f50d5..66a6700b490 100644
--- a/studio/backend/tests/test_diffusion_more_families.py
+++ b/studio/backend/tests/test_diffusion_more_families.py
@@ -81,8 +81,8 @@ def test_flux1_krea_dev_is_trusted_non_gguf():
def test_flux1_krea_dev_generation_defaults():
# Model-card recipe: 28 steps at guidance 4.5. The generic "krea" key (Turbo's 8-step no-CFG shape) must NOT swallow it, and the krea-2 defaults must stay intact.
- assert default_generation_params("black-forest-labs/FLUX.1-Krea-dev") == (20, 3.5)
- assert default_generation_params("QuantStack/FLUX.1-Krea-dev-GGUF") == (20, 3.5)
+ assert default_generation_params("black-forest-labs/FLUX.1-Krea-dev") == (28, 4.5)
+ assert default_generation_params("QuantStack/FLUX.1-Krea-dev-GGUF") == (28, 4.5)
assert default_generation_params("krea/Krea-2-Turbo") == (8, 0.0)
assert default_generation_params("krea/Krea-2-Raw") == (52, 3.5)
@@ -108,7 +108,7 @@ def test_flux_dev_and_krea_do_not_inherit_the_schnell_nvfp4_checkpoint():
def test_flux2_klein_generation_defaults_distinguish_base_from_distilled():
for size in ("4B", "9B"):
- assert default_generation_params(f"unsloth/FLUX.2-klein-base-{size}") == (20, 5.0)
+ assert default_generation_params(f"unsloth/FLUX.2-klein-base-{size}") == (50, 4.0)
assert default_generation_params(f"unsloth/FLUX.2-klein-{size}") == (4, 1.0)
@@ -167,10 +167,10 @@ def test_prequant_exclusion_does_not_break_a_family_type_that_lacks_the_field():
def test_zimage_base_generation_defaults_are_not_the_distilled_recipe():
# The base is undistilled: 20 steps at guidance 4. The more specific "z-image-turbo" key sits
# ahead of "z-image", so the 9-step CFG-free Turbo recipe must not swallow it.
- assert default_generation_params("Tongyi-MAI/Z-Image") == (25, 3.0)
- assert default_generation_params("unsloth/Z-Image-GGUF") == (25, 3.0)
- assert default_generation_params("Tongyi-MAI/Z-Image-Turbo") == (8, 0.0)
- assert default_generation_params("unsloth/Z-Image-Turbo-GGUF") == (8, 0.0)
+ assert default_generation_params("Tongyi-MAI/Z-Image") == (20, 4.0)
+ assert default_generation_params("unsloth/Z-Image-GGUF") == (20, 4.0)
+ assert default_generation_params("Tongyi-MAI/Z-Image-Turbo") == (9, 0.0)
+ assert default_generation_params("unsloth/Z-Image-Turbo-GGUF") == (9, 0.0)
# ── lumina-2 family ──────────────────────────────────────────────────────────
@@ -346,8 +346,8 @@ def test_hidream_bf16_component_table_present():
def test_ideogram4_generation_defaults():
- # ComfyUI's template: 20 steps at constant guidance 7 (an explicit 48 / 7 still keeps the card's tapered schedule).
- assert default_generation_params("ideogram-ai/ideogram-4-fp8") == (20, 7.0)
+ # Model-card settings: 48 steps, guidance 7 (an exact match keeps the pipeline's recommended tapered schedule).
+ assert default_generation_params("ideogram-ai/ideogram-4-fp8") == (48, 7.0)
def test_ideogram4_bf16_reservation_table_present():
diff --git a/studio/backend/tests/test_diffusion_unified_edit.py b/studio/backend/tests/test_diffusion_unified_edit.py
index d289bd40a34..fcd53a6712b 100644
--- a/studio/backend/tests/test_diffusion_unified_edit.py
+++ b/studio/backend/tests/test_diffusion_unified_edit.py
@@ -139,9 +139,9 @@ def test_sampling_defaults_resolve_for_every_21_artifact_name():
"unsloth/Qwen-Image-2.1-GGUF",
"unsloth/Qwen-Image-2.1-FP8",
):
- assert default_generation_params(name) == (25, 1.0), name
+ assert default_generation_params(name) == (40, 1.0), name
# The generic key still owns the other Qwen-Image checkpoints.
- assert default_generation_params("Qwen/Qwen-Image-2512") == (50, 4.0)
+ assert default_generation_params("Qwen/Qwen-Image-2512") == (20, 4.0)
def test_explicit_edit_hands_ordered_rgba_images_and_explicit_geometry(backend21):
diff --git a/studio/backend/tests/test_openai_images_generations_route.py b/studio/backend/tests/test_openai_images_generations_route.py
index 6ec61c01c76..d054fcd2640 100644
--- a/studio/backend/tests/test_openai_images_generations_route.py
+++ b/studio/backend/tests/test_openai_images_generations_route.py
@@ -36,16 +36,12 @@ from utils.api_errors import install_api_error_handlers
@pytest.mark.parametrize(
"repo_id, expected",
[
- ("unsloth/Z-Image-Turbo-GGUF", (8, 0.0)), # turbo entry, before the z-image fallback
- ("unsloth/Z-Image-GGUF", (25, 3.0)),
+ ("unsloth/Z-Image-Turbo-GGUF", (9, 0.0)), # turbo entry, before the z-image fallback
+ ("unsloth/Z-Image-GGUF", (20, 4.0)),
("unsloth/FLUX.1-schnell-GGUF", (4, 0.0)), # schnell entry, before the flux.1 entry
- ("black-forest-labs/FLUX.1-dev", (20, 3.5)),
+ ("black-forest-labs/FLUX.1-dev", (28, 3.5)),
("unsloth/FLUX.2-klein-4B-GGUF", (4, 1.0)),
- ("unsloth/Qwen-Image-2512-GGUF", (50, 4.0)),
- ("Qwen/Qwen-Image-Edit-2511", (40, 4.0)),
- ("black-forest-labs/FLUX.1-Kontext-dev", (20, 2.5)),
- ("black-forest-labs/FLUX.2-dev", (20, 4.0)),
- ("stabilityai/stable-diffusion-xl-base-1.0", (25, 7.0)),
+ ("unsloth/Qwen-Image-2512-GGUF", (20, 4.0)),
("some/unknown-model", (9, 0.0)), # fallback
("", (9, 0.0)),
],
@@ -64,14 +60,14 @@ def test_default_generation_params_specificity_ordering():
def test_default_generation_params_falls_back_to_base_repo():
# A local-path load: repo_id names no model, so the resolved base repo identifies it (and separates dev from schnell).
- assert default_generation_params("/models/my-ckpt", "black-forest-labs/FLUX.1-dev") == (20, 3.5)
+ assert default_generation_params("/models/my-ckpt", "black-forest-labs/FLUX.1-dev") == (28, 3.5)
assert default_generation_params("/models/my-ckpt", "black-forest-labs/FLUX.1-schnell") == (
4,
0.0,
)
assert default_generation_params("/models/my-ckpt", "Qwen/Qwen-Image") == (20, 4.0)
# repo_id wins when it already names the model; base repo is only a fallback.
- assert default_generation_params("unsloth/Z-Image-Turbo-GGUF", "Tongyi-MAI/Z-Image") == (8, 0.0)
+ assert default_generation_params("unsloth/Z-Image-Turbo-GGUF", "Tongyi-MAI/Z-Image") == (9, 0.0)
# Nothing identifiable -> fallback; None identifiers are skipped.
assert default_generation_params(None, None) == (9, 0.0)
assert default_generation_params("/models/x", None) == (9, 0.0)
@@ -236,12 +232,12 @@ def test_url_response_shape(client):
assert "url" in item and "b64_json" not in item # exclude_none drops the unused key
# Signed link, not the bearer-gated /file route: an OpenAI client downloads this URL with a plain GET and no auth header.
assert "/images/gallery/img0/file-signed?token=" in item["url"]
- # Z-Image-Turbo defaults (8 steps, 0 guidance) flow into the backend call.
+ # Z-Image-Turbo defaults (9 steps, 0 guidance) flow into the backend call.
assert client.backend.calls[0] == dict(
prompt = "a sloth",
width = 256,
height = 256,
- steps = 8,
+ steps = 9,
guidance = 0.0,
batch_size = 1,
expected_load = load_identity("unsloth/Z-Image-Turbo-GGUF", None, "z-image"),
@@ -302,7 +298,7 @@ def test_local_load_uses_base_repo_for_defaults(monkeypatch):
monkeypatch.setattr(gallery_module, "save", _save)
resp = cli.post("/v1/images/generations", json = {"prompt": "p", "size": "256x256"})
assert resp.status_code == 200
- assert backend.calls[0]["steps"] == 20 and backend.calls[0]["guidance"] == 3.5
+ assert backend.calls[0]["steps"] == 28 and backend.calls[0]["guidance"] == 3.5
def test_pipeline_runtime_error_is_sanitized_500(monkeypatch):
@@ -641,14 +637,14 @@ def test_generation_pins_the_status_read_it_derived_its_params_from(monkeypatch)
def test_replacement_retries_once_with_the_new_models_params(monkeypatch):
- # Z-Image-Turbo (8 steps, guidance 0) is replaced by Z-Image (25 steps, guidance 3). The first
+ # Z-Image-Turbo (9 steps, guidance 0) is replaced by Z-Image (20 steps, guidance 4). The first
# attempt is refused in-lock; the retry must re-derive from fresh state, not reuse the turbo's.
backend = _FakeBackend(replaced_by = [("unsloth/Z-Image-GGUF", None)])
cli, _ = _replacement_client(monkeypatch, backend)
resp = cli.post("/v1/images/generations", json = {"prompt": "p", "size": "256x256"})
assert resp.status_code == 200
assert len(backend.calls) == 1 # the refused attempt never generated
- assert (backend.calls[0]["steps"], backend.calls[0]["guidance"]) == (25, 3.0)
+ assert (backend.calls[0]["steps"], backend.calls[0]["guidance"]) == (20, 4.0)
def test_second_replacement_is_a_503_not_a_sanitized_500(monkeypatch):
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index b67eeb85921..d5a0259e53d 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -7501,9 +7501,7 @@ class TestApiMonitorProviderAndCompletionStreams:
body = b"".join([chunk async for chunk in response.body_iterator])
assert upstream_bodies[0]["return_progress"] is True
- # Dropped progress stands in with ``: prefill-progress`` (lease renewal), not stall keep-alive.
- assert (b": prefill-progress" in body) is not client_progress
- assert (b": keep-alive" in body) is False
+ assert (b": keep-alive" in body) is not client_progress
assert upstream_bodies[0]["stream_options"]["include_usage"] is True
assert b'"usage"' not in body
assert (b"prompt_progress" in body) is client_progress
diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.py
index 866c2fded01..533c285f7fc 100644
--- a/studio/backend/tests/test_sd_cpp_backend.py
+++ b/studio/backend/tests/test_sd_cpp_backend.py
@@ -754,12 +754,6 @@ def test_map_guidance_cfg_family_off_when_distilled():
assert _map_guidance(detect_family("qwen-image"), 4.0) == (4.0, None)
-def test_map_guidance_z_image_converts_diffusers_g_to_standard_cfg():
- # The shared default is diffusers' g = 3 (ComfyUI cfg 4); sd.cpp's standard CFG must get 4, Turbo's 0 stays off.
- assert _map_guidance(detect_family("Tongyi-MAI/Z-Image"), 3.0) == (4.0, None)
- assert _map_guidance(detect_family("Tongyi-MAI/Z-Image-Turbo"), 0.0) == (1.0, None)
-
-
# ── status ────────────────────────────────────────────────────────────────────
diff --git a/studio/backend/tests/test_startup_banner_loopback.py b/studio/backend/tests/test_startup_banner_loopback.py
index 1f19ee88ccc..9a541562d7f 100644
--- a/studio/backend/tests/test_startup_banner_loopback.py
+++ b/studio/backend/tests/test_startup_banner_loopback.py
@@ -43,89 +43,6 @@ def test_wildcard_aliases_show_reachable_urls(capsys, host, loopback_url):
assert "http://192.168.1.24:8891" in out
-WSL_HINT = "WSL2: open http://localhost:"
-
-
[email protected]("mode,wsl", [("nat", True), (None, False)])
-def test_wsl_hint_replaces_the_private_address_note(capsys, monkeypatch, mode, wsl):
- # Under WSL NAT the private address is WSL's own, so "reachable on this network" would be wrong.
- import lan_access
- import run
- from utils.paths import file_manager
-
- monkeypatch.setattr(lan_access, "_wsl_networking_mode", lambda: mode)
- monkeypatch.setattr(file_manager, "_in_container", lambda: False)
- monkeypatch.setattr(run, "_network_share_host_for_bind", lambda h: h)
- monkeypatch.setattr(run, "_print_cloudflare_line", lambda *a, **k: None)
- monkeypatch.setattr(run, "_localhost_ipv6_mismatch_url", lambda *a, **k: None)
- run._emit_startup_output("0.0.0.0", 8888, "172.25.35.232")
- out = capsys.readouterr().out
- assert (WSL_HINT + "8888" in out) is wsl
- assert ("networkingMode=mirrored" in out) is wsl
- assert ("172.25.35.232 is a private/LAN address" in out) is not wsl
- assert run._public_reachable is False
- if wsl:
- assert out.index("/api/health") < out.index(WSL_HINT)
-
-
- "host,mode,expected",
- [
- ("0.0.0.0", "nat", True),
- ("::", "nat", True),
- ("0.0.0.0", "unknown", True),
- ("0.0.0.0", "none", False),
- ("0.0.0.0", "mirrored", False),
- ("0.0.0.0", None, False),
- ("127.0.0.1", "nat", False),
- ],
-)
-def test_startup_output_wsl_hint_gating(capsys, monkeypatch, host, mode, expected):
- import lan_access
- import run
- from utils.paths import file_manager
-
- monkeypatch.setattr(lan_access, "_wsl_networking_mode", lambda: mode)
- monkeypatch.setattr(file_manager, "_in_container", lambda: False)
- monkeypatch.setattr(run, "_network_share_host_for_bind", lambda h: h)
- monkeypatch.setattr(run, "_verify_global_reachability", lambda *a, **k: None)
- monkeypatch.setattr(run, "_print_cloudflare_line", lambda *a, **k: None)
- monkeypatch.setattr(run, "_localhost_ipv6_mismatch_url", lambda *a, **k: None)
- run._emit_startup_output(host, 8888, host)
- assert (WSL_HINT in capsys.readouterr().out) is expected
-
-
-def test_startup_output_wsl_hint_skipped_in_container(capsys, monkeypatch):
- import lan_access
- import run
- from utils.paths import file_manager
-
- monkeypatch.setattr(lan_access, "_wsl_networking_mode", lambda: "unknown")
- monkeypatch.setattr(file_manager, "_in_container", lambda: True)
- monkeypatch.setattr(run, "_network_share_host_for_bind", lambda h: h)
- monkeypatch.setattr(run, "_verify_global_reachability", lambda *a, **k: None)
- monkeypatch.setattr(run, "_print_cloudflare_line", lambda *a, **k: None)
- monkeypatch.setattr(run, "_localhost_ipv6_mismatch_url", lambda *a, **k: None)
- run._emit_startup_output("0.0.0.0", 8000, "0.0.0.0")
- assert WSL_HINT not in capsys.readouterr().out
-
-
-def test_wsl_hint_check_skips_container_import_off_wsl(capsys, monkeypatch):
- # Every wildcard bind runs the WSL check, so off WSL it must not need the container probe's module
- # (a stubbed utils.paths in tests/studio/install has none).
- import lan_access
- import run
-
- monkeypatch.setattr(lan_access, "_wsl_networking_mode", lambda: None)
- monkeypatch.setitem(sys.modules, "utils.paths.file_manager", None)
- monkeypatch.setattr(run, "_network_share_host_for_bind", lambda h: h)
- monkeypatch.setattr(run, "_verify_global_reachability", lambda *a, **k: None)
- monkeypatch.setattr(run, "_print_cloudflare_line", lambda *a, **k: None)
- monkeypatch.setattr(run, "_localhost_ipv6_mismatch_url", lambda *a, **k: None)
- run._emit_startup_output("0.0.0.0", 8000, "0.0.0.0")
- assert WSL_HINT not in capsys.readouterr().out
-
-
def test_banner_prints_on_strict_cp1252_stdout(monkeypatch):
buf = io.BytesIO()
stdout = io.TextIOWrapper(buf, encoding = "cp1252", errors = "strict")
diff --git a/studio/backend/tests/test_transformers_version_optional_tiktoken.py b/studio/backend/tests/test_transformers_version_optional_tiktoken.py
index d4c77652039..39902e1dce7 100644
--- a/studio/backend/tests/test_transformers_version_optional_tiktoken.py
+++ b/studio/backend/tests/test_transformers_version_optional_tiktoken.py
@@ -1041,28 +1041,14 @@ def test_an_unlockable_filesystem_is_not_waited_out(tmp_path, monkeypatch) -> No
attempts.append(op)
raise OSError(errno.ENOTSUP, "locking not supported")
- import threading
-
slept = []
- real_sleep = _time.sleep
- main_thread = threading.current_thread()
-
- def record(seconds):
- # The patch is process-wide, and the lock is waited on this thread. A background
- # thread from an earlier test in the same worker sleeping 50 ms during the window
- # landed in `slept` and failed the row for a wait the lock never made.
- if threading.current_thread() is main_thread:
- slept.append(seconds)
- else:
- real_sleep(seconds)
-
monkeypatch.setattr(fcntl, "flock", unsupported)
- monkeypatch.setattr(_time, "sleep", record)
- monkeypatch.setattr(tv.time, "sleep", record)
+ monkeypatch.setattr(_time, "sleep", lambda s: slept.append(s))
+ monkeypatch.setattr(tv.time, "sleep", lambda s: slept.append(s))
with tv._optional_top_up_lock(str(root)) as held:
assert held is False
assert len(attempts) == 1, f"asked {len(attempts)} times for an answer that cannot change"
- assert not slept, f"waited on a filesystem that cannot lock: {slept}"
+ assert not slept, "waited on a filesystem that cannot lock"
def test_an_interpreter_without_fcntl_does_not_break_activation(tmp_path, monkeypatch) -> None:
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index 668989a84da..fa21e258088 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -2203,12 +2203,12 @@ def test_wan_frame_snapping_4k_plus_1(fake_runtime):
def test_wan_ti2v_defaults_applied(fake_runtime):
- # No steps/guidance passed -> ComfyUI's TI2V-5B template defaults (20 / 5.0).
+ # No steps/guidance passed -> the Wan pipeline defaults (50 / 5.0).
backend = VideoBackend()
backend.load_pipeline("Wan-AI/Wan2.2-TI2V-5B-Diffusers", model_kind = "pipeline")
backend.generate(prompt = "a sloth")
call = backend._state.pipe.last_kwargs
- assert call["num_inference_steps"] == 20
+ assert call["num_inference_steps"] == 50
assert call["guidance_scale"] == 5.0
diff --git a/studio/backend/tests/test_video_families.py b/studio/backend/tests/test_video_families.py
index f03a1a3f444..26400463eaa 100644
--- a/studio/backend/tests/test_video_families.py
+++ b/studio/backend/tests/test_video_families.py
@@ -240,14 +240,13 @@ def test_wan_snap_video_size_16():
def test_wan_generation_defaults():
- # ComfyUI's templates: TI2V-5B 20 steps / CFG 5, T2V-A14B 20 steps / CFG 3.5 (Lightning LoRA off).
- assert default_video_generation_params(None, "Wan-AI/Wan2.2-TI2V-5B-Diffusers") == (20, 5.0)
- assert default_video_generation_params(None, "Wan-AI/Wan2.2-T2V-A14B-Diffusers") == (20, 3.5)
- assert default_video_generation_params("wan2.2-14b") == (20, 3.5)
+ # Both Wan families default to the pipeline's 50 steps / CFG 5.0.
+ assert default_video_generation_params(None, "Wan-AI/Wan2.2-TI2V-5B-Diffusers") == (50, 5.0)
+ assert default_video_generation_params(None, "Wan-AI/Wan2.2-T2V-A14B-Diffusers") == (50, 5.0)
# A GGUF filename carrying the family name still lands on the Wan defaults.
assert default_video_generation_params(
"wan2.2-ti2v-5b-Q4_K_M.gguf", "Wan-AI/Wan2.2-TI2V-5B-Diffusers"
- ) == (20, 5.0)
+ ) == (50, 5.0)
def test_generation_defaults_fallback_honors_family():
@@ -257,7 +256,7 @@ def test_generation_defaults_fallback_honors_family():
"/models/my-clip", "/models/my-clip", fallback = (50, 5.0)
) == (50, 5.0)
# A recognised token still wins over the fallback.
- assert default_video_generation_params("wan2.2-ti2v-5b", fallback = (8, 1.0)) == (20, 5.0)
+ assert default_video_generation_params("wan2.2-ti2v-5b", fallback = (8, 1.0)) == (50, 5.0)
def test_generation_defaults_wan_is_segment_not_substring():
@@ -269,8 +268,8 @@ def test_generation_defaults_wan_is_segment_not_substring():
"taiwan-clips.gguf", "user/taiwan-clips", fallback = (40, 4.0)
) == (40, 4.0)
# Genuine Wan identifiers (segment-initial, with a version suffix or separator) still match.
- assert default_video_generation_params("wan2.2-ti2v-5b-Q4_K_M.gguf") == (20, 5.0)
- assert default_video_generation_params(None, "Wan-AI/Wan2.2-T2V-A14B") == (20, 3.5)
+ assert default_video_generation_params("wan2.2-ti2v-5b-Q4_K_M.gguf") == (50, 5.0)
+ assert default_video_generation_params(None, "Wan-AI/Wan2.2-T2V-A14B") == (50, 5.0)
# An "ltxv" style name still resolves to LTX (trailing letters stay free).
assert default_video_generation_params("ltxv-2.3-distilled") == (8, 1.0)
assert default_video_generation_params("Lightricks/LTXV-2.3") == (40, 4.0)
@@ -333,10 +332,10 @@ def test_hv15_detection_and_flags():
def test_hv15_generation_defaults():
- # The community repacks ship a guider with guidance_scale 6.0; ComfyUI's template samples 20 steps.
+ # The community repacks ship a guider with guidance_scale 6.0 and the pipeline's own 50-step schedule.
assert default_video_generation_params(
None, "hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_t2v"
- ) == (20, 6.0)
+ ) == (50, 6.0)
def test_hv15_720p_checkpoints_never_route_to_the_480p_family():
diff --git a/studio/backend/utils/datasets/chat_templates.py b/studio/backend/utils/datasets/chat_templates.py
index 963a0b90f5a..741a0b7d47c 100644
--- a/studio/backend/utils/datasets/chat_templates.py
+++ b/studio/backend/utils/datasets/chat_templates.py
@@ -297,18 +297,6 @@ def get_dataset_info_summary(dataset_info):
}
-def _with_system_turn(convo, system):
- if (
- isinstance(system, str)
- and system.strip()
- and convo
- and isinstance(convo[0], dict)
- and convo[0].get("role") != "system"
- ):
- return [{"role": "system", "content": system}, *convo]
- return convo
-
-
def apply_chat_template_to_dataset(
dataset_info,
tokenizer,
@@ -528,20 +516,12 @@ def apply_chat_template_to_dataset(
def _format_chatml(examples):
convos = examples[chat_column]
- systems = examples.get("system") or [None] * len(convos)
texts = []
row_errors = []
- for convo, system in zip(convos, systems):
+ for convo in convos:
try:
- with_system = _with_system_turn(convo, system)
- try:
- text = _render_conversation(tokenizer, with_system)
- except Exception:
- # A template without a system role still trains the conversation.
- if with_system is convo:
- raise
- text = _render_conversation(tokenizer, convo)
+ text = _render_conversation(tokenizer, convo)
if remove_bos_prefix:
text = text.removeprefix('<bos>')
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index e8533f08442..de782d25efc 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -2953,9 +2953,6 @@ export function AppSidebar() {
function handleInlineRenameKeyDown(
event: React.KeyboardEvent<HTMLInputElement>,
) {
- // Enter confirms an IME candidate; Escape dismisses one. Neither should
- // finish the rename. Check before preventDefault so the IME keeps its key.
- if (event.nativeEvent.isComposing || event.keyCode === 229) return;
if (event.key === "Enter") {
event.preventDefault();
skipRenameBlurRef.current = true;
@@ -5962,13 +5959,7 @@ export function AppSidebar() {
if (!open) setRenamingTarget(null);
}}
>
- <DialogContent
- className="corner-squircle dialog-soft-surface sm:max-w-md"
- // Radix closes on Escape before the input sees it; keep IME candidate dismissal from closing.
- onEscapeKeyDown={(event) => {
- if (event.isComposing || event.keyCode === 229) event.preventDefault();
- }}
- >
+ <DialogContent className="corner-squircle dialog-soft-surface sm:max-w-md">
<DialogHeader>
<DialogTitle>
{renamingTarget?.kind === "run"
@@ -5980,7 +5971,6 @@ export function AppSidebar() {
value={renameDraft}
onChange={(event) => setRenameDraft(event.target.value)}
onKeyDown={(event) => {
- if (event.nativeEvent.isComposing || event.keyCode === 229) return;
if (event.key === "Enter") {
event.preventDefault();
void commitRename();
diff --git a/studio/frontend/src/features/chat/hooks/use-sidebar-drag.ts b/studio/frontend/src/features/chat/hooks/use-sidebar-drag.ts
index 12455fd7d8a..f15da6fa9cc 100644
--- a/studio/frontend/src/features/chat/hooks/use-sidebar-drag.ts
+++ b/studio/frontend/src/features/chat/hooks/use-sidebar-drag.ts
@@ -215,7 +215,7 @@ const GHOST_DROPPED_ATTRS = [
"data-thread-type",
] as const;
-export interface RowGhost {
+interface RowGhost {
element: HTMLElement;
/** Where on the row the press landed, so the copy does not jump when it lifts. */
grab: number;
@@ -231,33 +231,16 @@ export interface RowGhost {
function liftRow(row: HTMLElement, pressY: number, view: Element): RowGhost | null {
const face = row.querySelector<HTMLElement>(ROW_FACE_SELECTOR);
if (!face) return null;
- const ghost = liftCopy(face, pressY, view, ROW_GHOST_CLASS, GHOST_DROPPED_ATTRS);
- // The icon size is the sidebar's own variable, which the copy leaves behind on the body.
- const iconSize = getComputedStyle(face).getPropertyValue("--icon-size");
- if (iconSize) ghost.element.style.setProperty("--icon-size", iconSize);
- return ghost;
-}
-
-/** A copy of `face` on a pill over where it sits. Also used by the model picker. */
-export function liftCopy(
- face: HTMLElement,
- pressY: number,
- view: Element,
- className: string,
- dropped: readonly string[],
-): RowGhost {
const rect = face.getBoundingClientRect();
const style = getComputedStyle(face);
const copy = face.cloneNode(true) as HTMLElement;
for (const node of [copy, ...copy.querySelectorAll<HTMLElement>("*")]) {
- for (const name of dropped) node.removeAttribute(name);
+ for (const name of GHOST_DROPPED_ATTRS) node.removeAttribute(name);
}
copy.tabIndex = -1;
const element = document.createElement("div");
element.setAttribute("aria-hidden", "true");
- // A picture, not controls.
- element.inert = true;
- element.className = className;
+ element.className = ROW_GHOST_CLASS;
element.append(copy);
// Lifted where the row is, so a frame drawn before its first transform lands shows it there,
// not at the top of the window.
@@ -270,13 +253,16 @@ export function liftCopy(
fontFamily: style.fontFamily,
color: style.color,
});
+ // The icon size is the sidebar's own variable, which the copy leaves behind on the body.
+ const iconSize = style.getPropertyValue("--icon-size");
+ if (iconSize) element.style.setProperty("--icon-size", iconSize);
dragLayer().append(element);
return { element, grab: pressY - rect.top, view, top: rect.top, cues: [] };
}
/** Draws each cue painted under the copy again over it: its border only, since the tint under
* the copy would otherwise double where the two meet. Clipped to the list, as the cue is. */
-export function placeCue(ghost: RowGhost) {
+function placeCue(ghost: RowGhost) {
const view = ghost.view.getBoundingClientRect();
let shown = 0;
for (const cue of document.querySelectorAll<HTMLElement>(`.${DROP_CUE_CLASS}`)) {
@@ -317,7 +303,7 @@ export function placeCue(ghost: RowGhost) {
}
/** Keeps the copy under the pointer, inside the list it came from. */
-export function placeGhost(ghost: RowGhost, y: number) {
+function placeGhost(ghost: RowGhost, y: number) {
const view = ghost.view.getBoundingClientRect();
const height = ghost.element.offsetHeight;
const top = Math.min(Math.max(y - ghost.grab, view.top), view.bottom - height);
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 32d1ab1d922..f81bc57314b 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -144,10 +144,6 @@ export {
DRAG_THRESHOLD_PX,
markDragging,
DROP_CUE_CLASS,
- liftCopy,
- placeCue,
- placeGhost,
- type RowGhost,
} from "./hooks/use-sidebar-drag";
export {
useSectionDrag,
diff --git a/studio/frontend/src/features/chat/thread-sidebar.tsx b/studio/frontend/src/features/chat/thread-sidebar.tsx
index 3273b1d9ec3..73a46f83940 100644
--- a/studio/frontend/src/features/chat/thread-sidebar.tsx
+++ b/studio/frontend/src/features/chat/thread-sidebar.tsx
@@ -352,21 +352,14 @@ export function ThreadSidebar({
{/* Rename dialog */}
<Dialog open={renamingItem !== null} onOpenChange={(open) => { if (!open) setRenamingItem(null); }}>
- <DialogContent
- className="corner-squircle dialog-soft-surface sm:max-w-sm"
- // Radix closes on Escape before the input sees it; keep IME candidate dismissal from closing.
- onEscapeKeyDown={(e) => { if (e.isComposing || e.keyCode === 229) e.preventDefault(); }}
- >
+ <DialogContent className="corner-squircle dialog-soft-surface sm:max-w-sm">
<DialogHeader>
<DialogTitle>Rename chat</DialogTitle>
</DialogHeader>
<Input
value={renameDraft}
onChange={(e) => setRenameDraft(e.target.value)}
- onKeyDown={(e) => {
- if (e.nativeEvent.isComposing || e.keyCode === 229) return;
- if (e.key === "Enter") void commitRename();
- }}
+ onKeyDown={(e) => { if (e.key === "Enter") void commitRename(); }}
autoFocus
/>
<DialogFooter>
diff --git a/studio/frontend/src/features/images/image-generation-defaults.ts b/studio/frontend/src/features/images/image-generation-defaults.ts
index 8fd65115e34..8f440c27fbb 100644
--- a/studio/frontend/src/features/images/image-generation-defaults.ts
+++ b/studio/frontend/src/features/images/image-generation-defaults.ts
@@ -11,37 +11,35 @@ const MODEL_DEFAULTS: Array<{
steps: number;
guidance: number;
}> = [
- { match: "z-image-turbo", steps: 8, guidance: 0 },
+ { match: "z-image-turbo", steps: 9, guidance: 0 },
// Krea 2 Raw is the undistilled base, so it must precede the distilled Krea key below.
{ match: "krea-2-raw", steps: 52, guidance: 3.5 },
{ match: "krea-2", steps: 8, guidance: 0 },
{ match: "flux.1-schnell", steps: 4, guidance: 0 },
// Kontext and the Krea dev finetune must precede generic FLUX.1.
- { match: "kontext", steps: 20, guidance: 2.5 },
- { match: "flux.1-krea", steps: 20, guidance: 3.5 },
- { match: "flux.1", steps: 20, guidance: 3.5 },
+ { match: "kontext", steps: 28, guidance: 2.5 },
+ { match: "flux.1-krea", steps: 28, guidance: 4.5 },
+ { match: "flux.1", steps: 28, guidance: 3.5 },
// Klein base is undistilled. The generic key below covers both distilled sizes.
- { match: "flux.2-klein-base", steps: 20, guidance: 5 },
+ { match: "flux.2-klein-base", steps: 50, guidance: 4 },
{ match: "flux.2-klein", steps: 4, guidance: 1 },
- { match: "flux.2-dev", steps: 20, guidance: 4 },
+ { match: "flux.2-dev", steps: 28, guidance: 4 },
// Qwen-Image-2.1 and its aliases, before the generic key.
- { match: "qwen-image-2.1", steps: 25, guidance: 1 },
- { match: "qwen-image-21", steps: 25, guidance: 1 },
- { match: "qwen_image_21", steps: 25, guidance: 1 },
- { match: "qwenimage21", steps: 25, guidance: 1 },
- { match: "qwen-image-edit", steps: 40, guidance: 4 },
- { match: "qwen-image-2512", steps: 50, guidance: 4 },
+ { match: "qwen-image-2.1", steps: 40, guidance: 1 },
+ { match: "qwen-image-21", steps: 40, guidance: 1 },
+ { match: "qwen_image_21", steps: 40, guidance: 1 },
+ { match: "qwenimage21", steps: 40, guidance: 1 },
{ match: "qwen-image", steps: 20, guidance: 4 },
- { match: "z-image", steps: 25, guidance: 3 },
- { match: "ideogram", steps: 20, guidance: 7 },
+ { match: "z-image", steps: 20, guidance: 4 },
+ { match: "ideogram", steps: 48, guidance: 7 },
{ match: "lumina", steps: 50, guidance: 4 },
{ match: "hunyuanimage", steps: 50, guidance: 3.25 },
{ match: "hidream-i1-dev", steps: 28, guidance: 0 },
{ match: "hidream-i1-fast", steps: 16, guidance: 0 },
{ match: "hidream", steps: 50, guidance: 5 },
{ match: "sdxl-turbo", steps: 3, guidance: 0 },
- { match: "stable-diffusion-xl", steps: 25, guidance: 7 },
- { match: "sdxl", steps: 25, guidance: 7 },
+ { match: "stable-diffusion-xl", steps: 30, guidance: 7 },
+ { match: "sdxl", steps: 30, guidance: 7 },
];
export function defaultsFor(repoId: string): {
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
index 6c814199a4d..389d5e7a316 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
@@ -29,7 +29,6 @@ import {
} from "@/features/chat";
import {
chatModelLoaded,
- DROP_CUE_CLASS,
isExternalModelId,
modelCatalogVersion,
parseExternalModelId,
@@ -5803,8 +5802,7 @@ export function HubModelPicker({
<div
key={key}
{...drag.rowProps(key)}
- // DROP_CUE_CLASS: the drag redraws the line above the carried copy.
- className={cn("relative", edge && [DROP_CUE_CLASS, PINNED_DROP_CUE[edge]])}
+ className={cn("relative", edge && PINNED_DROP_CUE[edge])}
style={drag.draggingKey === key ? { opacity: 0.4 } : undefined}
>
{row}
@@ -8297,11 +8295,7 @@ function FineTunedRows({
: tag;
return (
<div key={adapter.id}>
- <div
- className={downloadedRowShellClassName(value === adapter.id)}
- // The pill a Pinned drag lifts, not this wrapper (use-pinned-row-drag.ts).
- data-pinned-row-face=""
- >
+ <div className={downloadedRowShellClassName(value === adapter.id)}>
<div className="min-w-0 flex-1">
<ModelRow
label={adapter.name}
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/use-pinned-row-drag.ts b/studio/frontend/src/features/model-picker/components/model-selector/use-pinned-row-drag.ts
index b69af683125..ebd298e266d 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/use-pinned-row-drag.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/use-pinned-row-drag.ts
@@ -3,19 +3,10 @@
// Drag to reorder a Pinned group in the model selector, like pinned chats in the sidebar.
// Pointer events, not HTML5 drag: the desktop webview never forwards dragover or drop.
-// The carried row lifts as a copy that follows the pointer, as in the sidebar.
import { useCallback, useEffect, useRef, useState } from "react";
-import {
- DRAG_THRESHOLD_PX,
- liftCopy,
- markDragging,
- placeCue,
- placeGhost,
- type RowGhost,
-} from "@/features/chat";
-import { prefersReducedMotion } from "@/features/settings";
+import { DRAG_THRESHOLD_PX, markDragging } from "@/features/chat";
export type PinnedDropEdge = "top" | "bottom";
@@ -28,24 +19,6 @@ const KEY_ATTR = "data-pinned-drop-key";
const NO_DRAG_SELECTOR =
"button:not([data-model-picker-option]), a[href], [role='menuitem']";
-/** The raised copy of a carried row. */
-const ROW_GHOST_CLASS = "model-picker-row-ghost";
-
-/** Attributes the copy drops, so nothing finds it as an option or drop target. */
-const GHOST_DROPPED_ATTRS = [
- "id",
- SCOPE_ATTR,
- KEY_ATTR,
- "data-model-picker-option",
- "data-model-picker-active-option",
- "aria-current",
- "data-state",
- "data-slot",
-] as const;
-
-/** How long a dropped row takes to slide into its slot. */
-const SETTLE_MS = 180;
-
/** How far outside a row the pointer still aims at it. */
const NEAR_ROW_PX = 12;
@@ -72,49 +45,6 @@ function scrollerOf(element: Element | null): HTMLElement | null {
return null;
}
-/** The list the copy stays inside, even one too short to scroll. */
-function viewOf(row: HTMLElement): Element {
- for (let node = row.parentElement; node; node = node.parentElement) {
- const overflow = getComputedStyle(node).overflowY;
- if (overflow === "auto" || overflow === "scroll") return node;
- }
- return row.parentElement ?? document.documentElement;
-}
-
-/** Marks a row's pill when it is not the wrapper's first child (a fine-tuned row nests it). */
-const ROW_FACE_ATTR = "data-pinned-row-face";
-
-/** The row itself, inside the wrapper that holds the drop marks. */
-const faceOf = (row: Element): HTMLElement =>
- row.querySelector<HTMLElement>(`[${ROW_FACE_ATTR}]`) ??
- (row.firstElementChild as HTMLElement | null) ??
- (row as HTMLElement);
-
-/** Slides a dropped row from where it was let go into its slot. */
-function settleRow(scope: string, key: string, from: number) {
- // Two frames: measured after the drop re-renders the list.
- requestAnimationFrame(() =>
- requestAnimationFrame(() => {
- const row = document.querySelector<HTMLElement>(
- `[${SCOPE_ATTR}="${CSS.escape(scope)}"][${KEY_ATTR}="${CSS.escape(key)}"]`,
- );
- if (!row) return;
- const delta = from - faceOf(row).getBoundingClientRect().top;
- if (Math.abs(delta) < 2) return;
- row.style.transition = "none";
- row.style.transform = `translateY(${delta}px)`;
- row.style.zIndex = "1";
- row.getBoundingClientRect();
- row.style.transition = `transform ${SETTLE_MS}ms cubic-bezier(0.2, 0.8, 0.2, 1)`;
- row.style.transform = "";
- window.setTimeout(() => {
- row.style.transition = "";
- row.style.zIndex = "";
- }, SETTLE_MS + 20);
- }),
- );
-}
-
function edgeAt(rect: DOMRect, y: number): PinnedDropEdge {
return y < rect.top + rect.height / 2 ? "top" : "bottom";
}
@@ -195,7 +125,6 @@ export function usePinnedRowDrag(
const draggingRef = useRef<string | null>(null);
const targetRef = useRef<PinnedRowDrop | null>(null);
const scroller = useRef<HTMLElement | null>(null);
- const ghost = useRef<RowGhost | null>(null);
/** The gesture in flight, so a second press cannot overlap it. */
const press = useRef<{ end: () => void } | null>(null);
@@ -209,9 +138,6 @@ export function usePinnedRowDrag(
const clear = useCallback(() => {
draggingRef.current = null;
scroller.current = null;
- ghost.current?.element.remove();
- for (const overlay of ghost.current?.cues ?? []) overlay.remove();
- ghost.current = null;
markDragging(null, false);
setDraggingKey(null);
showTarget(null);
@@ -319,10 +245,7 @@ export function usePinnedRowDrag(
list.scrollTop += EDGE_STEP_PX;
}
}
- if (ghost.current) placeGhost(ghost.current, at.y);
showTarget(aim(at.x, at.y));
- // Redraw the drop line above the copy.
- if (ghost.current) placeCue(ghost.current);
};
const self = {
end: () => {
@@ -357,14 +280,6 @@ export function usePinnedRowDrag(
}
started = true;
scroller.current = scrollerOf(row);
- ghost.current = liftCopy(
- faceOf(row),
- startY,
- scroller.current ?? viewOf(row),
- ROW_GHOST_CLASS,
- GHOST_DROPPED_ATTRS,
- );
- placeGhost(ghost.current, moved.clientY);
// The picker's own list, not the body: see markDragging.
markDragging(scroller.current ?? row.parentElement, true);
try {
@@ -387,13 +302,8 @@ export function usePinnedRowDrag(
swallowClick();
if (escaped) return;
const drop = aim(released.clientX, released.clientY);
- const from = ghost.current?.element.getBoundingClientRect().top ?? null;
clear();
- if (!drop) return;
- optionsRef.current.onDrop(key, drop);
- if (from !== null && !prefersReducedMotion()) {
- settleRow(optionsRef.current.scope, key, from);
- }
+ if (drop) optionsRef.current.onDrop(key, drop);
}
function onCancel(aborted: PointerEvent) {
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index 326fe912827..ea22585783c 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -252,13 +252,10 @@ const MODEL_DEFAULTS: Array<{ match: string; steps: number; guidance: number }>
// "distilled" before the generic "ltx": the distilled model runs at 8 steps, guidance 1.
{ match: "distilled", steps: 8, guidance: 1 },
{ match: "ltx", steps: 40, guidance: 4 },
- // ComfyUI's templates for the same models. Wan2.2-T2V-A14B: 20 steps at CFG 3.5, before the generic Wan key.
- { match: "a14b", steps: 20, guidance: 3.5 },
- { match: "wan2.2-14b", steps: 20, guidance: 3.5 },
- // Wan2.2-TI2V-5B: 20 steps at CFG 5. The backend supplies the fps per family.
- { match: "wan", steps: 20, guidance: 5 },
- // HunyuanVideo-1.5 runs 20 steps; guidance 6 matches the guider the repo ships.
- { match: "hunyuanvideo", steps: 20, guidance: 6 },
+ // Wan2.2 pipelines default to 50 steps at CFG 5.0 (diffusers 0.39). The backend supplies the fps per family.
+ { match: "wan", steps: 50, guidance: 5 },
+ // HunyuanVideo-1.5 runs 50 steps; guidance 6 matches the guider the repo ships.
+ { match: "hunyuanvideo", steps: 50, guidance: 6 },
];
function defaultsFor(repoId: string): { steps: number; guidance: number } {
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index 785f56e819e..8b0a76fbe94 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -4755,72 +4755,25 @@ html[data-chat-font] .aui-root {
}
.sidebar-row-ghost {
- --row-ghost-surface: var(--sidebar);
position: fixed;
top: 0;
z-index: 60;
display: flex;
align-items: center;
border-radius: 10px;
+ background: var(--sidebar-accent);
+ box-shadow:
+ 0 0 0 1px color-mix(in oklab, var(--foreground) 8%, transparent),
+ 0 8px 24px -8px rgb(0 0 0 / 0.35);
pointer-events: none;
will-change: transform;
}
-.sidebar-section-ghost {
- --row-ghost-surface: var(--sidebar);
- display: flex;
- align-items: center;
- border-radius: 10px;
- will-change: transform;
-}
-
-/* A carried row or header: faintly frosted, a shade darker than its list, on a hairline. */
-:is(.sidebar-row-ghost, .sidebar-section-ghost, .model-picker-row-ghost) {
- background: color-mix(in oklab, color-mix(in oklab, var(--row-ghost-surface), black 4%) 62%, transparent);
- -webkit-backdrop-filter: blur(0.5px) saturate(1.05);
- backdrop-filter: blur(0.5px) saturate(1.05);
- box-shadow:
- 0 0 0 1px rgb(0 0 0 / 0.06),
- 0 4px 12px -4px rgb(0 0 0 / 0.12);
-}
-
-.dark :is(.sidebar-row-ghost, .sidebar-section-ghost, .model-picker-row-ghost) {
- background: color-mix(in oklab, color-mix(in oklab, var(--row-ghost-surface), black 22%) 62%, transparent);
- box-shadow:
- 0 0 0 1px rgb(255 255 255 / 0.045),
- 0 6px 16px -6px rgb(0 0 0 / 0.5);
-}
-
.sidebar-section-ghost > *,
.sidebar-row-ghost * {
pointer-events: none;
}
-/* A Pinned row carried in the model picker (use-pinned-row-drag.ts). */
-.model-picker-row-ghost {
- --row-ghost-surface: var(--popover);
- position: fixed;
- top: 0;
- z-index: 60;
- display: flex;
- align-items: center;
- pointer-events: none;
- will-change: transform;
-}
-
-.model-picker-row-ghost * {
- pointer-events: none;
-}
-
-/* The row fills the pill, which paints the tint. Its margin stays behind: the pill was sized
- without it, so a Connected row's ml-4 would push the copy off its own pill. */
-.model-picker-row-ghost > * {
- width: 100%;
- height: 100%;
- margin: 0;
- background: transparent;
-}
-
/* The drop cue under a carried row's copy, drawn again above it (use-sidebar-drag.ts). */
.sidebar-drop-cue-overlay {
position: fixed;
@@ -4830,7 +4783,7 @@ html[data-chat-font] .aui-root {
pointer-events: none;
}
-/* A row's copy is its face as drawn, never lit like the open chat. */
+/* A row's copy is its face as drawn, lit like a hovered row but never like the open chat. */
.sidebar-row-ghost > [data-sidebar="menu-button"] {
width: 100%;
height: 100%;
diff --git a/studio/frontend/tests/chat-rename-ime.test.ts b/studio/frontend/tests/chat-rename-ime.test.ts
deleted file mode 100644
index 53d860d0892..00000000000
--- a/studio/frontend/tests/chat-rename-ime.test.ts
+++ /dev/null
@@ -1,162 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-
-import assert from "node:assert/strict";
-import test from "node:test";
-import ts from "typescript";
-import { readSrc } from "./helpers/kit.ts";
-
-// Execute the shipped callbacks, following composer-submit-path.test.ts. This
-// catches guards placed after preventDefault or after the rename side effects.
-function handler(
- file: string,
- inline: boolean | "escape",
- deps: Record<string, unknown>,
-) {
- const source = ts.createSourceFile(
- file,
- readSrc(file),
- ts.ScriptTarget.Latest,
- true,
- ts.ScriptKind.TSX,
- );
- const matches: ts.Node[] = [];
- function visit(node: ts.Node) {
- if (inline === "escape") {
- // The rename dialog's DialogContent, which wraps the commitRename input.
- if (
- ts.isJsxAttribute(node) &&
- node.name.getText(source) === "onEscapeKeyDown" &&
- node.initializer &&
- ts.isJsxExpression(node.initializer) &&
- node.initializer.expression &&
- ts.isArrowFunction(node.initializer.expression) &&
- node.parent.parent.parent.getText(source).includes("commitRename()")
- )
- matches.push(node.initializer.expression);
- } else if (inline) {
- if (
- ts.isFunctionDeclaration(node) &&
- node.name?.text === "handleInlineRenameKeyDown"
- )
- matches.push(node);
- } else if (
- ts.isJsxAttribute(node) &&
- node.name.getText(source) === "onKeyDown" &&
- node.initializer &&
- ts.isJsxExpression(node.initializer) &&
- node.initializer.expression &&
- ts.isArrowFunction(node.initializer.expression) &&
- node.initializer.expression.getText(source).includes("commitRename()")
- )
- matches.push(node.initializer.expression);
- ts.forEachChild(node, visit);
- }
- visit(source);
- assert.equal(
- matches.length,
- 1,
- `${file}: unique ${inline === "escape" ? "dialog Escape" : "rename"} handler`,
- );
- const code = ts.transpileModule(`return (${matches[0].getText(source)});`, {
- compilerOptions: {
- target: ts.ScriptTarget.ES2022,
- module: ts.ModuleKind.None,
- },
- }).outputText;
- return new Function(...Object.keys(deps), code)(...Object.values(deps)) as (
- event: object,
- ) => void;
-}
-
-function fixture(file: string, inline: boolean, dirty = true) {
- const effects: string[] = [];
- const skipRenameBlurRef = { current: false };
- const onKey = handler(file, inline, {
- renameDirty: dirty,
- skipRenameBlurRef,
- commitRename: () => effects.push("save"),
- setRenamingTarget: () => effects.push("close"),
- });
- function key(
- key: string,
- isComposing = false,
- keyCode = key === "Enter" ? 13 : 27,
- ) {
- onKey({
- key,
- keyCode,
- nativeEvent: { isComposing, keyCode },
- preventDefault: () => effects.push("prevent"),
- });
- }
- return { effects, skipRenameBlurRef, key };
-}
-
-for (const [name, file, inline] of [
- ["sidebar inline", "components/app-sidebar.tsx", true],
- ["sidebar dialog", "components/app-sidebar.tsx", false],
- ["thread sidebar dialog", "features/chat/thread-sidebar.tsx", false],
-] as const) {
- for (const [isComposing, keyCode] of [
- [true, 13],
- [false, 229],
- [true, 229],
- ] as const) {
- test(`${name}: IME Enter (${isComposing}, ${keyCode}) keeps editing until a separate Enter`, () => {
- const f = fixture(file, inline);
- f.key("Enter", isComposing, keyCode);
- assert.deepEqual(f.effects, []);
- assert.equal(f.skipRenameBlurRef.current, false);
- f.key("Enter");
- assert.equal(f.effects.filter((effect) => effect === "save").length, 1);
- if (inline) assert.equal(f.skipRenameBlurRef.current, true);
- });
- }
-}
-
-for (const dirty of [true, false]) {
- test(`sidebar inline: candidate Escape preserves editing (dirty=${dirty})`, () => {
- const f = fixture("components/app-sidebar.tsx", true, dirty);
- f.key("Escape", true);
- f.key("Escape", false, 229);
- assert.deepEqual(f.effects, []);
- assert.equal(f.skipRenameBlurRef.current, false);
- f.key("Escape");
- assert.deepEqual(f.effects, ["prevent", "close"]);
- assert.equal(f.skipRenameBlurRef.current, true);
- });
-}
-
-test("sidebar inline: an unchanged IME Enter does not close the input", () => {
- const f = fixture("components/app-sidebar.tsx", true, false);
- f.key("Enter", true);
- f.key("Enter", false, 229);
- assert.deepEqual(f.effects, []);
- f.key("Enter");
- assert.deepEqual(f.effects, ["prevent", "close"]);
-});
-
-for (const [name, file] of [
- ["sidebar dialog", "components/app-sidebar.tsx"],
- ["thread sidebar dialog", "features/chat/thread-sidebar.tsx"],
-] as const) {
- test(`${name}: candidate Escape does not close the dialog`, () => {
- // Radix calls this from a document capture listener, before the input's
- // onKeyDown, so the input guard alone cannot keep the dialog open.
- const onEscape = handler(file, "escape", {});
- const press = (isComposing: boolean, keyCode: number) => {
- let prevented = false;
- onEscape({
- key: "Escape",
- isComposing,
- keyCode,
- preventDefault: () => (prevented = true),
- });
- return prevented;
- };
- assert.equal(press(true, 27), true);
- assert.equal(press(false, 229), true);
- assert.equal(press(false, 27), false);
- });
-}
diff --git a/studio/frontend/tests/image-generation-defaults.test.ts b/studio/frontend/tests/image-generation-defaults.test.ts
index 78d115c528b..5693f061710 100644
--- a/studio/frontend/tests/image-generation-defaults.test.ts
+++ b/studio/frontend/tests/image-generation-defaults.test.ts
@@ -17,8 +17,8 @@ import { readSrc } from "./helpers/kit.ts";
test("distinguishes Klein base checkpoints from distilled checkpoints", () => {
for (const size of ["4B", "9B"]) {
assert.deepEqual(defaultsFor(`unsloth/FLUX.2-klein-base-${size}`), {
- steps: 20,
- guidance: 5,
+ steps: 50,
+ guidance: 4,
});
assert.deepEqual(defaultsFor(`unsloth/FLUX.2-klein-${size}`), {
steps: 4,
@@ -33,7 +33,7 @@ test("keeps the existing family defaults and fallback", () => {
guidance: 3.5,
});
assert.deepEqual(defaultsFor("black-forest-labs/FLUX.1-dev"), {
- steps: 20,
+ steps: 28,
guidance: 3.5,
});
assert.deepEqual(defaultsFor("local/unknown-image-model"), {
@@ -158,22 +158,3 @@ test("every images-page canvas seed passes the quant provenance", () => {
assert.match(call.slice(0, 400), /transformerQuantSource: status\??\.resolved\?\.transformer_quant\?\.source/);
}
});
-
-test("defaults follow ComfyUI's official templates for the same model", () => {
- for (const [id, want] of [
- ["black-forest-labs/FLUX.1-dev", { steps: 20, guidance: 3.5 }],
- ["black-forest-labs/FLUX.1-Krea-dev", { steps: 20, guidance: 3.5 }],
- ["black-forest-labs/FLUX.1-Kontext-dev", { steps: 20, guidance: 2.5 }],
- ["black-forest-labs/FLUX.2-dev", { steps: 20, guidance: 4 }],
- ["Qwen/Qwen-Image-Edit-2511", { steps: 40, guidance: 4 }],
- ["Qwen/Qwen-Image-2512", { steps: 50, guidance: 4 }],
- ["Qwen/Qwen-Image", { steps: 20, guidance: 4 }],
- ["Tongyi-MAI/Z-Image-Turbo", { steps: 8, guidance: 0 }],
- // diffusers Z-Image guidance g equals ComfyUI cfg g + 1.
- ["Tongyi-MAI/Z-Image", { steps: 25, guidance: 3 }],
- ["stabilityai/stable-diffusion-xl-base-1.0", { steps: 25, guidance: 7 }],
- ["ideogram-ai/ideogram-4-fp8", { steps: 20, guidance: 7 }],
- ] as const) {
- assert.deepEqual(defaultsFor(id), want, id);
- }
-});
diff --git a/studio/frontend/tests/image-unified-edit.test.ts b/studio/frontend/tests/image-unified-edit.test.ts
index 6bd27846eef..d1485b96f38 100644
--- a/studio/frontend/tests/image-unified-edit.test.ts
+++ b/studio/frontend/tests/image-unified-edit.test.ts
@@ -200,16 +200,16 @@ test("prompt helpers edit the visible instruction idempotently", () => {
);
});
-test("Qwen-Image-2.1 samples at 25 steps without guidance under every artifact name", () => {
+test("Qwen-Image-2.1 samples at 40 steps without guidance under every artifact name", () => {
for (const id of [
"Qwen/Qwen-Image-2.1",
"unsloth/Qwen-Image-2.1-GGUF",
"unsloth/Qwen-Image-2.1-FP8",
]) {
- assert.deepEqual(defaultsFor(id), { steps: 25, guidance: 1 }, id);
+ assert.deepEqual(defaultsFor(id), { steps: 40, guidance: 1 }, id);
}
assert.deepEqual(defaultsFor("Qwen/Qwen-Image-2512"), {
- steps: 50,
+ steps: 20,
guidance: 4,
});
});
diff --git a/studio/frontend/tests/model-picker-pinned-drag-preview.test.ts b/studio/frontend/tests/model-picker-pinned-drag-preview.test.ts
deleted file mode 100644
index 1a972e1370c..00000000000
--- a/studio/frontend/tests/model-picker-pinned-drag-preview.test.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import { readSrc } from "./helpers/kit.ts";
-
-// A Pinned row carried in the model picker lifts as a copy under the pointer, as a sidebar chat
-// does, through the same helpers so the two never drift. Every tab (Chat, Images, Audio, Video)
-// draws its picker with HubModelPicker, so they all carry rows this way.
-
-const HOOK = readSrc("features/model-picker/components/model-selector/use-pinned-row-drag.ts");
-const SIDEBAR = readSrc("features/chat/hooks/use-sidebar-drag.ts");
-const PICKERS = readSrc("features/model-picker/components/model-selector/pickers.tsx");
-const CSS = readSrc("index.css");
-
-test("the sidebar's lift, follow and cue helpers are shared", () => {
- for (const name of ["liftCopy", "placeGhost", "placeCue"]) {
- assert.match(SIDEBAR, new RegExp(`export function ${name}\\(`), name);
- }
- // The sidebar still lifts its rows through the shared copy.
- assert.match(SIDEBAR, /liftCopy\(face, pressY, view, ROW_GHOST_CLASS, GHOST_DROPPED_ATTRS\)/);
-});
-
-test("a carried Pinned row lifts a copy that follows the pointer", () => {
- assert.match(
- HOOK,
- /started = true;\n\s*scroller\.current = scrollerOf\(row\);\n\s*ghost\.current = liftCopy\(\n\s*faceOf\(row\),/,
- );
- assert.match(HOOK, /if \(ghost\.current\) placeGhost\(ghost\.current, at\.y\);/);
- // A picture only: never an option the list's keys, the drop hit test or a tooltip finds.
- for (const attr of ['"id"', "SCOPE_ATTR", "KEY_ATTR", '"data-model-picker-option"', '"data-state"']) {
- assert.match(HOOK, new RegExp(`GHOST_DROPPED_ATTRS = \\[[^\\]]*${attr.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`), attr);
- }
- assert.match(CSS, /\.model-picker-row-ghost \{\n[^}]*position: fixed;[^}]*z-index: 60;/);
- assert.match(CSS, /\.model-picker-row-ghost \* \{\n\tpointer-events: none;/);
-});
-
-test("every copy is a faintly frosted shade darker than the list it came from", () => {
- const ghosts = String.raw`:is\(\.sidebar-row-ghost, \.sidebar-section-ghost, \.model-picker-row-ghost\)`;
- const light = new RegExp(String.raw`\n${ghosts} \{([^}]*)\}`).exec(CSS);
- const dark = new RegExp(String.raw`\.dark ${ghosts} \{([^}]*)\}`).exec(CSS);
- assert.ok(light, "shared ghost look");
- assert.ok(dark, "shared ghost look in dark mode");
- assert.match(light[1], /background: color-mix\(in oklab, color-mix\(in oklab, var\(--row-ghost-surface\), black 4%\) 62%, transparent\);/);
- assert.match(dark[1], /background: color-mix\(in oklab, color-mix\(in oklab, var\(--row-ghost-surface\), black 22%\) 62%, transparent\);/);
- // Faint blur, so what is underneath stays readable.
- assert.match(light[1], /\bbackdrop-filter: blur\(0\.5px\) saturate\(1\.05\);/);
- assert.match(light[1], /0 0 0 1px rgb\(0 0 0 \/ 0\.06\)/);
- assert.match(dark[1], /0 0 0 1px rgb\(255 255 255 \/ 0\.045\)/);
- assert.match(CSS, /\.sidebar-row-ghost \{\n\t--row-ghost-surface: var\(--sidebar\);/);
- assert.match(CSS, /\.sidebar-section-ghost \{\n\t--row-ghost-surface: var\(--sidebar\);/);
- assert.match(CSS, /\.model-picker-row-ghost \{\n\t--row-ghost-surface: var\(--popover\);/);
-});
-
-test("the drop line is drawn again above the copy", () => {
- // Read at render: the chat barrel imports the picker back, so a module-scope read is undefined.
- assert.match(PICKERS, /className=\{cn\("relative", edge && \[DROP_CUE_CLASS, PINNED_DROP_CUE\[edge\]\]\)\}/);
- assert.match(HOOK, /showTarget\(aim\(at\.x, at\.y\)\);\n[^\n]*\n\s*if \(ghost\.current\) placeCue\(ghost\.current\);/);
-});
-
-test("every way a drag ends takes the copy down, and a drop settles into place", () => {
- assert.match(
- HOOK,
- /const clear = useCallback\(\(\) => \{[^]*?ghost\.current\?\.element\.remove\(\);\n\s*for \(const overlay of ghost\.current\?\.cues \?\? \[\]\) overlay\.remove\(\);\n\s*ghost\.current = null;/,
- );
- assert.match(HOOK, /if \(from !== null && !prefersReducedMotion\(\)\) \{\n\s*settleRow\(optionsRef\.current\.scope, key, from\);/);
-});
-
-test("the copy sits on its own pill for every Pinned row kind", () => {
- // A Connected row's ml-4 is not part of the pill the copy is sized to, so it must not carry over.
- assert.match(CSS, /\.model-picker-row-ghost > \* \{\n[^}]*margin: 0;/);
- // A fine-tuned row nests its pill in a keyed wrapper; the drag lifts the marked pill instead.
- assert.match(HOOK, /const ROW_FACE_ATTR = "data-pinned-row-face";/);
- assert.match(HOOK, /const faceOf = \(row: Element\): HTMLElement =>\n\s*row\.querySelector<HTMLElement>\(`\[\$\{ROW_FACE_ATTR\}\]`\) \?\?/);
- assert.match(
- PICKERS,
- /<div key=\{adapter\.id\}>\n\s*<div\n\s*className=\{downloadedRowShellClassName\(value === adapter\.id\)\}\n[^\n]*\n\s*data-pinned-row-face=""/,
- );
-});
diff --git a/tests/studio/install/test_selection_logic.py b/tests/studio/install/test_selection_logic.py
index a0a83abdf4d..30e09461044 100644
--- a/tests/studio/install/test_selection_logic.py
+++ b/tests/studio/install/test_selection_logic.py
@@ -454,7 +454,7 @@ class TestStudioLocalhostIpv6Warning:
monkeypatch.setattr(
run_module,
"_verify_global_reachability",
- lambda display_host, port, **_: calls["reachability"].append((display_host, port)),
+ lambda display_host, port: calls["reachability"].append((display_host, port)),
)
return calls
diff --git a/tests/studio/test_nvidia_python_probe_parity.ps1 b/tests/studio/test_nvidia_python_probe_parity.ps1
index c09d78be9d4..09eb278afda 100644
--- a/tests/studio/test_nvidia_python_probe_parity.ps1
+++ b/tests/studio/test_nvidia_python_probe_parity.ps1
@@ -435,13 +435,10 @@ foreach ($row in @(
# Shared deadline 2 x 1500 ms; the first child burns 1200 ms of it, leaving under 3 s.
$got = Invoke-RawWithStub @("TIMEOUT", "cuda;12;8;8.9") -TimeoutMs 1500 -TimeoutSleepMs 1200
Check "stub: no CUDA-only child when under 3 s of the shared budget remain" ($script:StubCalls.Count -eq 1 -and $got -eq "")
-# Shared deadline 2 x 4000 ms; the first child hangs for 3200 ms. Each child's bound leaves 2 s to
-# reap it, so the CUDA-only child gets what is left minus that (about 2800 ms), and the pair ends
-# by the deadline. Not 3000 ms: that put the expected bound exactly on the window's upper edge, and
-# a Start-Sleep that wakes a tick early on Windows made it 3001 and failed a run that was right.
-$got = Invoke-RawWithStub @("TIMEOUT", "cuda;12;8;8.9") -TimeoutMs 4000 -TimeoutSleepMs 3200
-$secondMs = if ($script:StubCalls.Count -ge 2) { $script:StubCalls[1].TimeoutMs } else { "none" }
-Check "stub: every child's bound leaves 2 s of the shared deadline to reap it (second bound: $secondMs ms)" (
+# Shared deadline 2 x 4000 ms; the first child hangs for 3000 ms. Each child's bound leaves 2 s to
+# reap it, so the CUDA-only child gets what is left minus that, and the pair ends by the deadline.
+$got = Invoke-RawWithStub @("TIMEOUT", "cuda;12;8;8.9") -TimeoutMs 4000 -TimeoutSleepMs 3000
+Check "stub: every child's bound leaves 2 s of the shared deadline to reap it" (
$script:StubCalls.Count -eq 2 -and $script:StubCalls[0].TimeoutMs -eq 4000 -and
$script:StubCalls[1].TimeoutMs -le 3000 -and $script:StubCalls[1].TimeoutMs -ge 2000)
# Shared deadline 2 x 5000 ms; the first child burns 5000 ms, so the retry gets only the rest.