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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: pin FastFlowLM 1.0.7 for Qwen3.8 27B on the AMD NPU and keep Lemonade / FastFlowLM current (#13047)
Daniel Hand7bfce6990cc
diff --git a/.github/workflows/lemonade-pins-update.yml b/.github/workflows/lemonade-pins-update.ymlnew file mode 100644index 00000000000..320c756b6d2--- /dev/null+++ b/.github/workflows/lemonade-pins-update.yml@@ -0,0 +1,108 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.+#+# Opens one PR on ci/lemonade-pins when Lemonade or FastFlowLM has a newer stable release.+# The pins stay a reviewed choice. PRs opened with GITHUB_TOKEN start no CI: close and reopen.++name: Lemonade and FastFlowLM pin update++on:+ schedule:+ - cron: '41 7 * * *' # 07:41 UTC daily, off the cron rush+ workflow_dispatch:++concurrency:+ group: ${{ github.workflow }}+ cancel-in-progress: false++permissions:+ contents: read++jobs:+ update-pins:+ name: pin the latest Lemonade and FastFlowLM releases+ if: github.repository == 'unslothai/unsloth'+ runs-on: ubuntu-latest+ timeout-minutes: 15+ permissions:+ contents: write+ pull-requests: write+ env:+ BRANCH: ci/lemonade-pins+ PINS: studio/lemonade_prebuilt_pins.json+ steps:+ - name: Harden runner (egress block)+ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1+ with:+ egress-policy: block+ disable-sudo: true+ allowed-endpoints: >+ api.github.com:443+ github.com:443+ objects.githubusercontent.com:443+ release-assets.githubusercontent.com:443++ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ # A manual run from another branch must not base the update PR on it.+ ref: ${{ github.event.repository.default_branch || 'main' }}+ persist-credentials: false++ - name: Move the pins to the latest stable releases+ id: update+ env:+ GITHUB_TOKEN: ${{ github.token }}+ run: |+ # An unset shell is `bash -e` without pipefail: tee would hide the updater's exit code.+ set -euo pipefail+ python3 scripts/update_lemonade_pins.py --write | tee "$RUNNER_TEMP/changes.txt"+ if git diff --quiet -- "$PINS"; then+ echo "changed=false" >> "$GITHUB_OUTPUT"+ else+ echo "changed=true" >> "$GITHUB_OUTPUT"+ fi++ - name: Open or refresh the pin update pull request+ if: steps.update.outputs.changed == 'true'+ env:+ GH_TOKEN: ${{ github.token }}+ REPO: ${{ github.repository }}+ BASE: ${{ github.event.repository.default_branch || 'main' }}+ run: |+ set -euo pipefail+ remote="https://x-access-token:${GH_TOKEN}@github.com/${REPO}.git"+ push=true+ if git fetch --quiet --depth 1 "$remote" "refs/heads/${BRANCH}" 2>/dev/null \+ && git diff --quiet FETCH_HEAD -- "$PINS"; then+ echo "${BRANCH} already pins these releases."+ push=false+ fi+ number="$(gh pr list --repo "$REPO" --head "$BRANCH" --state open --json number --jq '.[0].number // empty')"+ # Re-open the PR when an earlier run pushed but failed to create it.+ if [ "$push" = false ] && [ -n "$number" ]; then+ exit 0+ fi+ title="Studio: update Lemonade and FastFlowLM pins ($(paste -sd ';' "$RUNNER_TEMP/changes.txt" | sed 's/;/, /g'))"+ {+ echo "The scheduled pin check found newer stable releases:"+ echo+ sed 's/^/- /' "$RUNNER_TEMP/changes.txt"+ echo+ echo "Every asset was downloaded, hashed and checked against the digest GitHub publishes."+ echo "Studio installs that already enabled the NPU upgrade on first use once this ships."+ echo+ echo "Before merging: enable the NPU and chat with one model on a Ryzen AI machine,"+ echo "on Windows and Linux if the Lemonade version moved. Close and reopen this PR to run CI."+ } > "$RUNNER_TEMP/body.md"+ git config user.name "github-actions[bot]"+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"+ if [ "$push" = true ]; then+ git checkout -B "$BRANCH"+ git commit --quiet -m "$title" -- "$PINS"+ git push --force "$remote" "HEAD:refs/heads/${BRANCH}"+ fi+ if [ -n "$number" ]; then+ gh pr edit "$number" --repo "$REPO" --title "$title" --body-file "$RUNNER_TEMP/body.md"+ else+ gh pr create --repo "$REPO" --base "$BASE" --head "$BRANCH" --title "$title" --body-file "$RUNNER_TEMP/body.md"+ fidiff --git a/scripts/update_lemonade_pins.py b/scripts/update_lemonade_pins.pynew file mode 100644index 00000000000..e98d5702da4--- /dev/null+++ b/scripts/update_lemonade_pins.py@@ -0,0 +1,153 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Move studio/lemonade_prebuilt_pins.json to the latest stable Lemonade and FastFlowLM releases.++Exit codes: 0 = current (or updated with --write); 1 = --check found a newer release; 2 = error.+"""++from __future__ import annotations++import argparse+import hashlib+import json+import os+import sys+import urllib.request+from pathlib import Path+from typing import Callable, Optional++PINS_PATH = Path(__file__).resolve().parents[1] / "studio" / "lemonade_prebuilt_pins.json"+_API = "https://api.github.com"+_TIMEOUT_S = 60+_CHUNK = 1 << 20+++def _lemonade_assets(version: str) -> dict[str, str]:+ return {+ "linux-x64": f"lemonade-embeddable-{version}-ubuntu-x64.tar.gz",+ "windows-x64": f"lemonade-embeddable-{version}-windows-x64.zip",+ }+++def _fastflowlm_assets(version: str) -> dict[str, str]:+ # The names lemond builds for its /v1/install download.+ return {+ "linux-x64": f"fastflowlm_{version}_linux.tar.gz",+ "windows-x64": f"fastflowlm_{version}_windows_amd64.zip",+ }+++# section -> (asset names, pin keeps the tag's "v", pin records sizes)+_SECTIONS: dict[str, tuple[Callable[[str], dict[str, str]], bool, bool]] = {+ "lemonade": (_lemonade_assets, False, True),+ "fastflowlm": (_fastflowlm_assets, True, False),+}+++def _request(url: str) -> urllib.request.Request:+ headers = {"User-Agent": "unsloth-pins-updater", "Accept": "application/vnd.github+json"}+ token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")+ if token and url.startswith(_API):+ headers["Authorization"] = f"Bearer {token}"+ return urllib.request.Request(url, headers = headers)+++def fetch_latest_release(repo: str) -> dict:+ """The latest stable release; GitHub's /latest skips drafts and prereleases."""+ with urllib.request.urlopen(+ _request(f"{_API}/repos/{repo}/releases/latest"), timeout = _TIMEOUT_S+ ) as r:+ return json.load(r)+++def hash_asset(url: str) -> tuple[str, int]:+ digest = hashlib.sha256()+ size = 0+ with urllib.request.urlopen(_request(url), timeout = _TIMEOUT_S) as response:+ while chunk := response.read(_CHUNK):+ digest.update(chunk)+ size += len(chunk)+ return digest.hexdigest(), size+++def version_key(version: str) -> tuple[int, ...]:+ """11.9.0 < 2026.41.1 and v1.0.3 < v1.0.7; anything else is not a release version."""+ parts = version.lstrip("v").split(".")+ if not parts or not all(part.isdigit() for part in parts):+ raise ValueError(f"{version!r} is not a numeric release version.")+ return tuple(int(part) for part in parts)+++def updated_section(+ name: str, section: dict, release: dict, hasher: Callable[[str], tuple[str, int]]+) -> Optional[dict]:+ tag = str(release["tag_name"])+ bare = tag[1:] if tag.startswith("v") else tag+ asset_names, keep_v, with_size = _SECTIONS[name]+ pinned = section["version"]+ if version_key(tag) <= version_key(pinned):+ return None+ published = {asset["name"]: asset for asset in release.get("assets") or []}+ assets = {}+ for key, asset_name in asset_names(bare).items():+ asset = published.get(asset_name)+ if asset is None:+ raise RuntimeError(f"{section['repo']} {tag} has no {asset_name}.")+ sha256, size = hasher(asset["browser_download_url"])+ github_digest = asset.get("digest")+ if github_digest and github_digest != f"sha256:{sha256}":+ raise RuntimeError(+ f"{asset_name} hashed to sha256:{sha256}, but GitHub publishes {github_digest}."+ )+ if asset.get("size") is not None and asset["size"] != size:+ raise RuntimeError(f"{asset_name} is {size} bytes, but GitHub lists {asset['size']}.")+ assets[key] = {"name": asset_name, "sha256": sha256}+ if with_size:+ assets[key]["size"] = size+ return {**section, "version": tag if keep_v else bare, "assets": assets}+++def update_pins(+ pins: dict,+ releases: Optional[Callable[[str], dict]] = None,+ hasher: Optional[Callable[[str], tuple[str, int]]] = None,+ only: Optional[str] = None,+) -> tuple[dict, list[str]]:+ releases = releases or fetch_latest_release+ hasher = hasher or hash_asset+ result = json.loads(json.dumps(pins))+ changes = []+ for name in [only] if only else _SECTIONS:+ section = result[name]+ moved = updated_section(name, section, releases(section["repo"]), hasher)+ if moved is not None:+ changes.append(f"{name}: {section['version']} -> {moved['version']}")+ result[name] = moved+ return result, changes+++def main(argv: Optional[list[str]] = None) -> int:+ parser = argparse.ArgumentParser(description = __doc__.splitlines()[0])+ parser.add_argument("--pins", type = Path, default = PINS_PATH)+ parser.add_argument("--only", choices = sorted(_SECTIONS), help = "Move one section only.")+ mode = parser.add_mutually_exclusive_group()+ mode.add_argument("--check", action = "store_true", help = "Exit 1 if a newer release exists.")+ mode.add_argument("--write", action = "store_true", help = "Rewrite the pins file.")+ args = parser.parse_args(argv)+ try:+ pins = json.loads(args.pins.read_text(encoding = "utf-8"))+ new_pins, changes = update_pins(pins, only = args.only)+ except Exception as exc: # noqa: BLE001 -- one line for the CI log, exit 2+ print(f"error: {exc}", file = sys.stderr)+ return 2+ for line in changes or ["Lemonade and FastFlowLM pins are current."]:+ print(line)+ if changes and args.write:+ args.pins.write_text(json.dumps(new_pins, indent = 2) + "\n", encoding = "utf-8")+ return 1 if changes and args.check else 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/studio/backend/core/inference/npu_backend.py b/studio/backend/core/inference/npu_backend.pyindex d83e80e95a3..a8e8bc2bc82 100644--- a/studio/backend/core/inference/npu_backend.py+++ b/studio/backend/core/inference/npu_backend.py@@ -170,6 +170,13 @@ def _installer_module():return install_lemonade_prebuilt+def _pinned_flm_version() -> Optional[str]:+ try:+ return str(_installer_module().load_pins()["fastflowlm"]["version"]).lstrip("v")+ except Exception: # noqa: BLE001 -- an unreadable pin skips the check, never blocks Enable+ return None++def _npu_root() -> Path:from utils.paths.storage_roots import studio_rootreturn studio_root() / "lemonade"@@ -300,12 +307,45 @@ class LemonadeNpuBackend:return Nonereturn marker.get("lemond") if isinstance(marker, dict) else None+ def _upgrade_pending(self, binary: Optional[Path]) -> bool:+ """Whether the NPU was enabled, but a Studio update has since moved the runtime's pins."""+ validated = self._validated_install()+ return binary is None and isinstance(validated, str) and bool(validated)++ def _flm_version(self) -> Optional[str]:+ binary = self._flm_binary()+ if binary is None:+ return None+ env = child_env_without_native_path_secret()+ env["FLM_MODEL_PATH"] = str(self._flm_model_dir)+ env["FLM_DISABLE_UPDATE_CHECK"] = "1"+ try:+ completed = subprocess.run(+ [str(binary), "version", "--json"],+ capture_output = True,+ stdin = subprocess.DEVNULL,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ timeout = 10,+ env = env,+ **windows_hidden_subprocess_kwargs(),+ )+ version = json.loads(completed.stdout).get("version")+ except (OSError, subprocess.SubprocessError, ValueError, AttributeError):+ return None+ return str(version).lstrip("v") if version else None+def status(self) -> dict[str, Any]:hardware = self.hardware()binary = self._installed_lemond()- installed = binary is not None- ready = self._state == "ready" or (- self._state == "idle" and installed and self._validated_install() == str(binary)+ # An enabled NPU stays enabled across a pin change: its first use upgrades the runtime.+ upgrade_pending = self._state == "idle" and self._upgrade_pending(binary)+ installed = binary is not None or upgrade_pending+ ready = (+ self._state == "ready"+ or upgrade_pending+ or (self._state == "idle" and installed and self._validated_install() == str(binary)))running = self._server is not None and self._server.is_alive()resident = self.resident()@@ -349,6 +389,12 @@ class LemonadeNpuBackend:if self._server is not None and self._server.is_alive():return self._serverbinary = self._installed_lemond()+ if self._upgrade_pending(binary):+ logger.info("Upgrading the NPU runtime to the Lemonade and FastFlowLM pins")+ self.enable()+ if self._server is not None and self._server.is_alive():+ return self._server+ binary = self._installed_lemond()if binary is None:raise NpuError("The NPU runtime is not installed. Enable it first.")if self._server is not None:@@ -382,6 +428,13 @@ class LemonadeNpuBackend:)if _failed(response):raise NpuError(f"Installing FastFlowLM failed: {_error_message(response)}")+ # lemond keeps the old FastFlowLM and answers success when an update download fails.+ expected, actual = _pinned_flm_version(), self._flm_version()+ if expected and actual and actual != expected:+ raise NpuError(+ f"Updating FastFlowLM to v{expected} failed; v{actual} is still installed. "+ "Check the internet connection, then try again."+ )self._state = "validating"self._validation = self._validate()if not self._validation.get("ready"):diff --git a/studio/backend/tests/fixtures/fake_lemond.py b/studio/backend/tests/fixtures/fake_lemond.pyindex b5b6c708949..8387fe14a1f 100644--- a/studio/backend/tests/fixtures/fake_lemond.py+++ b/studio/backend/tests/fixtures/fake_lemond.py@@ -151,7 +151,17 @@ def main() -> None:flm.parent.mkdir(parents = True, exist_ok = True)report = os.environ.get("FAKE_FLM_VALIDATE", '{"ready": true}')pause = os.environ.get("FAKE_FLM_VALIDATE_SECONDS", "0")- flm.write_text(f"#!/bin/sh\nsleep {pause}\necho '{report}'\n", encoding = "utf-8")+ version = os.environ.get("FAKE_FLM_VERSION", "")+ answer_version = (+ f'[ "$1" = version ] && {{ echo \'{{"version": "{version}"}}\'; exit 0; }}\n'+ if version+ else ""+ )+ flm.write_text(+ f'#!/bin/sh\n{answer_version}[ "$1" = validate ] && sleep {pause}\n'+ f"echo '{report}'\n",+ encoding = "utf-8",+ )flm.chmod(0o755)self._send(200, {"status": "success", "recipe": "flm", "backend": "npu"})elif self.path == "/v1/pull":diff --git a/studio/backend/tests/test_npu_backend.py b/studio/backend/tests/test_npu_backend.pyindex 88f0959356f..6d0605791e8 100644--- a/studio/backend/tests/test_npu_backend.py+++ b/studio/backend/tests/test_npu_backend.py@@ -460,6 +460,103 @@ def test_readiness_survives_a_restart_only_after_validation(npu, monkeypatch):assert nb.LemonadeNpuBackend(root = npu.root).status()["ready"] is False+class _PinsMoved(_Installer):+ def __init__(self, binary: Path) -> None:+ super().__init__(binary)+ self.current = False++ def installed_lemond(self, root):+ return self.binary if self.current else None++ def install(+ self,+ root,+ cancel = None,+ ):+ self.current = True+ return super().install(root, cancel = cancel)+++def _move_the_pins(npu, monkeypatch) -> nb.LemonadeNpuBackend:+ """Enable, then restart as a Studio update would, with the runtime's pins moved."""+ npu.enable()+ npu.shutdown()+ moved = _PinsMoved(npu.installer.binary)+ monkeypatch.setattr(nb, "_installer_module", lambda: moved)+ restarted = nb.LemonadeNpuBackend(root = npu.root)+ restarted.installer = moved+ return restarted+++def test_an_enabled_npu_upgrades_on_first_use_after_the_pins_move(npu, monkeypatch):+ restarted = _move_the_pins(npu, monkeypatch)+ try:+ status = restarted.status()+ assert status["ready"] is True and status["runtime_installed"] is True+ installs_before = len([r for r in _requests(restarted) if r["path"] == "/v1/install"])+ assert [model.id for model in restarted.catalog()]+ assert restarted.installer.installs == 1+ installs = [r for r in _requests(restarted) if r["path"] == "/v1/install"]+ assert len(installs) == installs_before + 1+ assert restarted.status()["ready"] is True+ restarted.catalog()+ assert restarted.installer.installs == 1+ finally:+ restarted.shutdown()+ again = nb.LemonadeNpuBackend(root = npu.root)+ assert again.status()["ready"] is True+++def test_an_upgrade_that_fails_validation_asks_to_try_again(npu, monkeypatch):+ restarted = _move_the_pins(npu, monkeypatch)+ try:+ monkeypatch.setenv("FAKE_FLM_VALIDATE", '{"ready": false, "all_fw_ok": false}')+ with pytest.raises(nb.NpuError, match = "firmware"):+ restarted.catalog()+ status = restarted.status()+ assert status["state"] == "failed" and status["ready"] is False+ finally:+ restarted.shutdown()+++def test_a_runtime_never_enabled_is_not_installed_behind_the_owners_back(tmp_path, monkeypatch):+ installer = _PinsMoved(_binary(tmp_path))+ monkeypatch.setattr(nb, "_installer_module", lambda: installer)+ monkeypatch.setattr(+ nb, "detect_amd_npu", lambda: {"present": True, "supported": True, "family": "XDNA2"}+ )+ backend = nb.LemonadeNpuBackend(root = tmp_path / "lemonade")+ assert backend.status()["ready"] is False+ assert backend.status()["runtime_installed"] is False+ with pytest.raises(nb.NpuError, match = "Enable it first"):+ backend.catalog()+ assert installer.installs == 0++[email protected]("installed, ok", [("1.0.7", True), ("1.0.3", False)])+def test_an_update_lemond_could_not_download_is_not_recorded_as_done(+ npu, monkeypatch, installed, ok+):+ npu.installer.load_pins = lambda: {"fastflowlm": {"version": "v1.0.7"}}+ monkeypatch.setenv("FAKE_FLM_VERSION", installed)+ if ok:+ assert npu.enable()["ready"] is True+ return+ with pytest.raises(nb.NpuError, match = r"v1\.0\.7 failed; v1\.0\.3 is still installed"):+ npu.enable()+ assert npu.status()["state"] == "failed"+ assert nb.LemonadeNpuBackend(root = npu.root).status()["ready"] is False+++def test_a_marker_without_an_install_path_does_not_start_an_upgrade(tmp_path, monkeypatch):+ installer = _PinsMoved(_binary(tmp_path))+ monkeypatch.setattr(nb, "_installer_module", lambda: installer)+ backend = nb.LemonadeNpuBackend(root = tmp_path / "lemonade")+ backend.root.mkdir(parents = True)+ (backend.root / "npu_validated.json").write_text('{"lemond": false}', encoding = "utf-8")+ assert backend._upgrade_pending(None) is False++def test_a_failed_replacement_leaves_nothing_on_the_npu(npu, monkeypatch):monkeypatch.setenv("FAKE_LEMOND_DOWNLOADED", '["qwen3-0.6b-FLM", "gemma3-4b-FLM"]')monkeypatch.setenv("FAKE_LEMOND_LOAD_FAILS_FOR", "gemma3-4b-FLM")diff --git a/studio/frontend/src/features/npu/npu-catalog-store.ts b/studio/frontend/src/features/npu/npu-catalog-store.tsindex ad23ba94089..94e1c460417 100644--- a/studio/frontend/src/features/npu/npu-catalog-store.ts+++ b/studio/frontend/src/features/npu/npu-catalog-store.ts@@ -34,7 +34,8 @@ useNpuCatalogStore.subscribe((state) =>let latestListing = 0;-export async function refreshNpuModels(): Promise<void> {+/** Whether the listing succeeded. */+export async function refreshNpuModels(): Promise<boolean> {// Only the newest answer lands: an older one could still list a finished pull as missing.const listing = ++latestListing;try {@@ -42,12 +43,14 @@ export async function refreshNpuModels(): Promise<void> {if (listing === latestListing) {useNpuCatalogStore.setState({ models, listError: null });}+ return true;} catch (error) {if (listing === latestListing) {useNpuCatalogStore.setState({listError: error instanceof Error ? error.message : String(error),});}+ return false;}}diff --git a/studio/frontend/src/features/npu/npu-setup-notice.tsx b/studio/frontend/src/features/npu/npu-setup-notice.tsxindex 42cbe23aa9b..64c90541166 100644--- a/studio/frontend/src/features/npu/npu-setup-notice.tsx+++ b/studio/frontend/src/features/npu/npu-setup-notice.tsx@@ -53,7 +53,9 @@ export function NpuSetupNotice({ catalog }: { catalog: NpuCatalog }) {</Button></div>) : null}- {listError ? <p className="text-destructive">{listError}</p> : null}+ {listError && listError !== status.error ? (+ <p className="text-destructive">{listError}</p>+ ) : null}{ready && status.runtime_installed && !models && !listError ? (<div className="flex justify-center py-2"><Spinner className="size-3.5 text-muted-foreground" />diff --git a/studio/frontend/src/features/npu/use-npu-catalog.ts b/studio/frontend/src/features/npu/use-npu-catalog.tsindex 358a5682a26..deda0609b09 100644--- a/studio/frontend/src/features/npu/use-npu-catalog.ts+++ b/studio/frontend/src/features/npu/use-npu-catalog.ts@@ -2,7 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { toast } from "@/lib/toast";-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import {type NpuModel,type NpuStatus,@@ -47,10 +47,21 @@ export function useNpuCatalog(const onStatusChange = source?.onStatusChange;// Listing starts lemond, so wait for a validated runtime.const ready = status?.ready === true;+ const statusChange = useRef(onStatusChange);+ useEffect(() => {+ statusChange.current = onStatusChange;+ });useEffect(() => {if (!ready) return;- void refreshNpuModels();+ // This listing can run a pending upgrade; on failure re-read status to offer Try again.+ void refreshNpuModels().then((listed) => {+ if (listed) return;+ getNpuStatus().then(+ (next) => statusChange.current?.(next),+ () => undefined,+ );+ });listNpuDownloads().then((running) => {for (const { model, percent } of running) {diff --git a/studio/frontend/tests/npu-catalog-store.test.ts b/studio/frontend/tests/npu-catalog-store.test.tsindex f2f8f2e38d3..49cb56e3068 100644--- a/studio/frontend/tests/npu-catalog-store.test.ts+++ b/studio/frontend/tests/npu-catalog-store.test.ts@@ -385,6 +385,16 @@ test("an older list answer never overwrites a newer one", async () => {]);});+test("a listing reports whether it succeeded, so a failed one can re-read the status", async () => {+ const { store, listings, backend } = harness();+ const listed = store.refreshNpuModels();+ listings[0].resolve([]);+ assert.equal(await listed, true);+ backend.reachable = false;+ assert.equal(await store.refreshNpuModels(), false);+ assert.equal(store.useNpuCatalogStore.getState().listError, "Failed to fetch");+});+test("a running pull counts as a download for the desktop quit warning", async () => {const { store, pulls, listings, activity } = harness();const job = store.followNpuDownload("qwen3-0.6b-FLM");diff --git a/studio/lemonade_prebuilt_pins.json b/studio/lemonade_prebuilt_pins.jsonindex d486af695b5..79e842adade 100644--- a/studio/lemonade_prebuilt_pins.json+++ b/studio/lemonade_prebuilt_pins.json@@ -17,16 +17,16 @@}},"fastflowlm": {- "version": "v1.0.3",+ "version": "v1.0.7","repo": "ROCm/FastFlowLM","assets": {"linux-x64": {- "name": "fastflowlm_1.0.3_linux.tar.gz",- "sha256": "f721254e6a1e06cbd729883e8a4bd583fa396aade761d59bb4333cea8f59ebd1"+ "name": "fastflowlm_1.0.7_linux.tar.gz",+ "sha256": "e5a0725284a845178b6e1136fc99efd6cd6cba0dcd55fc319ab7edfeb04b8433"},"windows-x64": {- "name": "fastflowlm_1.0.3_windows_amd64.zip",- "sha256": "ca92eaf5f01909391100a1e7fde47240489a3a9b93ef5f52ea01b648f46f8a55"+ "name": "fastflowlm_1.0.7_windows_amd64.zip",+ "sha256": "0377e501afe3595d491cde1ff91923f225240053437d6e55b47c6e86fadc54d8"}}}diff --git a/tests/studio/install/test_update_lemonade_pins.py b/tests/studio/install/test_update_lemonade_pins.pynew file mode 100644index 00000000000..5d2e86d659a--- /dev/null+++ b/tests/studio/install/test_update_lemonade_pins.py@@ -0,0 +1,120 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Test the Lemonade and FastFlowLM pin updater against canned GitHub releases, offline."""++from __future__ import annotations++import hashlib+import json+import sys+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[3]+if str(REPO_ROOT / "scripts") not in sys.path:+ sys.path.insert(0, str(REPO_ROOT / "scripts"))+if str(REPO_ROOT / "studio") not in sys.path:+ sys.path.insert(0, str(REPO_ROOT / "studio"))++import install_lemonade_prebuilt as lp # noqa: E402+import update_lemonade_pins as up # noqa: E402+++def _blob(name: str) -> bytes:+ return f"bytes of {name}".encode()+++def _release(tag: str, names: dict[str, str], **overrides) -> dict:+ assets = []+ for name in names.values():+ data = _blob(name)+ asset = {+ "name": name,+ "browser_download_url": f"https://example.invalid/{name}",+ "size": len(data),+ "digest": "sha256:" + hashlib.sha256(data).hexdigest(),+ }+ asset.update(overrides.get(name, {}))+ assets.append(asset)+ return {"tag_name": tag, "assets": assets}+++def _hasher(url: str) -> tuple[str, int]:+ data = _blob(url.rsplit("/", 1)[1])+ return hashlib.sha256(data).hexdigest(), len(data)+++def _releases(lemonade: str, flm: str, **overrides):+ by_repo = {+ "lemonade-sdk/lemonade": _release(+ lemonade, up._lemonade_assets(lemonade.lstrip("v")), **overrides+ ),+ "ROCm/FastFlowLM": _release(flm, up._fastflowlm_assets(flm.lstrip("v")), **overrides),+ }+ return lambda repo: by_repo[repo]+++def test_newer_releases_move_both_pins_in_the_installers_format():+ pins = lp.load_pins()+ new, changes = up.update_pins(pins, _releases("v99.0.0", "v99.0.1"), _hasher)+ assert changes == [+ f"lemonade: {pins['lemonade']['version']} -> 99.0.0",+ f"fastflowlm: {pins['fastflowlm']['version']} -> v99.0.1",+ ]+ assert new["lemonade"]["version"] == "99.0.0"+ assert new["fastflowlm"]["version"] == "v99.0.1"+ linux = new["lemonade"]["assets"]["linux-x64"]+ assert linux["name"] == "lemonade-embeddable-99.0.0-ubuntu-x64.tar.gz"+ assert linux["size"] == len(_blob(linux["name"]))+ assert new["fastflowlm"]["assets"]["windows-x64"] == {+ "name": "fastflowlm_99.0.1_windows_amd64.zip",+ "sha256": hashlib.sha256(_blob("fastflowlm_99.0.1_windows_amd64.zip")).hexdigest(),+ }+ assert pins == lp.load_pins(), "the input pins were modified"+++def test_current_or_older_releases_change_nothing():+ pins = lp.load_pins()+ current = _releases("v" + pins["lemonade"]["version"], pins["fastflowlm"]["version"])+ assert up.update_pins(pins, current, _hasher) == (pins, [])+ assert up.update_pins(pins, _releases("v1.0.0", "v0.0.1"), _hasher) == (pins, [])+++def test_calendar_versions_sort_after_the_old_scheme():+ assert up.version_key("v2026.41.1") > up.version_key("11.9.0")+ assert up.version_key("v1.0.10") > up.version_key("v1.0.7")+ with pytest.raises(ValueError):+ up.version_key("candidate-v2026.42.0")+++def test_a_digest_mismatch_is_refused():+ name = "fastflowlm_99.0.1_linux.tar.gz"+ releases = _releases("v1.0.0", "v99.0.1", **{name: {"digest": "sha256:" + "0" * 64}})+ with pytest.raises(RuntimeError, match = "GitHub publishes"):+ up.update_pins(lp.load_pins(), releases, _hasher)+++def test_a_release_missing_an_asset_is_refused():+ release = _release("v99.0.1", {"linux-x64": "fastflowlm_99.0.1_linux.tar.gz"})+ releases = {"lemonade-sdk/lemonade": {"tag_name": "v1.0.0", "assets": []}}+ releases["ROCm/FastFlowLM"] = release+ with pytest.raises(RuntimeError, match = "windows_amd64.zip"):+ up.update_pins(lp.load_pins(), releases.__getitem__, _hasher)+++def test_write_is_idempotent_and_only_limits_the_sections(tmp_path, monkeypatch):+ path = tmp_path / "pins.json"+ path.write_text(json.dumps(lp.load_pins(), indent = 2) + "\n", encoding = "utf-8")+ monkeypatch.setattr(up, "fetch_latest_release", _releases("v99.0.0", "v99.0.1"))+ monkeypatch.setattr(up, "hash_asset", _hasher)+ assert up.main(["--pins", str(path), "--check"]) == 1+ assert up.main(["--pins", str(path), "--write", "--only", "fastflowlm"]) == 0+ written = json.loads(path.read_text(encoding = "utf-8"))+ assert written["fastflowlm"]["version"] == "v99.0.1"+ assert written["lemonade"] == lp.load_pins()["lemonade"]+ lp.load_pins(path)+ before = path.read_text(encoding = "utf-8")+ assert up.main(["--pins", str(path), "--write", "--only", "fastflowlm"]) == 0+ assert path.read_text(encoding = "utf-8") == before