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
Make the desktop release contract tests fail when the contract breaks (#8228)
Daniel Han0cd73cf3fb89
diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.ymlindex bf7ac4e6adf..325b8a470b4 100644--- a/.github/workflows/release-desktop.yml+++ b/.github/workflows/release-desktop.yml@@ -2072,7 +2072,7 @@ jobs:sys.exit(f'desktop-latest latest.json URL mismatch: expected {expected_url}, got {actual_url}')PY- # ── Advisory multi-engine scan of the bundles just published ──+ # ── Advisory multi-engine scan of the bundles just uploaded ──# Defender (build job) is one vendor and gates only Windows. VirusTotal# aggregates ~70 engines across all four bundles, which is how a false# positive from some other vendor gets noticed here rather than in a user bug@@ -2086,11 +2086,14 @@ jobs:# job it was ~9 minutes of the ~9.5 the job took, delaying every release by its# full length while being unable to block one.virustotal-scan:- name: VirusTotal post-publish scan+ # Not "post-publish": `inputs.draft` defaults to true and the release is+ # created with `--draft` on that input, so the ordinary run has uploaded the+ # assets to a draft. The name has to read true for both dispatches.+ name: VirusTotal release asset scanneeds: [publish-release]runs-on: ubuntu-latest# A missing secret, a VirusTotal outage or quota exhaustion must not fail- # the release that already published.+ # the release whose assets are already uploaded.continue-on-error: truetimeout-minutes: 30steps:@@ -2137,7 +2140,10 @@ jobs:if [ -f "$summary" ]; thencat "$summary" >> "$GITHUB_STEP_SUMMARY"else- echo '### VirusTotal post-publish scan' >> "$GITHUB_STEP_SUMMARY"+ # Must stay byte-identical to SUMMARY_HEADING in+ # scripts/virustotal_scan.py, or a run that produced no summary shows+ # a second, unrelated section. A test ties the two together.+ echo '### VirusTotal release asset scan' >> "$GITHUB_STEP_SUMMARY"echo '' >> "$GITHUB_STEP_SUMMARY"echo 'The scan step produced no summary.' >> "$GITHUB_STEP_SUMMARY"fidiff --git a/scripts/virustotal_scan.py b/scripts/virustotal_scan.pyindex c3d480dc544..57a86107f15 100644--- a/scripts/virustotal_scan.py+++ b/scripts/virustotal_scan.py@@ -2,7 +2,10 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Advisory VirusTotal pre-flight scan of the built desktop release bundles.+"""Advisory VirusTotal scan of the desktop release bundles.++Runs after `publish-release` has uploaded the assets, which for the default+`draft: true` dispatch means they are attached to a draft rather than published.Stdlib only on purpose: this runs on a bare `ubuntu-latest` runner right after theartifacts are downloaded, before any Python environment is provisioned, so it cannot@@ -185,10 +188,20 @@ def _md_text(text: str) -> str:return escaped.replace("<", "<").replace(">", ">")+# Also written by the workflow's placeholder step, so a reader sees one heading+# whether or not the scan produced a summary.+#+# Says neither "pre-flight" nor "post-publish": the scan runs after+# `publish-release`, but `inputs.draft` defaults to true, so the ordinary run+# has uploaded the assets to a draft rather than published them. Naming the+# assets is the only wording true of both dispatches.+SUMMARY_HEADING = "### VirusTotal release asset scan"++def render_markdown(reports: Sequence[FileReport], threshold: int) -> str:"""Render the job-summary table. Kept pure so it is unit testable."""lines = [- "### VirusTotal pre-flight scan",+ SUMMARY_HEADING,"","| Asset | Malicious | Suspicious | Undetected | Harmless | Timeout | Source |","| --- | ---: | ---: | ---: | ---: | ---: | --- |",@@ -709,15 +722,13 @@ def main(argv: Sequence[str] | None = None) -> int:"virustotal_scan: VT_API_KEY is unset or empty; skipping the scan.",flush = True,)- _write_markdown(- "### VirusTotal pre-flight scan\n\nSkipped: no API key configured for this run.\n"- )+ _write_markdown(f"{SUMMARY_HEADING}\n\nSkipped: no API key configured for this run.\n")return 0targets = collect_paths(args.paths)if not targets:print("virustotal_scan: no scannable bundles found.", flush = True)- _write_markdown("### VirusTotal pre-flight scan\n\nSkipped: no scannable bundles found.\n")+ _write_markdown(f"{SUMMARY_HEADING}\n\nSkipped: no scannable bundles found.\n")return 0client = VirusTotalClient(api_key, request_interval = args.request_interval)diff --git a/tests/python/test_virustotal_scan.py b/tests/python/test_virustotal_scan.pyindex ccfccbccf81..45ead9e2252 100644--- a/tests/python/test_virustotal_scan.py+++ b/tests/python/test_virustotal_scan.py@@ -1,11 +1,13 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Unit tests for the advisory VirusTotal post-publish scan.+"""Unit tests for the advisory VirusTotal release asset scan.-The scan is a sweep of the bundles a release has already published, run in the-`virustotal-scan` job after `publish-release`. It is not a gate and cannot hold-a release back; Defender in the build job is the fail-closed check.+The scan is a sweep of the bundles `publish-release` uploaded, run in the+`virustotal-scan` job after it. Those bundles are attached to a draft on the+default dispatch and to a published release otherwise, which is why neither the+job nor the summary heading claims a publication. It is not a gate and cannot+hold a release back; Defender in the build job is the fail-closed check.Offline by design: every test injects a fake transport, so the suite never spendsthe account's 500/day quota and never uploads a build. The two behaviours worth@@ -20,8 +22,11 @@ protecting are the ones a release depends on:from __future__ import annotations+import fnmatchimport importlib.util+import itertoolsimport pathlib+import shleximport sysimport time@@ -446,7 +451,7 @@ class TestDeadlineEnforcement:])assert rc == 0- assert "VirusTotal pre-flight scan" in summary.read_text()+ assert vt.SUMMARY_HEADING in summary.read_text()class TestRenderMarkdown:@@ -855,6 +860,28 @@ class TestWorkflowOrdering:def _scan_step_names(self):return [step.get("name") for step in self._scan_job()["steps"]]+ @staticmethod+ def _runner_temp(path):+ """Normalise the three spellings of the runner temp dir to one token.++ `with:` uses `${{ runner.temp }}` and `run:` uses `$RUNNER_TEMP`, so two+ paths can name one directory and still compare unequal.+ """+ normalised = " ".join(str(path).split())+ for spelling in ("${{ runner.temp }}", "${RUNNER_TEMP}", "$RUNNER_TEMP"):+ normalised = normalised.replace(spelling, "<RUNNER_TEMP>")+ return normalised.rstrip("/")++ def _scan_script_argv(self):+ """The argv the `VirusTotal scan` step hands to virustotal_scan.py."""+ run = self._scan_step_map()["VirusTotal scan"]["run"]+ command = run.replace("\\\n", " ")+ line = next(+ text for text in command.split("\n") if "python3 scripts/virustotal_scan.py" in text+ )+ argv = shlex.split(line)+ return argv[argv.index("scripts/virustotal_scan.py") + 1 :]+def test_the_scan_is_its_own_job_gated_on_publish_release(self):# Pins the post-publish ordering rather than merely tolerating it: the# job must exist and must be downstream of publish-release, so dropping@@ -863,10 +890,24 @@ class TestWorkflowOrdering:assert job["needs"] == ["publish-release"]def test_the_scan_job_is_not_conditioned_away(self):- # A job-level `if:` is the quiet way to disable a scan without deleting- # it, so the job carries none: reaching it is decided by `needs` alone.+ # `needs:` alone carries GitHub's default `success()` gating, so whether+ # the scan runs is decided by publish-release and nothing else. The job+ # therefore carries no `if:` at all, and this rejects every one rather+ # than trying to sort the safe conditions from the unsafe.+ #+ # Sorting them does not work. A job-level `if:` fails in both directions:+ # `always()` or `success() || inputs.scan_anyway` sends build artifacts+ # to a third party after a publish that failed, while `${{ false }}` or+ # `success() && <anything falsey>` silently skips the sweep after a+ # publish that succeeded. Any rule permissive enough to admit an+ # arbitrary trailing predicate admits the second kind, so the contract+ # is simply that reaching this job is `needs:`'s decision alone.job = self._scan_job()- assert "if" not in job+ assert "if" not in job, (+ f"virustotal-scan carries `if: {job.get('if')}`; a job-level condition "+ "either runs the scan without a successful publish-release or skips it "+ "after one, and `needs:` already gates it correctly"+ )# Nor may the individual steps be skipped, except the summary, which is# `if: always()` precisely so the evidence survives a failed scan.@@ -882,18 +923,57 @@ class TestWorkflowOrdering:# artifacts the build matrix uploaded and publish-release shipped. A# pattern that matched nothing would scan an empty directory and still# report success.+ build = self._workflow()["jobs"]["build"]upload_names = {step.get("with", {}).get("name")- for step in self._workflow()["jobs"]["build"]["steps"]+ for step in build["steps"]if step.get("uses", "").startswith("actions/upload-artifact@")}assert "desktop-release-${{ matrix.artifact }}" in upload_namesdownload = self._scan_step_map()["Download published assets"]assert download["uses"].startswith("actions/download-artifact@")- assert download["with"]["pattern"] == "desktop-release-*"assert download["with"]["merge-multiple"] is True+ # Tie the scan's input to publish-release's own download rather than to+ # a literal repeated in both places: if publish ever ships a different+ # artifact set, a scan still pulling the old pattern leaves the shipped+ # installers unscanned and still reports a clean sweep.+ publish_download = next(+ step+ for step in self._publish_step_list()+ if step.get("uses", "").startswith("actions/download-artifact@")+ )+ for key in ("pattern", "merge-multiple"):+ assert download["with"][key] == publish_download["with"][key], (+ key,+ download["with"].get(key),+ publish_download["with"].get(key),+ )+ assert self._runner_temp(download["with"]["path"]) == self._runner_temp(+ publish_download["with"]["path"]+ ), (download["with"]["path"], publish_download["with"]["path"])++ # And the scan has to be pointed at that same directory. The script takes+ # its target as an argument, so comparing only the two download steps+ # lets a repointed argument scan an empty directory and report clean.+ argv = self._scan_script_argv()+ scan_paths = list(itertools.takewhile(lambda argument: not argument.startswith("-"), argv))+ assert scan_paths, argv+ assert [self._runner_temp(path) for path in scan_paths] == [+ self._runner_temp(download["with"]["path"])+ ], (argv, download["with"]["path"])++ # And that shared pattern has to match what the matrix actually uploads,+ # or both jobs would agree on a set that does not exist.+ template = "desktop-release-${{ matrix.artifact }}"+ for entry in build["strategy"]["matrix"]["include"]:+ artifact = template.replace("${{ matrix.artifact }}", entry["artifact"])+ assert fnmatch.fnmatch(artifact, download["with"]["pattern"]), (+ artifact,+ download["with"]["pattern"],+ )+names = self._scan_step_names()assert names.index("Download published assets") < names.index("VirusTotal scan")@@ -1020,3 +1100,28 @@ class TestWorkflowOrdering:assert summary["if"] == "always()"assert "$GITHUB_STEP_SUMMARY" in summary["run"]assert "virustotal-summary.md" in summary["run"]++ def test_the_placeholder_summary_matches_the_real_one(self):+ # The placeholder stands in when the scan produced no summary, so a+ # heading that drifts from the script's renders as a second, unrelated+ # section instead of the report the reader came for.+ summary = self._scan_step_map()["Publish VirusTotal summary"]+ assert vt.SUMMARY_HEADING in summary["run"], summary["run"]++ def test_the_summary_heading_holds_for_a_draft_release_too(self):+ # `inputs.draft` defaults to true and "Create versioned release" only+ # adds --draft when it is set, so the ordinary dispatch leaves a draft+ # behind and nothing is published. A heading calling this a post-publish+ # scan would tell a release operator the opposite of what happened, so+ # the wording has to cover an upload to a draft as well as a publication.+ workflow = self._workflow()+ draft = workflow.get("on", workflow.get(True))["workflow_dispatch"]["inputs"]["draft"]+ assert draft["default"] is True++ create = self._publish_step_map()["Create versioned release"]["run"]+ assert "release_flags+=(--draft)" in create+ assert '"$RELEASE_DRAFT" = "true"' in create++ heading = vt.SUMMARY_HEADING.lower()+ for claim in ("post-publish", "published", "pre-flight"):+ assert claim not in heading, (vt.SUMMARY_HEADING, claim)diff --git a/tests/security/test_release_desktop_permissions.py b/tests/security/test_release_desktop_permissions.pyindex 9ab0bb52e57..b6aba5d4f05 100644--- a/tests/security/test_release_desktop_permissions.py+++ b/tests/security/test_release_desktop_permissions.py@@ -1,5 +1,6 @@"""Permission-boundary checks for the desktop release workflow."""+import refrom pathlib import Pathimport yaml@@ -26,6 +27,39 @@ def test_only_publish_job_can_write_repository_contents():assert write_jobs == ["publish-release"]+def _poll_loop_body(script):+ """Return the body of the first live `while ...; do ... done` loop.++ Assertions about a wait have to land inside the loop that waits, not+ anywhere in the step, and that loop has to be one the shell actually+ enters: `while false; do` keeps a textually perfect body while skipping+ every API read and status check, and the step falls straight through to a+ download that races the matrix. So the condition must be the unconditional+ `:` or `true` that a poll exiting via `break` uses. Nesting is tracked by+ depth; every opener in this workflow ends its line with `do`.+ """+ lines = script.split("\n")+ opener = re.compile(r"\s*while\s+(?P<condition>.*?)\s*;\s*do\s*$")+ starts = [+ index+ for index, line in enumerate(lines)+ if (match := opener.match(line)) and match.group("condition") in (":", "true")+ ]+ assert starts, f"no live (`while :` / `while true`) poll loop in the wait step:\n{script}"++ start = starts[0]+ depth = 0+ for index in range(start, len(lines)):+ line = lines[index]+ if re.search(r"(?:^|;)\s*do\s*$", line):+ depth += 1+ if re.match(r"\s*done\b", line):+ depth -= 1+ if depth == 0:+ return "\n".join(lines[start + 1 : index])+ raise AssertionError(f"unterminated `while` loop in the wait step:\n{script}")++def test_build_matrix_hands_off_assets_without_release_credentials():"""The build matrix signs bundles; only publish-release may release them.@@ -78,8 +112,31 @@ def test_build_matrix_hands_off_assets_without_release_credentials():# Every one of those refusals has to be terminal.assert wait_run.count("exit 1") >= 3+ # Assert the mechanism, not just the error strings: those survive a step+ # that no longer loops or no longer reads a conclusion, and then the+ # download races the matrix. Everything below is checked inside the loop+ # body, because a one-shot `gh api` read beside a dead `while` would satisfy+ # the same substrings while waiting for nothing.+ loop_body = _poll_loop_body(wait_run)+ assert "actions/runs/${GITHUB_RUN_ID}/jobs" in loop_body, wait_run+ assert ".status" in loop_body and ".conclusion" in loop_body, wait_run+ # Not finished yet is "keep waiting"; finished but not `success` is a refusal.+ assert re.search(r'!=\s*"completed"', loop_body), wait_run+ assert re.search(r'!=\s*"success"', loop_body), wait_run+ # A loop that never sleeps is a spin, and one that never breaks never ends.+ assert re.search(r"^\s*sleep\b", loop_body, re.MULTILINE), wait_run+ assert re.search(r"^\s*break\b", loop_body, re.MULTILINE), wait_run+names = [step.get("name") for step in publish["steps"]]assert names.index("Wait for the build matrix") < names.index("Create versioned release")+ # And it has to clear before the assets are pulled, or the download races the+ # legs and publish-release dies on artifacts that do not exist yet.+ download = next(+ index+ for index, step in enumerate(publish["steps"])+ if step.get("uses", "").startswith("actions/download-artifact@")+ )+ assert names.index("Wait for the build matrix") < download, names# Creating a missing release is a separate step gated on validation, so a# non-draft release is never reserved before its assets are ready to upload.