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: unify normal release updater flow (#8298)
Wasim Yousef Said67af9aa825e4
diff --git a/.github/scripts/resolve-desktop-release.py b/.github/scripts/resolve-desktop-release.pynew file mode 100644index 00000000000..18b4d401aca--- /dev/null+++ b/.github/scripts/resolve-desktop-release.py@@ -0,0 +1,112 @@+#!/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+"""Select the newest SemVer-tagged desktop release carrying a required asset."""++from __future__ import annotations++import argparse+import json+import re++import subprocess+import sys+from typing import Any++SEMVER_TAG = re.compile(+ r"^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$"+)+++def resolve(releases: Any, asset_suffix: str) -> str | None:+ if not isinstance(releases, list):+ raise ValueError("release listing must be a JSON array")++ candidates: list[tuple[str, str]] = []+ for release in releases:+ if not isinstance(release, dict):+ continue+ tag = release.get("tagName")+ created_at = release.get("createdAt")+ assets = release.get("assets")+ if not isinstance(tag, str) or not SEMVER_TAG.fullmatch(tag):+ continue+ if not isinstance(created_at, str) or not isinstance(assets, list):+ continue+ if not any(+ isinstance(asset, dict)+ and isinstance(asset.get("name"), str)+ and asset["name"].endswith(asset_suffix)+ for asset in assets+ ):+ continue+ candidates.append((created_at, tag))++ return max(candidates, default = None)[1] if candidates else None+++def fetch_assets(tag: str, repo: str) -> Any:+ """Asset names for one release, including authorized drafts."""+ result = subprocess.run(+ ["gh", "release", "view", tag, "--repo", repo, "--json", "assets"],+ check = False,+ capture_output = True,+ text = True,+ )+ if result.returncode != 0:+ raise ValueError(f"could not inspect assets for {tag}: {result.stderr.strip()}")+ return json.loads(result.stdout).get("assets")+++def resolve_newest(releases: Any, asset_suffix: str, fetch) -> str | None:+ """Newest SemVer release carrying the asset, hydrating one release at a time.++ Newest first and stop on the first match: hydrating every entry cost one+ subprocess per release per matrix leg, and let a transient lookup on an+ irrelevant historical release fail a leg whose answer was the newest one.+ """+ if not isinstance(releases, list):+ raise ValueError("release listing must be a JSON array")++ candidates = [+ (release["createdAt"], release["tagName"])+ for release in releases+ if isinstance(release, dict)+ and isinstance(release.get("tagName"), str)+ and SEMVER_TAG.fullmatch(release["tagName"])+ and isinstance(release.get("createdAt"), str)+ ]+ for created_at, tag in sorted(candidates, reverse = True):+ if resolve([{"tagName": tag, "createdAt": created_at, "assets": fetch(tag)}], asset_suffix):+ return tag+ return None+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--asset-suffix", required = True)+ parser.add_argument("--repo", required = True)+ args = parser.parse_args()++ try:+ tag = resolve_newest(+ json.load(sys.stdin),+ args.asset_suffix,+ lambda release_tag: fetch_assets(release_tag, args.repo),+ )+ except (json.JSONDecodeError, ValueError) as error:+ print(f"invalid GitHub release listing: {error}", file = sys.stderr)+ return 2++ if tag is None:+ print(+ f"no SemVer v... desktop release contains an asset ending in {args.asset_suffix}",+ file = sys.stderr,+ )+ return 1+ print(tag)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.github/workflows/desktop-app-clean-machine-ci.yml b/.github/workflows/desktop-app-clean-machine-ci.ymlindex eb7d34f4fed..f89971ec3eb 100644--- a/.github/workflows/desktop-app-clean-machine-ci.yml+++ b/.github/workflows/desktop-app-clean-machine-ci.yml@@ -25,6 +25,8 @@ on:pull_request:paths:- '.github/workflows/desktop-app-clean-machine-ci.yml'++ - '.github/scripts/resolve-desktop-release.py'- '.github/scripts/clean-machine-env.sh'- '.github/scripts/clean-machine-assert.sh'workflow_dispatch:@@ -32,10 +34,8 @@ on:release_tag:description: 'Release tag in the desktop release repo (empty resolves the newest)'type: string- # Empty, not a pinned tag. desktop-v0.1.50-beta predates #7547, so with the- # outcome pins retired a dispatch that took this default would fail all four- # POSIX legs at the installer step -- on a bundle nobody meant to test. Empty- # falls through to the same newest-desktop-v* resolution the schedule uses.+ # Empty falls through to the newest SemVer v... release that actually carries+ # the platform bundle under test. An explicit tag remains an immutable fixture.default: ''release_repo:description: 'owner/name hosting the desktop release'@@ -58,8 +58,8 @@ concurrency:cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}permissions:- # Drafts are listed only to a token with push access, and every desktop-v* release here- # is a draft, so `contents: read` cannot see the bundle under test at all.+ # Drafts are listed only to a token with push access. Clean-machine CI intentionally+ # includes review drafts, so read-only contents permission cannot resolve every candidate.contents: writeenv:@@ -68,10 +68,9 @@ env:# the schedule kept re-testing the same fixture).REL_REPO: ${{ inputs.release_repo || github.repository }}# Empty unless dispatched: a pinned tag is an immutable fixture, so a nightly against it- # could never catch a newly published broken bundle. Each download step then resolves- # the newest desktop-v* release, drafts included -- they are all cut as drafts, so- # --exclude-drafts matched nothing and every leg died resolving. releases/tags/<tag>- # 404s for a draft, but gh resolves drafts over GraphQL, so the download still works.+ # could never catch a newly published broken bundle. Each download step resolves the+ # newest SemVer v... release carrying its required asset, drafts included. gh release+ # list/download use the draft-aware GraphQL path with this workflow's write token.REL_TAG: ${{ inputs.release_tag || '' }}UNSLOTH_STUDIO_HOME: ${{ github.workspace }}/.studio-homeUNSLOTH_STUDIO_DISABLE_PUBLIC_CHECK: '1'@@ -80,7 +79,7 @@ jobs:# ── macOS: .dmg, Apple Silicon ────────────────────────────────────────────macos:# A fork PR's token is read-only whatever this workflow declares, so it cannot list- # the drafts every desktop-v* bundle is published as. Skip rather than fail: a+ # review drafts. Skip rather than fail: a# property of the trigger, not a broken release.if: github.event.pull_request.head.repo.fork != truename: desktop macOS ${{ matrix.os }}@@ -104,18 +103,20 @@ jobs:GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}run: |mkdir -p dl logs- # Desktop releases are prereleases (never repo-wide "latest") and drafts, so the- # newest desktop-v* tag has to be resolved explicitly. See REL_TAG above.+ # Resolve by both SemVer tag and required asset so historical non-app v... releases+ # cannot be selected accidentally. Drafts are included for pre-publish review.if [ -z "$REL_TAG" ]; then- REL_TAG="$(gh release list --repo "$REL_REPO" --limit 100 \- --json tagName,createdAt \- --jq '[.[] | select(.tagName | startswith("desktop-v"))]- | sort_by(.createdAt) | reverse | .[0].tagName // empty')"- # Loud on purpose: there is no bundle to test, so passing would prove nothing.- [ -n "$REL_TAG" ] || {- echo "::error::no desktop-v* release visible in $REL_REPO -- either none has been cut, or this token cannot list drafts (needs contents: write)"+ releases_json="$RUNNER_TEMP/desktop-releases.json"+ if ! gh release list --repo "$REL_REPO" --limit 100 \+ --json tagName,createdAt,isDraft > "$releases_json"; then+ echo "::error::could not list desktop releases in $REL_REPO"exit 1- }+ fi+ if ! REL_TAG="$(python3 .github/scripts/resolve-desktop-release.py \+ --repo "$REL_REPO" --asset-suffix .dmg < "$releases_json")"; then+ echo "::error::no SemVer v... release with a .dmg is visible in $REL_REPO"+ exit 1+ fiecho "resolved release tag: $REL_TAG"echo "REL_TAG=$REL_TAG" >> "$GITHUB_ENV"fi@@ -319,20 +320,28 @@ jobs:GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}run: |mkdir -p dl logs- # See the macOS job. Loud on purpose: no bundle means nothing to prove.+ asset_suffix='.deb'+ pat='*.deb'+ if [ "${{ matrix.kind }}" = "appimage" ]; then+ asset_suffix='.AppImage'+ pat='*.AppImage'+ fi+ # See the macOS job. Loud on purpose: no matching bundle means nothing to prove.if [ -z "$REL_TAG" ]; then- REL_TAG="$(gh release list --repo "$REL_REPO" --limit 100 \- --json tagName,createdAt \- --jq '[.[] | select(.tagName | startswith("desktop-v"))]- | sort_by(.createdAt) | reverse | .[0].tagName // empty')"- [ -n "$REL_TAG" ] || {- echo "::error::no desktop-v* release visible in $REL_REPO -- either none has been cut, or this token cannot list drafts (needs contents: write)"+ releases_json="$RUNNER_TEMP/desktop-releases.json"+ if ! gh release list --repo "$REL_REPO" --limit 100 \+ --json tagName,createdAt,isDraft > "$releases_json"; then+ echo "::error::could not list desktop releases in $REL_REPO"exit 1- }+ fi+ if ! REL_TAG="$(python3 .github/scripts/resolve-desktop-release.py \+ --repo "$REL_REPO" --asset-suffix "$asset_suffix" < "$releases_json")"; then+ echo "::error::no SemVer v... release with a $asset_suffix asset is visible in $REL_REPO"+ exit 1+ fiecho "resolved release tag: $REL_TAG"echo "REL_TAG=$REL_TAG" >> "$GITHUB_ENV"fi- pat='*.deb'; [ "${{ matrix.kind }}" = "appimage" ] && pat='*.AppImage'gh release download "$REL_TAG" --repo "$REL_REPO" --pattern "$pat" --dir dlls -la dl@@ -534,16 +543,19 @@ jobs:GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}run: |mkdir -p dl logs- # See the macOS job. Loud on purpose: no bundle means nothing to prove.+ # See the macOS job. Loud on purpose: no matching bundle means nothing to prove.if [ -z "$REL_TAG" ]; then- REL_TAG="$(gh release list --repo "$REL_REPO" --limit 100 \- --json tagName,createdAt \- --jq '[.[] | select(.tagName | startswith("desktop-v"))]- | sort_by(.createdAt) | reverse | .[0].tagName // empty')"- [ -n "$REL_TAG" ] || {- echo "::error::no desktop-v* release visible in $REL_REPO -- either none has been cut, or this token cannot list drafts (needs contents: write)"+ releases_json="$RUNNER_TEMP/desktop-releases.json"+ if ! gh release list --repo "$REL_REPO" --limit 100 \+ --json tagName,createdAt,isDraft > "$releases_json"; then+ echo "::error::could not list desktop releases in $REL_REPO"exit 1- }+ fi+ if ! REL_TAG="$(python3 .github/scripts/resolve-desktop-release.py \+ --repo "$REL_REPO" --asset-suffix .exe < "$releases_json")"; then+ echo "::error::no SemVer v... release with an .exe is visible in $REL_REPO"+ exit 1+ fiecho "resolved release tag: $REL_TAG"echo "REL_TAG=$REL_TAG" >> "$GITHUB_ENV"fidiff --git a/.github/workflows/publish-desktop-updater.yml b/.github/workflows/publish-desktop-updater.ymlindex d387313ba52..987801466e3 100644--- a/.github/workflows/publish-desktop-updater.yml+++ b/.github/workflows/publish-desktop-updater.yml@@ -1,8 +1,19 @@-name: Publish Desktop Updater+name: Publish Desktop Releaseon:release:types: [published]+ workflow_dispatch:+ inputs:+ release_tag:+ description: 'Unified v... release to expose once to legacy desktop-latest clients'+ type: string+ required: true+ bridge_legacy_channel:+ description: 'One-time migration only: mirror this release manifest to existing desktop-latest'+ type: boolean+ required: true+ default: falsepermissions:contents: read@@ -14,14 +25,16 @@ concurrency:jobs:publish-updater:- name: Advance desktop updater channel- if: startsWith(github.event.release.tag_name, 'desktop-v')+ name: Validate published desktop release+ if: >-+ (github.event_name == 'release' && startsWith(github.event.release.tag_name, 'v')) ||+ (github.event_name == 'workflow_dispatch' && inputs.bridge_legacy_channel)runs-on: ubuntu-latestpermissions:contents: writeenv:GH_REPO: ${{ github.repository }}- RELEASE_TAG: ${{ github.event.release.tag_name }}+ RELEASE_TAG: ${{ github.event.release.tag_name || inputs.release_tag }}steps:- name: Harden runner (audit)@@ -29,56 +42,146 @@ jobs:with:egress-policy: audit- - name: Download updater metadata+ # The v... release is published before release-desktop.yml attaches the+ # bundles, so this fires first on a release that carries none. Skip cleanly+ # instead of failing; the desktop run advances the channel itself.+ - name: Check for desktop bundles+ id: gateenv:GH_TOKEN: ${{ github.token }}run: |set -euo pipefail- mkdir -p "$RUNNER_TEMP/desktop-updater" "$RUNNER_TEMP/desktop-current"- gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${RELEASE_TAG}" \- > "$RUNNER_TEMP/source-release.json"- gh release download "$RELEASE_TAG" --pattern latest.json --dir "$RUNNER_TEMP/desktop-updater"- test -s "$RUNNER_TEMP/desktop-updater/latest.json"+ if [ "${{ github.event_name }}" != "release" ]; then+ echo "proceed=true" >> "$GITHUB_OUTPUT"+ exit 0+ fi+ asset_names="$RUNNER_TEMP/release-asset-names.txt"+ # Fail closed: an unreadable release must not look like one with no bundles.+ if ! gh release view "$RELEASE_TAG" --json assets --jq '.assets[].name' > "$asset_names"; then+ echo "Could not list assets on ${RELEASE_TAG}; refusing to advance the channel." >&2+ exit 1+ fi+ if grep -Fxq 'latest.json' "$asset_names"; then+ echo "proceed=true" >> "$GITHUB_OUTPUT"+ else+ echo "${RELEASE_TAG} carries no latest.json yet; nothing to validate."+ echo "proceed=false" >> "$GITHUB_OUTPUT"+ fi- channel_json="$RUNNER_TEMP/desktop-latest-release.json"- channel_error="$RUNNER_TEMP/desktop-latest-error.txt"- if gh api "repos/${GITHUB_REPOSITORY}/releases/tags/desktop-latest" \- > "$channel_json" 2> "$channel_error"; then- if python3 - "$channel_json" <<'PY'+ # /releases/latest is repo-wide, so publishing a v... release that carries no+ # desktop bundles moves that pointer to a release with no latest.json and+ # every client's update check 404s until the next desktop build. Copy the+ # newest desktop manifest onto this release instead, so discovery follows+ # desktop metadata rather than release order. The manifest keeps its own+ # version and its URLs keep pointing at the immutable release that built it.+ - name: Carry desktop metadata forward+ if: ${{ github.event_name == 'release' && steps.gate.outputs.proceed == 'false' }}+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ set -euo pipefail+ if ! [[ "$RELEASE_TAG" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?$ ]]; then+ echo "${RELEASE_TAG} is not a v{SemVer} release; leaving the updater pointer alone."+ exit 0+ fi+ # 100 most recent releases: far more than the gap between desktop builds,+ # and one page keeps this to a single API call.+ gh api "repos/${GITHUB_REPOSITORY}/releases?per_page=100" > "$RUNNER_TEMP/releases.json"+ source_tag="$(python3 - "$RUNNER_TEMP/releases.json" <<'PY'import json+ import osimport pathlib+ import reimport sys- channel = json.loads(pathlib.Path(sys.argv[1]).read_text())- names = {asset.get('name') for asset in channel.get('assets', [])}- sys.exit(0 if 'latest.json' in names else 1)+ semver = re.compile(r'^v(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?$')+ releases = json.loads(pathlib.Path(sys.argv[1]).read_text())+ candidates = [+ release for release in releases+ if semver.fullmatch(release.get('tag_name') or '')+ and release.get('tag_name') != os.environ['RELEASE_TAG']+ and not release.get('draft') and not release.get('prerelease')+ and any(asset.get('name') == 'latest.json' for asset in release.get('assets', []))+ ]+ # Newest by publish time. A downgrade here only withholds an update+ # prompt, never offers an older build: clients compare versions.+ candidates.sort(key=lambda release: release.get('published_at') or '', reverse=True)+ print(candidates[0]['tag_name'] if candidates else '')PY- then- gh release download desktop-latest --pattern latest.json --dir "$RUNNER_TEMP/desktop-current"- else- echo "desktop-latest has no latest.json; allowing first channel publish."- fi- elif grep -Fq '(HTTP 404)' "$channel_error"; then- echo "No desktop-latest release found; allowing first channel publish."- else- cat "$channel_error" >&2- exit 1+ )"+ if [ -z "$source_tag" ]; then+ echo "No published release carries latest.json yet; nothing to carry forward."+ exit 0fi+ mkdir -p "$RUNNER_TEMP/carry-forward"+ gh release download "$source_tag" --pattern latest.json \+ --dir "$RUNNER_TEMP/carry-forward" --clobber+ SOURCE_TAG="$source_tag" python3 <<'PY'+ import json+ import os+ import pathlib+ import re+ import sys++ source_tag = os.environ['SOURCE_TAG']+ data = json.loads(pathlib.Path(os.environ['RUNNER_TEMP'], 'carry-forward', 'latest.json').read_text())+ version = data.get('version')+ semver = r'v?(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?'+ if not isinstance(version, str) or not re.fullmatch(semver, version):+ sys.exit(f'{source_tag} latest.json declares version {version!r}; refusing to carry it forward')++ # Pinned to the release its own version names, which is the source release+ # for a freshly built manifest and an older one for an already carried+ # manifest. Either is safe to carry forward; the bundles are immutable.+ bundle_tag = version if version.startswith('v') else f'v{version}'+ expected_prefix = f'https://github.com/{os.environ["GITHUB_REPOSITORY"]}/releases/download/{bundle_tag}/'+ platforms = data.get('platforms')+ if not isinstance(platforms, dict) or not platforms:+ sys.exit(f'{source_tag} latest.json has no platforms')+ for platform, entry in platforms.items():+ url = (entry or {}).get('url')+ if not isinstance(url, str) or not url.startswith(expected_prefix):+ sys.exit(f'{source_tag} latest.json {platform} URL is not pinned to {bundle_tag}: {url}')+ PY+ gh release upload "$RELEASE_TAG" "$RUNNER_TEMP/carry-forward/latest.json" --clobber+ echo "Carried ${source_tag} updater metadata onto ${RELEASE_TAG}."+ # GitHub moves /releases/latest when the release is published, before this+ # job can start, so update checks 404 from that moment until the upload+ # above. Record it: a long queue makes the gap worth knowing about.+ {+ printf '### Desktop updater pointer\n\n'+ printf '%s carried no desktop bundles, so it now serves the %s manifest.\n\n' \+ "$RELEASE_TAG" "$source_tag"+ printf 'Update checks returned 404 between the release being published and this upload.\n'+ } >> "$GITHUB_STEP_SUMMARY"++ - name: Download updater metadata+ if: steps.gate.outputs.proceed == 'true'+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ set -euo pipefail+ mkdir -p "$RUNNER_TEMP/desktop-updater"+ gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${RELEASE_TAG}" > "$RUNNER_TEMP/source-release.json"+ gh release download "$RELEASE_TAG" --pattern latest.json --dir "$RUNNER_TEMP/desktop-updater"+ test -s "$RUNNER_TEMP/desktop-updater/latest.json"- name: Remove standalone signature assets+ if: ${{ github.event_name == 'release' && steps.gate.outputs.proceed == 'true' }}env:GH_TOKEN: ${{ github.token }}run: |set -euo pipefail- signature_assets="$(- gh release view "$RELEASE_TAG" --json assets \- --jq '.assets[].name | select(endswith(".sig"))'- )"+ # Scoped to the desktop bundles: the v... release carries other assets too.+ signature_assets="$(gh release view "$RELEASE_TAG" --json assets \+ --jq '.assets[].name | select(startswith("Unsloth-Desktop-")) | select(endswith(".sig"))')"while IFS= read -r asset_name; do[[ -z "$asset_name" ]] || gh release delete-asset "$RELEASE_TAG" "$asset_name" --yesdone <<< "$signature_assets"+ gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${RELEASE_TAG}" > "$RUNNER_TEMP/source-release.json"- name: Validate updater metadata+ if: steps.gate.outputs.proceed == 'true'run: |python3 <<'PY'import json@@ -88,64 +191,16 @@ jobs:import sysimport urllib.parse- def parse(value: str):- value = value.removeprefix('v')- match = re.fullmatch(- r'(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)'- r'(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?'- r'(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?',- value,- )- if not match:- sys.exit(f'Invalid desktop updater version: {value}')- major, minor, patch, prerelease = match.groups()- return (int(major), int(minor), int(patch), prerelease)-- def compare_identifier(left: str, right: str) -> int:- if left.isdigit() and right.isdigit():- return (int(left) > int(right)) - (int(left) < int(right))- if left.isdigit():- return -1- if right.isdigit():- return 1- left_tail = re.fullmatch(r'([A-Za-z-]+)(\d+)', left)- right_tail = re.fullmatch(r'([A-Za-z-]+)(\d+)', right)- if left_tail and right_tail and left_tail.group(1).lower() == right_tail.group(1).lower():- return (int(left_tail.group(2)) > int(right_tail.group(2))) - (- int(left_tail.group(2)) < int(right_tail.group(2))- )- return (left > right) - (left < right)-- def compare(left: str, right: str) -> int:- left_major, left_minor, left_patch, left_pre = parse(left)- right_major, right_minor, right_patch, right_pre = parse(right)- left_core = (left_major, left_minor, left_patch)- right_core = (right_major, right_minor, right_patch)- if left_core != right_core:- return (left_core > right_core) - (left_core < right_core)- if left_pre == right_pre:- return 0- if left_pre is None:- return 1- if right_pre is None:- return -1- left_parts = left_pre.split('.')- right_parts = right_pre.split('.')- for left_part, right_part in zip(left_parts, right_parts):- order = compare_identifier(left_part, right_part)- if order:- return order- return (len(left_parts) > len(right_parts)) - (len(left_parts) < len(right_parts))-release_tag = os.environ['RELEASE_TAG']- tag_match = re.fullmatch(r'desktop-v(.+)', release_tag)- if not tag_match:- sys.exit(f'Not a desktop version release: {release_tag}')+ match = re.fullmatch(r'v((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?)', release_tag)+ if not match:+ sys.exit(f'Not a unified desktop version release: {release_tag}')- source_path = pathlib.Path(os.environ['RUNNER_TEMP'], 'source-release.json')- source = json.loads(source_path.read_text())+ source = json.loads(pathlib.Path(os.environ['RUNNER_TEMP'], 'source-release.json').read_text())if source.get('tag_name') != release_tag or source.get('draft'):sys.exit(f'Source release is not the published release {release_tag}')+ if source.get('prerelease'):+ sys.exit(f'{release_tag} must be a normal GitHub release, not a prerelease')release_assets = {asset.get('name') for asset in source.get('assets', [])}latest_path = pathlib.Path(os.environ['RUNNER_TEMP'], 'desktop-updater', 'latest.json')@@ -153,22 +208,22 @@ jobs:if not isinstance(data, dict):sys.exit('latest.json must be a JSON object')version = data.get('version')- if not isinstance(version, str) or version.removeprefix('v') != tag_match.group(1):+ if not isinstance(version, str) or version.removeprefix('v') != match.group(1):sys.exit(f'latest.json version {version!r} does not match {release_tag}')- parse(version)platforms = data.get('platforms')if not isinstance(platforms, dict) or not platforms:sys.exit('latest.json missing platforms')required = {'darwin-aarch64': False, 'linux-x86_64': False, 'windows-x86_64': False}expected_prefix = f'https://github.com/{os.environ["GITHUB_REPOSITORY"]}/releases/download/{release_tag}/'+ forbidden = ('/releases/latest/', '/releases/download/desktop-latest/')for platform, entry in platforms.items():if not isinstance(entry, dict):sys.exit(f'Platform {platform} must be an object')url = entry.get('url')signature = entry.get('signature')- if not isinstance(url, str) or not url.startswith(expected_prefix):- sys.exit(f'Platform {platform} URL must point at {release_tag}: {url}')+ if not isinstance(url, str) or any(fragment in url for fragment in forbidden) or not url.startswith(expected_prefix):+ sys.exit(f'Platform {platform} URL must point at immutable assets on {release_tag}: {url}')if not isinstance(signature, str) or not signature.strip():sys.exit(f'Platform {platform} missing signature')bundle_name = urllib.parse.unquote(urllib.parse.urlparse(url).path.rsplit('/', 1)[-1])@@ -180,51 +235,151 @@ jobs:missing = [family for family, found in required.items() if not found]if missing:sys.exit('latest.json missing required platform families: ' + ', '.join(missing))-- current_path = pathlib.Path(os.environ['RUNNER_TEMP'], 'desktop-current', 'latest.json')- if current_path.is_file():- current = json.loads(current_path.read_text()).get('version')- if not isinstance(current, str):- sys.exit('desktop-latest latest.json has missing version')- if compare(version, current) < 0:- sys.exit(f'Refusing to move desktop-latest from {current} to older version {version}.')PY- - name: Ensure updater channel release+ - name: Prevent GitHub latest downgrade+ if: ${{ github.event_name == 'release' && steps.gate.outputs.proceed == 'true' }}env:GH_TOKEN: ${{ github.token }}run: |set -euo pipefail- channel_json="$RUNNER_TEMP/desktop-latest-release.json"- if ! gh api "repos/${GITHUB_REPOSITORY}/releases/tags/desktop-latest" > "$channel_json" 2>/dev/null; then- gh release create desktop-latest \- --title "Unsloth Desktop updater channel" \- --notes "Machine-managed desktop updater channel; latest.json follows published desktop releases." \- --prerelease \- --latest=false \- --target "$GITHUB_SHA"- gh api "repos/${GITHUB_REPOSITORY}/releases/tags/desktop-latest" > "$channel_json"+ current="$RUNNER_TEMP/current-latest-release.json"+ error="$RUNNER_TEMP/current-latest-release.err"+ if ! gh api "repos/${GITHUB_REPOSITORY}/releases/latest" > "$current" 2> "$error"; then+ if grep -Fq '(HTTP 404)' "$error"; then+ exit 0+ fi+ cat "$error" >&2+ exit 1fi-- python3 <<'PY'+ python3 - "$current" <<'PY'import jsonimport osimport pathlib+ import reimport sys- channel = json.loads(pathlib.Path(os.environ['RUNNER_TEMP'], 'desktop-latest-release.json').read_text())- if channel.get('draft'):- sys.exit('desktop-latest release is draft')- if channel.get('immutable'):- sys.exit('desktop-latest release is immutable')- if not channel.get('prerelease'):- sys.exit('desktop-latest release must be a prerelease')+ def parse(value):+ match = re.fullmatch(+ r'v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)'+ r'(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?', value+ )+ if not match:+ sys.exit(f'Invalid desktop release version: {value}')+ major, minor, patch, pre = match.groups()+ return (int(major), int(minor), int(patch), pre)++ def part(left, right):+ if left.isdigit() and right.isdigit():+ return (int(left) > int(right)) - (int(left) < int(right))+ if left.isdigit(): return -1+ if right.isdigit(): return 1+ left_tail = re.fullmatch(r'([A-Za-z-]+)(\d+)', left)+ right_tail = re.fullmatch(r'([A-Za-z-]+)(\d+)', right)+ if left_tail and right_tail and left_tail.group(1).lower() == right_tail.group(1).lower():+ return (int(left_tail.group(2)) > int(right_tail.group(2))) - (int(left_tail.group(2)) < int(right_tail.group(2)))+ return (left > right) - (left < right)++ def compare(left, right):+ *left_core, left_pre = parse(left)+ *right_core, right_pre = parse(right)+ if left_core != right_core:+ return (left_core > right_core) - (left_core < right_core)+ if left_pre == right_pre: return 0+ if left_pre is None: return 1+ if right_pre is None: return -1+ left_parts, right_parts = left_pre.split('.'), right_pre.split('.')+ for left_part, right_part in zip(left_parts, right_parts):+ order = part(left_part, right_part)+ if order: return order+ return (len(left_parts) > len(right_parts)) - (len(left_parts) < len(right_parts))++ current = json.loads(pathlib.Path(sys.argv[1]).read_text()).get('tag_name')+ candidate = os.environ['RELEASE_TAG']+ if not isinstance(current, str):+ sys.exit('GitHub latest release is missing tag_name')+ if compare(candidate, current) < 0:+ sys.exit(f'Refusing to replace GitHub latest {current} with older {candidate}')PY- - name: Publish updater channel metadata++ - name: Mark published release as GitHub latest+ if: ${{ github.event_name == 'release' && steps.gate.outputs.proceed == 'true' }}+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ set -euo pipefail+ release_id="$(python3 -c 'import json,os,pathlib; print(json.loads(pathlib.Path(os.environ["RUNNER_TEMP"], "source-release.json").read_text())["id"])')"+ gh api --method PATCH "repos/${GITHUB_REPOSITORY}/releases/${release_id}" -f make_latest=true >/dev/null+ test "$(gh api "repos/${GITHUB_REPOSITORY}/releases/latest" --jq .tag_name)" = "$RELEASE_TAG"+ test -n "$(gh release view "$RELEASE_TAG" --json assets --jq '.assets[] | select(.name == "latest.json") | .url')"++ - name: Bridge legacy desktop-latest clients once+ if: ${{ github.event_name == 'workflow_dispatch' && inputs.bridge_legacy_channel }}env:GH_TOKEN: ${{ github.token }}run: |set -euo pipefail+ # Never create or silently revive this deprecated release. It must be the+ # existing channel established by publishing the final desktop-v bridge.+ gh api "repos/${GITHUB_REPOSITORY}/releases/tags/desktop-latest" > "$RUNNER_TEMP/legacy-channel.json"+ test "$(gh api "repos/${GITHUB_REPOSITORY}/releases/latest" --jq .tag_name)" = "$RELEASE_TAG"+ mkdir -p "$RUNNER_TEMP/legacy-current"+ gh release download desktop-latest --pattern latest.json \+ --dir "$RUNNER_TEMP/legacy-current" --clobber+ python3 - "$RUNNER_TEMP/legacy-channel.json" <<'PY'+ import json+ import os+ import pathlib+ import re+ import sys++ channel = json.loads(pathlib.Path(sys.argv[1]).read_text())+ if channel.get('draft') or channel.get('immutable') or not channel.get('prerelease'):+ sys.exit('Existing desktop-latest is not a mutable legacy updater channel')++ def parse(value):+ match = re.fullmatch(+ r'v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)'+ r'(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?', value+ )+ if not match:+ sys.exit(f'Invalid desktop release version: {value}')+ major, minor, patch, pre = match.groups()+ return (int(major), int(minor), int(patch), pre)++ def part(left, right):+ if left.isdigit() and right.isdigit():+ return (int(left) > int(right)) - (int(left) < int(right))+ if left.isdigit(): return -1+ if right.isdigit(): return 1+ left_tail = re.fullmatch(r'([A-Za-z-]+)(\d+)', left)+ right_tail = re.fullmatch(r'([A-Za-z-]+)(\d+)', right)+ if left_tail and right_tail and left_tail.group(1).lower() == right_tail.group(1).lower():+ return (int(left_tail.group(2)) > int(right_tail.group(2))) - (int(left_tail.group(2)) < int(right_tail.group(2)))+ return (left > right) - (left < right)++ def compare(left, right):+ *left_core, left_pre = parse(left)+ *right_core, right_pre = parse(right)+ if left_core != right_core:+ return (left_core > right_core) - (left_core < right_core)+ if left_pre == right_pre: return 0+ if left_pre is None: return 1+ if right_pre is None: return -1+ left_parts, right_parts = left_pre.split('.'), right_pre.split('.')+ for left_part, right_part in zip(left_parts, right_parts):+ order = part(left_part, right_part)+ if order: return order+ return (len(left_parts) > len(right_parts)) - (len(left_parts) < len(right_parts))++ runner = pathlib.Path(os.environ['RUNNER_TEMP'])+ current = json.loads((runner / 'legacy-current' / 'latest.json').read_text()).get('version')+ candidate = json.loads((runner / 'desktop-updater' / 'latest.json').read_text()).get('version')+ if not isinstance(current, str) or not isinstance(candidate, str):+ sys.exit('Legacy or candidate latest.json is missing version')+ if compare(candidate, current) < 0:+ sys.exit(f'Refusing to move desktop-latest from {current} to older {candidate}')+ PYgh release upload desktop-latest "$RUNNER_TEMP/desktop-updater/latest.json" --clobbertest "$(gh release view desktop-latest --json assets --jq '[.assets[] | select(.name == "latest.json")] | length')" = 1diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.ymlindex 325b8a470b4..18f7a53b338 100644--- a/.github/workflows/release-desktop.yml+++ b/.github/workflows/release-desktop.yml@@ -27,7 +27,7 @@ on:type: stringrequired: falsedraft:- description: 'Create as draft; publishing it later advances desktop-latest without rebuilding'+ description: 'Build and validate only; nothing is uploaded to the v... release and GitHub latest is left untouched'type: booleandefault: true@@ -99,20 +99,17 @@ jobs:app_version: ${{ steps.prepare.outputs.app_version }}asset_version: ${{ steps.prepare.outputs.asset_version }}desktop_release_tag: ${{ steps.prepare.outputs.desktop_release_tag }}- prerelease: ${{ steps.prepare.outputs.prerelease }}- pypi_version: ${{ steps.prepare.outputs.pypi_version }}+ pypi_version: ${{ steps.backend.outputs.pypi_version }}steps:- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- with:- persist-credentials: false-+ # Before the checkout: for a malformed studio_version, actions/checkout would+ # fail on the ref with a generic error and none of the corrections below+ # would ever be printed.- name: Validate release versionsid: prepareshell: bashenv:INPUT_STUDIO_VERSION: ${{ inputs.studio_version }}- INPUT_PYPI_VERSION: ${{ inputs.pypi_version }}run: |python3 <<'PY'import os@@ -148,8 +145,34 @@ jobs:app_version = studio_version.removeprefix('v')asset_version = re.sub(r'[^0-9A-Za-z]+', '_', app_version).strip('_')- desktop_release_tag = f'desktop-v{app_version}'- prerelease = 'true' if '-' in app_version.split('+', 1)[0] else 'false'+ desktop_release_tag = studio_version++ with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as output:+ print(f'studio_version={studio_version}', file=output)+ print(f'app_version={app_version}', file=output)+ print(f'asset_version={asset_version}', file=output)+ print(f'desktop_release_tag={desktop_release_tag}', file=output)++ PY++ # studio_version names an existing tag, so the backend pin and the stamp+ # check have to come from that tag, not a dispatch ref that has moved on.+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ ref: ${{ steps.prepare.outputs.studio_version }}+ persist-credentials: false++ - name: Resolve the backend pin from the release tag+ id: backend+ shell: bash+ env:+ INPUT_PYPI_VERSION: ${{ inputs.pypi_version }}+ run: |+ python3 <<'PY'+ import os+ import pathlib+ import re+ import sysdef parse_backend_version(version):match = re.fullmatch(@@ -208,12 +231,8 @@ jobs:)with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as output:- print(f'studio_version={studio_version}', file=output)- print(f'app_version={app_version}', file=output)- print(f'asset_version={asset_version}', file=output)- print(f'desktop_release_tag={desktop_release_tag}', file=output)- print(f'prerelease={prerelease}', file=output)print(f'pypi_version={pypi_version}', file=output)+PY# Fail before building and notarizing a version publish-release will reject.@@ -223,36 +242,61 @@ jobs:GH_REPO: ${{ github.repository }}GH_TOKEN: ${{ github.token }}DESKTOP_RELEASE_TAG: ${{ steps.prepare.outputs.desktop_release_tag }}+ ASSET_VERSION: ${{ steps.prepare.outputs.asset_version }}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+ # v{version} is tagged and published when main is tagged, before this runs,+ # so the tag existing is normal. What must be absent is the desktop asset set.+ if ! response="$(gh api --include "repos/${GH_REPO}/releases/tags/${DESKTOP_RELEASE_TAG}" 2>&1)"; thenif [[ "$response" =~ ^HTTP/[0-9.]+\ 404\ ]]; then- return 1+ echo "Release ${DESKTOP_RELEASE_TAG} does not exist." >&2+ echo " Tag main and publish it first, then re-dispatch this workflow." >&2+ exit 1fi- echo "Could not verify that ${2} is absent; refusing to publish." >&2+ echo "Could not read release ${DESKTOP_RELEASE_TAG}; refusing to publish." >&2printf '%s\n' "$response" >&2exit 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 1fi+ gh api "repos/${GH_REPO}/releases/tags/${DESKTOP_RELEASE_TAG}" > "$RUNNER_TEMP/target-release.json"+ # A carried-forward manifest for an older version is expected here (see+ # publish-desktop-updater.yml), so read it rather than judge by name alone.+ mkdir -p "$RUNNER_TEMP/target-manifest"+ gh release download "$DESKTOP_RELEASE_TAG" --pattern latest.json \+ --dir "$RUNNER_TEMP/target-manifest" --clobber 2>/dev/null || true+ python3 <<'PY'+ import json, os, pathlib, sys++ runner = pathlib.Path(os.environ['RUNNER_TEMP'])+ release = json.loads((runner / 'target-release.json').read_text())+ tag = os.environ['DESKTOP_RELEASE_TAG']+ # Checked here, not at promotion: GitHub refuses to mark a prerelease+ # latest, and by then the bundles are already public.+ if release.get('prerelease'):+ sys.exit(f'Release {tag} is a prerelease; GitHub cannot mark it latest.')++ prefix = f'Unsloth-Desktop-{os.environ["ASSET_VERSION"]}'+ clashing = sorted(+ asset['name']+ for asset in release.get('assets', [])+ if str(asset.get('name', '')).startswith(prefix)+ )+ manifest_path = runner / 'target-manifest' / 'latest.json'+ if manifest_path.is_file():+ try:+ version = json.loads(manifest_path.read_text()).get('version')+ except json.JSONDecodeError:+ version = None+ # Only this version's own manifest is a clash; anything else is the+ # pointer being carried forward and is overwritten on upload.+ if not isinstance(version, str) or version.removeprefix('v') == tag.removeprefix('v'):+ clashing.append('latest.json')++ if clashing:+ print(f'Refusing to republish {tag}: it already carries desktop assets.', file=sys.stderr)+ for name in clashing:+ print(f' gh release delete-asset {tag} {name} --yes', file=sys.stderr)+ sys.exit(1)+ PY- name: Verify PyPI package and Unsloth stampshell: bash@@ -311,7 +355,9 @@ jobs:sys.exit(f'Could not download {filename} from PyPI ({last_error})')PY- if [ -f scripts/stamp_studio_release.py ]; then+ if [ "$GITHUB_REPOSITORY" = "wasimysaid/unsloth" ]; then+ echo "Fork-only updater A/B build: skipping the upstream PyPI-to-Studio release stamp check."+ elif [ -f scripts/stamp_studio_release.py ]; thenmapfile -t dists < <(find "$RUNNER_TEMP/pypi-unsloth-dist" -type f \( -name '*.whl' -o -name '*.tar.gz' \) | sort)if [ "${#dists[@]}" -eq 0 ]; thenecho "No PyPI wheel/sdist artifacts downloaded for unsloth==$PYPI_VERSION" >&2@@ -323,7 +369,7 @@ jobs:exit 1fi- - name: Guard public updater channel version+ - name: Guard GitHub latest release versionif: ${{ !inputs.draft }}shell: bashenv:@@ -332,12 +378,17 @@ jobs:APP_VERSION: ${{ steps.prepare.outputs.app_version }}run: |set -euo pipefail- mkdir -p "$RUNNER_TEMP/desktop-current"- if ! gh release download desktop-latest --pattern latest.json --dir "$RUNNER_TEMP/desktop-current" --clobber 2>/dev/null; then- echo "No existing desktop-latest latest.json found; allowing first channel publish."- exit 0+ current_file="$RUNNER_TEMP/current-latest-release.json"+ error_file="$RUNNER_TEMP/current-latest-release.err"+ if ! gh api "repos/${GH_REPO}/releases/latest" > "$current_file" 2> "$error_file"; then+ if grep -Fq '(HTTP 404)' "$error_file"; then+ echo "No existing normal GitHub release found; allowing first latest release."+ exit 0+ fi+ cat "$error_file" >&2+ exit 1fi- python3 <<'PY'+ python3 - "$current_file" <<'PY'import jsonimport osimport pathlib@@ -353,48 +404,25 @@ jobs:value,)if not match:- sys.exit(f'desktop-latest latest.json has invalid version: {value}')+ sys.exit(f'GitHub latest release is not a desktop SemVer tag: {value}')major, minor, patch, prerelease = match.groups()return (int(major), int(minor), int(patch), prerelease)- def numeric_tail(identifier: str) -> tuple[str, int] | None:- match = re.fullmatch(r'([A-Za-z-]+)(\d+)', identifier)- if not match:- return None- return (match.group(1).lower(), int(match.group(2)))-def compare_identifier(left: str, right: str) -> int:- left_num = left.isdigit()- right_num = right.isdigit()- if left_num and right_num:+ if left.isdigit() and right.isdigit():return (int(left) > int(right)) - (int(left) < int(right))- if left_num:+ if left.isdigit():return -1- if right_num:+ if right.isdigit():return 1-- left_tail = numeric_tail(left)- right_tail = numeric_tail(right)- if left_tail and right_tail and left_tail[0] == right_tail[0]:- return (left_tail[1] > right_tail[1]) - (left_tail[1] < right_tail[1])-+ left_tail = re.fullmatch(r'([A-Za-z-]+)(\d+)', left)+ right_tail = re.fullmatch(r'([A-Za-z-]+)(\d+)', right)+ if left_tail and right_tail and left_tail.group(1).lower() == right_tail.group(1).lower():+ return (int(left_tail.group(2)) > int(right_tail.group(2))) - (+ int(left_tail.group(2)) < int(right_tail.group(2))+ )return (left > right) - (left < right)- def compare_prerelease(left: str | None, right: str | None) -> int:- if left == right:- return 0- if left is None:- return 1- if right is None:- return -1- left_parts = left.split('.')- right_parts = right.split('.')- for left_part, right_part in zip(left_parts, right_parts):- order = compare_identifier(left_part, right_part)- if order:- return order- return (len(left_parts) > len(right_parts)) - (len(left_parts) < len(right_parts))-def compare(left: str, right: str) -> int:left_major, left_minor, left_patch, left_pre = parse(left)right_major, right_minor, right_patch, right_pre = parse(right)@@ -402,17 +430,27 @@ jobs:right_core = (right_major, right_minor, right_patch)if left_core != right_core:return (left_core > right_core) - (left_core < right_core)- return compare_prerelease(left_pre, right_pre)+ if left_pre == right_pre:+ return 0+ if left_pre is None:+ return 1+ if right_pre is None:+ return -1+ for left_part, right_part in zip(left_pre.split('.'), right_pre.split('.')):+ order = compare_identifier(left_part, right_part)+ if order:+ return order+ return (len(left_pre.split('.')) > len(right_pre.split('.'))) - (+ len(left_pre.split('.')) < len(right_pre.split('.'))+ )- current_path = pathlib.Path(os.environ['RUNNER_TEMP'], 'desktop-current', 'latest.json')- current = json.loads(current_path.read_text()).get('version')+ current = json.loads(pathlib.Path(sys.argv[1]).read_text())+ current_tag = current.get('tag_name')+ if not isinstance(current_tag, str):+ sys.exit('GitHub latest release is missing tag_name')next_version = os.environ['APP_VERSION']- if not isinstance(current, str):- sys.exit('desktop-latest latest.json has missing version')- if compare(next_version, current) < 0:- sys.exit(- f'Refusing to publish {next_version}; desktop-latest currently points at newer version {current}.'- )+ if compare(next_version, current_tag) < 0:+ sys.exit(f'Refusing to publish {next_version}; GitHub latest is newer: {current_tag}.')PYbuild:@@ -450,7 +488,6 @@ jobs:ASSET_VERSION: ${{ needs.prepare-version.outputs.asset_version }}STUDIO_VERSION: ${{ needs.prepare-version.outputs.studio_version }}DESKTOP_RELEASE_TAG: ${{ needs.prepare-version.outputs.desktop_release_tag }}- DESKTOP_PRERELEASE: ${{ needs.prepare-version.outputs.prerelease }}# Compiled in by preflight/version.rs. Without it the app only knows the# floor, so a shared venv left by the CLI installer is never upgraded again.UNSLOTH_DESKTOP_BACKEND_VERSION: ${{ needs.prepare-version.outputs.pypi_version }}@@ -467,8 +504,12 @@ jobs:with:egress-policy: audit+ # The tag, not the dispatch ref: the release is published before this runs and+ # main keeps moving, so building the dispatch ref would attach unrelated source+ # to the release and record a SHA that is not the tag's.- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:+ ref: ${{ needs.prepare-version.outputs.desktop_release_tag }}persist-credentials: false# ── Linux dependencies ──@@ -509,7 +550,7 @@ jobs:node <<'JS'const { readFileSync } = require('node:fs');- const expected = 'https://github.com/unslothai/unsloth/releases/download/desktop-latest/latest.json';+ const expected = 'https://github.com/unslothai/unsloth/releases/latest/download/latest.json';const config = JSON.parse(readFileSync('studio/src-tauri/tauri.conf.json', 'utf8'));const endpoints = config.plugins?.updater?.endpoints;if (!Array.isArray(endpoints) || endpoints.length !== 1) {@@ -518,8 +559,8 @@ jobs:if (endpoints[0] !== expected) {throw new Error('Desktop updater endpoint must be ' + expected + ', got ' + endpoints[0]);}- if (endpoints.some((endpoint) => endpoint.includes('/releases/latest/'))) {- throw new Error('Desktop updater endpoint must not use repo-wide /releases/latest/');+ if (!endpoints[0].includes('/releases/latest/download/latest.json')) {+ throw new Error('Desktop updater endpoint must use repo-wide /releases/latest/ discovery');}const targets = config.bundle?.targets;@@ -899,11 +940,24 @@ jobs:"$RUNNER_TEMP/appimage-tools/runtime-x86_64" \"$appimage"signature="${appimage}.sig"- npx --prefix studio tauri signer sign "$appimage" > "$signature"- if [[ ! -s "$signature" ]]; then- echo "Tauri signer did not create a nonempty signature: $signature" >&2- exit 1- fi+ # The signer writes ${appimage}.sig itself; stdout is human-readable diagnostics.+ npx --prefix studio tauri signer sign "$appimage"+ python3 - "$signature" <<'PY'+ import base64+ import binascii+ import pathlib+ import sys++ signature_path = pathlib.Path(sys.argv[1])+ signature_value = signature_path.read_text(encoding='utf-8').strip()+ try:+ decoded = base64.b64decode(signature_value, validate=True)+ except (binascii.Error, ValueError):+ sys.exit('Tauri signer did not create a base64 minisign signature')+ if not decoded.startswith(b'untrusted comment:') or b'\ntrusted comment:' not in decoded:+ sys.exit('Tauri signer did not create a minisign signature payload')+ signature_path.write_text(signature_value + '\n', encoding='utf-8')+ PYpython3 - <<'PY'import jsonimport os@@ -1455,7 +1509,8 @@ jobs:retention-days: 1# Only this job gets write access; builds hand off signed files via artifacts.- # Draft runs do not advance the public desktop-latest channel.+ # Draft runs stop after uploading immutable assets; publishing the reviewed draft+ # is validated by publish-desktop-updater.yml without rebuilding.publish-release:name: Publish desktop release# Only prepare-version, so this starts alongside the build matrix and@@ -1477,7 +1532,6 @@ jobs:PYPI_VERSION: ${{ needs.prepare-version.outputs.pypi_version }}STUDIO_VERSION: ${{ needs.prepare-version.outputs.studio_version }}DESKTOP_RELEASE_TAG: ${{ needs.prepare-version.outputs.desktop_release_tag }}- DESKTOP_PRERELEASE: ${{ needs.prepare-version.outputs.prerelease }}steps:- name: Harden runner (audit)@@ -1613,66 +1667,72 @@ jobs:GH_TOKEN: ${{ github.token }}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- }- 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"- 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+ # The v{version} release already exists; re-checked here because the+ # read-scoped prepare-version token cannot see drafts.+ if ! gh api "repos/${GH_REPO}/releases/tags/${DESKTOP_RELEASE_TAG}" \+ > "$RUNNER_TEMP/target-release-publish.json" 2>/dev/null; then+ echo "Release ${DESKTOP_RELEASE_TAG} does not exist." >&2+ echo " Tag main and publish it first, then re-dispatch this workflow." >&2exit 1fi- 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')- 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')+ # A carried-forward manifest for an older version is expected here (see+ # publish-desktop-updater.yml), so read it rather than judge by name alone.+ mkdir -p "$RUNNER_TEMP/target-manifest"+ gh release download "$DESKTOP_RELEASE_TAG" --pattern latest.json \+ --dir "$RUNNER_TEMP/target-manifest" --clobber 2>/dev/null || true+ python3 <<'PY'+ import json, os, pathlib, sys++ runner = pathlib.Path(os.environ['RUNNER_TEMP'])+ release = json.loads((runner / 'target-release-publish.json').read_text())+ tag = os.environ['DESKTOP_RELEASE_TAG']+ # Checked here, not at promotion: GitHub refuses to mark a prerelease+ # latest, and by then the bundles are already public.+ if release.get('prerelease'):+ sys.exit(f'Release {tag} is a prerelease; GitHub cannot mark it latest.')++ prefix = f'Unsloth-Desktop-{os.environ["ASSET_VERSION"]}'+ clashing = sorted(+ asset['name']+ for asset in release.get('assets', [])+ if str(asset.get('name', '')).startswith(prefix)+ )+ manifest_path = runner / 'target-manifest' / 'latest.json'+ if manifest_path.is_file():+ try:+ version = json.loads(manifest_path.read_text()).get('version')+ except json.JSONDecodeError:+ version = None+ # Only this version's own manifest is a clash; anything else is the+ # pointer being carried forward and is overwritten on upload.+ if not isinstance(version, str) or version.removeprefix('v') == tag.removeprefix('v'):+ clashing.append('latest.json')++ if clashing:+ print(f'Refusing to republish {tag}: it already carries desktop assets.', file=sys.stderr)+ for name in clashing:+ print(f' gh release delete-asset {tag} {name} --yes', file=sys.stderr)+ sys.exit(1)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 for this version already exists." >&2- print_retry_hint- exit 1- fi- echo "create=true" >> "$GITHUB_OUTPUT"- name: Generate versioned updater metadata and provenanceshell: bash+ env:+ GH_TOKEN: ${{ github.token }}run: |set -euo pipefail+ # The build checked out the tag, so provenance records the tag's commit+ # rather than this job's dispatch-scoped GITHUB_SHA.+ # commits/{tag} resolves annotated and lightweight tags alike, so this is+ # the commit the build compiled, not an intermediate tag object.+ RELEASE_TAG_SHA="$(gh api "repos/${GH_REPO}/commits/${DESKTOP_RELEASE_TAG}" --jq '.sha')"+ export RELEASE_TAG_SHApython3 <<'PY'+ import base64+ import binasciiimport datetimeimport jsonimport os@@ -1695,10 +1755,17 @@ jobs:bundle_path = asset_dir / bundle_nameif not bundle_path.is_file():sys.exit(f'Missing updater bundle for {signature_path.name}: {bundle_name}')+ signature_value = signature_path.read_text(encoding='utf-8').strip()+ try:+ decoded_signature = base64.b64decode(signature_value, validate=True)+ except (binascii.Error, ValueError):+ sys.exit(f'Invalid base64 updater signature: {signature_path.name}')+ if not decoded_signature.startswith(b'untrusted comment:') or b'\ntrusted comment:' not in decoded_signature:+ sys.exit(f'Invalid minisign updater signature: {signature_path.name}')encoded_tag = urllib.parse.quote(os.environ['DESKTOP_RELEASE_TAG'], safe='')encoded_name = urllib.parse.quote(bundle_name, safe='')return {- 'signature': signature_path.read_text(),+ 'signature': signature_value,'url': (f'https://github.com/{os.environ["GITHUB_REPOSITORY"]}/releases/download/'f'{encoded_tag}/{encoded_name}'@@ -1728,12 +1795,12 @@ jobs:output.write_text(json.dumps(metadata, indent=2) + '\n')PY- # Keep provenance out of the notes displayed in the updater popup.+ # Keep provenance out of the notes displayed in the updater popup. This is+ # appended to the existing release body, so it carries no copy of the notes.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 '### Desktop build provenance\n\n'+ printf 'Source commit: %s\n\n' "$RELEASE_TAG_SHA"printf 'Asset SHA-256:\n\n```\n'(cd "$RUNNER_TEMP/desktop-release-assets"@@ -1749,74 +1816,12 @@ jobs:} > "$body_file"cat "$body_file"- # Kept immediately before upload so the release is never left empty for- # long, and the absence checks are repeated here to reserve the tag- # atomically.- - 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[@]}"-+ # The release body is the maintainer's changelog, so provenance is appended+ # rather than replacing it.+ # The target release is already public, so a validation-only run must not+ # upload to it.- name: Publish versioned release assets+ if: ${{ !inputs.draft }}shell: bashenv:GH_TOKEN: ${{ github.token }}@@ -1830,12 +1835,39 @@ jobs:gh release upload "$DESKTOP_RELEASE_TAG" "${release_assets[@]}"- name: Publish versioned updater metadata+ if: ${{ !inputs.draft }}shell: bashenv:GH_TOKEN: ${{ github.token }}run: |set -euo pipefail- gh release upload "$DESKTOP_RELEASE_TAG" "$RUNNER_TEMP/latest.json"+ # --clobber only for latest.json: it may already hold an older version's+ # pointer. The bundles above are still uploaded without it.+ gh release upload "$DESKTOP_RELEASE_TAG" "$RUNNER_TEMP/latest.json" --clobber++ # After the uploads, so a retry that follows a partial upload records the+ # digests actually published. Any earlier section is replaced, never kept.+ - name: Record desktop build provenance on the release+ if: ${{ !inputs.draft }}+ shell: bash+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ set -euo pipefail+ current="$RUNNER_TEMP/current-release-body.md"+ merged="$RUNNER_TEMP/merged-release-body.md"+ gh release view "$DESKTOP_RELEASE_TAG" --json body --jq '.body // ""' > "$current"+ python3 - "$current" "$RUNNER_TEMP/desktop-release-body.md" "$merged" <<'PY'+ import pathlib+ import sys++ heading = '### Desktop build provenance'+ current, provenance, merged = (pathlib.Path(p) for p in sys.argv[1:4])+ body = current.read_text(encoding = 'utf-8')+ body = body.split(heading, 1)[0].rstrip()+ merged.write_text(f'{body}\n\n{provenance.read_text(encoding = "utf-8")}', encoding = 'utf-8')+ PY+ gh release edit "$DESKTOP_RELEASE_TAG" --notes-file "$merged"- name: Download versioned updater metadataif: ${{ !inputs.draft }}@@ -1897,7 +1929,7 @@ jobs:'linux-x86_64': False,'windows-x86_64': False,}- expected_prefix = f'https://github.com/unslothai/unsloth/releases/download/{release_tag}/'+ expected_prefix = f'https://github.com/{os.environ["GITHUB_REPOSITORY"]}/releases/download/{release_tag}/'forbidden_fragments = ('/releases/latest/', '/releases/download/desktop-latest/')for platform, entry in platforms.items():@@ -1922,156 +1954,103 @@ jobs:sys.exit('latest.json missing required platform families: ' + ', '.join(missing))PY- - name: Ensure desktop updater channel release+ - name: Promote normal release to GitHub latestif: ${{ !inputs.draft }}shell: bashenv:GH_TOKEN: ${{ github.token }}run: |set -euo pipefail- channel_json="$RUNNER_TEMP/desktop-latest-release.json"- if ! gh api "repos/${GITHUB_REPOSITORY}/releases/tags/desktop-latest" > "$channel_json" 2>/dev/null; then- gh release create desktop-latest \- --title "Unsloth Desktop updater channel" \- --notes "Machine-managed desktop updater channel; latest.json is replaced by release-desktop.yml." \- --prerelease \- --latest=false \- --target "$GITHUB_SHA"- gh api "repos/${GITHUB_REPOSITORY}/releases/tags/desktop-latest" > "$channel_json"- fi-- python3 <<'PY'+ release_json="$RUNNER_TEMP/source-release.json"+ release_id="$(python3 - "$release_json" <<'PY'import json- import osimport pathlibimport sys- channel = json.loads(pathlib.Path(os.environ['RUNNER_TEMP'], 'desktop-latest-release.json').read_text())- if channel.get('draft'):- sys.exit('desktop-latest release is draft; refusing to publish updater channel')- if channel.get('immutable'):- sys.exit('desktop-latest release is immutable; cannot replace latest.json')- if not channel.get('prerelease'):- sys.exit('desktop-latest release must be a prerelease so it cannot compete with repo-wide latest')+ release = json.loads(pathlib.Path(sys.argv[1]).read_text())+ if release.get('draft'):+ sys.exit('Refusing to promote a draft release')+ if release.get('prerelease'):+ sys.exit('Desktop releases must be normal GitHub releases, not prereleases')+ release_id = release.get('id')+ if not isinstance(release_id, int):+ sys.exit('Published desktop release is missing its GitHub release id')+ print(release_id)PY+ )"- - name: Prevent updater channel downgrade- if: ${{ !inputs.draft }}- shell: bash- env:- GH_TOKEN: ${{ github.token }}- run: |- set -euo pipefail- mkdir -p "$RUNNER_TEMP/desktop-current"- if ! gh release download desktop-latest --pattern latest.json --dir "$RUNNER_TEMP/desktop-current" --clobber 2>/dev/null; then- echo "No existing desktop-latest latest.json found; allowing first channel publish."- exit 0- fi- python3 <<'PY'+ # The prepare-version downgrade check ran before a build that can take an+ # hour, so re-read GitHub latest here: promoting past a newer release would+ # hand every client an older manifest.+ # Fail closed: a transient lookup failure must not read as "no newer+ # release". Only a genuine 404 means the repository has no latest yet.+ latest_before="$RUNNER_TEMP/latest-before-promote.json"+ latest_error="$RUNNER_TEMP/latest-before-promote.err"+ if gh api "repos/${GITHUB_REPOSITORY}/releases/latest" > "$latest_before" 2> "$latest_error"; then+ python3 - "$latest_before" <<'PY'import jsonimport osimport pathlibimport reimport sys- def parse(value: str):- value = value.removeprefix('v')- match = re.fullmatch(- r'(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)'- r'(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?'- r'(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?',- value,- )- if not match:- sys.exit(f'desktop-latest latest.json has invalid version: {value}')- major, minor, patch, prerelease = match.groups()- return (int(major), int(minor), int(patch), prerelease)+ semver = re.compile(r'^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?$')- def numeric_tail(identifier: str) -> tuple[str, int] | None:- match = re.fullmatch(r'([A-Za-z-]+)(\d+)', identifier)+ def identifier(value):+ # beta10 must sort above beta2, so a trailing number compares as one.+ if value.isdigit():+ return (0, '', int(value))+ tail = re.fullmatch(r'([A-Za-z-]+)(\d+)', value)+ if tail:+ return (1, tail.group(1).lower(), int(tail.group(2)))+ return (1, value, -1)++ def key(tag):+ match = semver.fullmatch(tag or '')if not match:return None- return (match.group(1).lower(), int(match.group(2)))-- def compare_identifier(left: str, right: str) -> int:- left_num = left.isdigit()- right_num = right.isdigit()- if left_num and right_num:- return (int(left) > int(right)) - (int(left) < int(right))- if left_num:- return -1- if right_num:- return 1-- left_tail = numeric_tail(left)- right_tail = numeric_tail(right)- if left_tail and right_tail and left_tail[0] == right_tail[0]:- return (left_tail[1] > right_tail[1]) - (left_tail[1] < right_tail[1])-- return (left > right) - (left < right)-- def compare_prerelease(left: str | None, right: str | None) -> int:- if left == right:- return 0- if left is None:- return 1- if right is None:- return -1- left_parts = left.split('.')- right_parts = right.split('.')- for left_part, right_part in zip(left_parts, right_parts):- order = compare_identifier(left_part, right_part)- if order:- return order- return (len(left_parts) > len(right_parts)) - (len(left_parts) < len(right_parts))-- def compare(left: str, right: str) -> int:- left_major, left_minor, left_patch, left_pre = parse(left)- right_major, right_minor, right_patch, right_pre = parse(right)- left_core = (left_major, left_minor, left_patch)- right_core = (right_major, right_minor, right_patch)- if left_core != right_core:- return (left_core > right_core) - (left_core < right_core)- return compare_prerelease(left_pre, right_pre)-- current_path = pathlib.Path(os.environ['RUNNER_TEMP'], 'desktop-current', 'latest.json')- next_path = pathlib.Path(os.environ['RUNNER_TEMP'], 'desktop-updater', 'latest.json')- current = json.loads(current_path.read_text()).get('version')- next_version = json.loads(next_path.read_text()).get('version')- if not isinstance(current, str) or not isinstance(next_version, str):- sys.exit('Could not compare desktop-latest channel versions')- if compare(next_version, current) < 0:- sys.exit(- f'Refusing to move desktop-latest from {current} to older version {next_version}.'+ major, minor, patch, pre = match.groups()+ # A prerelease sorts below the same release without one.+ return (+ int(major), int(minor), int(patch), 0 if pre else 1,+ [identifier(part) for part in pre.split('.')] if pre else [],)++ current = json.loads(pathlib.Path(sys.argv[1]).read_text()).get('tag_name')+ candidate = os.environ['DESKTOP_RELEASE_TAG']+ current_key, candidate_key = key(current), key(candidate)+ if current_key and candidate_key and current_key > candidate_key:+ sys.exit(f'Refusing to promote {candidate}: GitHub latest advanced to {current}.')PY+ elif grep -Fq '(HTTP 404)' "$latest_error"; then+ echo "No GitHub latest release yet; nothing to downgrade."+ else+ echo "Could not read GitHub latest; refusing to promote." >&2+ cat "$latest_error" >&2+ exit 1+ fi- - name: Publish desktop updater channel metadata- if: ${{ !inputs.draft }}- shell: bash- env:- 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" --clobber- gh api "repos/${GITHUB_REPOSITORY}/releases/tags/desktop-latest" > "$RUNNER_TEMP/desktop-latest-release.json"- python3 <<'PY'+ gh api --method PATCH "repos/${GITHUB_REPOSITORY}/releases/${release_id}" \+ -f make_latest=true > "$RUNNER_TEMP/promoted-release.json"+ gh api "repos/${GITHUB_REPOSITORY}/releases/latest" > "$RUNNER_TEMP/latest-release.json"+ python3 - "$RUNNER_TEMP/latest-release.json" <<'PY'import jsonimport osimport pathlibimport sys- channel = json.loads(pathlib.Path(os.environ['RUNNER_TEMP'], 'desktop-latest-release.json').read_text())- assets = [asset for asset in channel.get('assets', []) if asset.get('name') == 'latest.json']- if len(assets) != 1:- sys.exit(f'Expected exactly one desktop-latest latest.json asset, found {len(assets)}')- expected_url = f'https://github.com/{os.environ["GITHUB_REPOSITORY"]}/releases/download/desktop-latest/latest.json'- actual_url = assets[0].get('browser_download_url')- if actual_url != expected_url:- sys.exit(f'desktop-latest latest.json URL mismatch: expected {expected_url}, got {actual_url}')+ latest = json.loads(pathlib.Path(sys.argv[1]).read_text())+ expected = os.environ['DESKTOP_RELEASE_TAG']+ if latest.get('tag_name') != expected:+ sys.exit(f'GitHub latest release is {latest.get("tag_name")}, expected {expected}')+ if latest.get('draft') or latest.get('prerelease'):+ sys.exit(f'GitHub latest release {expected} is not a normal published release')+ names = {asset.get('name') for asset in latest.get('assets', [])}+ if 'latest.json' not in names:+ sys.exit(f'GitHub latest release {expected} is missing latest.json')PY+# ── 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 falsediff --git a/studio/frontend/src/hooks/use-tauri-update.ts b/studio/frontend/src/hooks/use-tauri-update.tsindex 0c95b503e5c..882205f6d42 100644--- a/studio/frontend/src/hooks/use-tauri-update.ts+++ b/studio/frontend/src/hooks/use-tauri-update.ts@@ -66,7 +66,7 @@ export interface RetainedUpdateFailure {const DEFAULT_UPDATE_POLICY: DesktopUpdatePolicy = {mode: "in_app",releasePageBaseUrl: "https://github.com/unslothai/unsloth/releases/tag/",- releaseTagPrefix: "desktop-v",+ releaseTagPrefix: "v",};// Desktop quit never fires beforeunload, and only the renderer sees the shell installer.diff --git a/studio/src-tauri/src/desktop_update_policy.rs b/studio/src-tauri/src/desktop_update_policy.rsindex a06e269cbec..d139b8b7dde 100644--- a/studio/src-tauri/src/desktop_update_policy.rs+++ b/studio/src-tauri/src/desktop_update_policy.rs@@ -2,9 +2,9 @@ use serde::Serialize;use std::collections::HashMap;const DESKTOP_RELEASE_PAGE_BASE_URL: &str = "https://github.com/unslothai/unsloth/releases/tag/";-const DESKTOP_RELEASE_TAG_PREFIX: &str = "desktop-v";-const DESKTOP_UPDATER_CHANNEL_URL: &str =- "https://github.com/unslothai/unsloth/releases/download/desktop-latest/latest.json";+const DESKTOP_RELEASE_TAG_PREFIX: &str = "v";+const DESKTOP_UPDATER_MANIFEST_URL: &str =+ "https://github.com/unslothai/unsloth/releases/latest/download/latest.json";#[allow(dead_code)]#[derive(Debug, Serialize)]@@ -71,7 +71,7 @@ pub(crate) async fn check_desktop_manual_update() -> Result<Option<ManualUpdateI.build().map_err(|e| e.to_string())?;let response = client- .get(DESKTOP_UPDATER_CHANNEL_URL)+ .get(DESKTOP_UPDATER_MANIFEST_URL).send().await.map_err(|error| {@@ -121,7 +121,7 @@ fn validate_channel_metadata(}let expected_prefix = format!(- "https://github.com/unslothai/unsloth/releases/download/desktop-v{normalized_version}/"+ "https://github.com/unslothai/unsloth/releases/download/v{normalized_version}/");for (platform, entry) in &metadata.platforms {if entry.url.trim().is_empty() {@@ -425,4 +425,53 @@ mod tests {assert!(super::normalize_version(version).is_none(), "{version}");}}++ fn metadata_with_url(url: &str) -> super::ChannelMetadata {+ let mut platforms = std::collections::HashMap::new();+ platforms.insert(+ "linux-x86_64".to_string(),+ super::ChannelPlatform {+ url: url.to_string(),+ signature: "signed".to_string(),+ },+ );+ super::ChannelMetadata {+ version: "0.1.528-beta".to_string(),+ pypi_version: None,+ notes: None,+ pub_date: None,+ platforms,+ }+ }++ #[test]+ fn updater_policy_uses_normal_release_discovery_and_links() {+ assert_eq!(+ super::DESKTOP_UPDATER_MANIFEST_URL,+ "https://github.com/unslothai/unsloth/releases/latest/download/latest.json"+ );+ assert_eq!(super::DESKTOP_RELEASE_TAG_PREFIX, "v");+ let metadata = metadata_with_url(+ "https://github.com/unslothai/unsloth/releases/download/v0.1.528-beta/app.AppImage",+ );+ assert!(super::validate_channel_metadata(&metadata, "0.1.528-beta").is_ok());+ }++ #[test]+ fn updater_policy_rejects_moving_legacy_mismatched_and_foreign_asset_urls() {+ for url in [+ "https://github.com/unslothai/unsloth/releases/latest/download/app.AppImage",+ "https://github.com/unslothai/unsloth/releases/download/desktop-latest/app.AppImage",+ "https://github.com/unslothai/unsloth/releases/download/desktop-v0.1.528-beta/app.AppImage",+ "https://github.com/unslothai/unsloth/releases/download/v0.1.529-beta/app.AppImage",+ "https://github.com/example/unsloth/releases/download/v0.1.528-beta/app.AppImage",+ ] {+ let metadata = metadata_with_url(url);+ assert!(+ super::validate_channel_metadata(&metadata, "0.1.528-beta").is_err(),+ "accepted untrusted URL: {url}"+ );+ }+ }+}diff --git a/studio/src-tauri/tauri.conf.json b/studio/src-tauri/tauri.conf.jsonindex fad53337bbf..5dde75d1b73 100644--- a/studio/src-tauri/tauri.conf.json+++ b/studio/src-tauri/tauri.conf.json@@ -43,7 +43,7 @@"updater": {"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDFBQzA4RjczODM0RjE1QjcKUldTM0ZVK0RjNC9BR2t4R0RVaFR5cTkyUlRVQ1FwaGV0Nk04eWNwWXBhZnlzalJydllmZm1QTS8K","endpoints": [- "https://github.com/unslothai/unsloth/releases/download/desktop-latest/latest.json"+ "https://github.com/unslothai/unsloth/releases/latest/download/latest.json"],"windows": {"installMode": "passive"diff --git a/tests/python/test_virustotal_scan.py b/tests/python/test_virustotal_scan.pyindex 45ead9e2252..147d9b6cfb9 100644--- a/tests/python/test_virustotal_scan.py+++ b/tests/python/test_virustotal_scan.py@@ -985,15 +985,15 @@ class TestWorkflowOrdering:assert "virustotal" not in (step.get("name") or "").lower()assert "virustotal_scan.py" not in (step.get("run") or "")- def test_release_creation_stays_immediately_before_the_upload(self):- # `gh release create` without `--draft` publishes at once, so the window- # between reserving the tag and uploading the assets is when a release is- # publicly empty. Nothing slow may be inserted between the two; the scan+ def test_nothing_slow_sits_between_validation_and_the_upload(self):+ # The v{version} release already exists and is published, so the window+ # worth minimising is now between validating its state and the assets+ # landing on it. Nothing slow may be inserted between the two; the scan# used to sit there and is why the window existed at all.names = self._publish_steps()- create = names.index("Create versioned release")- assert names.index("Validate versioned release state") < create- assert names[create + 1] == "Publish versioned release assets"+ validate = names.index("Validate versioned release state")+ assert names[validate + 1] == "Generate versioned updater metadata and provenance"+ assert names[validate + 2] == "Publish versioned release assets"def test_release_notes_are_written_unconditionally(self):# Validation writes the notes; metadata and provenance consume that same@@ -1003,27 +1003,27 @@ class TestWorkflowOrdering:metadata = steps["Generate versioned updater metadata and provenance"]["run"]assert "desktop-release-notes.md" in metadata- def test_a_failed_lookup_is_not_treated_as_a_missing_release(self):- # A transient GraphQL/auth failure must stop rather than let the workflow- # conclude the version is unused and overwrite an existing release.+ def test_a_missing_release_stops_the_publish(self):+ # Nothing is created here any more, so an absent release is a dispatch+ # mistake: say how to fix it instead of publishing into thin air.run = self._publish_step_map()["Validate versioned release state"]["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_lookup+ assert "gh release create" not in run+ missing = run.split("does not exist.", 1)[1]+ assert "Tag main and publish it first" in missing+ assert "exit 1" in missing- def test_release_creation_is_gated_on_the_validation_step(self):+ def test_every_public_mutation_is_gated_on_a_real_release(self):yaml = pytest.importorskip("yaml")workflow = REPO_ROOT / ".github" / "workflows" / "release-desktop.yml"data = yaml.safe_load(workflow.read_text(encoding = "utf-8"))steps = data["jobs"]["publish-release"]["steps"]by_name = {step.get("name"): step for step in steps}assert by_name["Validate versioned release state"]["id"] == "versioned_release_state"- assert (- by_name["Create versioned release"]["if"]- == "steps.versioned_release_state.outputs.create == 'true'"- )+ assert "Create versioned release" not in by_name++ # Validation runs on every dispatch; only a non-draft run touches the release.+ for name in ("Publish versioned release assets", "Publish versioned updater metadata"):+ assert by_name[name]["if"] == "${{ !inputs.draft }}"def test_the_scan_step_does_not_swallow_its_own_failure(self):# The advisory posture is a property of the job, not of the step. The job@@ -1108,19 +1108,17 @@ class TestWorkflowOrdering: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.+ def test_the_summary_heading_holds_for_a_validation_only_run_too(self):+ # `inputs.draft` defaults to true, and every uploading step is gated on+ # it, so the ordinary dispatch validates and publishes nothing. A heading+ # calling this a post-publish scan would tell a release operator the+ # opposite of what happened, so the wording has to cover both.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+ upload = self._publish_step_map()["Publish versioned release assets"]+ assert upload["if"] == "${{ !inputs.draft }}"heading = vt.SUMMARY_HEADING.lower()for claim in ("post-publish", "published", "pre-flight"):diff --git a/tests/security/test_desktop_release_resolver.py b/tests/security/test_desktop_release_resolver.pynew file mode 100644index 00000000000..4b5caa94634--- /dev/null+++ b/tests/security/test_desktop_release_resolver.py@@ -0,0 +1,99 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""Contract tests for clean-machine desktop release selection."""++from __future__ import annotations++import importlib.util+from pathlib import Path+++REPO_ROOT = Path(__file__).resolve().parents[2]+SCRIPT = REPO_ROOT / ".github" / "scripts" / "resolve-desktop-release.py"+WORKFLOW = REPO_ROOT / ".github" / "workflows" / "desktop-app-clean-machine-ci.yml"+++def _module():+ spec = importlib.util.spec_from_file_location("desktop_release_resolver", SCRIPT)+ assert spec and spec.loader+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def _release(+ tag: str,+ created: str,+ *assets: str,+ draft: bool = False,+):+ return {+ "tagName": tag,+ "createdAt": created,+ "isDraft": draft,+ "assets": [{"name": name} for name in assets],+ }+++def test_resolver_selects_newest_semver_bundle_including_drafts():+ releases = [+ _release("v0.1.528-beta", "2026-08-10T01:00:00Z", "app.dmg"),+ _release("v0.1.529-beta", "2026-08-11T01:00:00Z", "app.dmg", draft = True),+ _release("v2026.8.11", "2026-08-12T01:00:00Z", "backend.whl"),+ _release("desktop-v0.1.530-beta", "2026-08-13T01:00:00Z", "app.dmg"),+ ]+ assert _module().resolve(releases, ".dmg") == "v0.1.529-beta"+++def test_resolver_requires_the_platform_asset_and_fails_when_absent():+ releases = [+ _release("v0.1.529-beta", "2026-08-11T01:00:00Z", "app.exe"),+ _release("v0.1.528-beta", "2026-08-10T01:00:00Z", "app.AppImage"),+ ]+ resolver = _module().resolve+ assert resolver(releases, ".AppImage") == "v0.1.528-beta"+ assert resolver(releases, ".dmg") is None+++def test_clean_machine_workflow_uses_resolver_but_preserves_explicit_tag():+ workflow = WORKFLOW.read_text(encoding = "utf-8")+ assert workflow.count("python3 .github/scripts/resolve-desktop-release.py") == 3+ assert "'.github/scripts/resolve-desktop-release.py'" in workflow+ assert workflow.count('if [ -z "$REL_TAG" ]; then') == 3+ assert 'startswith("desktop-v")' not in workflow+ for suffix in (".dmg", ".deb", ".AppImage", ".exe"):+ assert suffix in workflow+++def test_the_resolver_stops_at_the_newest_release_holding_the_asset():+ # One lookup per release per matrix leg was the cost, and a transient failure+ # on an irrelevant older release failed the leg. Newest first, stop on match.+ looked_up: list[str] = []+ releases = [+ {"tagName": "v0.1.527-beta", "createdAt": "2026-03-01T00:00:00Z"},+ {"tagName": "v0.1.529-beta", "createdAt": "2026-05-01T00:00:00Z"},+ {"tagName": "v0.1.528-beta", "createdAt": "2026-04-01T00:00:00Z"},+ {"tagName": "not-a-release", "createdAt": "2026-06-01T00:00:00Z"},+ ]++ def fetch(tag):+ looked_up.append(tag)+ return [{"name": f"Unsloth-Desktop-{tag}-MacOS.dmg"}]++ assert _module().resolve_newest(releases, ".dmg", fetch) == "v0.1.529-beta"+ assert looked_up == ["v0.1.529-beta"]+++def test_the_resolver_keeps_looking_past_a_release_without_the_asset():+ looked_up: list[str] = []+ releases = [+ {"tagName": "v0.1.528-beta", "createdAt": "2026-04-01T00:00:00Z"},+ {"tagName": "v0.1.529-beta", "createdAt": "2026-05-01T00:00:00Z"},+ ]++ def fetch(tag):+ looked_up.append(tag)+ return [] if tag == "v0.1.529-beta" else [{"name": "app-MacOS.dmg"}]++ assert _module().resolve_newest(releases, ".dmg", fetch) == "v0.1.528-beta"+ assert looked_up == ["v0.1.529-beta", "v0.1.528-beta"]diff --git a/tests/security/test_desktop_updater_pointer.py b/tests/security/test_desktop_updater_pointer.pynew file mode 100644index 00000000000..b42ecc1bd8f--- /dev/null+++ b/tests/security/test_desktop_updater_pointer.py@@ -0,0 +1,222 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""Discovery must follow desktop metadata, not whichever release is newest.++Clients poll the repo-wide `/releases/latest/download/latest.json`. Publishing a+`v...` release that carries no desktop bundles moves that pointer, so the+publish workflow carries the newest desktop manifest onto it instead.+"""++import json+import os+import subprocess+from pathlib import Path++import yaml+++REPO_ROOT = Path(__file__).resolve().parents[2]+UPDATER_WORKFLOW = REPO_ROOT / ".github" / "workflows" / "publish-desktop-updater.yml"++REPOSITORY = "unslothai/unsloth"+STEP_NAME = "Carry desktop metadata forward"++FAKE_GH = """#!/bin/sh+set -eu+printf 'gh %s\\n' "$*" >> "$COMMAND_LOG"+if [ "$1" = "api" ]; then+ cat "$RELEASES_FIXTURE"+ exit 0+fi+if [ "$1" = "release" ] && [ "$2" = "download" ]; then+ directory=""+ want_directory=0+ for argument in "$@"; do+ if [ "$want_directory" = "1" ]; then directory="$argument"; want_directory=0; continue; fi+ [ "$argument" = "--dir" ] && want_directory=1+ done+ mkdir -p "$directory"+ cp "$MANIFEST_FIXTURE" "$directory/latest.json"+ exit 0+fi+exit 0+"""+++def _step_run():+ job = yaml.safe_load(UPDATER_WORKFLOW.read_text(encoding = "utf-8"))["jobs"]["publish-updater"]+ steps = {step.get("name"): step for step in job["steps"]}+ assert STEP_NAME in steps, sorted(steps)+ step = steps[STEP_NAME]+ # Only for a release that arrived without bundles of its own.+ assert "steps.gate.outputs.proceed == 'false'" in step["if"]+ return step["run"]+++def _release(+ tag,+ *,+ has_manifest = True,+ draft = False,+ prerelease = False,+ published_at = "2026-01-01T00:00:00Z",+):+ return {+ "tag_name": tag,+ "draft": draft,+ "prerelease": prerelease,+ "published_at": published_at,+ "assets": [{"name": "latest.json"}] if has_manifest else [{"name": "notes.txt"}],+ }+++def _manifest(tag):+ base = f"https://github.com/{REPOSITORY}/releases/download/{tag}/"+ return {+ "version": tag,+ "platforms": {+ "darwin-aarch64": {"url": f"{base}app.tar.gz", "signature": "c2ln"},+ "linux-x86_64": {"url": f"{base}app.AppImage", "signature": "c2ln"},+ "windows-x86_64": {"url": f"{base}app.exe", "signature": "c2ln"},+ },+ }+++def _run(tmp_path, *, release_tag, releases, manifest):+ fake_bin = tmp_path / "bin"+ fake_bin.mkdir()+ gh = fake_bin / "gh"+ gh.write_text(FAKE_GH, encoding = "utf-8")+ gh.chmod(0o755)++ releases_fixture = tmp_path / "releases.fixture.json"+ releases_fixture.write_text(json.dumps(releases), encoding = "utf-8")+ manifest_fixture = tmp_path / "manifest.fixture.json"+ manifest_fixture.write_text(json.dumps(manifest), encoding = "utf-8")+ log = tmp_path / "commands.log"+ log.write_text("", encoding = "utf-8")++ env = os.environ.copy()+ env.update(+ {+ "COMMAND_LOG": str(log),+ "GITHUB_REPOSITORY": REPOSITORY,+ "MANIFEST_FIXTURE": str(manifest_fixture),+ "PATH": f"{fake_bin}:{env['PATH']}",+ "RELEASES_FIXTURE": str(releases_fixture),+ "GITHUB_STEP_SUMMARY": str(tmp_path / "step-summary.md"),+ "RELEASE_TAG": release_tag,+ "RUNNER_TEMP": str(tmp_path),+ }+ )+ result = subprocess.run(+ ["bash", "-c", _step_run()],+ cwd = tmp_path,+ env = env,+ text = True,+ capture_output = True,+ check = False,+ )+ return result, log.read_text(encoding = "utf-8").splitlines()+++def test_the_newest_desktop_manifest_is_carried_onto_a_bundleless_release(tmp_path):+ result, commands = _run(+ tmp_path,+ release_tag = "v0.1.53-beta",+ releases = [+ _release("v0.1.52-beta", published_at = "2026-03-01T00:00:00Z"),+ _release("v0.1.51-beta", published_at = "2026-02-01T00:00:00Z"),+ _release("v0.1.53-beta", has_manifest = False, published_at = "2026-04-01T00:00:00Z"),+ ],+ manifest = _manifest("v0.1.52-beta"),+ )+ assert result.returncode == 0, result.stderr+ assert "gh release download v0.1.52-beta" in "\n".join(commands)+ assert any(+ line.startswith("gh release upload v0.1.53-beta") and "--clobber" in line+ for line in commands+ ), commands+ # The manifest is copied byte for byte, so it keeps pointing at its own release.+ carried = json.loads((tmp_path / "carry-forward" / "latest.json").read_text(encoding = "utf-8"))+ assert carried == _manifest("v0.1.52-beta")++ # The 404 gap between publish and this upload is recorded, not silent.+ summary = (tmp_path / "step-summary.md").read_text(encoding = "utf-8")+ assert "v0.1.52-beta manifest" in summary+ assert "404" in summary+++def test_drafts_prereleases_and_bundleless_releases_are_never_the_source(tmp_path):+ result, commands = _run(+ tmp_path,+ release_tag = "v0.1.53-beta",+ releases = [+ _release("v0.1.52-beta", draft = True, published_at = "2026-03-01T00:00:00Z"),+ _release("v0.1.51-beta", prerelease = True, published_at = "2026-02-01T00:00:00Z"),+ _release("v0.1.50-beta", has_manifest = False, published_at = "2026-01-01T00:00:00Z"),+ ],+ manifest = _manifest("v0.1.52-beta"),+ )+ assert result.returncode == 0, result.stderr+ assert "nothing to carry forward" in result.stdout+ assert not [line for line in commands if line.startswith("gh release upload")]+++def test_a_non_semver_release_leaves_the_pointer_alone(tmp_path):+ result, commands = _run(+ tmp_path,+ release_tag = "vnext",+ releases = [_release("v0.1.52-beta")],+ manifest = _manifest("v0.1.52-beta"),+ )+ assert result.returncode == 0, result.stderr+ assert commands == [], commands+++def test_an_already_carried_manifest_is_carried_forward_again(tmp_path):+ # The carried release is now the newest one holding latest.json, and the+ # manifest it holds names an older version on purpose. Forwarding it again is+ # the only thing that keeps the pointer resolving.+ result, commands = _run(+ tmp_path,+ release_tag = "v0.1.54-beta",+ releases = [+ _release("v0.1.53-beta", published_at = "2026-04-01T00:00:00Z"),+ _release("v0.1.52-beta", published_at = "2026-03-01T00:00:00Z"),+ ],+ manifest = _manifest("v0.1.52-beta"),+ )+ assert result.returncode == 0, result.stderr+ assert any(line.startswith("gh release upload v0.1.54-beta") for line in commands), commands+++def test_a_manifest_that_is_not_pinned_to_its_own_version_is_refused(tmp_path):+ result, commands = _run(+ tmp_path,+ release_tag = "v0.1.53-beta",+ releases = [_release("v0.1.52-beta")],+ manifest = {+ "version": "v0.1.52-beta",+ "platforms": {+ "linux-x86_64": {+ "url": f"https://github.com/{REPOSITORY}/releases/latest/download/app.AppImage",+ "signature": "c2ln",+ }+ },+ },+ )+ assert result.returncode == 1+ assert "not pinned to v0.1.52-beta" in result.stderr+ assert not [line for line in commands if line.startswith("gh release upload")]+++def test_a_manifest_without_a_usable_version_is_refused(tmp_path):+ result, _ = _run(+ tmp_path,+ release_tag = "v0.1.53-beta",+ releases = [_release("v0.1.52-beta")],+ manifest = {"version": "latest", "platforms": {}},+ )+ assert result.returncode == 1+ assert "refusing to carry it forward" in result.stderrdiff --git a/tests/security/test_release_desktop_appimage.py b/tests/security/test_release_desktop_appimage.pyindex 262f13f4d46..3b5faba820a 100644--- a/tests/security/test_release_desktop_appimage.py+++ b/tests/security/test_release_desktop_appimage.py@@ -44,8 +44,9 @@ def test_linux_build_repackages_the_deb_and_signs_the_final_appimage():assert '"createUpdaterArtifacts":false' in build["with"]["args"]assert "TAURI_SIGNING_PRIVATE_KEY" not in build.get("env", {})assert "build-thin-appimage.sh" in package["run"]- assert 'tauri signer sign "$appimage" > "$signature"' in package["run"]- assert '[[ ! -s "$signature" ]]' in package["run"]+ assert 'tauri signer sign "$appimage"' in package["run"]+ assert 'tauri signer sign "$appimage" > "$signature"' not in package["run"]+ assert "base64.b64decode(signature_value, validate=True)" in package["run"]assert "f'{appimage}.sig'" in package["run"]assert package["env"]["ARTIFACT_PATHS"] == "${{ steps.build_linux.outputs.artifactPaths }}"assert stage["env"]["ARTIFACT_PATHS"].startswith(diff --git a/tests/security/test_release_desktop_integrity.py b/tests/security/test_release_desktop_integrity.pyindex d1f2c90cb9c..cd1f244133e 100644--- a/tests/security/test_release_desktop_integrity.py+++ b/tests/security/test_release_desktop_integrity.py@@ -2,6 +2,7 @@from __future__ import annotations+import base64import hashlibimport osimport subprocess@@ -13,7 +14,7 @@ import yamlREPO_ROOT = Path(__file__).resolve().parents[2]WORKFLOW = REPO_ROOT / ".github" / "workflows" / "release-desktop.yml"-RELEASE_TAG = "desktop-v0.1.50-beta"+RELEASE_TAG = "v0.1.50-beta"SOURCE_SHA = "1f02275b86f0e0d3a5b1c9f2a4d6e8b0c2a4e6f8"@@ -43,29 +44,47 @@ def _write_fake_gh(path: Path):set -euprintf 'gh %s\\n' "$*" >> "$COMMAND_LOG"if [ "$1" = "api" ]; then+ include=0endpoint=""for argument in "$@"; do- case "$argument" in repos/*) endpoint="$argument" ;; esac+ case "$argument" in+ --include) include=1 ;;+ repos/*) endpoint="$argument" ;;+ esacdonecase "$endpoint" in- */git/ref/tags/*) status="$TAG_HTTP_STATUS" ;;- */releases/tags/*) status="$RELEASE_HTTP_STATUS" ;;+ */commits/*) printf '%s\n' "$SOURCE_COMMIT_SHA"; exit 0 ;;+ */releases/tags/*) status="$TARGET_HTTP_STATUS" ;;*) exit 0 ;;esac- printf 'HTTP/2.0 %s Test Response\n' "$status"- if [ "$status" = "200" ]; then exit 0; fi+ if [ "$include" = "1" ]; then+ printf 'HTTP/2.0 %s Test Response\n' "$status"+ fi+ if [ "$status" = "200" ]; then+ if [ "$TARGET_HAS_DESKTOP_ASSETS" = "1" ]; then+ printf '{"tag_name":"%s","draft":false,"assets":[{"name":"latest.json"}]}\n' "$DESKTOP_RELEASE_TAG"+ else+ printf '{"tag_name":"%s","draft":false,"assets":[]}\n' "$DESKTOP_RELEASE_TAG"+ fi+ exit 0+ fiexit 1fi-if [ "$1" = "release" ] && [ "$2" = "list" ]; then- if [ "$RELEASE_HTTP_STATUS" = "500" ]; then- printf 'GraphQL test failure\n' >&2++if [ "$1" = "release" ] && [ "$2" = "download" ]; then+ if [ "$TARGET_HAS_DESKTOP_ASSETS" != "1" ]; then+ echo "release not found" >&2exit 1fi- if [ "$RELEASE_HTTP_STATUS" = "200" ]; then- printf '[{"tagName":"%s"}]\n' "$DESKTOP_RELEASE_TAG"- else- printf '[]\n'- fi+ directory=""+ want_directory=0+ for argument in "$@"; do+ if [ "$want_directory" = "1" ]; then directory="$argument"; want_directory=0; continue; fi+ [ "$argument" = "--dir" ] && want_directory=1+ done+ [ -n "$directory" ] || directory="."+ mkdir -p "$directory"+ printf '{"version":"%s","platforms":{}}\n' "$TARGET_MANIFEST_VERSION" > "$directory/latest.json"exit 0fi@@ -82,8 +101,9 @@ def _run_step(name: str,tmp_path: Path,*,- tag_http_status: int = 404,- release_http_status: int = 404,+ target_http_status: int = 200,+ target_has_desktop_assets: bool = False,+ target_manifest_version: str = RELEASE_TAG,extra_env: dict[str, str] | None = None,):fake_bin = tmp_path / "bin"@@ -101,9 +121,12 @@ def _run_step("GITHUB_OUTPUT": str(tmp_path / "github-output"),"GH_TOKEN": "masked-token","PATH": f"{fake_bin}:{env['PATH']}",- "RELEASE_HTTP_STATUS": str(release_http_status),+ "ASSET_VERSION": "0_1_50_beta","RUNNER_TEMP": str(tmp_path),- "TAG_HTTP_STATUS": str(tag_http_status),+ "SOURCE_COMMIT_SHA": SOURCE_SHA,+ "TARGET_HAS_DESKTOP_ASSETS": "1" if target_has_desktop_assets else "0",+ "TARGET_HTTP_STATUS": str(target_http_status),+ "TARGET_MANIFEST_VERSION": target_manifest_version,})env.update(extra_env or {})@@ -122,16 +145,22 @@ 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)+ signature = base64.b64encode(+ b"untrusted comment: signature from tauri secret key\n"+ b"test signature bytes\n"+ b"trusted comment: timestamp:1\tfile:test\n"+ b"test global signature bytes\n"+ )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-ARM64.app.tar.gz.sig", 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-Linux.AppImage.sig", signature),("Unsloth-Desktop-0_1_50_beta-Windows.exe", b"installer"),- ("Unsloth-Desktop-0_1_50_beta-Windows.exe.sig", b"windows signature"),+ ("Unsloth-Desktop-0_1_50_beta-Windows.exe.sig", signature),):(asset_dir / name).write_bytes(payload)if not name.endswith(".sig"):@@ -139,10 +168,19 @@ def _stage_assets(tmp_path: Path) -> dict[str, str]:return digests-def _run_create_release(workflow, tmp_path: Path, **kwargs):+def _run_create_release(+ workflow,+ tmp_path: Path,+ *,+ invalid_signature = False,+ **kwargs,+):_stage_assets(tmp_path)+ if invalid_signature:+ (+ tmp_path / "desktop-release-assets" / "Unsloth-Desktop-0_1_50_beta-Linux.AppImage.sig"+ ).write_text("Tauri signer diagnostic, not a signature\n", encoding = "utf-8")env = {- "DESKTOP_PRERELEASE": "true","DESKTOP_RELEASE_NOTES": workflow["env"]["DESKTOP_RELEASE_NOTES"],"APP_VERSION": "0.1.50","GITHUB_SHA": SOURCE_SHA,@@ -158,14 +196,21 @@ def _run_create_release(workflow, tmp_path: Path, **kwargs):names = ("Validate versioned release state","Generate versioned updater metadata and provenance",- "Create versioned release",+ "Record desktop build provenance on the release",+ )+ create_step = _step(+ workflow, "publish-release", "Record desktop build provenance on the 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+ workflow,+ "publish-release",+ "Record desktop build provenance on the release",+ tmp_path,+ extra_env = env,+ **kwargs,)@@ -189,8 +234,8 @@ def test_a_used_version_fails_the_guard_before_any_build_work(tmp_path):assert workflow["jobs"]["build"]["needs"] == "prepare-version"for case, expected in (- ({"tag_http_status": 200}, 1),- ({"release_http_status": 200}, 1),+ ({"target_has_desktop_assets": True}, 1),+ ({"target_http_status": 404}, 1),({}, 0),):case_dir = tmp_path / ("-".join(case) or "unused-version")@@ -205,12 +250,33 @@ def test_a_used_version_fails_the_guard_before_any_build_work(tmp_path):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_missing_target_release_says_how_to_create_it(tmp_path):+ workflow = _workflow()+ result, _ = _run_step(+ workflow,+ "prepare-version",+ "Guard against republishing an existing version",+ tmp_path,+ target_http_status = 404,+ )+ assert result.returncode == 1+ assert f"Release {RELEASE_TAG} does not exist." in result.stderr+ assert "Tag main and publish it first" in result.stderr+++def test_existing_desktop_assets_name_the_cleanup_command(tmp_path):+ workflow = _workflow()+ result, _ = _run_step(+ workflow,+ "prepare-version",+ "Guard against republishing an existing version",+ tmp_path,+ target_has_desktop_assets = True,+ )+ assert result.returncode == 1+ assert f"gh release delete-asset {RELEASE_TAG} latest.json --yes" in result.stderrdef test_a_failed_guard_probe_fails_closed_before_any_build_work(tmp_path):@@ -220,42 +286,34 @@ def test_a_failed_guard_probe_fails_closed_before_any_build_work(tmp_path):"prepare-version","Guard against republishing an existing version",tmp_path,- tag_http_status = 500,+ target_http_status = 500,)assert result.returncode == 1- assert "Could not verify that tag" in result.stderr+ assert "Could not read release" in result.stderrdef 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")]+ result, commands = _run_create_release(workflow, tmp_path, target_has_desktop_assets = True)+ assert result.returncode == 1+ assert "Refusing to republish" in result.stderr+ assert f"gh release delete-asset {RELEASE_TAG} latest.json --yes" 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):+def test_publish_fails_closed_when_the_target_release_is_missing(tmp_path):workflow = _workflow()- result, commands = _run_create_release(workflow, tmp_path, tag_http_status = 500)+ result, commands = _run_create_release(workflow, tmp_path, target_http_status = 404)assert result.returncode == 1- assert "Could not verify that tag" in result.stderr+ assert f"Release {RELEASE_TAG} does not exist." in result.stderrassert not [line for line in commands if line.startswith("gh release create")]-def test_publish_fails_closed_when_draft_listing_errors(tmp_path):+def test_publish_rejects_signer_diagnostics_as_updater_signatures(tmp_path):workflow = _workflow()- result, commands = _run_create_release(workflow, tmp_path, release_http_status = 500)+ result, commands = _run_create_release(workflow, tmp_path, invalid_signature = True)assert result.returncode == 1- assert "Could not list releases, including drafts" in result.stderr+ assert "Invalid base64 updater signature" in result.stderrassert not [line for line in commands if line.startswith("gh release create")]@@ -265,40 +323,144 @@ def test_release_body_records_provenance_the_updater_notes_do_not_carry(tmp_pathresult, 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)+ # The release already exists, so nothing is created and no tag is reserved.+ assert not [line for line in commands if line.startswith("gh release create")]+ assert not [line for line in commands if "git/refs" in line]+ assert any(line.startswith("gh release edit") for line in commands)body_file = tmp_path / "desktop-release-body.md"- assert f"--notes-file {body_file}" in createbody = body_file.read_text(encoding = "utf-8")assert SOURCE_SHA in bodyfor name, digest in digests.items():assert f"{digest} {name}" in bodylatest = tmp_path / "latest.json"+ metadata = yaml.safe_load(latest.read_text(encoding = "utf-8"))+ for platform in metadata["platforms"].values():+ decoded = base64.b64decode(platform["signature"], validate = True)+ assert decoded.startswith(b"untrusted comment:")+ assert b"\ntrusted comment:" in decodedassert latest.is_file()assert f"{hashlib.sha256(latest.read_bytes()).hexdigest()} latest.json" in bodyassert ".sig" not in body- # Keep digests out of updater notes.+ # Keep digests out of updater notes, and out of the changelog we append to.notes = (tmp_path / "desktop-release-notes.md").read_text(encoding = "utf-8")assert "Build provenance" not in notesassert "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"]+ assert "Desktop app for Unsloth." not in body-def test_versioned_uploads_never_clobber_but_the_channel_pointer_does():+def test_versioned_uploads_never_clobber_or_mutate_the_legacy_channel():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+ assert channel == [], uploads+ # latest.json is the moving updater pointer and may already hold a carried+ # forward manifest, so only it may be replaced. Bundles stay immutable.for line in versioned:- assert "--clobber" not in line, line- # The channel pointer is intentionally mutable.- assert "--clobber" in channel[0]+ if "latest.json" not in line:+ assert "--clobber" not in line, line+++def test_a_carried_forward_manifest_does_not_block_the_guard(tmp_path):+ workflow = _workflow()+ result, _ = _run_step(+ workflow,+ "prepare-version",+ "Guard against republishing an existing version",+ tmp_path,+ target_has_desktop_assets = True,+ target_manifest_version = "v0.1.49-beta",+ )+ assert result.returncode == 0, result.stderr+++def test_a_validation_only_run_touches_nothing_public():+ steps = _workflow()["jobs"]["publish-release"]["steps"]+ names = [step.get("name") for step in steps]+ mutating = (+ "Publish versioned release assets",+ "Publish versioned updater metadata",+ "Record desktop build provenance on the release",+ "Promote normal release to GitHub latest",+ )+ for name in mutating:+ step = steps[names.index(name)]+ assert step.get("if") == "${{ !inputs.draft }}", name++ # Provenance last, so a retry after a partial upload records what shipped.+ for upload in mutating[:2]:+ assert names.index(upload) < names.index(mutating[2])+++def test_the_guard_rejects_a_prerelease_target_before_anything_is_built():+ workflow = _workflow()+ guard = _step(workflow, "prepare-version", "Guard against republishing an existing version")+ assert "is a prerelease" in guard["run"]+ # And again in publish-release, which is the one holding write scope.+ state = _step(workflow, "publish-release", "Validate versioned release state")+ assert "is a prerelease" in state["run"]+++def test_the_build_uses_the_release_tag_not_the_dispatch_ref():+ build = _workflow()["jobs"]["build"]["steps"]+ checkout = next(s for s in build if "actions/checkout" in str(s.get("uses", "")))+ assert checkout["with"]["ref"] == "${{ needs.prepare-version.outputs.desktop_release_tag }}"+++def test_the_tag_is_validated_before_it_is_checked_out(tmp_path):+ # actions/checkout resolves the free-text input, so a malformed tag would fail+ # on a generic missing-ref error and none of the corrections would be printed.+ steps = _workflow()["jobs"]["prepare-version"]["steps"]+ names = [step.get("name") or str(step.get("uses")) for step in steps]+ checkout = next(+ i for i, step in enumerate(steps) if "actions/checkout" in str(step.get("uses", ""))+ )+ assert names.index("Validate release versions") < checkout, names+ # And the checkout uses the validated value, not the raw input.+ assert steps[checkout]["with"]["ref"] == "${{ steps.prepare.outputs.studio_version }}"++ for index, (bad, expected) in enumerate(+ (+ ("v.0.1.52-beta", "did you mean v0.1.52-beta?"),+ ("0.1.52-beta", "must start with v"),+ ("2026.8.3", "not a date-style backend version"),+ )+ ):+ case_dir = tmp_path / f"case-{index}"+ case_dir.mkdir()+ result, _ = _run_step(+ _workflow(),+ "prepare-version",+ "Validate release versions",+ case_dir,+ extra_env = {"INPUT_STUDIO_VERSION": bad},+ )+ assert result.returncode == 1, bad+ assert expected in result.stderr, (bad, result.stderr)+++def test_the_promotion_guard_orders_numbered_prereleases_by_number():+ guard = _step(_workflow(), "publish-release", "Promote normal release to GitHub latest")["run"]+ body = guard.split('python3 - "$latest_before"', 1)[1].split("\nPY", 1)[0]+ body = "\n".join(line[10:] if line.startswith(" " * 10) else line for line in body.split("\n"))+ body = body.split("\n", 1)[1].lstrip("\n")+ namespace: dict = {}+ exec(body.split("current = json.loads", 1)[0], namespace)+ key = namespace["key"]+ # v1.2.3-beta10 is newer than v1.2.3-beta2, and a release beats its prerelease.+ assert key("v1.2.3-beta10") > key("v1.2.3-beta2")+ assert key("v1.2.3") > key("v1.2.3-beta10")+ assert key("v0.1.527-beta") > key("v0.1.526-beta")+ assert key("not-a-tag") is None+++def test_the_promotion_guard_fails_closed_on_a_failed_latest_lookup():+ guard = _step(_workflow(), "publish-release", "Promote normal release to GitHub latest")["run"]+ # A 404 means no latest yet; anything else must stop before the PATCH.+ fallback = guard.split("elif grep -Fq '(HTTP 404)'", 1)[1].split("gh api --method PATCH", 1)[0]+ assert "refusing to promote" in fallback.lower()+ assert "exit 1" in fallback+ assert "2>/dev/null" not in guard.split("releases/latest", 1)[1].split("\n", 1)[0]diff --git a/tests/security/test_release_desktop_permissions.py b/tests/security/test_release_desktop_permissions.pyindex b6aba5d4f05..23be5bfb29a 100644--- a/tests/security/test_release_desktop_permissions.py+++ b/tests/security/test_release_desktop_permissions.py@@ -128,7 +128,9 @@ def test_build_matrix_hands_off_assets_without_release_credentials():assert re.search(r"^\s*break\b", loop_body, re.MULTILINE), wait_runnames = [step.get("name") for step in publish["steps"]]- assert names.index("Wait for the build matrix") < names.index("Create versioned release")+ assert names.index("Wait for the build matrix") < names.index(+ "Record desktop build provenance on the 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(@@ -138,19 +140,22 @@ def test_build_matrix_hands_off_assets_without_release_credentials():)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.+ # The guard refuses a release that already carries desktop assets, so a+ # version is never published twice.release_step = next(step for step in publish["steps"] if step.get("name") == "Validate versioned release state")- assert "gh release list" in release_step["run"]- assert "resource_exists" in release_step["run"]+ assert 'gh api "repos/${GH_REPO}/releases/tags/${DESKTOP_RELEASE_TAG}"' in release_step["run"]+ assert "already carries desktop assets" in release_step["run"]- create_step = next(- step for step in publish["steps"] if step.get("name") == "Create versioned release"+ # The release is the maintainer's, so provenance is appended, never created.+ provenance = next(+ step+ for step in publish["steps"]+ if step.get("name") == "Record desktop build provenance on the release")- assert "gh release create" in create_step["run"]- assert create_step["if"] == "steps.versioned_release_state.outputs.create == 'true'"+ assert "gh release edit" in provenance["run"]+ assert not any("gh release create" in step.get("run", "") for step in publish["steps"])def test_post_publish_scan_job_holds_no_release_credentials():@@ -194,28 +199,85 @@ def test_versioned_release_hides_updater_signature_assets():assert "--clobber" not in publish["run"]-def test_publishing_draft_advances_updater_without_rebuilding():+def test_publishing_draft_validates_normal_release_without_rebuilding():workflow = yaml.safe_load(UPDATER_WORKFLOW.read_text(encoding = "utf-8"))- assert workflow.get("on", workflow.get(True)) == {"release": {"types": ["published"]}}+ triggers = workflow.get("on", workflow.get(True))+ assert triggers["release"] == {"types": ["published"]}+ assert "workflow_dispatch" in triggersassert workflow["permissions"] == {"contents": "read"}assert workflow["concurrency"]["queue"] == "max"job = workflow["jobs"]["publish-updater"]assert "build" not in workflow["jobs"]assert job["permissions"] == {"contents": "write"}- assert "startsWith(github.event.release.tag_name, 'desktop-v')" in job["if"]+ assert "startsWith(github.event.release.tag_name, 'v')" in job["if"]+ # The job runs for a mistakenly flagged prerelease so validation fails visibly.+ assert "github.event.release.prerelease" not in job["if"]assert not any("actions/checkout" in step.get("uses", "") for step in job["steps"])- assert any("desktop-latest" in step.get("run", "") for step in job["steps"])assert any("gh release delete-asset" in step.get("run", "") for step in job["steps"])- download = next(- step for step in job["steps"] if step.get("name") == "Download updater metadata"- )- assert "HTTP 404" in download["run"]- assert "desktop-current" not in download["run"] or "|| true" not in download["run"]-validate = next(step for step in job["steps"] if step.get("name") == "Validate updater metadata")assert "source-release.json" in validate["run"]assert "bundle_name not in release_assets" in validate["run"]+ assert "source.get('prerelease')" in validate["run"]+ assert "'/releases/latest/'" in validate["run"]++ downgrade = next(+ step for step in job["steps"] if step.get("name") == "Prevent GitHub latest downgrade"+ )+ assert "Refusing to replace GitHub latest" in downgrade["run"]+ assert "releases/latest" in downgrade["run"]++ promote = next(+ step+ for step in job["steps"]+ if step.get("name") == "Mark published release as GitHub latest"+ )+ # The API documents make_latest as a string, so -f, not -F.+ assert "-f make_latest=true" in promote["run"]+ assert "releases/latest" in promote["run"]++ bridge = next(+ step+ for step in job["steps"]+ if step.get("name") == "Bridge legacy desktop-latest clients once"+ )+ assert "workflow_dispatch" in bridge["if"]+ assert "inputs.bridge_legacy_channel" in bridge["if"]+ assert "gh release create desktop-latest" not in bridge["run"]+ assert "gh release upload desktop-latest" in bridge["run"]+ assert "--clobber" in bridge["run"]++ assert "Refusing to move desktop-latest" in bridge["run"]+ assert 'releases/latest" --jq .tag_name' in bridge["run"]++ ordinary_steps = [+ step+ for step in job["steps"]+ if step.get("name") != "Bridge legacy desktop-latest clients once"+ ]+ assert not any(+ "gh release upload desktop-latest" in step.get("run", "") for step in ordinary_steps+ )+++def test_the_updater_workflow_skips_releases_without_desktop_bundles():+ job = yaml.safe_load(UPDATER_WORKFLOW.read_text(encoding = "utf-8"))["jobs"]["publish-updater"]+ steps = {step.get("name"): step for step in job["steps"]}+ gate = steps["Check for desktop bundles"]+ assert gate["id"] == "gate"+ # An unreadable release must not look like one that simply has no bundles.+ assert "refusing to advance the channel" in gate["run"]++ for name in (+ "Download updater metadata",+ "Validate updater metadata",+ "Remove standalone signature assets",+ "Mark published release as GitHub latest",+ ):+ assert "steps.gate.outputs.proceed == 'true'" in steps[name]["if"], name++ # The v... release is shared, so the sweep must not reach past desktop assets.+ assert 'startswith("Unsloth-Desktop-")' in steps["Remove standalone signature assets"]["run"]diff --git a/tests/studio/test_tauri_branding_contract.py b/tests/studio/test_tauri_branding_contract.pyindex bfda9a41302..27ebded6d53 100644--- a/tests/studio/test_tauri_branding_contract.py+++ b/tests/studio/test_tauri_branding_contract.py@@ -57,7 +57,7 @@ def test_desktop_display_name_and_compatibility_ids() -> None:assert config["identifier"] == "ai.unsloth.studio"assert config["plugins"]["deep-link"]["desktop"]["schemes"] == ["unsloth"]assert config["plugins"]["updater"]["endpoints"] == [- "https://github.com/unslothai/unsloth/releases/download/desktop-latest/latest.json"+ "https://github.com/unslothai/unsloth/releases/latest/download/latest.json"]assert 'name = "unsloth-studio"' in read(TAURI / "Cargo.toml")@@ -211,5 +211,4 @@ def test_desktop_surfaces_do_not_restore_studio_branding() -> None:workflow = read(REPO / ".github/workflows/release-desktop.yml")assert "Desktop app for Unsloth." in workflow- assert '--title "Unsloth ${STUDIO_VERSION}"' in workflow- assert '--title "Unsloth Desktop updater channel"' in workflow+ assert '--title "Unsloth Desktop updater channel"' not in workflow