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.

Tests: make the --help, media scan, installer comparer and harness resolver checks hold on every host (#14116)

Daniel Han4c5fb4007ed0
diff --git a/.github/scripts/compare_installer_evidence.py b/.github/scripts/compare_installer_evidence.py
index 6a018c5ec82..b9b16550659 100644
--- a/.github/scripts/compare_installer_evidence.py
+++ b/.github/scripts/compare_installer_evidence.py
@@ -222,17 +222,34 @@ _PARTIAL_PROGRESS_FRAME = re.compile(r"[█▒]*▒[█▒]*\s+(?:<percent>|<siz
# bar that repeats the line kept right before it is dropped, so a download that never finishes, or a
# second download (its own "Downloading" line sits between the bars), still compares.
_FULL_PROGRESS_FRAME = re.compile(r"█+\s+(?:<percent>|<size> / <size>)")
+_CONTROL = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07]*\x07")
+
+
+def _raw_frame(raw: str) -> str:
+ """The frame as drawn, sizes and units included, without terminal escapes, redraw controls or spacing."""
+ return " ".join(re.sub(r"[\r\x08]", "", _CONTROL.sub("", raw)).split())
def normalise_transcript(text: str) -> list[str]:
lines = []
+ # A repeated full bar is a redraw only if no partial frame came between and the raw frame matches.
+ last_frame = None
+ frame_since_kept = False
for raw in text.splitlines():
line = normalise_line(raw)
+ if _PARTIAL_PROGRESS_FRAME.fullmatch(line.strip()):
+ frame_since_kept = True
+ continue
if (
not line.strip()
or line.strip() in _SPINNER_FRAMES
- or _PARTIAL_PROGRESS_FRAME.fullmatch(line.strip())
- or (lines and line == lines[-1] and _FULL_PROGRESS_FRAME.fullmatch(line.strip()))
+ or (
+ lines
+ and line == lines[-1]
+ and not frame_since_kept
+ and _raw_frame(raw) == last_frame
+ and _FULL_PROGRESS_FRAME.fullmatch(line.strip())
+ )
):
continue
# Runner-injected noise, and ONLY what the runner injects. These carry the workflow's own
@@ -253,6 +270,8 @@ def normalise_transcript(text: str) -> list[str]:
if line.startswith(("##[group]", "##[endgroup]", "::group::", "::endgroup::", "##[debug]")):
continue
lines.append(line)
+ last_frame = _raw_frame(raw)
+ frame_since_kept = False
return lines
diff --git a/studio/backend/tests/test_media_model_index_accounts.py b/studio/backend/tests/test_media_model_index_accounts.py
index 47cfd3a246c..0f4e15aa73d 100644
--- a/studio/backend/tests/test_media_model_index_accounts.py
+++ b/studio/backend/tests/test_media_model_index_accounts.py
@@ -27,6 +27,18 @@ def home(monkeypatch, tmp_path):
# machine with image models downloaded, they would be listed beside the private ones.
monkeypatch.delitem(hf_cache_settings._EXPLICIT_CACHE_ENV, "HF_HOME", raising = False)
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "xdg"))
+ # The scan also reads hf_default_cache_dir() (ignores XDG), the LM Studio / Hermes / Ollama / oMLX dirs and ./models.
+ import utils.paths
+
+ monkeypatch.setattr(utils.paths, "hf_default_cache_dir", lambda: tmp_path / "default_hub")
+ for name in (
+ "lmstudio_model_dirs",
+ "hermes_model_dirs",
+ "ollama_model_dirs",
+ "omlx_model_dirs",
+ ):
+ monkeypatch.setattr(utils.paths, name, lambda: [])
+ monkeypatch.chdir(tmp_path)
monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)
monkeypatch.setattr(models_route, "_local_model_task", lambda info: mas.IMAGE_TASK)
mas.invalidate_index()
diff --git a/studio/backend/tests/test_openai_catalog.py b/studio/backend/tests/test_openai_catalog.py
index 50960523a40..947db907339 100644
--- a/studio/backend/tests/test_openai_catalog.py
+++ b/studio/backend/tests/test_openai_catalog.py
@@ -26,6 +26,18 @@ def _no_host_default_hf_cache(monkeypatch, tmp_path):
monkeypatch.delitem(hf_cache_settings._EXPLICIT_CACHE_ENV, "HF_HOME", raising = False)
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "xdg"))
+ # The scan also reads hf_default_cache_dir() (ignores XDG), the LM Studio / Hermes / Ollama / oMLX dirs and ./models.
+ import utils.paths
+
+ monkeypatch.setattr(utils.paths, "hf_default_cache_dir", lambda: tmp_path / "default_hub")
+ for name in (
+ "lmstudio_model_dirs",
+ "hermes_model_dirs",
+ "ollama_model_dirs",
+ "omlx_model_dirs",
+ ):
+ monkeypatch.setattr(utils.paths, name, lambda: [])
+ monkeypatch.chdir(tmp_path)
class _Info:
diff --git a/studio/backend/tests/test_studio_api.py b/studio/backend/tests/test_studio_api.py
index 0972bcfca6e..f25b8b92a4c 100644
--- a/studio/backend/tests/test_studio_api.py
+++ b/studio/backend/tests/test_studio_api.py
@@ -131,13 +131,22 @@ def _stream_http(
def test_help_output():
"""``unsloth studio run --help`` should show all documented options."""
# Rich lays the help out at 80 columns when stdout is not a terminal and cuts the
- # "--max-seq-length, --context-length" cell to "--max-seq-lengt…".
+ # "--max-seq-length, --context-length" cell to "--max-seq-lengt…". Typer passes an inherited
+ # TERMINAL_WIDTH as an explicit width, and GITHUB_ACTIONS / FORCE_COLOR / PY_COLORS force a
+ # terminal whose colour codes split every flag, so pin both. The child writes UTF-8.
result = subprocess.run(
["unsloth", "studio", "run", "--help"],
capture_output = True,
text = True,
+ encoding = "utf-8",
+ errors = "replace",
timeout = 15,
- env = {**os.environ, "COLUMNS": "200"},
+ env = {
+ **os.environ,
+ "COLUMNS": "200",
+ "TERMINAL_WIDTH": "200",
+ "_TYPER_FORCE_DISABLE_TERMINAL": "1",
+ },
)
out = result.stdout
assert result.returncode == 0, f"--help exited with {result.returncode}"
diff --git a/tests/python/test_installer_differential_comparer.py b/tests/python/test_installer_differential_comparer.py
index 1b71c289ecd..92eaf927680 100644
--- a/tests/python/test_installer_differential_comparer.py
+++ b/tests/python/test_installer_differential_comparer.py
@@ -230,6 +230,58 @@ def test_a_second_download_still_compares(tmp_path: Path) -> None:
assert _run(base, head).returncode == 2
+def test_a_second_transfer_with_no_header_still_compares(tmp_path: Path) -> None:
+ """A partial frame between two full bars is a new transfer, not a redraw of the first."""
+ full = " ██████████████████████████████ 17.2 MB / 17.2 MB"
+ partial = " ███████████████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ 8.6 MB / 17.2 MB"
+ lines = BASELINE.split("\n")
+ base = _write(
+ tmp_path / "base", transcript = "\n".join(lines[:1] + [full, partial, full] + lines[1:])
+ )
+ head = _write(tmp_path / "head", transcript = "\n".join(lines[:1] + [full] + lines[1:]))
+ assert _run(base, head).returncode == 2
+
+
+def test_a_redraw_that_only_adds_a_colour_escape_is_still_a_redraw(tmp_path: Path) -> None:
+ """A style escape on one copy of the full bar does not make it a second download."""
+ full = " ██████████████████████████████ 17.2 MB / 17.2 MB"
+ styled = "\x1b[32m" + full + "\x1b[0m"
+ lines = BASELINE.split("\n")
+ base = _write(tmp_path / "base", transcript = "\n".join(lines[:1] + [full, styled] + lines[1:]))
+ head = _write(tmp_path / "head", transcript = "\n".join(lines[:1] + [full] + lines[1:]))
+ assert _run(base, head).returncode == 0
+
+
+def test_a_redraw_drawn_with_backspaces_is_still_a_redraw(tmp_path: Path) -> None:
+ """Backspaces the terminal used to redraw the finished bar do not make it a second download."""
+ full = " ██████████████████████████████ 17.2 MB / 17.2 MB"
+ redrawn = "\x08" * 4 + full
+ lines = BASELINE.split("\n")
+ base = _write(tmp_path / "base", transcript = "\n".join(lines[:1] + [full, redrawn] + lines[1:]))
+ head = _write(tmp_path / "head", transcript = "\n".join(lines[:1] + [full] + lines[1:]))
+ assert _run(base, head).returncode == 0
+
+
+def test_two_finished_downloads_of_different_sizes_still_compare(tmp_path: Path) -> None:
+ """Both bars normalise to <size> / <size>, but different raw sizes are two downloads."""
+ first = " ██████████████████████████████ 17.2 MB / 17.2 MB"
+ second = " ██████████████████████████████ 34.4 MB / 34.4 MB"
+ lines = BASELINE.split("\n")
+ base = _write(tmp_path / "base", transcript = "\n".join(lines[:1] + [first, second] + lines[1:]))
+ head = _write(tmp_path / "head", transcript = "\n".join(lines[:1] + [first] + lines[1:]))
+ assert _run(base, head).returncode == 2
+
+
+def test_two_finished_downloads_differing_only_in_units_still_compare(tmp_path: Path) -> None:
+ """`1.0 MB / 1.0 MB` then `1.0 GB / 1.0 GB` are two downloads, not a redraw."""
+ first = " ██████████████████████████████ 1.0 MB / 1.0 MB"
+ second = " ██████████████████████████████ 1.0 GB / 1.0 GB"
+ lines = BASELINE.split("\n")
+ base = _write(tmp_path / "base", transcript = "\n".join(lines[:1] + [first, second] + lines[1:]))
+ head = _write(tmp_path / "head", transcript = "\n".join(lines[:1] + [first] + lines[1:]))
+ assert _run(base, head).returncode == 2
+
+
def test_a_download_that_never_finishes_still_compares(tmp_path: Path) -> None:
"""The full bar a finished download ends on is kept, so losing it is reported."""
lines = BASELINE.split("\n")
diff --git a/tests/studio/_ts_deps.py b/tests/studio/_ts_deps.py
index ce7e1b90eef..04e89ba98a9 100644
--- a/tests/studio/_ts_deps.py
+++ b/tests/studio/_ts_deps.py
@@ -21,6 +21,10 @@ _IDENT_RE = re.compile(r"(?<![\w$])([A-Za-z_$][\w$]*)")
_IMPORT_RE = re.compile(
r"^import\s+(?P<clause>[^;]*?)\s+from\s+[\"'](?P<spec>[^\"']+)[\"']", re.MULTILINE
)
+_TYPE_REEXPORT_RE = re.compile(
+ r"^export\s+type\s+\{(?P<names>[^}]*)\}\s+from\s+[\"'](?P<spec>[^\"']+)[\"']", re.MULTILINE
+)
+_TYPE_REEXPORT_NAME_RE = re.compile(r"([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?")
_REEXPORT_RE = re.compile(
r"^export\s+(?P<clause>\{[^}]*\}|\*)\s+from\s+[\"'](?P<spec>[^\"']+)[\"']", re.MULTILINE
)
@@ -32,6 +36,29 @@ _FUNCTION_DECL_RE = re.compile(
r"^(?:export\s+)?(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*=\s*"
r"(?:async\s+function\b|function\b|(?:async\s*)?(?:\([^()]*\)|[A-Za-z_$][\w$]*)\s*=>)"
)
+_FUNCTION_KEYWORD_INIT_RE = re.compile(r"=\s*(?:async\s+)?function\b")
+
+
+def _invokes_its_function(text: str) -> bool:
+ """`const v = function () {...}(...)` calls the function on load; `{...} as Fn` and `{...};` do not."""
+ blanked = _blank_noise(text)
+ found = _FUNCTION_KEYWORD_INIT_RE.search(blanked)
+ if found is None:
+ return False
+ start = blanked.find("{", found.end())
+ if start == -1:
+ return False
+ depth = 0
+ for i in range(start, len(blanked)):
+ if blanked[i] in "{([":
+ depth += 1
+ elif blanked[i] in "})]":
+ depth -= 1
+ if depth == 0:
+ return blanked[i + 1 :].lstrip().startswith(("(", ")("))
+ return False
+
+
_SAFE_INIT_RE = re.compile(
r"^(?:/|[\"'`]|\d|\[|\{|!|new\s+(?:Set|Map|RegExp|Date)\b"
r"|async\s+function\b|function\b|async\s*\(|\(|[A-Za-z_$][\w$]*\s*(?:=>|;))"
@@ -250,6 +277,23 @@ class _Module:
)
self.imports = self._parse(_IMPORT_RE)
self.reexports = self._parse(_REEXPORT_RE)
+ # Type-only re-exports (`export type { A }`, `export { type A }`) name erased types; never lifted.
+ self.type_reexports = {
+ (alias or name): (match.group("spec"), name)
+ for match in _TYPE_REEXPORT_RE.finditer(self.uncommented)
+ for name, alias in _TYPE_REEXPORT_NAME_RE.findall(match.group("names"))
+ }
+ for match in _REEXPORT_RE.finditer(self.uncommented):
+ braces = re.search(r"\{([^}]*)\}", match.group("clause"), re.DOTALL)
+ for entry in braces.group(1).split(",") if braces else ():
+ inline = re.fullmatch(
+ r"\s*type\s+([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*", entry
+ )
+ if inline:
+ self.type_reexports[inline.group(2) or inline.group(1)] = (
+ match.group("spec"),
+ inline.group(1),
+ )
def _parse(self, pattern: re.Pattern[str]) -> dict[str, tuple[str, str]]:
"""``local name -> (module specifier, exported name)`` for one statement kind."""
@@ -414,6 +458,29 @@ def resolve_dependencies(
order: list[str] = []
seen: set[tuple[Path, str]] = set()
+ def type_only(
+ name: str,
+ origin: Path,
+ hops: int = 0,
+ ) -> bool:
+ """``name`` as seen from ``origin`` is a type or interface, which Node erases."""
+ home = module(origin)
+ if name in home.declarations:
+ return all(kind in {"type", "interface"} for kind, _ in home.declarations[name])
+ target = home.imports.get(name) or home.reexports.get(name) or home.type_reexports.get(name)
+ if target is None or hops > 8:
+ return False
+ path = _resolve_module(target[0], origin, root)
+ if path is None and target[0].startswith((".", _ALIAS)):
+ # Lifting never follows into a component file, but a type declared there is still erased.
+ base = (
+ root / target[0][len(_ALIAS) :]
+ if target[0].startswith(_ALIAS)
+ else origin.parent / target[0]
+ )
+ path = next((c for c in (Path(f"{base}.tsx"), base / "index.tsx") if c.is_file()), None)
+ return path is not None and type_only(target[1], path, hops + 1)
+
def pull(name: str, origin: Path) -> None:
"""Emit ``name`` as resolved from ``origin``, dependencies first."""
if name in defined or (origin, name) in seen:
@@ -446,11 +513,11 @@ def resolve_dependencies(
reference in home.declarations
or reference in home.imports
or reference in home.reexports
- ):
+ ) and not type_only(reference, origin):
wanted.add(reference)
pull(reference, origin)
kind = home.kind(name) or "const"
- if _FUNCTION_DECL_RE.match(text.lstrip()):
+ if _FUNCTION_DECL_RE.match(text.lstrip()) and not _invokes_its_function(text):
kind = "function"
pulled[name] = (
kind,
@@ -472,10 +539,22 @@ def resolve_dependencies(
# one from here is a TDZ error rather than a resolution.
eager = {"const", "let", "var", "class"}
while True:
+ # Any reference to a half-resolved lazy helper dooms an eager declaration: whether it is called on load is
+ # not decided, and a load-time crash costs more than a dropped declaration.
+ partial: set[str] = set()
+ while True:
+ grown = {
+ name
+ for name, (kind, _, wanted) in pulled.items()
+ if kind not in eager and not wanted <= set(pulled) - partial
+ }
+ if grown == partial:
+ break
+ partial = grown
doomed = {
name
for name, (kind, _, wanted) in pulled.items()
- if kind in eager and not wanted <= set(pulled)
+ if kind in eager and not wanted <= set(pulled) - partial
}
if not doomed:
break
diff --git a/tests/studio/test_node_harness_dependency_resolution.py b/tests/studio/test_node_harness_dependency_resolution.py
index 3ca626f4335..aa41c4c83ea 100644
--- a/tests/studio/test_node_harness_dependency_resolution.py
+++ b/tests/studio/test_node_harness_dependency_resolution.py
@@ -141,6 +141,129 @@ def test_a_pulled_arrow_const_is_kept_like_a_function(tmp_path):
assert "create(" not in resolved
+def test_an_eager_const_naming_a_half_resolved_helper_is_dropped(tmp_path):
+ """`TABLE = { v: g() }` and `NAMES = [g]` both reach `f`, which is missing a reference: both are dropped."""
+ module = tmp_path / "src" / "m.ts"
+ module.parent.mkdir(parents = True)
+ module.write_text(
+ 'import { missing } from "./nowhere";\n'
+ "const f = () => missing();\n"
+ "const g = () => f();\n"
+ "const TABLE = { v: g() };\n"
+ "const NAMES = [g];\n"
+ "export function useIt() {\n return [TABLE, NAMES];\n}\n"
+ )
+ resolved = resolve_dependencies("const used = useIt();\n", (module,), root = tmp_path / "src")
+ assert "const TABLE" not in resolved
+ assert "const NAMES" not in resolved
+ assert "const g = () => f();" in resolved
+
+
+ "initializer",
+ [
+ "{ run: () => f() }",
+ "{ run() {\n return f();\n} }",
+ "function () {\n return f();\n}()",
+ "function () {\n return f();\n}(Math.max(1, 2))",
+ "(() => f())()",
+ "{ v: f?.() }",
+ "!true && f()",
+ "alias",
+ ],
+)
+def test_any_eager_reference_to_a_half_resolved_helper_drops_the_const(tmp_path, initializer):
+ """Whether an initializer really calls `f` on load is not decided: a load-time crash costs more than a drop."""
+ module = tmp_path / "src" / "m.ts"
+ module.parent.mkdir(parents = True)
+ module.write_text(
+ 'import { missing } from "./nowhere";\n'
+ "const f = () => missing();\n"
+ "const alias = f;\n"
+ f"const VALUE = {initializer};\n"
+ "export function read() {\n return VALUE;\n}\n"
+ )
+ resolved = resolve_dependencies("const used = read();\n", (module,), root = tmp_path / "src")
+ assert "const VALUE" not in resolved
+
+
+def test_a_type_reexported_through_a_barrel_is_still_erased(tmp_path):
+ """`export type { Props } from "./types"` in a barrel names a type Node erases."""
+ module = tmp_path / "src" / "m.ts"
+ module.parent.mkdir(parents = True)
+ module.write_text(
+ 'import { Props } from "./barrel";\n'
+ "const f = (p?: Props) => 1;\n"
+ "const TABLE = { v: f() };\n"
+ "export function useIt() {\n return TABLE;\n}\n"
+ )
+ (module.parent / "barrel.ts").write_text('export type { Props } from "./view";\n')
+ (module.parent / "view.tsx").write_text("export interface Props {\n on: boolean;\n}\n")
+ resolved = resolve_dependencies("const used = useIt();\n", (module,), root = tmp_path / "src")
+ assert "const TABLE" in resolved
+
+
+def test_an_inline_type_reexport_through_a_barrel_is_still_erased(tmp_path):
+ """`export { type Props, helper } from "./view"` names a type Node erases next to a value."""
+ module = tmp_path / "src" / "m.ts"
+ module.parent.mkdir(parents = True)
+ module.write_text(
+ 'import { Props } from "./barrel";\n'
+ "const f = (p?: Props) => 1;\n"
+ "const TABLE = { v: f() };\n"
+ "export function useIt() {\n return TABLE;\n}\n"
+ )
+ (module.parent / "barrel.ts").write_text('export { type Props, helper } from "./view";\n')
+ (module.parent / "view.tsx").write_text(
+ "export interface Props {\n on: boolean;\n}\nexport function helper() {\n return 1;\n}\n"
+ )
+ resolved = resolve_dependencies("const used = useIt();\n", (module,), root = tmp_path / "src")
+ assert "const TABLE" in resolved
+
+
+def test_an_asserted_function_expression_stays_lazy(tmp_path):
+ """`function () {...} as Fn` builds a function without calling it, so it is kept like one."""
+ module = tmp_path / "src" / "m.ts"
+ module.parent.mkdir(parents = True)
+ module.write_text(
+ 'import { missing } from "./nowhere";\n'
+ "type Fn = () => unknown;\n"
+ "const f = function () {\n return missing();\n} as Fn;\n"
+ "export function get() {\n return f;\n}\n"
+ )
+ resolved = resolve_dependencies("const used = get();\n", (module,), root = tmp_path / "src")
+ assert "const f = function" in resolved
+
+
+def test_a_type_only_reference_does_not_make_a_helper_half_resolved(tmp_path):
+ """A type Node erases (here from a .tsx file, which is never lifted) is not a missing runtime value."""
+ module = tmp_path / "src" / "m.ts"
+ module.parent.mkdir(parents = True)
+ module.write_text(
+ 'import { Props } from "./view";\n'
+ "const f = (p?: Props) => 1;\n"
+ "const TABLE = { v: f() };\n"
+ "export function useIt() {\n return TABLE;\n}\n"
+ )
+ (module.parent / "view.tsx").write_text("export interface Props {\n on: boolean;\n}\n")
+ resolved = resolve_dependencies("const used = useIt();\n", (module,), root = tmp_path / "src")
+ assert "const TABLE" in resolved
+
+
+def test_an_immediately_invoked_function_stays_eager(tmp_path):
+ """`const v = function () { ... }();` runs on load, so it is dropped when its body cannot be resolved."""
+ module = tmp_path / "src" / "m.ts"
+ module.parent.mkdir(parents = True)
+ module.write_text(
+ 'import { store } from "./store";\n'
+ "const value = function () {\n return store.getState();\n}();\n"
+ "export function read() {\n return value;\n}\n"
+ )
+ (module.parent / "store.ts").write_text("export const store = create(() => ({ on: null }));\n")
+ resolved = resolve_dependencies("const used = read();\n", (module,), root = tmp_path / "src")
+ assert "const value" not in resolved
+
+
def test_a_destructured_fixture_is_not_declared_twice(tmp_path):
"""``const { only, ...rest } = ...`` is a binding a declaration regex does not see."""
module = tmp_path / "src" / "m.ts"