Repository navigation
2073 lines (1900 loc) · 95.5 KB
/
Copy pathrelease-desktop.yml
File metadata and controls
2073 lines (1900 loc) · 95.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
name: Release Desktop App
on:
workflow_dispatch:
# studio_version alone decides the release tag (e.g. v0.1.52-beta); pypi_version has no v
# (e.g. 2026.8.3). Keep these examples in sync with the validation step's error messages.
inputs:
studio_version:
description: 'Unsloth SemVer tag to release, leading v with no dot after it (for example, v0.1.52-beta)'
type: string
required: true
pypi_version:
description: 'Exact PyPI unsloth version just published/stamped, no leading v (for example, 2026.8.3); leave blank to use MIN_DESKTOP_BACKEND_VERSION'
type: string
required: false
draft:
description: 'Build and validate only; nothing is uploaded to the v... release and GitHub latest is left untouched'
type: boolean
default: true
permissions:
contents: read
env:
DESKTOP_RELEASE_NOTES: |
Desktop app for Unsloth.
**macOS**: Download `Unsloth-Desktop-MacOS.dmg` (Apple Silicon).
**Windows**: Download `Unsloth-Desktop-Windows.exe`, or `Unsloth-Desktop-Windows-ARM64.exe` on a Windows on ARM machine.
**Linux x64**: Download `Unsloth-Desktop-Ubuntu.deb` for Ubuntu/Debian. `.AppImage` is experimental.
**Linux ARM64**: Download `Unsloth-Desktop-Ubuntu-ARM64.deb` for Ubuntu 24.04 or newer on aarch64, such as a DGX Spark. `Unsloth-Desktop-ARM64.app.tar.gz` is macOS-only.
> Linux in-app updates cover `.deb` and AppImage installs. A `.deb` installed before in-app updates shipped needs one manual update first.
> Linux AppImage can show a blank window on some Tauri/WebKitGTK + Wayland/Mesa stacks; use `.deb` when available.
> Linux AppImage on Ubuntu 24.04+ may require: `sudo apt install libfuse2t64`
> First-run system dependency elevation is supported on Ubuntu/Debian. Other Linux distributions should install system packages manually.
concurrency:
group: release-desktop-${{ github.repository }}
cancel-in-progress: false
# queue: max, or a second dispatch or publish silently cancels a pending release.
queue: max
jobs:
prepare-version:
name: Prepare release versions
runs-on: ubuntu-latest
timeout-minutes: 15
outputs:
studio_version: ${{ steps.prepare.outputs.studio_version }}
app_version: ${{ steps.prepare.outputs.app_version }}
desktop_release_tag: ${{ steps.prepare.outputs.desktop_release_tag }}
pypi_version: ${{ steps.backend.outputs.pypi_version }}
steps:
# Before checkout, which would fail with a generic error on a malformed version.
- name: Validate release versions
id: prepare
shell: bash
env:
INPUT_STUDIO_VERSION: ${{ inputs.studio_version }}
GH_TOKEN: ${{ github.token }}
run: |
python3 <<'PY'
import json
import os
import pathlib
import re
import sys
import urllib.request
RELEASES_API_URL = (
'https://api.github.com/repos/unslothai/unsloth/releases?per_page=30'
)
studio_version = os.environ['INPUT_STUDIO_VERSION'].strip()
if not studio_version:
sys.exit('studio_version is required, for example v0.1.52-beta')
if re.fullmatch(r'v?20\d{2}\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?', studio_version):
sys.exit(f'studio_version must be an Unsloth SemVer tag, not a date-style backend version: {studio_version}')
# Name the single wrong character for the near-miss shapes. The generic
# SemVer error below is easy to skim past when everything except one
# separator looks correct, so spell out the correction instead.
separator_after_v = re.fullmatch(r'v[._\-](\d[0-9A-Za-z.\-+]*)', studio_version)
if separator_after_v:
suggestion = f'v{separator_after_v.group(1)}'
sys.exit(
'studio_version must not have a separator after the leading v: '
f'{studio_version} (did you mean {suggestion}?)'
)
semver_tag = re.compile(
r'^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)'
r'(?:-[0-9A-Za-z.][0-9A-Za-z.-]*)?$'
)
if semver_tag.fullmatch(f'v{studio_version}'):
sys.exit(f'studio_version must start with v, for example v{studio_version}')
if not semver_tag.fullmatch(studio_version):
sys.exit(f'studio_version must be a SemVer tag with leading v, for example v0.1.52-beta: {studio_version}')
app_version = studio_version.removeprefix('v')
desktop_release_tag = studio_version
# Both updater paths compare SemVer, so a tag whose numbers go backwards
# strands its own clients: 60 < 527, so v0.1.60-beta offered no one.
def semver_key(version):
# Full precedence, not just the triple: v0.1.528 and v0.1.528-rc
# both beat v0.1.528-beta, and the updater knows it.
version = version.strip().removeprefix('v')
match = semver_tag.fullmatch(f'v{version}')
if not match:
return None
release = tuple(int(part) for part in match.groups())
pre = version.partition('-')[2]
if not pre:
return release, (1,) # a release outranks its own prereleases
# SemVer: numeric identifiers sort below alphanumeric, as numbers.
return release, (0, *(
(0, int(part), '') if part.isdigit() else (1, 0, part)
for part in pre.split('.')
))
def fetch(url):
headers = {'Accept': 'application/vnd.github+json'}
token = os.environ.get('GH_TOKEN', '')
if token:
headers['Authorization'] = f'Bearer {token}'
with urllib.request.urlopen(
urllib.request.Request(url, headers = headers), timeout = 30
) as response:
return json.loads(response.read())
def published_desktop_version():
# Not /releases/latest: an llama.cpp prebuilt can hold that slot
# and ships no manifest, so the read would 404 and skip this check.
studio = [
release for release in fetch(RELEASES_API_URL)
if not release['draft'] and semver_tag.fullmatch(release['tag_name'])
]
studio.sort(key = lambda release: release['published_at'], reverse = True)
for release in studio:
for asset in release['assets']:
if asset['name'] == 'latest.json':
return fetch(asset['browser_download_url']).get('version', '')
return ''
try:
published = published_desktop_version()
except (OSError, ValueError, KeyError) as error:
# An unreachable manifest is not a bad tag, and the first has none.
print(f'::warning::could not read the published desktop version: {error}')
published = ''
published_key = semver_key(published)
if published_key and published_key >= semver_key(app_version):
sys.exit(
f'studio_version {studio_version} is not newer than the published '
f'v{published}, so clients on it would never be offered this release'
)
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'desktop_release_tag={desktop_release_tag}', file=output)
PY
# Check out the tag, not the dispatch ref, which may have 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 sys
def parse_backend_version(version):
match = re.fullmatch(
r'(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)'
r'(?:([a-zA-Z]|\.dev|dev|\.rc|rc|\.post|post)(\d*))?'
r'(?:[-+]([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?',
version,
)
if not match:
return None
major, minor, patch, suffix_name, suffix_number, suffix_text = match.groups()
if suffix_name:
normalized = suffix_name.lower().lstrip('.')
order = {'dev': 0, 'a': 1, 'b': 2, 'rc': 3, 'post': 5}.get(normalized)
if order is None:
return None
number = int(suffix_number or '0')
elif suffix_text:
order = 3 if version[version.find(suffix_text) - 1] == '-' else 4
number = 0
else:
order = 4
number = 0
return (int(major), int(minor), int(patch), order, number)
preflight = pathlib.Path('studio/src-tauri/src/preflight/version.rs').read_text()
match = re.search(r'MIN_DESKTOP_BACKEND_VERSION:\s*&str\s*=\s*"([^"]+)"', preflight)
if not match:
sys.exit('Could not read MIN_DESKTOP_BACKEND_VERSION')
min_backend_version = match.group(1)
input_pypi_version = os.environ.get('INPUT_PYPI_VERSION', '').strip()
parsed_min_backend = parse_backend_version(min_backend_version)
if parsed_min_backend is None:
sys.exit(f'MIN_DESKTOP_BACKEND_VERSION is not a supported backend package version: {min_backend_version}')
pypi_version = input_pypi_version or min_backend_version
parsed_pypi = parse_backend_version(pypi_version)
if parsed_pypi is None:
sys.exit(f'pypi_version is not a supported backend package version: {pypi_version}')
if parsed_pypi < parsed_min_backend:
sys.exit(
f'pypi_version {pypi_version} is lower than desktop minimum '
f'MIN_DESKTOP_BACKEND_VERSION {min_backend_version}'
)
if input_pypi_version:
print(
'Using exact PyPI unsloth version from pypi_version input: '
f'{pypi_version} (desktop minimum: {min_backend_version})'
)
else:
print(
'Using exact PyPI unsloth version from MIN_DESKTOP_BACKEND_VERSION: '
f'{pypi_version}'
)
with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as output:
print(f'pypi_version={pypi_version}', file=output)
PY
# Fail before building and notarizing a version publish-release will reject.
- name: Guard against republishing an existing version
shell: bash
env:
GH_REPO: ${{ github.repository }}
GH_TOKEN: ${{ github.token }}
DESKTOP_RELEASE_TAG: ${{ steps.prepare.outputs.desktop_release_tag }}
run: |
set -euo pipefail
# The v 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)"; then
if [[ "$response" =~ ^HTTP/[0-9.]+\ 404\ ]]; then
echo "Release ${DESKTOP_RELEASE_TAG} does not exist." >&2
echo " Tag main and publish it first, then re-dispatch this workflow." >&2
exit 1
fi
echo "Could not read release ${DESKTOP_RELEASE_TAG}; refusing to publish." >&2
printf '%s\n' "$response" >&2
exit 1
fi
gh api "repos/${GH_REPO}/releases/tags/${DESKTOP_RELEASE_TAG}" > "$RUNNER_TEMP/target-release.json"
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 = 'Unsloth-Desktop-'
clashing = sorted(
asset['name']
for asset in release.get('assets', [])
if str(asset.get('name', '')).startswith(prefix)
or asset.get('name') == '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)
if 'latest.json' in clashing:
# Deleting a manifest off whichever release is currently GitHub
# latest 404s every update check until this workflow finishes.
print(
' latest.json is the live updater manifest: only delete it once '
f'{tag} is not the GitHub latest release.',
file=sys.stderr,
)
sys.exit(1)
PY
- name: Verify PyPI package and Unsloth stamp
shell: bash
env:
STUDIO_VERSION: ${{ steps.prepare.outputs.studio_version }}
PYPI_VERSION: ${{ steps.prepare.outputs.pypi_version }}
run: |
set -euo pipefail
python3 <<'PY'
import json
import os
import pathlib
import sys
import time
import urllib.error
import urllib.request
pypi_version = os.environ['PYPI_VERSION']
dist_dir = pathlib.Path(os.environ['RUNNER_TEMP'], 'pypi-unsloth-dist')
dist_dir.mkdir(parents=True, exist_ok=True)
metadata_url = f'https://pypi.org/pypi/unsloth/{pypi_version}/json'
last_error = None
for attempt in range(1, 6):
try:
with urllib.request.urlopen(metadata_url, timeout=30) as response:
metadata = json.load(response)
break
except Exception as exc:
last_error = exc
if attempt < 5:
time.sleep(10 * attempt)
else:
sys.exit(f'Publish unsloth=={pypi_version} to PyPI before the desktop release ({last_error})')
files = metadata.get('urls') or []
if not files:
sys.exit(f'PyPI returned no distribution files for unsloth=={pypi_version}')
for file_info in files:
filename = file_info.get('filename')
url = file_info.get('url')
if not filename or '/' in filename or not url:
sys.exit(f'Unexpected PyPI file entry for unsloth=={pypi_version}: {file_info!r}')
target = dist_dir / filename
for attempt in range(1, 4):
try:
with urllib.request.urlopen(url, timeout=60) as response:
target.write_bytes(response.read())
break
except Exception as exc:
last_error = exc
if attempt < 3:
time.sleep(5 * attempt)
else:
sys.exit(f'Could not download {filename} from PyPI ({last_error})')
PY
if [ "$GITHUB_REPOSITORY" = "wasimysaid/unsloth" ]; then
echo "Fork-only updater A/B build: skipping the upstream PyPI-to-Unsloth release stamp check."
elif [ -f scripts/stamp_studio_release.py ]; then
mapfile -t dists < <(find "$RUNNER_TEMP/pypi-unsloth-dist" -type f \( -name '*.whl' -o -name '*.tar.gz' \) | sort)
if [ "${#dists[@]}" -eq 0 ]; then
echo "No PyPI wheel/sdist artifacts downloaded for unsloth==$PYPI_VERSION" >&2
exit 1
fi
python3 scripts/stamp_studio_release.py --verify-dist "$RUNNER_TEMP/pypi-unsloth-dist" --expected "$STUDIO_VERSION"
else
echo "scripts/stamp_studio_release.py not found; release-desktop requires #5308 to verify the PyPI Unsloth stamp." >&2
exit 1
fi
- name: Guard GitHub latest release version
if: ${{ !inputs.draft }}
shell: bash
env:
GH_REPO: ${{ github.repository }}
GH_TOKEN: ${{ github.token }}
APP_VERSION: ${{ steps.prepare.outputs.app_version }}
run: |
set -euo pipefail
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 1
fi
python3 - "$current_file" <<'PY'
import json
import os
import pathlib
import re
import 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'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 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
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 = 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 compare(next_version, current_tag) < 0:
sys.exit(f'Refusing to publish {next_version}; GitHub latest is newer: {current_tag}.')
PY
build:
strategy:
fail-fast: false
matrix:
include:
- platform: macos-latest
args: '--target aarch64-apple-darwin'
label: macOS (Apple Silicon)
artifact: macos-aarch64
# - platform: macos-latest
# args: '--target x86_64-apple-darwin'
# label: macOS (Intel)
- platform: ubuntu-22.04
args: ''
label: Linux (x64)
artifact: linux-x64
- platform: ubuntu-24.04-arm
args: ''
label: Linux (ARM64)
artifact: linux-arm64
- platform: windows-latest
args: ''
label: Windows (x64)
artifact: windows-x64
# Windows ARM64 is cross-compiled from x64; NSIS (not WiX) supports ARM64.
- platform: windows-latest
args: '--target aarch64-pc-windows-msvc'
label: Windows (ARM64)
artifact: windows-arm64
name: Build ${{ matrix.label }}
needs: prepare-version
runs-on: ${{ matrix.platform }}
# All signing secrets are read only by this job; the environment makes them gateable once
# required reviewers are configured in repo settings.
environment: release-signing
timeout-minutes: 60
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
APP_VERSION: ${{ needs.prepare-version.outputs.app_version }}
STUDIO_VERSION: ${{ needs.prepare-version.outputs.studio_version }}
DESKTOP_RELEASE_TAG: ${{ needs.prepare-version.outputs.desktop_release_tag }}
# Without it a shared venv left by the CLI installer is never upgraded.
UNSLOTH_DESKTOP_BACKEND_VERSION: ${{ needs.prepare-version.outputs.pypi_version }}
steps:
- name: Harden runner (audit)
uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3
with:
egress-policy: audit
# The tag, not the dispatch ref: main keeps moving after the release is published.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ needs.prepare-version.outputs.desktop_release_tag }}
persist-credentials: false
# ── Linux dependencies ──
- name: Install Linux dependencies
if: startsWith(matrix.artifact, 'linux-')
# Bounded and retried: a hung apt step is reported as `cancelled` with no reason.
# update + install retry as one unit; two long attempts, since slow mirrors are common.
timeout-minutes: 15
env:
RETRY_ATTEMPTS: '2'
RETRY_ATTEMPT_TIMEOUT: '360'
run: |
bash .github/scripts/retry-with-apt-lock.sh sudo sh -c \
'apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf xdg-utils fonts-noto-color-emoji gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-libav || { apt-get update && apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf xdg-utils fonts-noto-color-emoji gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-libav; }'
# ── Node.js ──
- name: Setup Node.js
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 24
- name: Lockfile supply-chain audit (pre-install scan)
shell: bash
# Must run BEFORE any `npm ci`: this job has contents: write, so a malicious lockfile
# postinstall could publish binaries.
run: python3 scripts/lockfile_supply_chain_audit.py
- name: Install pinned Tauri CLI
# Lifecycle scripts are required for `vite build`; the lockfile audit above runs first.
run: npm ci --prefix studio --no-fund --no-audit
- name: Verify pinned Tauri CLI
shell: bash
run: |
out="$(npx --prefix studio tauri --version)"
echo "$out"
if [ "$out" != "tauri-cli 2.10.1" ]; then
echo "Expected tauri-cli 2.10.1, got $out" >&2
exit 1
fi
- name: Verify desktop updater and Linux package config
shell: bash
run: |
node <<'JS'
const { readFileSync } = require('node:fs');
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) {
throw new Error('Expected exactly one desktop updater endpoint');
}
if (endpoints[0] !== expected) {
throw new Error('Desktop updater endpoint must be ' + expected + ', got ' + endpoints[0]);
}
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;
if (Array.isArray(targets) && targets.some((target) => String(target).toLowerCase() === 'rpm')) {
throw new Error('Desktop release must not target RPM packages');
}
if (!Array.isArray(targets) || !targets.some((target) => String(target).toLowerCase() === 'appimage')) {
throw new Error('Desktop release must build the complete Tauri AppImage target');
}
if (config.bundle?.linux?.rpm) {
throw new Error('bundle.linux.rpm must not be configured');
}
// The media plugins must match the bundled GStreamer core.
if (config.bundle?.linux?.appimage?.bundleMediaFramework !== true) {
throw new Error('Linux AppImage bundleMediaFramework must stay true');
}
const workflow = readFileSync('.github/workflows/release-desktop.yml', 'utf8');
const lines = workflow.split(/\r?\n/);
// The needle is assembled rather than written as a literal: this file is
// what gets scanned, so a literal would match this very line and let a
// genuinely missing install slip through.
const aptInstallNeedle = ['apt-get', 'install'].join(' ');
const linuxInstallLines = lines.filter((line) => line.includes(aptInstallNeedle));
const ayatanaPackage = ['libayatana', 'appindicator3-dev'].join('-');
if (linuxInstallLines.some((line) => line.includes(ayatanaPackage))) {
throw new Error('Desktop Linux release must not install the Ayatana appindicator dev package');
}
if (!linuxInstallLines.some((line) => line.includes('libappindicator3-dev'))) {
throw new Error('Desktop Linux release must install libappindicator3-dev');
}
const requiredFetchedTools = [
'linuxdeploy-x86_64.AppImage',
'linuxdeploy-plugin-gtk.sh',
'linuxdeploy-plugin-gstreamer.sh',
'linuxdeploy-plugin-appimage.AppImage',
];
const toolScript = readFileSync(
'studio/src-tauri/linux/prepare-complete-appimage-tools.sh',
'utf8',
);
const localAppRunInstall =
'install -m 755 "$script_dir/appimage-apprun.sh" "$tools_dir/AppRun-x86_64"';
if (!toolScript.includes(localAppRunInstall)) {
throw new Error('Desktop Linux release must install the repository AppRun');
}
const fetchCalls = toolScript
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => /^fetch "\$[A-Z_]+_URL" "\$[A-Z_]+_SHA256" \S+$/.test(line));
const fetchedTools = fetchCalls.map((line) => line.split(/\s+/).at(-1));
if (fetchCalls.length !== requiredFetchedTools.length) {
throw new Error(
`Expected ${requiredFetchedTools.length} digest-verified fetch calls, got ${fetchCalls.length}`,
);
}
for (const tool of requiredFetchedTools) {
if (!fetchedTools.includes(tool)) {
throw new Error(`Desktop Linux release must digest-verify its fetch of ${tool}`);
}
}
const releaseBody = process.env.DESKTOP_RELEASE_NOTES;
if (!releaseBody) throw new Error('DESKTOP_RELEASE_NOTES must not be empty');
if (/\brpm\b|\.rpm/i.test(releaseBody)) {
throw new Error('Desktop release body must not advertise RPM packages');
}
if (/AppImage.*universal|universal.*AppImage/i.test(releaseBody)) {
throw new Error('Desktop release body must not advertise AppImage as universal');
}
if (!/AppImage.*experimental/i.test(releaseBody)) {
throw new Error('Desktop release body must mark AppImage as experimental');
}
JS
- name: Install frontend dependencies
working-directory: studio/frontend
# Lifecycle scripts are required for `vite build`; the lockfile audit runs first.
run: npm ci --no-fund --no-audit
# ── Rust ──
- name: Install Rust stable
uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable @ 2026-03-27
with:
targets: ${{ matrix.platform == 'macos-latest' && 'aarch64-apple-darwin,x86_64-apple-darwin' || (matrix.artifact == 'windows-arm64' && 'aarch64-pc-windows-msvc' || '') }}
- name: Patch desktop app version
shell: bash
working-directory: studio/src-tauri
run: |
set -euo pipefail
if command -v python3 >/dev/null 2>&1; then
PYTHON=python3
else
PYTHON=python
fi
"$PYTHON" <<'PY'
import os
import pathlib
import re
import sys
app_version = os.environ['APP_VERSION']
if not app_version:
sys.exit('APP_VERSION is required')
cargo_toml = pathlib.Path('Cargo.toml')
lines = cargo_toml.read_text().splitlines(keepends=True)
in_package = False
patched = False
for index, line in enumerate(lines):
stripped = line.strip()
if stripped == '[package]':
in_package = True
continue
if stripped.startswith('[') and stripped.endswith(']'):
in_package = False
if in_package and re.fullmatch(r'version\s*=\s*"[^"]+"\s*', stripped):
lines[index] = f'version = "{app_version}"\n'
patched = True
break
if not patched:
sys.exit('Could not patch [package] version in Cargo.toml')
cargo_toml.write_text(''.join(lines))
cargo_lock = pathlib.Path('Cargo.lock')
lock_text = cargo_lock.read_text()
lock_text, count = re.subn(
r'(?m)(^\[\[package\]\]\nname = "unsloth-studio"\nversion = ")[^"]+(")',
lambda match: f'{match.group(1)}{app_version}{match.group(2)}',
lock_text,
)
if count != 1:
sys.exit(f'Could not patch unsloth-studio version in Cargo.lock (matches={count})')
cargo_lock.write_text(lock_text)
PY
cargo metadata --locked --no-deps --format-version 1 > "$RUNNER_TEMP/cargo-metadata.json"
"$PYTHON" <<'PY'
import json
import os
import pathlib
import sys
app_version = os.environ['APP_VERSION']
metadata = json.loads(pathlib.Path(os.environ['RUNNER_TEMP'], 'cargo-metadata.json').read_text())
versions = [package['version'] for package in metadata.get('packages', []) if package.get('name') == 'unsloth-studio']
if versions != [app_version]:
sys.exit(f'cargo metadata unsloth-studio version mismatch: expected {app_version}, got {versions}')
PY
git diff -- Cargo.toml Cargo.lock
- name: Rust cache
uses: swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
workspaces: 'studio/src-tauri -> target'
# Restore only: this job holds signing secrets, and caches saved on main are readable by
# every PR. Cargo fingerprints can capture rerun-if-env-changed values.
save-if: false
# ── macOS: fail before the build if notarization cannot run ──
- name: Check Apple notarization credentials
if: matrix.platform == 'macos-latest'
shell: bash
env:
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: |
set -euo pipefail
# A missing secret is an empty string and tauri-action then silently skips notarization.
for required in APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID; do
if [ -z "${!required:-}" ]; then
echo "Missing $required; refusing to publish an unnotarized disk image." >&2
exit 1
fi
done
# ── macOS: import signing certificate ──
- name: Import Apple certificate
if: matrix.platform == 'macos-latest'
env:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
run: |
# Quoted printf passes the secret through byte for byte.
printf '%s' "$APPLE_CERTIFICATE" | base64 --decode > certificate.p12
security create-keychain -p "$KEYCHAIN_PASSWORD" build.keychain
security default-keychain -s build.keychain
security unlock-keychain -p "$KEYCHAIN_PASSWORD" build.keychain
security set-keychain-settings -t 3600 -u build.keychain
security import certificate.p12 -k build.keychain -P "$APPLE_CERTIFICATE_PASSWORD" -T /usr/bin/codesign
security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PASSWORD" build.keychain
security find-identity -v -p codesigning build.keychain
rm -f certificate.p12
# ── Windows: install Azure Trusted Signing CLI ──
# Pinned prebuilt with a SHA-256 check: this binary runs next to the signing secrets.
# Bump the URL and digest together.
- name: Install trusted-signing-cli
if: matrix.platform == 'windows-latest'
# pwsh: the retry parameters below need PowerShell 6+.
shell: pwsh
env:
TRUSTED_SIGNING_CLI_URL: "https://github.com/Levminer/artifact-signing-cli/releases/download/0.10.0/trusted-signing-cli.exe"
TRUSTED_SIGNING_CLI_SHA256: "8c9d750ca582891a7433925dcf302d5d3761fbed757b46c4bf5b417562dccb0e"
run: |
$ErrorActionPreference = "Stop"
$dir = Join-Path $env:RUNNER_TEMP "trusted-signing-cli"
New-Item -ItemType Directory -Force -Path $dir | Out-Null
$dest = Join-Path $dir "trusted-signing-cli.exe"
Invoke-WebRequest -Uri $env:TRUSTED_SIGNING_CLI_URL -OutFile $dest -MaximumRetryCount 3 -RetryIntervalSec 5
$actual = (Get-FileHash -Path $dest -Algorithm SHA256).Hash.ToLower()
$expected = $env:TRUSTED_SIGNING_CLI_SHA256.ToLower()
if ($actual -ne $expected) {
Remove-Item -Force $dest
Write-Output "::error::trusted-signing-cli digest mismatch, refusing to sign with an unverified binary. Expected $expected, got $actual. Re-pin TRUSTED_SIGNING_CLI_SHA256 deliberately if upstream republished the asset."
exit 1
}
Write-Output "verified trusted-signing-cli sha256=$actual"
# $GITHUB_PATH prepends, so the verified copy wins over a stale one in ~/.cargo/bin.
$dir | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
# ── Windows: verify signing CLI is accessible ──
# Fails closed, so a broken binary does not surface later as an obscure signing error.
- name: Verify trusted-signing-cli
if: matrix.platform == 'windows-latest'
shell: pwsh
run: |
$ErrorActionPreference = "Stop"
Write-Output "PATH: $env:PATH"
$cli = Get-Command trusted-signing-cli -ErrorAction SilentlyContinue
if (-not $cli) {
Write-Output "::error::trusted-signing-cli is not on PATH. Check the 'Install trusted-signing-cli' step above."
exit 1
}
Write-Output "resolved: $($cli.Source)"
# Signing resolves the bare name, so PATH must resolve to the digest-verified copy.
$verified = [IO.Path]::GetFullPath((Join-Path (Join-Path $env:RUNNER_TEMP "trusted-signing-cli") "trusted-signing-cli.exe"))
if ([IO.Path]::GetFullPath($cli.Source) -ne $verified) {
Write-Output "::error::trusted-signing-cli resolved to $($cli.Source), not the verified $verified. Refusing to sign with a binary that was never digest checked."
exit 1
}
# Catch start failures (terminating) and also check $LASTEXITCODE (non-terminating).
try {
& $cli.Source --version
}
catch {
# Annotations truncate at the first newline, so flatten and put the recovery first.
$detail = ($_.Exception.Message -replace '\s+', ' ').Trim()
Write-Output "::error::trusted-signing-cli could not be started. Re-run to fetch it again; if it persists the pinned asset is bad. Underlying error: $detail"
exit 1
}
if ($LASTEXITCODE -ne 0) {
Write-Output "::error::trusted-signing-cli is on PATH but exited $LASTEXITCODE."
exit 1
}
# ── Linux: preseed every executable/script consumed by Tauri's AppImage bundler ──
- name: Pin complete AppImage toolchain
if: matrix.platform == 'ubuntu-22.04'
shell: bash
run: |
studio/src-tauri/linux/prepare-complete-appimage-tools.sh \
"$RUNNER_TEMP/tauri-tools-cache/tauri"
# ── Linux: build and sign the native package and complete AppImage together ──
- name: Build Linux bundles
id: build_linux
if: matrix.platform == 'ubuntu-22.04'
uses: tauri-apps/tauri-action@1deb371b0cd8bd54025b384f1cd735e725c4060f # v1.0.0
env:
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ''
XDG_CACHE_HOME: ${{ runner.temp }}/tauri-tools-cache
with:
projectPath: studio
tauriScript: npx --prefix . tauri
args: -v --bundles deb,appimage
- name: Build Linux ARM64 package
id: build_linux_arm64
if: matrix.platform == 'ubuntu-24.04-arm'
uses: tauri-apps/tauri-action@1deb371b0cd8bd54025b384f1cd735e725c4060f
env:
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ''
with:
projectPath: studio
tauriScript: npx --prefix . tauri
args: -v --bundles deb
- name: Verify complete Linux AppImage
if: matrix.platform == 'ubuntu-22.04'
shell: bash
env:
ARTIFACT_PATHS: ${{ steps.build_linux.outputs.artifactPaths }}
run: |
set -euo pipefail
appimage="$(python3 - <<'PY'
import json, os, pathlib, sys
matches = [pathlib.Path(p) for p in json.loads(os.environ['ARTIFACT_PATHS']) if p.endswith('.AppImage')]
if len(matches) != 1 or not matches[0].is_file():
sys.exit(f'Expected exactly one AppImage artifact, got {matches}')
print(matches[0])
PY
)"
studio/src-tauri/linux/verify-complete-appimage.sh "$appimage"
# ── macOS: build + sign + notarize ──
- name: Build macOS app
id: build_macos
if: matrix.platform == 'macos-latest'
uses: tauri-apps/tauri-action@1deb371b0cd8bd54025b384f1cd735e725c4060f # v1.0.0
env:
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
# Must be the empty string, not unset: tauri prompts for a password when absent and hangs.
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ''
APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
with:
projectPath: studio
tauriScript: npx --prefix . tauri
args: -v ${{ matrix.args }}
# ── macOS: notarize + staple the disk image itself ──
# tauri notarizes the .app but only codesigns the .dmg (tauri-apps/tauri#7533), so
# notarize and staple the disk image here.
- name: Notarize final macOS disk image
if: matrix.platform == 'macos-latest'
shell: bash
# --timeout does not cap the upload, so add a step backstop.
timeout-minutes: 45
env:
ARTIFACT_PATHS: ${{ steps.build_macos.outputs.artifactPaths }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: |
set -euo pipefail
dmg_path="$(
python3 <<'PY'
import json
import os
import sys
raw_paths = os.environ.get('ARTIFACT_PATHS', '')
try:
artifact_paths = json.loads(raw_paths)
except json.JSONDecodeError as error:
sys.exit(f'Invalid tauri-action artifactPaths output: {error}')
if not isinstance(artifact_paths, list):
sys.exit('tauri-action artifactPaths must be a JSON list')
matches = [
path
for path in artifact_paths
if isinstance(path, str) and path.lower().endswith('.dmg')
]
if len(matches) != 1:
sys.exit(f'Expected exactly one final DMG from tauri-action, found {len(matches)}')
print(matches[0])
PY
)"
# An unsigned DMG here means the signing step silently did nothing.
codesign --verify --verbose=2 "$dmg_path"
# notarytool has no non-argv form for --password; accepted on an ephemeral runner.
submit_status=0
submission="$(
xcrun notarytool submit "$dmg_path" \
--apple-id "$APPLE_ID" \
--password "$APPLE_PASSWORD" \
--team-id "$APPLE_TEAM_ID" \
--output-format json \
--timeout 30m \
--wait
)" || submit_status=$?
printf '%s\n' "$submission"
submission_id="$(
printf '%s' "$submission" \
| python3 -c 'import json, sys; print(json.load(sys.stdin).get("id", ""))' \
2>/dev/null
)" || submission_id=""
submission_result="$(
printf '%s' "$submission" \
| python3 -c 'import json, sys; print(json.load(sys.stdin).get("status", ""))' \
2>/dev/null
)" || submission_result=""
if [ "$submit_status" -ne 0 ] || [ "$submission_result" != "Accepted" ]; then
# Check the JSON status independently of the exit code.
if [ -n "$submission_id" ]; then
xcrun notarytool log "$submission_id" \
--apple-id "$APPLE_ID" \
--password "$APPLE_PASSWORD" \
--team-id "$APPLE_TEAM_ID" >&2 || true
fi
if [ "$submit_status" -ne 0 ]; then
exit "$submit_status"
fi
echo "Notarization did not return Accepted (status=${submission_result:-missing})." >&2
exit 1
fi
# Ticket lookup can lag an Accepted verdict; retry it.
for attempt in 1 2 3; do
staple_status=0
xcrun stapler staple "$dmg_path" || staple_status=$?
if [ "$staple_status" -eq 0 ]; then
break
fi
if [ "$attempt" -eq 3 ]; then
exit "$staple_status"
fi
delay=$((15 * attempt))
echo "::warning::Stapling failed (attempt $attempt/3); retrying in ${delay}s."