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
Desktop: refuse to republish an existing release version (#7941)
oobabooga38dec58e0848
diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.ymlindex 050839df103..1ab21eb6346 100644--- a/.github/workflows/release-desktop.yml+++ b/.github/workflows/release-desktop.yml@@ -216,6 +216,44 @@ jobs:print(f'pypi_version={pypi_version}', file=output)PY+ # Fail before building and notarizing a version publish-release will reject.+ - name: Guard against republishing an existing version+ shell: bash+ env:+ GH_REPO: ${{ github.repository }}+ GH_TOKEN: ${{ github.token }}+ DESKTOP_RELEASE_TAG: ${{ steps.prepare.outputs.desktop_release_tag }}+ run: |+ set -euo pipefail+ print_retry_hint() {+ echo "To retry a failed publish of this version:" >&2+ echo " If a release exists, delete it and its tag: gh release delete ${DESKTOP_RELEASE_TAG} --cleanup-tag" >&2+ echo " If release creation failed after reserving only the tag, delete the orphan tag: gh api --method DELETE repos/${GH_REPO}/git/refs/tags/${DESKTOP_RELEASE_TAG}" >&2+ }+ resource_exists() {+ local response+ if response="$(gh api --include "$1" 2>&1)"; then+ return 0+ fi+ if [[ "$response" =~ ^HTTP/[0-9.]+\ 404\ ]]; then+ return 1+ fi+ echo "Could not verify that ${2} is absent; refusing to publish." >&2+ printf '%s\n' "$response" >&2+ exit 1+ }+ if resource_exists "repos/${GH_REPO}/git/ref/tags/${DESKTOP_RELEASE_TAG}" "tag ${DESKTOP_RELEASE_TAG}"; then+ echo "Tag ${DESKTOP_RELEASE_TAG} already exists. Release a new studio_version instead of rebuilding a shipped one." >&2+ print_retry_hint+ exit 1+ fi+ # A read token cannot see drafts, so publish-release repeats this check.+ if resource_exists "repos/${GH_REPO}/releases/tags/${DESKTOP_RELEASE_TAG}" "release ${DESKTOP_RELEASE_TAG}"; then+ echo "Release ${DESKTOP_RELEASE_TAG} already exists. Release a new studio_version instead of rebuilding a shipped one." >&2+ print_retry_hint+ exit 1+ fi+- name: Verify PyPI package and Unsloth stampshell: bashenv:@@ -1493,59 +1531,70 @@ jobs:print('\n'.join(sorted(actual_names)))PY- # Validation runs before the scan so a run with a mismatched release state is- # rejected before any bundle is disclosed to VirusTotal. Creating a release- # that does not exist yet is deferred to after the scan: `gh release create`- # without `--draft` publishes immediately, and doing that here would leave a- # public, assetless release for the duration of the scan (and indefinitely if- # the run is cancelled part way through).+ # Validation runs before the scan so an already-used version is rejected+ # before any bundle is disclosed to VirusTotal. Creation remains deferred+ # until after the scan so a non-draft release is never left public and empty.- name: Validate versioned release stateid: versioned_release_stateshell: bashenv:GH_TOKEN: ${{ github.token }}- RELEASE_DRAFT: ${{ inputs.draft }}run: |set -euo pipefail- # Written here rather than in the conditional create step below, because- # `Generate and publish versioned updater metadata` reads this file on- # every run, including reruns against an already existing release.+ resource_exists() {+ local response+ if response="$(gh api --include "$1" 2>&1)"; then+ return 0+ fi+ if [[ "$response" =~ ^HTTP/[0-9.]+\ 404\ ]]; then+ return 1+ fi+ echo "Could not verify that ${2} is absent; refusing to publish." >&2+ printf '%s\n' "$response" >&2+ exit 1+ }+ print_retry_hint() {+ echo "Release a new studio_version, or recover the failed publish before retrying:" >&2+ echo " If a release exists, delete it and its tag: gh release delete ${DESKTOP_RELEASE_TAG} --cleanup-tag" >&2+ echo " If only a tag exists, delete it: gh api --method DELETE repos/${GH_REPO}/git/refs/tags/${DESKTOP_RELEASE_TAG}" >&2+ }+notes_file="$RUNNER_TEMP/desktop-release-notes.md"printf '%s\n' "$DESKTOP_RELEASE_NOTES" > "$notes_file"- release_json="$RUNNER_TEMP/versioned-release.json"- view_error="$RUNNER_TEMP/versioned-release-view.err"- # REST tag lookup omits drafts; `gh release view` also checks pending tags.- if gh release view "$DESKTOP_RELEASE_TAG" \- --json tagName,isDraft,isPrerelease > "$release_json" 2>"$view_error"; then- python3 <<'PY'+ releases_file="$RUNNER_TEMP/desktop-releases.json"+ # Both release REST endpoints omit drafts. `gh release list` uses the+ # draft-aware GraphQL path and fails nonzero on API/auth errors.+ if ! gh release list --limit 10000 --json tagName > "$releases_file"; then+ echo "Could not list releases, including drafts; refusing to publish." >&2+ exit 1+ fi+ release_state="$(python3 - "$releases_file" "$DESKTOP_RELEASE_TAG" <<'PY'import json- import osimport pathlibimport sys- release = json.loads(pathlib.Path(os.environ['RUNNER_TEMP'], 'versioned-release.json').read_text())- expected_draft = os.environ['RELEASE_DRAFT'].lower() == 'true'- expected_prerelease = os.environ['DESKTOP_PRERELEASE'].lower() == 'true'- if release.get('tagName') != os.environ['DESKTOP_RELEASE_TAG']:- sys.exit('Existing desktop release tag does not match the requested tag')- if bool(release.get('isDraft')) != expected_draft:- sys.exit('Existing desktop release draft state does not match the workflow input')- if bool(release.get('isPrerelease')) != expected_prerelease:- sys.exit('Existing desktop release prerelease state does not match the requested version')+ releases = json.loads(pathlib.Path(sys.argv[1]).read_text())+ if not isinstance(releases, list):+ sys.exit('Unexpected response while listing desktop releases')+ matches = [+ release+ for release in releases+ if isinstance(release, dict) and release.get('tagName') == sys.argv[2]+ ]+ if len(matches) > 1:+ sys.exit(f'Found duplicate releases for {sys.argv[2]}')+ print('exists' if matches else 'absent')PY- echo "create=false" >> "$GITHUB_OUTPUT"- elif grep -qi 'release not found' "$view_error"; then- echo "create=true" >> "$GITHUB_OUTPUT"- else- # `gh` exits non-zero for any failure, so a transient API, auth or rate- # limit error looks identical to a missing release. Treating those as- # "not found" would disclose the bundles to VirusTotal for a run that- # cannot publish, so fail here instead.- echo "::error::Could not determine whether $DESKTOP_RELEASE_TAG exists; refusing to treat this as a missing release"- cat "$view_error" >&2+ )"++ if resource_exists "repos/${GH_REPO}/git/ref/tags/${DESKTOP_RELEASE_TAG}" "tag ${DESKTOP_RELEASE_TAG}" \+ || [ "$release_state" = "exists" ]; then+ echo "Refusing to republish ${DESKTOP_RELEASE_TAG}: a release or tag for this version already exists." >&2+ print_retry_hintexit 1fi+ echo "create=true" >> "$GITHUB_OUTPUT"# ── Advisory multi-engine scan of the bundles we are about to publish ──# Defender (build job) is one vendor and gates only Windows. VirusTotal@@ -1589,56 +1638,8 @@ jobs:echo 'The scan step produced no summary.' >> "$GITHUB_STEP_SUMMARY"fi- # Deferred from the validation step above so the release is created directly- # ahead of its assets, rather than sitting empty for the length of the scan.- - name: Create versioned release- if: steps.versioned_release_state.outputs.create == 'true'- shell: bash- env:- GH_TOKEN: ${{ github.token }}- RELEASE_DRAFT: ${{ inputs.draft }}- run: |- set -euo pipefail- # Written by the validation step above, which always runs.- notes_file="$RUNNER_TEMP/desktop-release-notes.md"-- release_flags=(- --title "Unsloth ${STUDIO_VERSION}"- --notes-file "$notes_file"- --target "$GITHUB_SHA"- )- if [ "$RELEASE_DRAFT" = "true" ]; then- release_flags+=(--draft)- fi- if [ "$DESKTOP_PRERELEASE" = "true" ]; then- release_flags+=(--prerelease)- fi- gh release create "$DESKTOP_RELEASE_TAG" "${release_flags[@]}"-- - name: Publish versioned release assets+ - name: Generate versioned updater metadata and provenanceshell: bash- env:- GH_TOKEN: ${{ github.token }}- run: |- set -euo pipefail- signature_assets="$(- gh release view "$DESKTOP_RELEASE_TAG" --json assets \- --jq '.assets[].name | select(endswith(".sig"))'- )"- while IFS= read -r asset_name; do- [[ -z "$asset_name" ]] || gh release delete-asset "$DESKTOP_RELEASE_TAG" "$asset_name" --yes- done <<< "$signature_assets"-- release_assets=()- for asset in "$RUNNER_TEMP/desktop-release-assets"/*; do- [[ "$asset" == *.sig ]] || release_assets+=("$asset")- done- gh release upload "$DESKTOP_RELEASE_TAG" "${release_assets[@]}" --clobber-- - name: Generate and publish versioned updater metadata- shell: bash- env:- GH_TOKEN: ${{ github.token }}run: |set -euo pipefailpython3 <<'PY'@@ -1696,7 +1697,115 @@ jobs:output = pathlib.Path(os.environ['RUNNER_TEMP'], 'latest.json')output.write_text(json.dumps(metadata, indent=2) + '\n')PY- gh release upload "$DESKTOP_RELEASE_TAG" "$RUNNER_TEMP/latest.json" --clobber++ # Keep provenance out of the notes displayed in the updater popup.+ body_file="$RUNNER_TEMP/desktop-release-body.md"+ {+ cat "$RUNNER_TEMP/desktop-release-notes.md"+ printf '\n### Build provenance\n\n'+ printf 'Source commit: %s\n\n' "$GITHUB_SHA"+ printf 'Asset SHA-256:\n\n```\n'+ (+ cd "$RUNNER_TEMP/desktop-release-assets"+ for asset in *; do+ [[ "$asset" == *.sig ]] || sha256sum -- "$asset"+ done+ )+ (+ cd "$RUNNER_TEMP"+ sha256sum -- latest.json+ )+ printf '```\n'+ } > "$body_file"+ cat "$body_file"++ # Deferred until immediately before upload so public releases are not left+ # empty during the VirusTotal scan. Repeat the absence checks here to close+ # the race introduced by that scan before atomically reserving the tag.+ - name: Create versioned release+ if: steps.versioned_release_state.outputs.create == 'true'+ shell: bash+ env:+ GH_TOKEN: ${{ github.token }}+ RELEASE_DRAFT: ${{ inputs.draft }}+ run: |+ set -euo pipefail+ resource_exists() {+ local response+ if response="$(gh api --include "$1" 2>&1)"; then+ return 0+ fi+ if [[ "$response" =~ ^HTTP/[0-9.]+\ 404\ ]]; then+ return 1+ fi+ echo "Could not verify that ${2} is absent; refusing to publish." >&2+ printf '%s\n' "$response" >&2+ exit 1+ }++ releases_file="$RUNNER_TEMP/desktop-releases-before-create.json"+ if ! gh release list --limit 10000 --json tagName > "$releases_file"; then+ echo "Could not list releases, including drafts; refusing to publish." >&2+ exit 1+ fi+ release_state="$(python3 - "$releases_file" "$DESKTOP_RELEASE_TAG" <<'PY'+ import json+ import pathlib+ import sys++ releases = json.loads(pathlib.Path(sys.argv[1]).read_text())+ if not isinstance(releases, list):+ sys.exit('Unexpected response while listing desktop releases')+ print('exists' if any(+ isinstance(release, dict) and release.get('tagName') == sys.argv[2]+ for release in releases+ ) else 'absent')+ PY+ )"+ if resource_exists "repos/${GH_REPO}/git/ref/tags/${DESKTOP_RELEASE_TAG}" "tag ${DESKTOP_RELEASE_TAG}" \+ || [ "$release_state" = "exists" ]; then+ echo "Refusing to republish ${DESKTOP_RELEASE_TAG}: a release or tag appeared during the pre-flight scan." >&2+ exit 1+ fi++ # Reserve the tag at this source commit before creating the release.+ gh api --method POST "repos/${GH_REPO}/git/refs" \+ -f "ref=refs/tags/${DESKTOP_RELEASE_TAG}" \+ -f "sha=${GITHUB_SHA}"++ release_flags=(+ --title "Unsloth ${STUDIO_VERSION}"+ --notes-file "$RUNNER_TEMP/desktop-release-body.md"+ --verify-tag+ )+ if [ "$RELEASE_DRAFT" = "true" ]; then+ release_flags+=(--draft)+ fi+ if [ "$DESKTOP_PRERELEASE" = "true" ]; then+ release_flags+=(--prerelease)+ fi+ gh release create "$DESKTOP_RELEASE_TAG" "${release_flags[@]}"++ - name: Publish versioned release assets+ shell: bash+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ set -euo pipefail+ release_assets=()+ for asset in "$RUNNER_TEMP/desktop-release-assets"/*; do+ [[ "$asset" == *.sig ]] || release_assets+=("$asset")+ done+ # Preserve the published digests by refusing existing asset names.+ gh release upload "$DESKTOP_RELEASE_TAG" "${release_assets[@]}"++ - name: Publish versioned updater metadata+ shell: bash+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ set -euo pipefail+ gh release upload "$DESKTOP_RELEASE_TAG" "$RUNNER_TEMP/latest.json"- name: Download versioned updater metadataif: ${{ !inputs.draft }}@@ -1914,6 +2023,7 @@ jobs:GH_TOKEN: ${{ github.token }}run: |set -euo pipefail+ # The channel pointer is intentionally mutable.gh release upload desktop-latest "$RUNNER_TEMP/desktop-updater/latest.json" --clobbergh api "repos/${GITHUB_REPOSITORY}/releases/tags/desktop-latest" > "$RUNNER_TEMP/desktop-latest-release.json"python3 <<'PY'diff --git a/tests/python/test_virustotal_scan.py b/tests/python/test_virustotal_scan.pyindex 6bd2a32cf00..b29fe5ce23e 100644--- a/tests/python/test_virustotal_scan.py+++ b/tests/python/test_virustotal_scan.py@@ -839,20 +839,22 @@ class TestWorkflowOrdering:)def test_release_notes_are_written_unconditionally(self):- # The updater metadata step reads this file on every run, including a- # rerun against an existing release where creation is skipped.+ # Validation writes the notes before the advisory scan; metadata and+ # provenance consume that same file before the release is created.steps = self._publish_step_map()assert "desktop-release-notes.md" in steps["Validate versioned release state"]["run"]- metadata = steps["Generate and publish versioned updater metadata"]["run"]+ metadata = steps["Generate versioned updater metadata and provenance"]["run"]assert "desktop-release-notes.md" in metadatadef test_a_failed_lookup_is_not_treated_as_a_missing_release(self):- # `gh` exits non-zero for any failure, so a transient API or auth error- # would otherwise disclose the bundles for a run that cannot publish.+ # A transient GraphQL/auth failure must stop before the workflow marks+ # the version clean and discloses its bundles to VirusTotal.run = self._publish_step_map()["Validate versioned release state"]["run"]- assert "release not found" in run- assert "create=true" in run.split("release not found", 1)[1]- assert "exit 1" in run+ assert "if ! gh release list" in run+ failed_lookup = run.split("if ! gh release list", 1)[1].split("release_state=", 1)[0]+ assert "Could not list releases, including drafts" in failed_lookup+ assert "exit 1" in failed_lookup+ assert "create=true" not in failed_lookupdef test_release_creation_is_gated_on_the_validation_step(self):yaml = pytest.importorskip("yaml")diff --git a/tests/security/test_release_desktop_integrity.py b/tests/security/test_release_desktop_integrity.pynew file mode 100644index 00000000000..d1f2c90cb9c--- /dev/null+++ b/tests/security/test_release_desktop_integrity.py@@ -0,0 +1,304 @@+"""Checks that one desktop version tag can only ever serve one set of binaries."""++from __future__ import annotations++import hashlib+import os+import subprocess+from pathlib import Path++import yaml+++REPO_ROOT = Path(__file__).resolve().parents[2]+WORKFLOW = REPO_ROOT / ".github" / "workflows" / "release-desktop.yml"++RELEASE_TAG = "desktop-v0.1.50-beta"+SOURCE_SHA = "1f02275b86f0e0d3a5b1c9f2a4d6e8b0c2a4e6f8"+++def _workflow():+ return yaml.safe_load(WORKFLOW.read_text(encoding = "utf-8"))+++def _steps(workflow, job):+ return workflow["jobs"][job]["steps"]+++def _step_index(workflow, job, name):+ """Locate a step and report its available names on failure."""+ names = [step.get("name") for step in _steps(workflow, job)]+ assert name in names, f"{job} has no step named {name!r}; steps are {names}"+ return names.index(name)+++def _step(workflow, job, name):+ return _steps(workflow, job)[_step_index(workflow, job, name)]+++def _write_fake_gh(path: Path):+ """Record gh arguments and return configured statuses."""+ path.write_text(+ """#!/bin/sh+set -eu+printf 'gh %s\\n' "$*" >> "$COMMAND_LOG"+if [ "$1" = "api" ]; then+ endpoint=""+ for argument in "$@"; do+ case "$argument" in repos/*) endpoint="$argument" ;; esac+ done+ case "$endpoint" in+ */git/ref/tags/*) status="$TAG_HTTP_STATUS" ;;+ */releases/tags/*) status="$RELEASE_HTTP_STATUS" ;;+ *) exit 0 ;;+ esac+ printf 'HTTP/2.0 %s Test Response\n' "$status"+ if [ "$status" = "200" ]; then exit 0; fi+ exit 1+fi+if [ "$1" = "release" ] && [ "$2" = "list" ]; then+ if [ "$RELEASE_HTTP_STATUS" = "500" ]; then+ printf 'GraphQL test failure\n' >&2+ exit 1+ fi+ if [ "$RELEASE_HTTP_STATUS" = "200" ]; then+ printf '[{"tagName":"%s"}]\n' "$DESKTOP_RELEASE_TAG"+ else+ printf '[]\n'+ fi+ exit 0+fi++exit 0+""",+ encoding = "utf-8",+ )+ path.chmod(0o755)+++def _run_step(+ workflow,+ job: str,+ name: str,+ tmp_path: Path,+ *,+ tag_http_status: int = 404,+ release_http_status: int = 404,+ extra_env: dict[str, str] | None = None,+):+ fake_bin = tmp_path / "bin"+ fake_bin.mkdir(exist_ok = True)+ _write_fake_gh(fake_bin / "gh")+ log = tmp_path / "commands.log"+ log.write_text("", encoding = "utf-8")++ env = os.environ.copy()+ env.update(+ {+ "COMMAND_LOG": str(log),+ "DESKTOP_RELEASE_TAG": RELEASE_TAG,+ "GH_REPO": "unslothai/unsloth",+ "GITHUB_OUTPUT": str(tmp_path / "github-output"),+ "GH_TOKEN": "masked-token",+ "PATH": f"{fake_bin}:{env['PATH']}",+ "RELEASE_HTTP_STATUS": str(release_http_status),+ "RUNNER_TEMP": str(tmp_path),+ "TAG_HTTP_STATUS": str(tag_http_status),+ }+ )+ env.update(extra_env or {})+ result = subprocess.run(+ ["bash", "-c", _step(workflow, job, name)["run"]],+ cwd = tmp_path,+ env = env,+ text = True,+ capture_output = True,+ check = False,+ )+ return result, log.read_text(encoding = "utf-8").splitlines()+++def _stage_assets(tmp_path: Path) -> dict[str, str]:+ """Create release assets and return their digests."""+ asset_dir = tmp_path / "desktop-release-assets"+ asset_dir.mkdir(exist_ok = True)+ digests = {}+ for name, payload in (+ ("Unsloth-Desktop-0_1_50_beta-MacOS.dmg", b"disk image"),+ ("Unsloth-Desktop-0_1_50_beta-Ubuntu.deb", b"package"),+ ("Unsloth-Desktop-0_1_50_beta-ARM64.app.tar.gz", b"mac updater"),+ ("Unsloth-Desktop-0_1_50_beta-ARM64.app.tar.gz.sig", b"mac signature"),+ ("Unsloth-Desktop-0_1_50_beta-Linux.AppImage", b"linux updater"),+ ("Unsloth-Desktop-0_1_50_beta-Linux.AppImage.sig", b"linux signature"),+ ("Unsloth-Desktop-0_1_50_beta-Windows.exe", b"installer"),+ ("Unsloth-Desktop-0_1_50_beta-Windows.exe.sig", b"windows signature"),+ ):+ (asset_dir / name).write_bytes(payload)+ if not name.endswith(".sig"):+ digests[name] = hashlib.sha256(payload).hexdigest()+ return digests+++def _run_create_release(workflow, tmp_path: Path, **kwargs):+ _stage_assets(tmp_path)+ env = {+ "DESKTOP_PRERELEASE": "true",+ "DESKTOP_RELEASE_NOTES": workflow["env"]["DESKTOP_RELEASE_NOTES"],+ "APP_VERSION": "0.1.50",+ "GITHUB_SHA": SOURCE_SHA,+ "GITHUB_REPOSITORY": "unslothai/unsloth",+ "PYPI_VERSION": "2026.8.7",+ "RELEASE_DRAFT": "true",+ "STUDIO_VERSION": "v0.1.50-beta",+ }+ env.update(kwargs.pop("extra_env", None) or {})++ # Execute the production publish sequence in one shell so the notes,+ # metadata and provenance files cross the same step boundaries as Actions.+ names = (+ "Validate versioned release state",+ "Generate versioned updater metadata and provenance",+ "Create versioned release",+ )+ create_step = _step(workflow, "publish-release", "Create versioned release")+ create_step["run"] = "\n".join(+ _step(workflow, "publish-release", name)["run"] for name in names+ )+ return _run_step(+ workflow, "publish-release", "Create versioned release", tmp_path, extra_env = env, **kwargs+ )+++def _upload_commands(workflow):+ commands = []+ for step in _steps(workflow, "publish-release"):+ # Join backslash continuations so a flag parked on the next line counts.+ for line in step.get("run", "").replace("\\\n", " ").splitlines():+ stripped = line.strip()+ if stripped.startswith("gh release upload"):+ commands.append(stripped)+ return commands+++def test_a_used_version_fails_the_guard_before_any_build_work(tmp_path):+ workflow = _workflow()+ # Fail before the build matrix and notarization.+ assert _step_index(+ workflow, "prepare-version", "Guard against republishing an existing version"+ ) < _step_index(workflow, "prepare-version", "Verify PyPI package and Unsloth stamp")+ assert workflow["jobs"]["build"]["needs"] == "prepare-version"++ for case, expected in (+ ({"tag_http_status": 200}, 1),+ ({"release_http_status": 200}, 1),+ ({}, 0),+ ):+ case_dir = tmp_path / ("-".join(case) or "unused-version")+ case_dir.mkdir()+ result, _ = _run_step(+ workflow,+ "prepare-version",+ "Guard against republishing an existing version",+ case_dir,+ **case,+ )+ assert result.returncode == expected, (case, result.stderr)+ if expected:+ assert RELEASE_TAG in result.stderr+ # Avoid leaving a tag that fails the next attempt.+ assert f"gh release delete {RELEASE_TAG} --cleanup-tag" in result.stderr+ assert (+ f"gh api --method DELETE repos/unslothai/unsloth/git/refs/tags/{RELEASE_TAG}"+ in result.stderr+ )+++def test_a_failed_guard_probe_fails_closed_before_any_build_work(tmp_path):+ workflow = _workflow()+ result, _ = _run_step(+ workflow,+ "prepare-version",+ "Guard against republishing an existing version",+ tmp_path,+ tag_http_status = 500,+ )+ assert result.returncode == 1+ assert "Could not verify that tag" in result.stderr+++def test_publish_refuses_to_reuse_an_existing_release(tmp_path):+ workflow = _workflow()+ # The write-scoped publish job can see drafts that prepare-version cannot.+ for case in ({"tag_http_status": 200}, {"release_http_status": 200}):+ case_dir = tmp_path / "-".join(case)+ case_dir.mkdir()+ result, commands = _run_create_release(workflow, case_dir, **case)+ assert result.returncode == 1, case+ assert "Refusing to republish" in result.stderr+ assert f"gh release delete {RELEASE_TAG} --cleanup-tag" in result.stderr+ assert (+ f"gh api --method DELETE repos/unslothai/unsloth/git/refs/tags/{RELEASE_TAG}"+ in result.stderr+ )+ assert not [line for line in commands if line.startswith("gh release create")]+++def test_publish_fails_closed_when_a_guard_probe_errors(tmp_path):+ workflow = _workflow()+ result, commands = _run_create_release(workflow, tmp_path, tag_http_status = 500)+ assert result.returncode == 1+ assert "Could not verify that tag" in result.stderr+ assert not [line for line in commands if line.startswith("gh release create")]+++def test_publish_fails_closed_when_draft_listing_errors(tmp_path):+ workflow = _workflow()+ result, commands = _run_create_release(workflow, tmp_path, release_http_status = 500)+ assert result.returncode == 1+ assert "Could not list releases, including drafts" in result.stderr+ assert not [line for line in commands if line.startswith("gh release create")]+++def test_release_body_records_provenance_the_updater_notes_do_not_carry(tmp_path):+ workflow = _workflow()+ digests = _stage_assets(tmp_path)+ result, commands = _run_create_release(workflow, tmp_path)+ assert result.returncode == 0, result.stderr++ create = next(line for line in commands if line.startswith("gh release create"))+ assert RELEASE_TAG in create+ assert "--target" not in create+ assert "--verify-tag" in create+ assert any("git/refs" in line and f"sha={SOURCE_SHA}" in line for line in commands)++ body_file = tmp_path / "desktop-release-body.md"+ assert f"--notes-file {body_file}" in create+ body = body_file.read_text(encoding = "utf-8")+ assert SOURCE_SHA in body+ for name, digest in digests.items():+ assert f"{digest} {name}" in body+ latest = tmp_path / "latest.json"+ assert latest.is_file()+ assert f"{hashlib.sha256(latest.read_bytes()).hexdigest()} latest.json" in body+ assert ".sig" not in body++ # Keep digests out of updater notes.+ notes = (tmp_path / "desktop-release-notes.md").read_text(encoding = "utf-8")+ assert "Build provenance" not in notes+ assert "Desktop app for Unsloth." in notes+ create_step = _step(workflow, "publish-release", "Create versioned release")+ assert "'desktop-release-notes.md'" in create_step["run"]+ assert "latest.json" in create_step["run"]+++def test_versioned_uploads_never_clobber_but_the_channel_pointer_does():+ uploads = _upload_commands(_workflow())+ versioned = [line for line in uploads if "$DESKTOP_RELEASE_TAG" in line]+ channel = [line for line in uploads if "desktop-latest" in line]+ assert len(versioned) == 2, uploads+ assert len(channel) == 1, uploads++ for line in versioned:+ assert "--clobber" not in line, line+ # The channel pointer is intentionally mutable.+ assert "--clobber" in channel[0]diff --git a/tests/security/test_release_desktop_permissions.py b/tests/security/test_release_desktop_permissions.pyindex fe22e6af965..b304d9afdc3 100644--- a/tests/security/test_release_desktop_permissions.py+++ b/tests/security/test_release_desktop_permissions.py@@ -56,8 +56,8 @@ def test_build_matrix_hands_off_assets_without_release_credentials():release_step = next(step for step in publish["steps"] if step.get("name") == "Validate versioned release state")- assert "gh release view" in release_step["run"]- assert "--json tagName,isDraft,isPrerelease" in release_step["run"]+ assert "gh release list" in release_step["run"]+ assert "resource_exists" in release_step["run"]create_step = next(step for step in publish["steps"] if step.get("name") == "Create versioned release"@@ -71,8 +71,8 @@ def test_versioned_release_hides_updater_signature_assets():publish = next(step for step in steps if step.get("name") == "Publish versioned release assets")assert '[[ "$asset" == *.sig ]] || release_assets+=("$asset")' in publish["run"]- assert "gh release delete-asset" in publish["run"]assert '"${release_assets[@]}"' in publish["run"]+ assert "--clobber" not in publish["run"]def test_publishing_draft_advances_updater_without_rebuilding():