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: ship a complete Linux AppImage (#9113)
oobaboogade102032ee9c
diff --git a/.github/workflows/desktop-app-clean-machine-ci.yml b/.github/workflows/desktop-app-clean-machine-ci.ymlindex e3f6bd64b74..21076c21841 100644--- a/.github/workflows/desktop-app-clean-machine-ci.yml+++ b/.github/workflows/desktop-app-clean-machine-ci.yml@@ -30,6 +30,15 @@ on:- '.github/scripts/resolve-desktop-release.py'- '.github/scripts/clean-machine-env.sh'- '.github/scripts/clean-machine-assert.sh'+ - '.github/workflows/release-desktop.yml'+ - 'studio/src-tauri/linux/**'+ - 'studio/src-tauri/src/**'+ - 'studio/src-tauri/tauri.conf.json'+ - 'tests/security/test_release_desktop_appimage.py'+ - 'tests/studio/appimage_test_support.py'+ - 'tests/studio/appimage_portability_smoke.py'+ - 'tests/studio/appimage_media_pipeline_probe.py'+ - 'tests/studio/appimage_model_download_webdriver.py'workflow_dispatch:inputs:release_tag:@@ -416,8 +425,9 @@ jobs:}BIN="$(dpkg -L "$(dpkg-deb -f dl/*.deb Package)" | grep -E '/usr/bin/' | head -1)"else- sudo apt-get install -y -qq --no-install-recommends libfuse2 \- libwebkit2gtk-4.1-0 libgtk-3-0 libayatana-appindicator3-1 || true+ sudo apt-get install -y -qq --no-install-recommends \+ libfuse2 libgles2 libgl1 libegl1 libgbm1 libwayland-client0 \+ libharfbuzz0b libnghttp2-14 fontconfig libfribidi0chmod +x dl/*.AppImageBIN="$(ls dl/*.AppImage | head -1)"fi@@ -577,6 +587,337 @@ jobs:retention-days: 7if-no-files-found: warn+ # Build the PR AppImage once for every artifact test below.+ appimage-pr-build:+ if: github.event_name == 'pull_request'+ name: Build PR AppImage+ runs-on: ubuntu-22.04+ timeout-minutes: 60+ permissions:+ contents: read+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false++ - name: Install AppImage build dependencies+ 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 -qq libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf xdg-utils gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-libav || { apt-get update -qq && apt-get install -y -qq libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf xdg-utils gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-libav; }'++ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0+ with:+ node-version: 24++ - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable @ 2026-03-27++ - uses: swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2.9.1+ with:+ save-if: false+ workspaces: 'studio/src-tauri -> target'++ - name: Audit lockfiles before package scripts run+ run: python3 scripts/lockfile_supply_chain_audit.py++ - name: Install pinned Tauri CLI+ run: npm install --save-dev --prefix studio @tauri-apps/[email protected] --no-fund --no-audit++ - name: Install frontend dependencies+ working-directory: studio/frontend+ run: npm ci --strict-allow-scripts --no-fund --no-audit++ - name: Pin complete AppImage toolchain+ run: |+ studio/src-tauri/linux/prepare-complete-appimage-tools.sh \+ "$RUNNER_TEMP/tauri-tools-cache/tauri"++ - name: Build unsigned AppImage from the PR+ env:+ XDG_CACHE_HOME: ${{ runner.temp }}/tauri-tools-cache+ run: |+ set -euo pipefail+ npx --prefix studio tauri build -v --bundles appimage \+ --config '{"bundle":{"createUpdaterArtifacts":false}}'+ mapfile -t appimages < <(find studio/src-tauri/target/release/bundle/appimage \+ -maxdepth 1 -type f -name '*.AppImage' -print)+ if [[ ${#appimages[@]} -ne 1 ]]; then+ echo "::error::expected one PR AppImage, got ${#appimages[@]}"+ printf '%s\n' "${appimages[@]}"+ exit 1+ fi+ studio/src-tauri/linux/verify-complete-appimage.sh "${appimages[0]}"+ mkdir -p "$RUNNER_TEMP/appimage-pr-build"+ cp "${appimages[0]}" "$RUNNER_TEMP/appimage-pr-build/Unsloth.AppImage"++ - name: Upload branch-built AppImage+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: appimage-pr-build+ path: ${{ runner.temp }}/appimage-pr-build/Unsloth.AppImage+ retention-days: 1+ if-no-files-found: error+++ # These images deliberately omit host GTK, WebKitGTK, and AppIndicator.+ appimage-portability:+ needs: appimage-pr-build+ if: >-+ always() &&+ (github.event_name != 'pull_request' || needs.appimage-pr-build.result == 'success')+ name: AppImage ${{ matrix.label }}+ runs-on: ubuntu-22.04+ container: ${{ matrix.image }}+ timeout-minutes: 20+ defaults:+ run:+ shell: bash+ strategy:+ fail-fast: false+ matrix:+ include:+ - {label: ubuntu-22.04, image: 'ubuntu:22.04', display_backend: x11, install_gles: true}+ - {label: ubuntu-22.04-no-gles, image: 'ubuntu:22.04', display_backend: x11, install_gles: false}+ - {label: ubuntu-24.04-wayland, image: 'ubuntu:24.04', display_backend: wayland, install_gles: true}+ - {label: debian-12, image: 'debian:12', display_backend: x11, install_gles: true}+ - {label: fedora-44, image: 'fedora:44', display_backend: x11, install_gles: true}++ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false++ - name: Install only generic display and graphics prerequisites+ timeout-minutes: 15+ run: |+ set -euo pipefail+ if command -v apt-get >/dev/null 2>&1; then+ RETRY_ATTEMPTS=2 RETRY_ATTEMPT_TIMEOUT=360 \+ bash .github/scripts/retry-with-apt-lock.sh bash -c '+ set -euo pipefail+ apt-get update -qq+ alsa_package=libasound2+ if apt-cache policy "$alsa_package" | grep -q "Candidate: (none)"; then+ alsa_package=libasound2t64+ fi+ DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \+ ca-certificates python3 xvfb xauth binutils libgl1 libegl1 libgbm1 \+ libwayland-client0 libwayland-cursor0 libwayland-egl1 libwayland-server0 \+ libx11-6 libx11-xcb1 libxcb1 libxcb-randr0 libxcb-render0 libxcb-shm0 \+ libxext6 libxrandr2 libxi6 libxcursor1 libxfixes3 libxrender1 \+ libxcomposite1 libxdamage1 libxinerama1 libxau6 libxdmcp6 libxshmfence1 \+ "$alsa_package" libpulse0 libharfbuzz0b libnghttp2-14 fontconfig libfribidi0+ if [[ "${{ matrix.install_gles }}" == "true" ]]; then+ DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends libgles2+ fi+ if [[ "${{ matrix.display_backend }}" == "wayland" ]]; then+ DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends weston+ fi+ '+ forbidden="$(dpkg-query -W -f='${binary:Package}\n' 2>/dev/null | \+ grep -Ei 'webkit|javascriptcore|appindicator|libgtk-3' || true)"+ else+ dnf install -y -q ca-certificates python3 binutils xorg-x11-server-Xvfb xorg-x11-xauth \+ mesa-libEGL mesa-libgbm mesa-dri-drivers mesa-libGL \+ libwayland-client libwayland-cursor libwayland-egl libwayland-server \+ libX11 libX11-xcb libxcb libXext libXrandr libXi libXcursor libXfixes \+ libXrender libXcomposite libXdamage libXinerama libXau libXdmcp libxshmfence \+ alsa-lib pulseaudio-libs libnghttp2 harfbuzz fontconfig fribidi procps-ng findutils+ if [[ "${{ matrix.install_gles }}" == "true" ]]; then+ dnf install -y -q mesa-libGLES+ fi+ forbidden="$(rpm -qa | grep -Ei 'webkit|javascriptcore|appindicator|gtk3' || true)"+ fi+ if [[ "${{ matrix.install_gles }}" == "false" ]] && \+ ldconfig -p | grep -q 'libGLESv2\.so\.2'; then+ echo "::error::no-GLES portability lane unexpectedly provides libGLESv2.so.2"+ exit 1+ fi++ if [ -n "$forbidden" ]; then+ echo "::error::portability image unexpectedly contains a host desktop runtime"+ printf '%s\n' "$forbidden"+ exit 1+ fi++ - name: Download the AppImage built from this PR+ if: github.event_name == 'pull_request'+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1+ with:+ name: appimage-pr-build+ path: dl+++ - name: Download the shipped AppImage+ if: github.event_name != 'pull_request'+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ REL_REPO: ${{ inputs.release_repo || github.repository }}+ REL_TAG: ${{ inputs.release_tag || '' }}+ run: |+ set -euo pipefail+ mkdir -p dl logs/appimage-portability+ python3 - <<'PY'+ import json+ import os+ import pathlib+ import re+ import urllib.request++ repo = os.environ["REL_REPO"]+ requested = os.environ.get("REL_TAG", "").strip()+ headers = {+ "Accept": "application/vnd.github+json",+ "Authorization": f"Bearer {os.environ['GH_TOKEN']}",+ "X-GitHub-Api-Version": "2022-11-28",+ }++ def get(url, *, accept=None):+ request_headers = dict(headers)+ if accept:+ request_headers["Accept"] = accept+ with urllib.request.urlopen(+ urllib.request.Request(url, headers=request_headers), timeout=60+ ) as response:+ return response.read()++ releases = json.loads(get(f"https://api.github.com/repos/{repo}/releases?per_page=100"))+ candidates = []+ for release in releases:+ tag = release.get("tag_name", "")+ if requested and tag != requested:+ continue+ match = re.fullmatch(r"v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?", tag)+ asset = next(+ (item for item in release.get("assets", []) if item.get("name", "").endswith(".AppImage")),+ None,+ )+ if match and asset:+ candidates.append((tuple(map(int, match.groups())), release, asset))+ if not candidates:+ raise SystemExit(f"No AppImage release found in {repo} for {requested or 'latest SemVer'}")+ _, release, asset = max(candidates, key=lambda item: item[0])+ output = pathlib.Path("dl/Unsloth.AppImage")+ output.write_bytes(get(asset["url"], accept="application/octet-stream"))+ output.chmod(0o755)+ print(f"Downloaded {release['tag_name']} {asset['name']} ({output.stat().st_size} bytes)")+ PY++ - name: Prepare the selected AppImage+ run: |+ mkdir -p logs/appimage-portability+ chmod +x dl/Unsloth.AppImage+++ - name: Audit and launch the complete AppImage+ env:+ APPIMAGE_PATH: ${{ github.workspace }}/dl/Unsloth.AppImage+ APPIMAGE_SMOKE_ART_DIR: ${{ github.workspace }}/logs/appimage-portability++ APPIMAGE_DISPLAY_BACKEND: ${{ matrix.display_backend }}+ GALLIUM_DRIVER: llvmpipe+ run: |+ set -euo pipefail+ studio/src-tauri/linux/verify-complete-appimage.sh "$APPIMAGE_PATH"+ # Check bundled plugin loadability on each target host.+ python3 tests/studio/appimage_media_pipeline_probe.py+ python3 tests/studio/appimage_portability_smoke.py++ - name: Upload portability evidence+ if: always()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: appimage-portability-${{ matrix.label }}+ path: logs/appimage-portability/+ retention-days: 7+ if-no-files-found: warn+++ # WebDriver uses the same PR artifact to exercise a real model download request.+ appimage-model-download:+ needs: appimage-pr-build+ if: >-+ always() &&+ (github.event_name != 'pull_request' || needs.appimage-pr-build.result == 'success')+ name: AppImage model download E2E+ runs-on: ubuntu-22.04+ timeout-minutes: 25++ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false++ - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable @ 2026-03-27++ - name: Install WebDriver prerequisites+ timeout-minutes: 20+ env:+ RETRY_ATTEMPTS: '2'+ RETRY_ATTEMPT_TIMEOUT: '360'+ run: |+ bash .github/scripts/retry-with-apt-lock.sh sudo sh -c \+ 'apt-get install -y -qq --no-install-recommends python3 xvfb xauth webkit2gtk-driver libgles2 libgl1 libegl1 libgbm1 libwayland-client0 libharfbuzz0b libnghttp2-14 fontconfig libfribidi0 libasound2 libpulse0 || { apt-get update -qq && apt-get install -y -qq --no-install-recommends python3 xvfb xauth webkit2gtk-driver libgles2 libgl1 libegl1 libgbm1 libwayland-client0 libharfbuzz0b libnghttp2-14 fontconfig libfribidi0 libasound2 libpulse0; }'+ cargo install tauri-driver --version 2.0.6 --locked++ - name: Download the AppImage built from this PR+ if: github.event_name == 'pull_request'+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1+ with:+ name: appimage-pr-build+ path: dl+++ - name: Download the shipped AppImage for WebDriver+ if: github.event_name != 'pull_request'+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ run: |+ set -euo pipefail+ mkdir -p dl logs/appimage-model-download+ if [ -z "$REL_TAG" ]; then+ releases_json="$RUNNER_TEMP/desktop-releases.json"+ gh release list --repo "$REL_REPO" --limit 100 \+ --json tagName,createdAt,isDraft > "$releases_json"+ REL_TAG="$(python3 .github/scripts/resolve-desktop-release.py \+ --repo "$REL_REPO" --asset-suffix .AppImage < "$releases_json")"+ echo "resolved release tag: $REL_TAG"+ fi+ gh release download "$REL_TAG" --repo "$REL_REPO" \+ --pattern '*.AppImage' --dir dl+ chmod +x dl/*.AppImage++ - name: Prepare the selected AppImage+ run: |+ mkdir -p logs/appimage-model-download+ chmod +x dl/*.AppImage+++ - name: Select, download, render progress, and cancel+ env:+ APPIMAGE_PATH: ${{ github.workspace }}/dl/Unsloth.AppImage+ APPIMAGE_E2E_ART_DIR: ${{ github.workspace }}/logs/appimage-model-download+ run: |+ set -euo pipefail+ appimage="$(find dl -maxdepth 1 -type f -name '*.AppImage' -print -quit)"+ test -n "$appimage"+ export APPIMAGE_PATH="$PWD/$appimage"+ xvfb-run -a --server-args="-screen 0 1440x900x24" \+ python3 tests/studio/appimage_model_download_webdriver.py++ - name: Upload model-download evidence+ if: always()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: appimage-model-download+ path: logs/appimage-model-download/+ retention-days: 7+ if-no-files-found: warn++# ── Windows: NSIS setup.exe, silent install ──────────────────────────────windows:# See the macOS job: a fork PR's token cannot list drafts, so skip rather than fail.diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.ymlindex 43423891aed..3043efb081c 100644--- a/.github/workflows/release-desktop.yml+++ b/.github/workflows/release-desktop.yml@@ -568,8 +568,9 @@ jobs:RETRY_ATTEMPTS: '2'RETRY_ATTEMPT_TIMEOUT: '360'run: |+ # Install the GStreamer plugins needed for H.264 playback and capture.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 || { apt-get update && apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf; }'+ 'apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf xdg-utils 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 gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-libav; }'# ── Node.js ──- name: Setup Node.js@@ -619,14 +620,15 @@ jobs: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('Tauri AppImage bundling must stay disabled; the release uses the thin AppImage packager');+ 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');}- if (config.bundle?.linux?.appimage) {- throw new Error('bundle.linux.appimage must not be configured for the thin AppImage release path');+ // 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');@@ -639,64 +641,38 @@ jobs:if (!linuxInstallLines.some((line) => line.includes('libappindicator3-dev'))) {throw new Error('Desktop Linux release must install libappindicator3-dev');}- const appimagetoolLines = lines.filter((line) => line.includes('github.com/AppImage/appimagetool/releases/download'));- if (!appimagetoolLines.some((line) => line.includes('1.9.1/appimagetool-x86_64.AppImage'))) {- throw new Error('Desktop Linux release must pin appimagetool 1.9.1');+ 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');}- // A pinned version/path is reproducibility, not integrity: the asset- // can be replaced after upload. Require the immutable SHA-256 digest- // to be pinned AND verified before chmod +x. Scope every check to the- // real "Pin thin AppImage toolchain" step so this guard cannot- // satisfy itself; a file-wide scan would match the guard's own code.- const expectedAppimagetoolDigest = 'ed4ce84f0d9caff66f50bcca6ff6f35aae54ce8135408b3fa33abfc3cb384eb0';- const expectedRuntimeDigest = '2fca8b443c92510f1483a883f60061ad09b46b978b2631c807cd873a47ec260d';- const isComment = (line) => {- const trimmed = line.trim();- return trimmed.startsWith('#') || trimmed.startsWith('//');- };- const stepStart = lines.findIndex((line) => /^\s*- name: Pin thin AppImage toolchain\s*$/.test(line));- if (stepStart === -1) {- throw new Error('Desktop Linux release must keep the "Pin thin AppImage toolchain" step');+ 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}`,+ );}- const stepIndent = lines[stepStart].search(/\S/);- let stepEnd = lines.length;- for (let i = stepStart + 1; i < lines.length; i += 1) {- const line = lines[i];- if (line.trim() === '') continue;- const indent = line.search(/\S/);- // The next sibling step ('- ...') at the same indent, or any dedent- // below the step, ends this step's block.- if (indent < stepIndent || (indent === stepIndent && /^\s*-\s/.test(line))) {- stepEnd = i;- break;+ for (const tool of requiredFetchedTools) {+ if (!fetchedTools.includes(tool)) {+ throw new Error(`Desktop Linux release must digest-verify its fetch of ${tool}`);}}- const stepLines = lines.slice(stepStart, stepEnd);- const digest = (name) => {- const pattern = new RegExp(`^\\s*${name}:\\s*["']([0-9a-f]{64})["']\\s*$`);- const line = stepLines.find((candidate) => pattern.test(candidate));- return line?.match(pattern)?.[1];- };- if (digest('APPIMAGETOOL_SHA256') !== expectedAppimagetoolDigest) {- throw new Error('Desktop Linux release must pin the appimagetool SHA-256 digest');- }- if (digest('APPIMAGE_RUNTIME_SHA256') !== expectedRuntimeDigest) {- throw new Error('Desktop Linux release must pin the AppImage runtime SHA-256 digest');- }- const sha256Indexes = stepLines- .map((line, index) => !isComment(line) && line.includes('sha256sum -c') ? index : -1)- .filter((index) => index !== -1);- if (sha256Indexes.length !== 2) {- throw new Error('Desktop Linux release must verify both AppImage toolchain digests');- }- const chmodIdx = stepLines.findIndex((line) => !isComment(line) && /chmod\s+\+x/.test(line));- if (chmodIdx !== -1 && Math.max(...sha256Indexes) > chmodIdx) {- throw new Error('Desktop Linux release must verify the AppImage toolchain before chmod +x');- }const releaseBody = process.env.DESKTOP_RELEASE_NOTES;- if (!releaseBody) {- throw new Error('DESKTOP_RELEASE_NOTES must not be empty');- }+ 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');}@@ -941,118 +917,44 @@ jobs:exit 1}- # ── Linux: pin AppImage packaging toolchain ──- - name: Pin thin AppImage toolchain+ # ── Linux: preseed every executable/script consumed by Tauri's AppImage bundler ──+ - name: Pin complete AppImage toolchainif: matrix.platform == 'ubuntu-22.04'shell: bash- env:- # Pinning the versioned release path is reproducibility, not- # integrity: a GitHub release asset can be replaced (or its delivery- # path compromised) after upload. The SHA-256 digests of these exact- # assets are the integrity gate. A replaced- # release asset fails closed and must be re-pinned deliberately.- APPIMAGETOOL_URL: "https://github.com/AppImage/appimagetool/releases/download/1.9.1/appimagetool-x86_64.AppImage"- APPIMAGETOOL_SHA256: "ed4ce84f0d9caff66f50bcca6ff6f35aae54ce8135408b3fa33abfc3cb384eb0"- APPIMAGE_RUNTIME_URL: "https://github.com/AppImage/type2-runtime/releases/download/20251108/runtime-x86_64"- APPIMAGE_RUNTIME_SHA256: "2fca8b443c92510f1483a883f60061ad09b46b978b2631c807cd873a47ec260d"run: |- set -euo pipefail- tools_dir="$RUNNER_TEMP/appimage-tools"- mkdir -p "$tools_dir"- appimagetool="$tools_dir/appimagetool-x86_64.AppImage"- runtime="$tools_dir/runtime-x86_64"- curl -fsSL "$APPIMAGETOOL_URL" -o "$appimagetool"- curl -fsSL "$APPIMAGE_RUNTIME_URL" -o "$runtime"- # Verify the digest BEFORE the binary is ever marked executable. The- # later step builds the AppImage with the Tauri signing key, so a- # substituted packager that ran there could exfiltrate signing- # material or tamper with release artifacts. Fail closed on any- # mismatch.- echo "${APPIMAGETOOL_SHA256} ${appimagetool}" | sha256sum -c -- echo "${APPIMAGE_RUNTIME_SHA256} ${runtime}" | sha256sum -c -- chmod +x "$appimagetool"-- # ── Linux: build the native package once ──- - name: Build Linux deb+ 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 bundlesid: build_linuxif: matrix.platform == 'ubuntu-22.04'uses: tauri-apps/tauri-action@84b9d35b5fc46c1e45415bdb6144030364f7ebc5 # v0.6.2+ env:+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ''+ XDG_CACHE_HOME: ${{ runner.temp }}/tauri-tools-cachewith:projectPath: studiotauriScript: npx --prefix . tauri- args: >-- -v --bundles deb- --config '{"bundle":{"createUpdaterArtifacts":false}}'+ args: -v --bundles deb,appimage- # ── Linux: wrap the deb payload without bundling the GTK/WebKit stack ──- - name: Build and sign thin Linux AppImage- id: package_linux+ - name: Verify complete Linux AppImageif: matrix.platform == 'ubuntu-22.04'shell: bashenv:ARTIFACT_PATHS: ${{ steps.build_linux.outputs.artifactPaths }}- TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}- # The signing key is not password protected, and no secret of this name- # exists, so this expression has always resolved to the empty string.- # Stated literally rather than left pointing at a secret that is not- # there: the value is unchanged, but it no longer reads as configuration- # someone forgot to set. Empty is not the same as unset here -- tauri- # prompts for a password when the variable is absent, which would hang- # the job, so the line stays.- TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ''run: |set -euo pipefail- deb_path="$(- python3 - <<'PY'- import json- import os- import pathlib- import sys-- paths = json.loads(os.environ.get('ARTIFACT_PATHS', ''))- matches = [pathlib.Path(path) for path in paths if str(path).endswith('.deb')]+ 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 Linux deb artifact, got {matches}')+ sys.exit(f'Expected exactly one AppImage artifact, got {matches}')print(matches[0])PY)"- output_dir="studio/src-tauri/target/release/bundle/appimage"- appimage="$output_dir/unsloth-studio_${APP_VERSION}_amd64.AppImage"- export APPIMAGE_PATH="$appimage"- studio/src-tauri/linux/build-thin-appimage.sh \- "$deb_path" \- "$RUNNER_TEMP/appimage-tools/appimagetool-x86_64.AppImage" \- "$RUNNER_TEMP/appimage-tools/runtime-x86_64" \- "$appimage"- signature="${appimage}.sig"- # 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')- PY- python3 - <<'PY'- import json- import os-- deb_paths = json.loads(os.environ['ARTIFACT_PATHS'])- appimage = os.environ['APPIMAGE_PATH']- paths = [*deb_paths, appimage, f'{appimage}.sig']- with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as output:- output.write(f'artifactPaths={json.dumps(paths)}\n')- PY+ studio/src-tauri/linux/verify-complete-appimage.sh "$appimage"# ── macOS: build + sign + notarize ──- name: Build macOS app@@ -1561,7 +1463,7 @@ jobs:- name: Stage release assetsshell: bashenv:- ARTIFACT_PATHS: ${{ steps.package_linux.outputs.artifactPaths || steps.build_macos.outputs.artifactPaths || steps.build_windows.outputs.artifactPaths }}+ ARTIFACT_PATHS: ${{ steps.build_linux.outputs.artifactPaths || steps.build_macos.outputs.artifactPaths || steps.build_windows.outputs.artifactPaths }}run: |set -euo pipefailif command -v python3 >/dev/null 2>&1; thendiff --git a/studio/src-tauri/linux/appimage-apprun.sh b/studio/src-tauri/linux/appimage-apprun.shnew file mode 100755index 00000000000..9976c954425--- /dev/null+++ b/studio/src-tauri/linux/appimage-apprun.sh@@ -0,0 +1,25 @@+#!/bin/sh+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++set -eu++# Bundled ELF objects use $ORIGIN RUNPATHs; display and driver libraries stay host-owned.+APPDIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)+PATH="$APPDIR/usr/bin:$APPDIR/usr/sbin:${PATH:-/usr/local/bin:/usr/bin:/bin}"+export APPDIR PATH++# The loader reads LD_LIBRARY_PATH before those RUNPATHs, so an inherited value would put+# host GLib, GTK, WebKit or GStreamer in front of the bundle. Managed children still get it;+# the guard keeps a restart of an already-cleared process from erasing the saved value.+if [ "${LD_LIBRARY_PATH+x}" = x ]; then+ UNSLOTH_HOST_LD_LIBRARY_PATH="$LD_LIBRARY_PATH"+ export UNSLOTH_HOST_LD_LIBRARY_PATH+ unset LD_LIBRARY_PATH+fi++# WebKitGTK resolves its helpers relative to its /usr prefix.+cd "$APPDIR/usr"+++exec "$APPDIR/usr/bin/unsloth-studio" "$@"diff --git a/studio/src-tauri/linux/build-thin-appimage.sh b/studio/src-tauri/linux/build-thin-appimage.shdeleted file mode 100755index f222eb1629b..00000000000--- a/studio/src-tauri/linux/build-thin-appimage.sh+++ /dev/null@@ -1,259 +0,0 @@-#!/usr/bin/env bash--set -euo pipefail--assert_thin_appdir() {- local root="$1"- local found=0- local path-- while IFS= read -r -d '' path; do- case "$(basename -- "$path")" in- libglib-2.0.so*|libgobject-2.0.so*|libgio-2.0.so*|libgmodule-2.0.so*|\- libgtk-3.so*|libgdk-3.so*|libgdk_pixbuf-2.0.so*|\- libwebkit2gtk-4.1.so*|libjavascriptcoregtk-4.1.so*|libsoup-3.0.so*|\- libcurl.so*|libcurl-gnutls.so*|libnghttp2.so*)- echo "Thin AppImage unexpectedly contains host desktop library: $path" >&2- found=1- ;;- esac- done < <(find "$root" \( -type f -o -type l \) -print0)-- if [[ $found -ne 0 ]]; then- return 1- fi-}--stamp_appimage_bundle_type() {- local binary_path="$1"-- python3 - "$binary_path" <<'PY'-import pathlib-import sys--binary_path = pathlib.Path(sys.argv[1])-deb_marker = b"__TAURI_BUNDLE_TYPE_VAR_DEB"-appimage_marker = b"__TAURI_BUNDLE_TYPE_VAR_APP"-binary = binary_path.read_bytes()--deb_count = binary.count(deb_marker)-appimage_count = binary.count(appimage_marker)-if deb_count != 1 or appimage_count != 0:- sys.exit(- f"Expected exactly one Tauri deb bundle marker and no AppImage marker in "- f"{binary_path}; found deb={deb_count}, appimage={appimage_count}"- )--binary_path.write_bytes(binary.replace(deb_marker, appimage_marker, 1))--stamped = binary_path.read_bytes()-if stamped.count(deb_marker) != 0 or stamped.count(appimage_marker) != 1:- sys.exit(f"Failed to stamp the Tauri AppImage bundle marker in {binary_path}")-PY-}--# Keep the safety check directly executable so its behavior can be covered by-# a regression test without constructing a deb or downloading the toolchain.-if [[ $# -eq 2 && "$1" == "--verify-appdir" ]]; then- assert_thin_appdir "$2"- exit-fi--if [[ $# -ne 4 ]]; then- echo "Usage: $0 DEB APPIMAGETOOL RUNTIME OUTPUT" >&2- echo " $0 --verify-appdir APPDIR" >&2- exit 2-fi--deb_path="$1"-appimagetool_path="$2"-runtime_path="$3"-output_path="$4"--for input_path in "$deb_path" "$appimagetool_path" "$runtime_path"; do- if [[ ! -f "$input_path" ]]; then- echo "Required AppImage input does not exist: $input_path" >&2- exit 1- fi-done--if [[ "$(dpkg-deb --field "$deb_path" Architecture)" != "amd64" ]]; then- echo "The Linux AppImage must be built from an amd64 deb." >&2- exit 1-fi--work_root="$(mktemp -d "${RUNNER_TEMP:-/tmp}/unsloth-thin-appimage.XXXXXX")"-trap 'rm -rf -- "$work_root"' EXIT-app_dir="$work_root/AppDir"-verify_dir="$work_root/verify"-output_dir="$(dirname -- "$output_path")"-mkdir -p "$app_dir" "$verify_dir" "$output_dir"-output_dir="$(CDPATH= cd -- "$output_dir" && pwd -P)"-output_path="$output_dir/$(basename -- "$output_path")"--# The deb is already a working host-integrated package. Reusing its payload-# avoids a partial GTK/WebKit dependency closure, which can mix an-# old bundled GLib with newer host GIO modules and network libraries.-dpkg-deb --extract "$deb_path" "$app_dir"--desktop_file="$app_dir/usr/share/applications/Unsloth.desktop"-icon_file="$app_dir/usr/share/icons/hicolor/128x128/apps/unsloth-studio.png"-binary_file="$app_dir/usr/bin/unsloth-studio"-for required_path in "$desktop_file" "$icon_file" "$binary_file"; do- if [[ ! -f "$required_path" ]]; then- echo "The deb is missing an AppImage input: $required_path" >&2- exit 1- fi-done--# tauri-bundler stamps the executable copied into a deb so the updater selects-# the deb installer. This executable is going into an AppImage instead, so-# stamp the equal-length AppImage marker before packaging it. Without this,-# the updater downloads the AppImage and then rejects it as an invalid deb.-stamp_appimage_bundle_type "$binary_file"--ln -s usr/share/applications/Unsloth.desktop "$app_dir/Unsloth.desktop"-ln -s usr/share/icons/hicolor/128x128/apps/unsloth-studio.png "$app_dir/unsloth-studio.png"-ln -s unsloth-studio.png "$app_dir/.DirIcon"--cat > "$app_dir/AppRun" <<'EOF'-#!/bin/sh-set -eu--appdir=${APPDIR:-$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)}-export PATH="$appdir/usr/bin${PATH:+:$PATH}"-export XDG_DATA_DIRS="$appdir/usr/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"--binary="$appdir/usr/bin/unsloth-studio"-missing=$(- ldd "$binary" 2>/dev/null |- sed -n 's/^[[:space:]]*\([^[:space:]]*\)[[:space:]]*=>[[:space:]]*not found.*$/\1/p'-)--# The tray crate dlopens AppIndicator, so it never appears in the binary's ldd-# output. libappindicator-sys tries the versioned sonames then the unversioned-# ones, so accept all four in that order or we reject hosts whose tray works.-appindicator_names="libayatana-appindicator3.so.1 libappindicator3.so.1"-appindicator_names="$appindicator_names libayatana-appindicator3.so libappindicator3.so"--appindicator_is_usable() {- [ -r "$1" ] || return 1- # An absent ldd is inconclusive, as in the guard above: the loader, not ldd,- # decides whether a readable candidate can load.- command -v ldd >/dev/null 2>&1 || return 0- appindicator_ldd=$(ldd "$1" 2>&1) || return 1- ! printf '%s\n' "$appindicator_ldd" | grep -q 'not found'-}--# Every path the loader tries for a dlopen name, in order: LD_LIBRARY_PATH,-# the ldconfig cache, then the default directories.-appindicator_candidates() {- library_name="$1"-- if [ "${LD_LIBRARY_PATH+x}" = x ]; then- # The loader accepts ':' and ';', and an empty component means the current- # directory. The appended separator keeps a trailing empty one visible.- library_path="${LD_LIBRARY_PATH}:"- while [ -n "$library_path" ]; do- library_dir=${library_path%%[:;]*}- library_path=${library_path#*[:;]}- [ -n "$library_dir" ] || library_dir=.- printf '%s\n' "$library_dir/$library_name"- done- fi-- if command -v ldconfig >/dev/null 2>&1; then- ldconfig -p 2>/dev/null | awk -v name="$library_name" '$1 == name { print $NF }'- fi-- printf '%s\n' \- /lib/"$library_name" \- /lib/*-linux-gnu/"$library_name" \- /lib64/"$library_name" \- /usr/lib/"$library_name" \- /usr/lib/*-linux-gnu/"$library_name" \- /usr/lib64/"$library_name" \- /usr/local/lib/"$library_name"-}--find_appindicator() {- for library_name in $appindicator_names; do- # The loader commits to the first file it finds for a name, so stop there:- # skipping ahead would pass a host whose dlopen still fails.- first_candidate=$(- appindicator_candidates "$library_name" |- while IFS= read -r candidate; do- if [ -r "$candidate" ]; then- printf '%s\n' "$candidate"- break- fi- done- )- [ -n "$first_candidate" ] || continue- if appindicator_is_usable "$first_candidate"; then- printf '%s\n' "$first_candidate"- return 0- fi- done- return 1-}--if ! find_appindicator >/dev/null; then- if [ -n "$missing" ]; then- missing="$missing-"- fi- missing="${missing}libayatana-appindicator3.so.1 or libappindicator3.so.1"-fi--if [ -n "$missing" ]; then- message="Unsloth cannot start because required Linux libraries are missing:--$missing--On Ubuntu or Linux Mint, install them with:-sudo apt install libayatana-appindicator3-1 libwebkit2gtk-4.1-0 libgtk-3-0"- printf '%s\n' "$message" >&2- if command -v zenity >/dev/null 2>&1; then- zenity --error --title="Unsloth cannot start" --text="$message" >/dev/null 2>&1 || true- elif command -v xmessage >/dev/null 2>&1; then- xmessage -center "$message" >/dev/null 2>&1 || true- fi- exit 127-fi--exec "$binary" "$@"-EOF-chmod +x "$app_dir/AppRun"--assert_thin_appdir "$app_dir"--ARCH=x86_64 "$appimagetool_path" --appimage-extract-and-run \- --no-appstream \- --runtime-file "$runtime_path" \- "$app_dir" "$output_path"--if [[ ! -x "$output_path" ]]; then- echo "appimagetool did not create an executable AppImage: $output_path" >&2- exit 1-fi--(- cd "$verify_dir"- "$output_path" --appimage-extract >/dev/null-)-assert_thin_appdir "$verify_dir/squashfs-root"--if grep -Eq '(^|[[:space:]])(export[[:space:]]+)?LD_LIBRARY_PATH=' \- "$verify_dir/squashfs-root/AppRun"; then- echo "Thin AppImage must not override the host library search path." >&2- exit 1-fi--ldd_output="$(ldd "$verify_dir/squashfs-root/usr/bin/unsloth-studio")"-if grep -q 'not found' <<< "$ldd_output"; then- echo "The AppImage binary has unresolved dependencies on the build host." >&2- exit 1-fi--echo "Built thin AppImage: $output_path"diff --git a/studio/src-tauri/linux/finalize-complete-appimage.sh b/studio/src-tauri/linux/finalize-complete-appimage.shnew file mode 100755index 00000000000..4b671b17acb--- /dev/null+++ b/studio/src-tauri/linux/finalize-complete-appimage.sh@@ -0,0 +1,57 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++set -euo pipefail++# The ELF sweep below parses readelf output, which is translated.+export LC_ALL=C++if [[ $# -ne 1 || ! -d "$1" ]]; then+ echo "Usage: $0 APPDIR" >&2+ exit 2+fi++appdir="$(realpath "$1")"+libdir="$appdir/usr/lib"+[[ -d "$libdir" ]] || { echo "AppDir has no usr/lib: $appdir" >&2; exit 1; }+command -v patchelf >/dev/null || { echo "patchelf is required" >&2; exit 1; }++# Remove host-coupled libraries after all input plugins deploy their dependencies.+host_patterns=(+ 'ld-linux*.so*' 'libc.so*' 'libm.so*' 'libdl.so*' 'libpthread.so*'+ 'librt.so*' 'libresolv.so*' 'libnss_*.so*' 'libutil.so*' 'libanl.so*'+ 'libGL*.so*' 'libEGL*.so*' 'libGLES*.so*' 'libOpenGL*.so*'+ 'libgbm.so*' 'libdrm.so*' 'libglapi.so*' 'libvulkan.so*' 'libcuda.so*'+ 'libX11.so*' 'libX11-xcb.so*' 'libxcb*.so*' 'libXext.so*'+ 'libXrandr.so*' 'libXi.so*' 'libXcursor.so*' 'libXfixes.so*'+ 'libXrender.so*' 'libXcomposite.so*' 'libXdamage.so*'+ 'libXinerama.so*' 'libXau.so*' 'libXdmcp.so*' 'libxshmfence.so*'+ 'libwayland-*.so*' 'libasound.so*' 'libpulse*.so*'+ # Keep libva and libvdpau so libgstlibav can load without host VA-API.+ 'libnvidia-*.so*'+ 'libstdc++.so*' 'libgcc_s.so*' 'libnghttp2.so*' 'libcurl*.so*'+)+for pattern in "${host_patterns[@]}"; do+ while IFS= read -r -d '' bundled; do+ rm -f -- "$bundled"+ done < <(find "$appdir" \( -type f -o -type l \) -name "$pattern" -print0)+done++# Use $ORIGIN RUNPATHs so host objects do not inherit bundled libraries (#7953).+patched=0+while IFS= read -r -d '' object; do+ [[ "$(head -c 4 "$object" 2>/dev/null || true)" == $'\177ELF' ]] || continue+ readelf -d "$object" 2>/dev/null | grep -q 'Dynamic section' || continue+ relative="$(realpath --relative-to="$(dirname -- "$object")" "$libdir")"+ if [[ "$relative" == "." ]]; then+ runpath='$ORIGIN'+ else+ runpath="\$ORIGIN/$relative"+ fi+ patchelf --set-rpath "$runpath" "$object"+ ((patched += 1))+done < <(find "$appdir" -type f -print0)++((patched > 0)) || { echo "AppDir contains no dynamic ELF objects" >&2; exit 1; }+printf 'Finalized AppImage runtime with %d $ORIGIN RUNPATHs: %s\n' "$patched" "$appdir"diff --git a/studio/src-tauri/linux/prepare-complete-appimage-tools.sh b/studio/src-tauri/linux/prepare-complete-appimage-tools.shnew file mode 100755index 00000000000..2961086a0b3--- /dev/null+++ b/studio/src-tauri/linux/prepare-complete-appimage-tools.sh@@ -0,0 +1,109 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++set -euo pipefail++if [[ $# -ne 1 ]]; then+ echo "Usage: $0 TOOL_CACHE_DIR" >&2+ exit 2+fi++tools_dir="$1"+mkdir -p "$tools_dir"++script_dir="$(cd -- "$(dirname -- "$0")" && pwd -P)"+LINUXDEPLOY_URL="https://github.com/tauri-apps/binary-releases/releases/download/linuxdeploy/linuxdeploy-x86_64.AppImage"+LINUXDEPLOY_SHA256="e762bea85c8eb0d4b3508d46e5c1f037f717d0f9303ae3b4aafc8b04991fa1ef"+GTK_PLUGIN_URL="https://raw.githubusercontent.com/tauri-apps/linuxdeploy-plugin-gtk/b5eb8d05b4c0ed40107fe2158c5d8527f94568ef/linuxdeploy-plugin-gtk.sh"+GTK_PLUGIN_SHA256="cb379f9b0733e9ad9f8bd78f8c2fa038aef2478523bb7d4c8e64ff6a1ea3501a"+GSTREAMER_PLUGIN_URL="https://raw.githubusercontent.com/tauri-apps/linuxdeploy-plugin-gstreamer/2a2e67491c32995a3f279ad0ecbe77abd512b42a/linuxdeploy-plugin-gstreamer.sh"+GSTREAMER_PLUGIN_SHA256="c107b49d84edbffc6ab226ed1007e0626a4f7aa2c3a36b7782bef62351d49e94"+APPIMAGE_PLUGIN_URL="https://github.com/linuxdeploy/linuxdeploy-plugin-appimage/releases/download/continuous/linuxdeploy-plugin-appimage-x86_64.AppImage"+APPIMAGE_PLUGIN_SHA256="a45d3e227bc7f397e9cf6bfa4c9507494efa2293357b6e86690a3de2ca992e79"++fetch() {+ local url="$1" digest="$2" name="$3"+ local dest="$tools_dir/$name"+ curl -fsSL "$url" -o "$dest"+ echo "$digest $dest" | sha256sum -c -+ chmod +x "$dest"+}++fetch "$LINUXDEPLOY_URL" "$LINUXDEPLOY_SHA256" linuxdeploy-x86_64.AppImage+fetch "$GTK_PLUGIN_URL" "$GTK_PLUGIN_SHA256" linuxdeploy-plugin-gtk.sh+fetch "$GSTREAMER_PLUGIN_URL" "$GSTREAMER_PLUGIN_SHA256" linuxdeploy-plugin-gstreamer.sh+fetch "$APPIMAGE_PLUGIN_URL" "$APPIMAGE_PLUGIN_SHA256" linuxdeploy-plugin-appimage.AppImage++# Replace Tauri's global LD_LIBRARY_PATH launcher to avoid #7953.+install -m 755 "$script_dir/appimage-apprun.sh" "$tools_dir/AppRun-x86_64"++# Run the finalizer after the GTK plugin deploys its dependencies.+install -m 755 \+ "$script_dir/finalize-complete-appimage.sh" \+ "$tools_dir/finalize-complete-appimage.sh"+++# Let GTK select X11 or Wayland instead of forcing X11.+sed -i '/export GDK_BACKEND=x11/d' "$tools_dir/linuxdeploy-plugin-gtk.sh"++# Remove host module paths from the generated AppRun hook (#7953).+cat >> "$tools_dir/linuxdeploy-plugin-gtk.sh" <<'SH'+# Canonicalize the relative APPDIR used by APPIMAGE_EXTRACT_AND_RUN.+sed -i '2i\+case "${APPDIR:-}" in\+ /*) ;;\+ *) APPDIR="$(dirname "$(realpath "$0")")" ;;\+esac\+export APPDIR+' "$HOOKFILE"++# Remove foreign-architecture GIO modules copied from multilib hosts.+while IFS= read -r -d '' gio_module; do+ machine="$(LC_ALL=C readelf -h "$gio_module" 2>/dev/null |+ sed -n 's/^[[:space:]]*Machine:[[:space:]]*//p')"+ [[ "$machine" == "Advanced Micro Devices X86-64" ]] || rm -f "$gio_module"+done < <(find "$APPDIR"/usr/lib* -path '*/gio/modules/*' -type f -print0)++# Pin GIO to the bundled modules that survived the architecture sweep.+mapfile -t gio_module_dirs < <(+ find "$APPDIR"/usr/lib* -path '*/gio/modules/*' -type f -printf '%h\n' | sort -u+)+if [[ ${#gio_module_dirs[@]} -ne 1 ]]; then+ echo "Complete AppImage needs exactly one bundled GIO module directory," \+ "found: ${gio_module_dirs[*]:-none}" >&2+ exit 1+fi+cat >> "$HOOKFILE" <<EOF+unset GIO_EXTRA_MODULES+export GIO_MODULE_DIR="\$APPDIR/${gio_module_dirs[0]#"$APPDIR"/}"+EOF++# Pin GTK_PATH so GTK_MODULES cannot load host modules into bundled GTK.+mapfile -t gtk_module_dirs < <(+ find "$APPDIR"/usr/lib* -maxdepth 2 -type d -name 'gtk-[0-9]*' | sort -u+)+if [[ ${#gtk_module_dirs[@]} -ne 1 ]]; then+ echo "Complete AppImage needs exactly one bundled GTK module directory," \+ "found: ${gtk_module_dirs[*]:-none}" >&2+ exit 1+fi+cat >> "$HOOKFILE" <<EOF+export GTK_PATH="\$APPDIR/${gtk_module_dirs[0]#"$APPDIR"/}"+EOF++# Replace Tauri's build-machine .DirIcon target with a relative link.+dir_icon_target="$(readlink "$APPDIR/.DirIcon" 2>/dev/null || true)"+if [[ "$dir_icon_target" == /* ]]; then+ ln -sfn "${dir_icon_target##*/}" "$APPDIR/.DirIcon"+fi+SH++# Append the idempotent finalizer because linuxdeploy does not guarantee plugin order.+for plugin in linuxdeploy-plugin-gtk.sh linuxdeploy-plugin-gstreamer.sh; do+ cat >> "$tools_dir/$plugin" <<'SH'++plugin_dir="$(cd -- "$(dirname -- "$0")" && pwd -P)"+"$plugin_dir/finalize-complete-appimage.sh" "$APPDIR"+SH+donediff --git a/studio/src-tauri/linux/verify-complete-appimage.sh b/studio/src-tauri/linux/verify-complete-appimage.shnew file mode 100755index 00000000000..5456d63e774--- /dev/null+++ b/studio/src-tauri/linux/verify-complete-appimage.sh@@ -0,0 +1,185 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++set -euo pipefail++# Every check below parses readelf output, which is translated.+export LC_ALL=C++usage() {+ echo "Usage: $0 APPIMAGE|--appdir APPDIR" >&2+ exit 2+}++if [[ $# -eq 2 && "$1" == "--appdir" ]]; then+ appdir="$2"+ cleanup=""+elif [[ $# -eq 1 && -f "$1" ]]; then+ work_root="$(mktemp -d "${RUNNER_TEMP:-/tmp}/unsloth-appimage-verify.XXXXXX")"+ cleanup="$work_root"+ trap 'rm -rf -- "$cleanup"' EXIT+ appimage="$(realpath "$1")"+ (+ cd "$work_root"+ "$appimage" --appimage-extract >/dev/null+ )+ appdir="$work_root/squashfs-root"+else+ usage+fi++[[ -d "$appdir" ]] || { echo "AppDir does not exist: $appdir" >&2; exit 1; }+[[ -x "$appdir/AppRun" ]] || { echo "Complete AppImage has no executable AppRun" >&2; exit 1; }+++launchers=("$appdir/AppRun")+[[ ! -e "$appdir/AppRun.wrapped" ]] || launchers+=("$appdir/AppRun.wrapped")+if grep -aEq '^[[:space:]]*(export[[:space:]]+)?LD_LIBRARY_PATH=' "${launchers[@]}" \+ "$appdir/apprun-hooks"/* 2>/dev/null || \+ grep -aFq 'LD_LIBRARY_PATH=%s/usr/lib/' "${launchers[@]}" 2>/dev/null; then+ echo "Complete AppImage must not set a global AppDir LD_LIBRARY_PATH (#7953)" >&2+ exit 1+fi++# An inherited LD_LIBRARY_PATH outranks the $ORIGIN RUNPATHs below.+if ! grep -aEq '^[[:space:]]*unset[[:space:]]+LD_LIBRARY_PATH([[:space:]]|$)' \+ "${launchers[@]}" 2>/dev/null; then+ echo "Complete AppImage does not clear an inherited LD_LIBRARY_PATH" >&2+ exit 1+fi++if ! grep -Rqs 'GIO_MODULE_DIR=' \+ "$appdir/AppRun" "$appdir/apprun-hooks" "$appdir/usr/lib" 2>/dev/null; then+ echo "Complete AppImage does not isolate bundled GIO modules" >&2+ exit 1+fi++if ! grep -Rqs 'unset[[:space:]]\+GIO_EXTRA_MODULES' \+ "$appdir/AppRun" "$appdir/apprun-hooks" "$appdir/usr/lib" 2>/dev/null; then+ echo "Complete AppImage does not reject host GIO_EXTRA_MODULES" >&2+ exit 1+fi++# Require module search paths to stay inside the AppDir.+for module_path in GTK_PATH GIO_MODULE_DIR; do+ value="$(grep -hs "^export ${module_path}=" "$appdir/apprun-hooks"/* 2>/dev/null |+ tail -1 | sed "s/^export ${module_path}=//; s/^\"//; s/\"$//")"+ if [[ -z "$value" ]]; then+ echo "Complete AppImage does not pin $module_path to the bundle" >&2+ exit 1+ fi+ IFS=':' read -ra entries <<<"$value"+ for entry in "${entries[@]}"; do+ case "$entry" in+ '$APPDIR/'*) ;;+ *)+ echo "Bundled $module_path reaches a host module directory: $entry" >&2+ exit 1+ ;;+ esac+ done+done+# Reject Tauri's absolute build-machine .DirIcon link.+[[ -e "$appdir/.DirIcon" ]] || { echo "Complete AppImage has no resolvable .DirIcon" >&2; exit 1; }+case "$(readlink "$appdir/.DirIcon" 2>/dev/null)" in+ /*) echo "Complete AppImage pins .DirIcon to a build-machine path" >&2; exit 1 ;;+esac++binary="$(find "$appdir/usr/bin" -maxdepth 1 -type f -name 'unsloth*' -perm -111 -print -quit 2>/dev/null)"+[[ -n "$binary" ]] || { echo "Complete AppImage has no Unsloth executable" >&2; exit 1; }++machine="$(readelf -h "$binary" | sed -n 's/^[[:space:]]*Machine:[[:space:]]*//p')"+[[ "$machine" == "Advanced Micro Devices X86-64" ]] || {+ echo "Complete AppImage has the wrong architecture: ${machine:-unknown}" >&2+ exit 1+}++require_basename() {+ local pattern="$1"+ if ! find "$appdir" \( -type f -o -type l \) -name "$pattern" -print -quit | grep -q .; then+ echo "Complete AppImage is missing required runtime component: $pattern" >&2+ return 1+ fi+}++for component in \+ 'libglib-2.0.so*' 'libgobject-2.0.so*' 'libgio-2.0.so*' \+ 'libgtk-3.so*' 'libgdk-3.so*' 'libgdk_pixbuf-2.0.so*' \+ 'libwebkit2gtk-4.1.so*' 'libjavascriptcoregtk-4.1.so*' 'libsoup-3.0.so*' \+ 'libappindicator3.so*' 'WebKitNetworkProcess' 'WebKitWebProcess' \+ 'libwebkit2gtkinjectedbundle.so' \+ 'libgiognutls.so' \+ 'libgstcoreelements.so' 'libgstplayback.so' 'libgstpulseaudio.so' \+ 'libgstisomp4.so' 'libgstvideoparsersbad.so' 'libgstlibav.so' \+ 'gst-plugin-scanner'; do+ require_basename "$component"+done++# Require the media plugins that must match the bundled GStreamer core.+gst_plugin_count="$(find "$appdir/usr/lib/gstreamer-1.0" -maxdepth 1 -type f -name '*.so' 2>/dev/null | wc -l)"+if [[ "$gst_plugin_count" -lt 50 ]]; then+ echo "Complete AppImage bundles only $gst_plugin_count GStreamer plugins" >&2+ exit 1+fi++# Reject libraries that must remain part of the host runtime.+for forbidden in \+ 'ld-linux*.so*' 'libc.so*' 'libpthread.so*' 'libm.so*' 'libdl.so*' 'librt.so*' \+ 'libresolv.so*' 'libnss_*.so*' 'libutil.so*' 'libanl.so*' \+ 'libGL*.so*' 'libEGL*.so*' 'libGLES*.so*' 'libOpenGL*.so*' \+ 'libdrm.so*' 'libgbm.so*' 'libglapi.so*' 'libvulkan.so*' 'libcuda.so*' \+ 'libX11.so*' 'libX11-xcb.so*' 'libxcb*.so*' 'libXext.so*' \+ 'libXrandr.so*' 'libXi.so*' 'libXcursor.so*' 'libXfixes.so*' \+ 'libXrender.so*' 'libXcomposite.so*' 'libXdamage.so*' \+ 'libXinerama.so*' 'libXau.so*' 'libXdmcp.so*' 'libxshmfence.so*' \+ 'libwayland-*.so*' 'libasound.so*' 'libpulse*.so*' \+ 'libnvidia-*.so*' \+ 'libnghttp2.so*' 'libcurl*.so*' 'libstdc++.so*' 'libgcc_s.so*'; do+ if found="$(find "$appdir" \( -type f -o -type l \) -name "$forbidden" -print -quit)" && [[ -n "$found" ]]; then+ echo "Complete AppImage must leave host runtime component unbundled: $found" >&2+ exit 1+ fi+done+dynamic_count=0+runpath_failures=0+while IFS= read -r -d '' object; do+ [[ "$(head -c 4 "$object" 2>/dev/null || true)" == $'\177ELF' ]] || continue+ # Reject foreign-architecture objects copied from multilib hosts.+ object_machine="$(readelf -h "$object" 2>/dev/null |+ sed -n 's/^[[:space:]]*Machine:[[:space:]]*//p')"+ if [[ "$object_machine" != "Advanced Micro Devices X86-64" ]]; then+ echo "Bundled object has the wrong architecture (${object_machine:-unknown}): $object" >&2+ ((runpath_failures += 1))+ continue+ fi+ dynamic="$(readelf -d "$object" 2>/dev/null || true)"+ grep -q 'Dynamic section' <<<"$dynamic" || continue+ ((dynamic_count += 1))+ runpath="$(sed -n 's/.*\(RPATH\|RUNPATH\).*Library .*path: \[\(.*\)\].*/\2/p' <<<"$dynamic")"+ case "$runpath" in+ '$ORIGIN'|'$ORIGIN/'*) ;;+ *)+ echo "Dynamic AppImage object lacks an \$ORIGIN-relative RUNPATH: $object" >&2+ ((runpath_failures += 1))+ ;;+ esac+ if grep -Eq '\(NEEDED\).*Shared library: \[/' <<<"$dynamic"; then+ echo "Dynamic AppImage object has an absolute DT_NEEDED entry: $object" >&2+ ((runpath_failures += 1))+ fi+done < <(find "$appdir" -type f -print0)+((dynamic_count > 0)) || { echo "Complete AppImage contains no dynamic ELF objects" >&2; exit 1; }+((runpath_failures == 0)) || exit 1++++max_glibc="$({ readelf --version-info "$binary" 2>/dev/null || true; } |+ grep -oE 'GLIBC_[0-9]+\.[0-9]+' | sed 's/GLIBC_//' | sort -Vu | tail -1)"+[[ -n "$max_glibc" ]] || { echo "Could not determine the executable glibc floor" >&2; exit 1; }+if [[ "$(printf '%s\n%s\n' 2.35 "$max_glibc" | sort -V | tail -1)" != "2.35" ]]; then+ echo "Executable requires GLIBC_$max_glibc, newer than the Ubuntu 22.04 floor GLIBC_2.35" >&2+ exit 1+fi++printf 'Verified complete x86_64 AppImage runtime (GLIBC_%s): %s\n' "$max_glibc" "$appdir"diff --git a/studio/src-tauri/src/commands.rs b/studio/src-tauri/src/commands.rsindex 6f5566e95f5..47f49b19ba5 100644--- a/studio/src-tauri/src/commands.rs+++ b/studio/src-tauri/src/commands.rs@@ -485,7 +485,7 @@ where}fn open_existing_dir(dir: &std::path::Path) -> Result<(), String> {- open_existing_dir_with(dir, |path| open::that_detached(path))+ open_existing_dir_with(dir, |path| crate::process::open_detached(path))}/// Open the Unsloth directory in the system file manager.diff --git a/studio/src-tauri/src/linux_webkit.rs b/studio/src-tauri/src/linux_webkit.rsindex 1e7f44b3aab..d2386c1f9df 100644--- a/studio/src-tauri/src/linux_webkit.rs+++ b/studio/src-tauri/src/linux_webkit.rs@@ -3,6 +3,9 @@use std::ffi::{OsStr, OsString};+const APPIMAGE: &str = "APPIMAGE";+const GLES_V2: &[u8] = b"libGLESv2.so.2\0";+const WAYLAND_DISPLAY: &str = "WAYLAND_DISPLAY";const GDK_BACKEND: &str = "GDK_BACKEND";const FORCE_SHARED_MEMORY: &str = "WEBKIT_DMABUF_RENDERER_FORCE_SHM";@@ -44,6 +47,7 @@ fn supports_force_shared_memory((major, minor, _micro): (u32, u32, u32)) -> boolfn rendering_plan(env: impl Fn(&str) -> Option<OsString>,webkit_version: (u32, u32, u32),+ gles_usable: bool,) -> RenderingPlan {// Presence is an operator override, including `=0` and an empty value. Do// not combine the modern shared-memory switch with legacy instructions a@@ -52,6 +56,12 @@ fn rendering_plan(return RenderingPlan::PreserveEnvironment;}+ let is_appimage = env(APPIMAGE).is_some();+ // libepoxy loads GLES at runtime; disabling DMA-BUF handles a missing copy (#8343).+ if is_appimage && !gles_usable {+ return RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf);+ }+let configured_backends = env(GDK_BACKEND);let explicit_wayland = configured_backends.as_deref()@@ -72,7 +82,10 @@ fn rendering_plan(return RenderingPlan::PreserveEnvironment;}- let workaround = if supports_force_shared_memory(webkit_version) {+ let workaround = if is_appimage {+ // FORCE_SHM still reaches the failing libepoxy path in AppImages.+ RenderingWorkaround::DisableDmabuf+ } else if supports_force_shared_memory(webkit_version) {RenderingWorkaround::ForceSharedMemory} else {// FORCE_SHM was added with WebKitGTK 2.44. Older host libraries ignore@@ -82,6 +95,19 @@ fn rendering_plan(RenderingPlan::Apply(workaround)}+fn gles_is_usable() -> bool {+ // Match libepoxy's runtime load, including unresolved dependencies.+ unsafe {+ let handle = libc::dlopen(GLES_V2.as_ptr().cast(), libc::RTLD_LAZY | libc::RTLD_LOCAL);+ if handle.is_null() {+ false+ } else {+ libc::dlclose(handle);+ true+ }+ }+}+fn runtime_webkit_version() -> (u32, u32, u32) {// These accessors read compile-time version constants from the already// linked WebKitGTK library; they do not initialize GTK or a web view.@@ -97,8 +123,13 @@ fn runtime_webkit_version() -> (u32, u32, u32) {/// Select a compatible WebKitGTK rendering transport before GTK initialization.////// Returns the variable applied by this launch, if any.-pub fn configure_wayland_renderer() -> Option<&'static str> {- match rendering_plan(|name| std::env::var_os(name), runtime_webkit_version()) {+pub fn configure_renderer() -> Option<&'static str> {+ let gles_usable = std::env::var_os(APPIMAGE).is_none() || gles_is_usable();+ match rendering_plan(+ |name| std::env::var_os(name),+ runtime_webkit_version(),+ gles_usable,+ ) {RenderingPlan::Apply(workaround) => {let variable = workaround.variable();std::env::set_var(variable, "1");@@ -114,7 +145,11 @@ mod tests {const MODERN_WEBKIT: (u32, u32, u32) = (2, 44, 0);- fn plan_with_version(vars: &[(&str, &str)], webkit_version: (u32, u32, u32)) -> RenderingPlan {+ fn plan_with_version_and_gles(+ vars: &[(&str, &str)],+ webkit_version: (u32, u32, u32),+ gles_usable: bool,+ ) -> RenderingPlan {rendering_plan(|name| {vars.iter()@@ -122,9 +157,14 @@ mod tests {.map(|(_, value)| OsString::from(value))},webkit_version,+ gles_usable,)}+ fn plan_with_version(vars: &[(&str, &str)], webkit_version: (u32, u32, u32)) -> RenderingPlan {+ plan_with_version_and_gles(vars, webkit_version, true)+ }+fn plan(vars: &[(&str, &str)]) -> RenderingPlan {plan_with_version(vars, MODERN_WEBKIT)}@@ -174,6 +214,37 @@ mod tests {);}+ #[test]+ fn appimage_without_usable_gles_disables_dmabuf_on_x11() {+ assert_eq!(+ plan_with_version_and_gles(+ &[(APPIMAGE, "/tmp/Unsloth.AppImage")],+ MODERN_WEBKIT,+ false+ ),+ RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf)+ );+ }++ #[test]+ fn native_package_without_gles_keeps_existing_x11_behavior() {+ assert_eq!(+ plan_with_version_and_gles(&[], MODERN_WEBKIT, false),+ RenderingPlan::PreserveEnvironment+ );+ }++ #[test]+ fn appimage_wayland_disables_dmabuf_completely() {+ assert_eq!(+ plan(&[+ (APPIMAGE, "/tmp/Unsloth.AppImage"),+ (WAYLAND_DISPLAY, "wayland-0")+ ]),+ RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf)+ );+ }+#[test]fn old_webkit_uses_the_legacy_renderer_switch() {assert_eq!(diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rsindex 56424907368..e2c82abc169 100644--- a/studio/src-tauri/src/main.rs+++ b/studio/src-tauri/src/main.rs@@ -1807,7 +1807,7 @@ fn main() {// protocol on current NVIDIA/Mesa stacks. Select a compatible fallback// before any GTK/WebKit object can be initialized.#[cfg(target_os = "linux")]- let webkit_rendering_workaround = linux_webkit::configure_wayland_renderer();+ let webkit_rendering_workaround = linux_webkit::configure_renderer();// Fix PATH for GUI apps (macOS .app bundles, Linux AppImage, Windows)// GUI apps don't inherit shell dotfile PATH — this spawns the user's// login shell to source .zshrc/.bashrc/.profile and sets PATH properly.@@ -1818,7 +1818,7 @@ fn main() {#[cfg(target_os = "linux")]if let Some(variable) = webkit_rendering_workaround {- info!("Wayland detected; set {variable}=1 for WebKitGTK compatibility");+ info!("Set {variable}=1 for WebKitGTK compatibility");}windows_job::initialize();diff --git a/studio/src-tauri/src/native_intents.rs b/studio/src-tauri/src/native_intents.rsindex ad1944cceaa..b3ab4b792f0 100644--- a/studio/src-tauri/src/native_intents.rs+++ b/studio/src-tauri/src/native_intents.rs@@ -585,7 +585,7 @@ pub fn reveal_path_token(}}let target = reveal_target(&entry.canonical_path);- open::that_detached(target).map_err(|e| format!("Failed to reveal path: {e}"))+ crate::process::open_detached(target).map_err(|e| format!("Failed to reveal path: {e}"))}#[tauri::command]@@ -596,7 +596,7 @@ pub fn open_path_token() -> Result<(), String> {ensure_main_window(&window)?;let entry = state.path_for_operation(&token, NativePathOperation::Open)?;- open::that_detached(entry.canonical_path).map_err(|e| format!("Failed to open path: {e}"))+ crate::process::open_detached(entry.canonical_path).map_err(|e| format!("Failed to open path: {e}"))}// Covers the largest client-side limit (audio, 25 MB).diff --git a/studio/src-tauri/src/process.rs b/studio/src-tauri/src/process.rsindex 0c4b43f42ac..a2b588bc3a4 100644--- a/studio/src-tauri/src/process.rs+++ b/studio/src-tauri/src/process.rs@@ -12,25 +12,328 @@ use tauri::{AppHandle, Emitter, Manager};const MAX_LOG_LINES: usize = 1000;-// An AppImage can be launched from an activated Python environment. Keep the-// host library path the thin bundle needs, but do not let PYTHONHOME/PYTHONPATH-// shadow the managed Studio environment.+// Where the AppRun parks the host LD_LIBRARY_PATH it must keep away from the bundle.+#[cfg(target_os = "linux")]+const APPIMAGE_HOST_LIBRARY_PATH: &str = "UNSLOTH_HOST_LD_LIBRARY_PATH";++// Keep AppImage GUI paths and Python overrides out of managed host Python.+#[cfg(target_os = "linux")]+fn scrub_appimage_library_path() -> Option<std::ffi::OsString> {+ let appdir = std::env::var_os("APPDIR")?;+ let library_path = std::env::var_os("LD_LIBRARY_PATH")+ .or_else(|| std::env::var_os(APPIMAGE_HOST_LIBRARY_PATH))?;+ let host_paths: Vec<_> = std::env::split_paths(&library_path)+ .filter(|path| !path.starts_with(&appdir))+ .collect();+ if host_paths.is_empty() {+ None+ } else {+ std::env::join_paths(host_paths).ok()+ }+}++#[cfg(target_os = "linux")]+fn apply_scrubbed_appimage_library_path(cmd: &mut Command) {+ cmd.env_remove(APPIMAGE_HOST_LIBRARY_PATH);+ match scrub_appimage_library_path() {+ Some(library_path) => {+ cmd.env("LD_LIBRARY_PATH", library_path);+ }+ None => {+ cmd.env_remove("LD_LIBRARY_PATH");+ }+ }+}+#[cfg(target_os = "linux")]pub(crate) fn scrub_appimage_python_env(cmd: &mut Command) {if std::env::var_os("APPIMAGE").is_some() {+ apply_scrubbed_appimage_library_path(cmd);++ if let Some(path) = appdir_entries_demoted("PATH") {+ cmd.env("PATH", path);+ }+ for name in APPIMAGE_GUI_ONLY_VARS {+ cmd.env_remove(name);+ }cmd.env_remove("PYTHONHOME");cmd.env_remove("PYTHONPATH");}}+// Restore a host-safe environment before launching browsers and file managers.+#[cfg(target_os = "linux")]+const APPIMAGE_GUI_ONLY_VARS: &[&str] = &[+ "GIO_MODULE_DIR",+ "GIO_EXTRA_MODULES",+ "GTK_PATH",+ "GTK_EXE_PREFIX",+ "GTK_DATA_PREFIX",+ "GTK_IM_MODULE_FILE",+ "GDK_PIXBUF_MODULE_FILE",+ "GSETTINGS_SCHEMA_DIR",+ "GST_PLUGIN_SYSTEM_PATH",+ "GST_PLUGIN_SYSTEM_PATH_1_0",+ "GST_PLUGIN_PATH",+ "GST_PLUGIN_PATH_1_0",+ "GST_PLUGIN_SCANNER",+ "GST_PLUGIN_SCANNER_1_0",+ "GST_PTP_HELPER_1_0",+ "GST_REGISTRY_REUSE_PLUGIN_SCANNER",+ "QT_PLUGIN_PATH",+ "PERLLIB",+];++#[cfg(target_os = "linux")]+fn appdir_entries_demoted(name: &str) -> Option<std::ffi::OsString> {+ let appdir = std::env::var_os("APPDIR")?;+ let value = std::env::var_os(name)?;+ let (bundled, host): (Vec<_>, Vec<_>) =+ std::env::split_paths(&value).partition(|path| path.starts_with(&appdir));+ if bundled.is_empty() {+ return None;+ }+ std::env::join_paths(host.into_iter().chain(bundled)).ok()+}++#[cfg(target_os = "linux")]+fn scrub_appimage_launcher_env(cmd: &mut Command) {+ if std::env::var_os("APPIMAGE").is_none() {+ return;+ }+ apply_scrubbed_appimage_library_path(cmd);+ if let Some(path) = appdir_entries_demoted("PATH") {+ cmd.env("PATH", path);+ }+ for name in APPIMAGE_GUI_ONLY_VARS {+ cmd.env_remove(name);+ }+ cmd.env_remove("PYTHONHOME");+ cmd.env_remove("PYTHONPATH");+}++/// Open a target detached with a host-safe environment.+#[cfg(target_os = "linux")]+pub(crate) fn open_detached(target: impl AsRef<std::ffi::OsStr>) -> std::io::Result<()> {+ let mut last_error = None;+ for mut cmd in open::commands(target.as_ref()) {+ scrub_appimage_launcher_env(&mut cmd);+ cmd.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());+ // The same double fork plus setsid the `open` crate uses, so the+ // launcher outlives us; waiting reaps the intermediate child.+ unsafe {+ use std::os::unix::process::CommandExt;+ cmd.pre_exec(|| {+ match libc::fork() {+ -1 => return Err(std::io::Error::last_os_error()),+ 0 => (),+ _ => libc::_exit(0),+ }+ if libc::setsid() == -1 {+ return Err(std::io::Error::last_os_error());+ }+ Ok(())+ });+ }+ match cmd.spawn() {+ Ok(mut child) => {+ let _ = child.wait();+ return Ok(());+ }+ Err(error) => last_error = Some(error),+ }+ }+ Err(last_error.unwrap_or_else(|| std::io::Error::other("no launcher is available")))+}++#[cfg(not(target_os = "linux"))]+pub(crate) fn open_detached(target: impl AsRef<std::ffi::OsStr>) -> std::io::Result<()> {+ open::that_detached(target)+}+#[cfg(target_os = "linux")]pub(crate) fn scrub_appimage_python_env_tokio(cmd: &mut tokio::process::Command) {if std::env::var_os("APPIMAGE").is_some() {+ cmd.env_remove(APPIMAGE_HOST_LIBRARY_PATH);+ match scrub_appimage_library_path() {+ Some(library_path) => {+ cmd.env("LD_LIBRARY_PATH", library_path);+ }+ None => {+ cmd.env_remove("LD_LIBRARY_PATH");+ }+ }+ if let Some(path) = appdir_entries_demoted("PATH") {+ cmd.env("PATH", path);+ }+ for name in APPIMAGE_GUI_ONLY_VARS {+ cmd.env_remove(name);+ }+cmd.env_remove("PYTHONHOME");cmd.env_remove("PYTHONPATH");}}+#[cfg(all(test, target_os = "linux"))]+mod appimage_environment_tests {+ use super::*;+ use std::ffi::OsStr;+ use std::sync::{Mutex, OnceLock};++ fn env_lock() -> std::sync::MutexGuard<'static, ()> {+ static LOCK: OnceLock<Mutex<()>> = OnceLock::new();+ LOCK.get_or_init(|| Mutex::new(())).lock().unwrap()+ }++ fn appimage_isolated_path() -> &'static OsStr {+ OsStr::new("/tmp/.mount_Unsloth/usr/lib")+ }++ fn env_contains_name(env: &str, name: &str) -> bool {+ let prefix = format!("{name}=");+ env.lines().any(|line| line.starts_with(&prefix))+ }++ #[test]+ fn std_managed_child_drops_appimage_gui_and_python_paths() {+ let _guard = env_lock();+ let old_appimage = std::env::var_os("APPIMAGE");+ let old_appdir = std::env::var_os("APPDIR");+ let old_library_path = std::env::var_os("LD_LIBRARY_PATH");+ let old_path = std::env::var_os("PATH");+ std::env::set_var("APPIMAGE", "/tmp/Unsloth.AppImage");+ std::env::set_var("APPDIR", "/tmp/.mount_Unsloth");+ std::env::set_var(+ "LD_LIBRARY_PATH",+ "/tmp/.mount_Unsloth/usr/lib:/opt/cuda/lib64:/private/runtime",+ );+ std::env::set_var("PATH", "/tmp/.mount_Unsloth/usr/bin:/usr/bin:/bin");+ let mut cmd = Command::new("/usr/bin/env");+ cmd.env("PYTHONHOME", "/activated/python")+ .env("PYTHONPATH", "/activated/modules");+ for name in APPIMAGE_GUI_ONLY_VARS {+ cmd.env(name, format!("/tmp/.mount_Unsloth/gui-runtime/{name}"));+ }+ scrub_appimage_python_env(&mut cmd);+ let output = cmd.output().expect("run isolated child");+ let env = String::from_utf8(output.stdout).unwrap();+ assert!(env.contains("LD_LIBRARY_PATH=/opt/cuda/lib64:/private/runtime"));+ // The bundled xdg-utils must not shadow the host copies for a child+ // that reaches the desktop, but they stay available as a fallback.+ assert!(env.contains("PATH=/usr/bin:/bin:/tmp/.mount_Unsloth/usr/bin"));+ assert!(!env.contains(appimage_isolated_path().to_string_lossy().as_ref()));+ assert!(!env.contains("PYTHONHOME="));+ assert!(!env.contains("PYTHONPATH="));+ for name in APPIMAGE_GUI_ONLY_VARS {+ assert!(+ !env_contains_name(&env, name),+ "managed AppImage child inherited {name}: {env}"+ );+ }+ for (key, old_value) in [+ ("APPIMAGE", old_appimage),+ ("APPDIR", old_appdir),+ ("LD_LIBRARY_PATH", old_library_path),+ ("PATH", old_path),+ ] {+ match old_value {+ Some(value) => std::env::set_var(key, value),+ None => std::env::remove_var(key),+ }+ }+ }++ #[test]+ fn managed_child_recovers_the_library_path_the_apprun_parked() {+ let _guard = env_lock();+ let old = ["APPIMAGE", "APPDIR", "LD_LIBRARY_PATH", APPIMAGE_HOST_LIBRARY_PATH]+ .map(|key| (key, std::env::var_os(key)));+ std::env::set_var("APPIMAGE", "/tmp/Unsloth.AppImage");+ std::env::set_var("APPDIR", "/tmp/.mount_Unsloth");+ // The AppRun cleared it so the host copies could not outrank the bundle.+ std::env::remove_var("LD_LIBRARY_PATH");+ std::env::set_var(+ APPIMAGE_HOST_LIBRARY_PATH,+ "/tmp/.mount_Unsloth/usr/lib:/opt/rocm/lib",+ );+ let mut cmd = Command::new("/usr/bin/env");+ scrub_appimage_python_env(&mut cmd);+ let output = cmd.output().expect("run managed child");+ let env = String::from_utf8(output.stdout).unwrap();+ assert!(env.lines().any(|line| line == "LD_LIBRARY_PATH=/opt/rocm/lib"), "{env}");+ assert!(!env_contains_name(&env, APPIMAGE_HOST_LIBRARY_PATH), "{env}");+ for (key, value) in old {+ match value {+ Some(value) => std::env::set_var(key, value),+ None => std::env::remove_var(key),+ }+ }+ }++ #[test]+ fn native_package_child_keeps_caller_environment() {+ let _guard = env_lock();+ let old_appimage = std::env::var_os("APPIMAGE");+ std::env::remove_var("APPIMAGE");+ let mut cmd = Command::new("/usr/bin/env");+ cmd.env("LD_LIBRARY_PATH", appimage_isolated_path())+ .env("PYTHONHOME", "/activated/python")+ .env("PYTHONPATH", "/activated/modules");+ for name in APPIMAGE_GUI_ONLY_VARS {+ cmd.env(name, format!("/native/gui-runtime/{name}"));+ }+ scrub_appimage_python_env(&mut cmd);+ let output = cmd.output().expect("run native-package child");+ let env = String::from_utf8(output.stdout).unwrap();+ assert!(env.contains("LD_LIBRARY_PATH=/tmp/.mount_Unsloth/usr/lib"));+ assert!(env.contains("PYTHONHOME=/activated/python"));+ assert!(env.contains("PYTHONPATH=/activated/modules"));+ for name in APPIMAGE_GUI_ONLY_VARS {+ assert!(+ env_contains_name(&env, name),+ "native-package child unexpectedly lost {name}: {env}"+ );+ }+ if let Some(value) = old_appimage {+ std::env::set_var("APPIMAGE", value);+ }+ }++ #[test]+ fn host_launcher_child_keeps_the_bundle_off_the_host_runtime() {+ let _guard = env_lock();+ let old = ["APPIMAGE", "APPDIR", "LD_LIBRARY_PATH", "PATH"]+ .map(|key| (key, std::env::var_os(key)));+ std::env::set_var("APPIMAGE", "/tmp/Unsloth.AppImage");+ std::env::set_var("APPDIR", "/tmp/.mount_Unsloth");+ std::env::set_var(+ "LD_LIBRARY_PATH",+ "/tmp/.mount_Unsloth/usr/lib:/opt/cuda/lib64",+ );+ std::env::set_var("PATH", "/tmp/.mount_Unsloth/usr/bin:/usr/bin:/bin");+ let mut cmd = Command::new("/usr/bin/env");+ cmd.env("GTK_PATH", "/tmp/.mount_Unsloth/usr/lib/gtk-3.0")+ .env("QT_PLUGIN_PATH", "/tmp/.mount_Unsloth/usr/lib/qt5/plugins")+ .env("PYTHONPATH", "/tmp/.mount_Unsloth/usr/share/pyshared");+ scrub_appimage_launcher_env(&mut cmd);+ let output = cmd.output().expect("run host launcher");+ let env = String::from_utf8(output.stdout).unwrap();+ // The host's own GLib binaries must win, and the bundled tools stay last.+ assert!(env.contains("LD_LIBRARY_PATH=/opt/cuda/lib64"));+ assert!(env.contains("PATH=/usr/bin:/bin:/tmp/.mount_Unsloth/usr/bin"));+ assert!(!env.contains("GTK_PATH="));+ assert!(!env.contains("QT_PLUGIN_PATH="));+ assert!(!env.contains("PYTHONPATH="));+ for (key, value) in old {+ match value {+ Some(value) => std::env::set_var(key, value),+ None => std::env::remove_var(key),+ }+ }+ }+}+#[cfg(windows)]const STUDIO_MANAGED_RUNTIME_MUTEX_PREFIX: &str = "Global\\UnslothStudioManagedEnvironment-";@@ -1334,8 +1637,9 @@ fn is_inside_windows_dir(path: &std::path::Path, windirs: &[std::path::PathBuf])/// so a late-mounting profile recovers, and never falls back to a temp dir.pub(crate) fn managed_cli_working_dir() -> Result<std::path::PathBuf, String> {let windirs = windows_roots();+ let appdir = std::env::var_os("APPDIR").map(std::path::PathBuf::from);if let Ok(cwd) = std::env::current_dir() {- if !is_unusable_cwd(&cwd, &windirs) {+ if !is_unusable_cwd(&cwd, &windirs, appdir.as_deref()) {return Ok(cwd);}}@@ -1345,7 +1649,16 @@ pub(crate) fn managed_cli_working_dir() -> Result<std::path::PathBuf, String> {/// The directories the CLI guard refuses to run from, and only those. The rest of/// the Windows tree still disqualifies a *home*, but a child already running from/// C:\Windows\Temp keeps doing so: the guard allowed that before this change.-fn is_unusable_cwd(path: &std::path::Path, windirs: &[std::path::PathBuf]) -> bool {+///+/// Managed children must not inherit the AppImage's read-only `$APPDIR/usr` directory.+fn is_unusable_cwd(+ path: &std::path::Path,+ windirs: &[std::path::PathBuf],+ appdir: Option<&std::path::Path>,+) -> bool {+ if appdir.is_some_and(|appdir| path.starts_with(appdir)) {+ return true;+ }windirs.iter().any(|windir| {["System32", "SysWOW64"].iter()@@ -4729,6 +5042,29 @@ mod managed_cli_working_dir_tests {fs::remove_dir_all(&work_dir).ok();}+ #[test]+ fn a_mounted_appimage_is_never_a_managed_child_working_directory() {+ let appdir = PathBuf::from("/tmp/.mount_Unsloth1a2b3c");+ for unusable in ["/tmp/.mount_Unsloth1a2b3c", "/tmp/.mount_Unsloth1a2b3c/usr"] {+ assert!(+ is_unusable_cwd(std::path::Path::new(unusable), &[], Some(&appdir)),+ "{unusable} must be replaced"+ );+ }+ for usable in ["/home/me/projects", "/tmp/.mount_Other/usr"] {+ assert!(+ !is_unusable_cwd(std::path::Path::new(usable), &[], Some(&appdir)),+ "{usable} must be kept"+ );+ }+ // A native package sets no APPDIR, so nothing changes for it.+ assert!(!is_unusable_cwd(+ std::path::Path::new("/tmp/.mount_Unsloth1a2b3c/usr"),+ &[],+ None+ ));+ }+#[test]fn only_the_folders_the_cli_refuses_count_as_unusable() {let windirs = [PathBuf::from("C:\\Windows")];@@ -4739,7 +5075,7 @@ mod managed_cli_working_dir_tests {"\\\\?\\C:\\Windows\\System32",] {assert!(- is_unusable_cwd(std::path::Path::new(unusable), &windirs),+ is_unusable_cwd(std::path::Path::new(unusable), &windirs, None),"{unusable} must be replaced");}@@ -4752,7 +5088,7 @@ mod managed_cli_working_dir_tests {"C:\\Users\\me\\projects",] {assert!(- !is_unusable_cwd(std::path::Path::new(usable), &windirs),+ !is_unusable_cwd(std::path::Path::new(usable), &windirs, None),"{usable} must be kept");}diff --git a/studio/src-tauri/tauri.conf.json b/studio/src-tauri/tauri.conf.jsonindex c8cc4b334d4..6001944b065 100644--- a/studio/src-tauri/tauri.conf.json+++ b/studio/src-tauri/tauri.conf.json@@ -57,7 +57,7 @@"homepage": "https://unsloth.ai/","copyright": "© 2026 Unsloth AI. All rights reserved.","license": "AGPL-3.0-only",- "targets": ["app", "deb", "dmg", "nsis"],+ "targets": ["app", "appimage", "deb", "dmg", "nsis"],"icon": ["icons/32x32.png","icons/128x128.png",@@ -81,6 +81,12 @@}},"linux": {+ "appimage": {+ "bundleMediaFramework": true,+ "files": {+ "/usr/lib/libappindicator3.so.1": "/usr/lib/x86_64-linux-gnu/libappindicator3.so.1"+ }+ },"deb": {"desktopTemplate": "./linux/unsloth.desktop","provides": ["unsloth-studio-desktop"],diff --git a/tests/security/test_desktop_release_resolver.py b/tests/security/test_desktop_release_resolver.pyindex 4b5caa94634..397fd1045cd 100644--- a/tests/security/test_desktop_release_resolver.py+++ b/tests/security/test_desktop_release_resolver.py@@ -57,9 +57,10 @@ def test_resolver_requires_the_platform_asset_and_fails_when_absent():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+ # One lookup per shipped-asset lane: .dmg, .deb, .AppImage, .exe.+ assert workflow.count("python3 .github/scripts/resolve-desktop-release.py") == 4assert "'.github/scripts/resolve-desktop-release.py'" in workflow- assert workflow.count('if [ -z "$REL_TAG" ]; then') == 3+ assert workflow.count('if [ -z "$REL_TAG" ]; then') == 4assert 'startswith("desktop-v")' not in workflowfor suffix in (".dmg", ".deb", ".AppImage", ".exe"):assert suffix in workflowdiff --git a/tests/security/test_release_desktop_appimage.py b/tests/security/test_release_desktop_appimage.pyindex 3b5faba820a..1497263d376 100644--- a/tests/security/test_release_desktop_appimage.py+++ b/tests/security/test_release_desktop_appimage.py@@ -1,8 +1,7 @@-"""Contracts for the host-integrated Linux AppImage release path."""+"""Contracts for the complete Linux AppImage release path."""-import os-import shlex-import shutil+import json+import reimport subprocessfrom pathlib import Path@@ -11,7 +10,13 @@ import yamlREPO_ROOT = Path(__file__).resolve().parents[2]WORKFLOW = REPO_ROOT / ".github" / "workflows" / "release-desktop.yml"-PACKAGER = REPO_ROOT / "studio" / "src-tauri" / "linux" / "build-thin-appimage.sh"++CLEAN_MACHINE_WORKFLOW = REPO_ROOT / ".github" / "workflows" / "desktop-app-clean-machine-ci.yml"+VERIFIER = REPO_ROOT / "studio" / "src-tauri" / "linux" / "verify-complete-appimage.sh"++FINALIZER = REPO_ROOT / "studio" / "src-tauri" / "linux" / "finalize-complete-appimage.sh"++APPRUN = REPO_ROOT / "studio" / "src-tauri" / "linux" / "appimage-apprun.sh"def _workflow():@@ -19,436 +24,486 @@ def _workflow():def _step(name: str):- steps = _workflow()["jobs"]["build"]["steps"]- return next(step for step in steps if step.get("name") == name)+ return next(step for step in _workflow()["jobs"]["build"]["steps"] if step.get("name") == name)-def test_release_pins_the_appimage_builder_and_runtime_by_digest():- step = _step("Pin thin AppImage toolchain")- assert step["if"] == "matrix.platform == 'ubuntu-22.04'"- assert "/AppImage/appimagetool/releases/download/1.9.1/" in step["env"]["APPIMAGETOOL_URL"]- assert len(step["env"]["APPIMAGETOOL_SHA256"]) == 64- assert (- "/AppImage/type2-runtime/releases/download/20251108/" in step["env"]["APPIMAGE_RUNTIME_URL"]+def test_tauri_builds_and_signs_deb_and_complete_appimage_together():+ config = json.loads(+ (REPO_ROOT / "studio/src-tauri/tauri.conf.json").read_text(encoding = "utf-8")+ )+ assert "appimage" in config["bundle"]["targets"]+ appimage = config["bundle"]["linux"]["appimage"]+ assert appimage["bundleMediaFramework"] is True+ assert appimage["files"]["/usr/lib/libappindicator3.so.1"].endswith("/libappindicator3.so.1")++ # Require plugins compatible with the bundled GStreamer core.+ dependencies = _step("Install Linux dependencies")["run"]+ for package in ("gstreamer1.0-plugins-good", "gstreamer1.0-plugins-bad", "gstreamer1.0-libav"):+ assert package in dependencies++ build = _step("Build Linux bundles")+ verify = _step("Verify complete Linux AppImage")+ stage = _step("Stage release assets")+ assert "--bundles deb,appimage" in build["with"]["args"]+ assert build["env"]["XDG_CACHE_HOME"] == "${{ runner.temp }}/tauri-tools-cache"+ assert "TAURI_SIGNING_PRIVATE_KEY" in build["env"]+ assert "verify-complete-appimage.sh" in verify["run"]+ assert stage["env"]["ARTIFACT_PATHS"].startswith("${{ steps.build_linux.outputs.artifactPaths")++ clean_machine = yaml.safe_load(CLEAN_MACHINE_WORKFLOW.read_text(encoding = "utf-8"))+ e2e = clean_machine["jobs"]["appimage-model-download"]+ e2e_source = yaml.safe_dump(e2e)+ webdriver_install = next(+ step for step in e2e["steps"] if step.get("name") == "Install WebDriver prerequisites"+ )+ assert "webkit2gtk-driver" in webdriver_install["run"]+ assert "tauri-driver --version 2.0.6 --locked" in webdriver_install["run"]+ assert "appimage_model_download_webdriver.py" in e2e_source+++def test_appimage_pr_build_is_unsigned_and_feeds_every_artifact_test():+ workflow = yaml.safe_load(CLEAN_MACHINE_WORKFLOW.read_text(encoding = "utf-8"))+ pull_request_paths = workflow[True]["pull_request"]["paths"]+ for relevant_path in (+ ".github/workflows/release-desktop.yml",+ ".github/workflows/desktop-app-clean-machine-ci.yml",+ "studio/src-tauri/linux/**",+ "studio/src-tauri/src/**",+ "studio/src-tauri/tauri.conf.json",+ "tests/security/test_release_desktop_appimage.py",+ ):+ assert relevant_path in pull_request_paths++ jobs = workflow["jobs"]+ build = jobs["appimage-pr-build"]+ build_source = yaml.safe_dump(build)+ assert "github.event_name == 'pull_request'" in build["if"]+ for package in ("gstreamer1.0-plugins-good", "gstreamer1.0-plugins-bad", "gstreamer1.0-libav"):+ assert package in build_source+ assert "TAURI_SIGNING_PRIVATE_KEY" not in build_source+ assert "createUpdaterArtifacts" in build_source+ assert "false" in build_source+ assert "--bundles appimage" in build_source+ assert "verify-complete-appimage.sh" in build_source+ assert "appimage-pr-build" in build_source++ for job_name in ("appimage-portability", "appimage-model-download"):+ job = jobs[job_name]+ source = yaml.safe_dump(job)+ assert "appimage-pr-build" in job["needs"]+ assert "github.event_name != 'pull_request'" in job["if"]+ assert "actions/download-artifact" in source+ assert "name: appimage-pr-build" in source+ assert "github.event_name == 'pull_request'" in source+ assert "github.event_name != 'pull_request'" in source+ assert "head.repo.fork" not in source+++def test_debian_portability_lanes_install_verifier_and_host_runtime_prerequisites():+ workflow = yaml.safe_load(CLEAN_MACHINE_WORKFLOW.read_text(encoding = "utf-8"))+ job = workflow["jobs"]["appimage-portability"]+ source = yaml.safe_dump(job)+ for package in (+ "binutils",+ "libegl1",+ "libgbm1",+ "libwayland-client0",+ "libwayland-egl1",+ "libxcb1",+ "libxinerama1",+ "libasound2t64",+ "libharfbuzz0b",+ "libnghttp2-14",+ ):+ assert package in source+ assert "weston" in source+ assert "APPIMAGE_DISPLAY_BACKEND" in source+ assert "wayland" in source++ no_gles = next(+ lane+ for lane in job["strategy"]["matrix"]["include"]+ if lane["label"] == "ubuntu-22.04-no-gles")- assert len(step["env"]["APPIMAGE_RUNTIME_SHA256"]) == 64- assert step["run"].count("sha256sum -c") == 2+ assert no_gles["install_gles"] is False+ assert "libGLESv2.so.2" in source++ # Probe plugin loadability on every target host.+ assert "appimage_media_pipeline_probe.py" in source++ linux_source = yaml.safe_dump(workflow["jobs"]["linux"])+ webdriver_source = yaml.safe_dump(workflow["jobs"]["appimage-model-download"])+ for package in (+ "libegl1",+ "libgbm1",+ "libwayland-client0",+ "libharfbuzz0b",+ "libnghttp2-14",+ ):+ assert package in linux_source+ assert package in webdriver_source+ # Provide the host audio libraries used by bundled media plugins.+ for package in ("libasound2", "libpulse0"):+ assert package in webdriver_source+ for package in ("libwayland-client", "libxcb", "libXinerama", "libnghttp2"):+ assert package in source-def test_linux_build_repackages_the_deb_and_signs_the_final_appimage():- build = _step("Build Linux deb")- package = _step("Build and sign thin Linux AppImage")- stage = _step("Stage release assets")- assert "--bundles deb" in build["with"]["args"]- 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"' 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(- "${{ steps.package_linux.outputs.artifactPaths"- )+def test_release_preseeds_every_tauri_appimage_tool_with_a_digest():+ step = _step("Pin complete AppImage toolchain")+ assert step["if"] == "matrix.platform == 'ubuntu-22.04'"+ assert "prepare-complete-appimage-tools.sh" in step["run"]+ tool_script = (+ REPO_ROOT / "studio/src-tauri/linux/prepare-complete-appimage-tools.sh"+ ).read_text(encoding = "utf-8")++ finalizer_source = FINALIZER.read_text(encoding = "utf-8")+ expected = {+ "LINUXDEPLOY": ("linuxdeploy-x86_64.AppImage", "linuxdeploy-x86_64.AppImage"),+ "GTK_PLUGIN": ("linuxdeploy-plugin-gtk.sh", "linuxdeploy-plugin-gtk.sh"),+ "GSTREAMER_PLUGIN": (+ "linuxdeploy-plugin-gstreamer.sh",+ "linuxdeploy-plugin-gstreamer.sh",+ ),+ "APPIMAGE_PLUGIN": (+ "linuxdeploy-plugin-appimage-x86_64.AppImage",+ "linuxdeploy-plugin-appimage.AppImage",+ ),+ }+ for prefix, (url_filename, destination) in expected.items():+ assert re.search(rf'^{prefix}_URL="[^"]*{re.escape(url_filename)}"$', tool_script, re.M)+ assert re.search(rf'^{prefix}_SHA256="[0-9a-f]{{64}}"$', tool_script, re.M)+ assert f'fetch "${prefix}_URL" "${prefix}_SHA256" {destination}' in tool_script+ fetch_calls = [+ line.strip() for line in tool_script.splitlines() if line.strip().startswith("fetch ")+ ]+ assert len(fetch_calls) == len(expected)+ assert tool_script.index("sha256sum -c") < tool_script.index("chmod +x")++ assert "apprun-old" not in tool_script+ for local_tool in ("appimage-apprun.sh", "finalize-complete-appimage.sh"):+ assert local_tool in tool_script++ assert "patchelf --set-rpath" in finalizer_source+ assert "$ORIGIN" in finalizer_source+ assert 'case "${APPDIR:-}" in' in tool_script+ assert 'APPDIR="$(dirname "$(realpath "$0")")"' in tool_script+ for host_library in (+ "libwayland-*.so*",+ "libGLES*.so*",+ "libGL*.so*",+ "libEGL*.so*",+ "libnghttp2.so*",+ "libcurl*.so*",+ "libstdc++.so*",+ "libgcc_s.so*",+ ):+ assert host_library in finalizer_source+ assert "GIO_MODULE_DIR" in tool_script+ assert "unset GIO_EXTRA_MODULES" in tool_script-def test_tauri_cannot_build_the_old_bundled_appimage():- config = yaml.safe_load(- (REPO_ROOT / "studio" / "src-tauri" / "tauri.conf.json").read_text(encoding = "utf-8")- )- assert "appimage" not in config["bundle"]["targets"]- assert "appimage" not in config["bundle"]["linux"]+ assert "sed -i '/export GDK_BACKEND=x11/d'" in tool_script+ # Keep foreign GIO and GTK modules out of the bundled runtime.+ assert "-path '*/gio/modules/*' -type f -print0" in tool_script+ assert 'export GTK_PATH="\\$APPDIR/' in tool_script-def test_thin_appimage_never_injects_a_partial_desktop_runtime():- script = PACKAGER.read_text(encoding = "utf-8")- assert "dpkg-deb --extract" in script- assert "--runtime-file" in script- assert "linuxdeploy" not in script- assert "export LD_LIBRARY_PATH" not in script- for library in (- "libglib-2.0.so",- "libgio-2.0.so",- "libgtk-3.so",- "libwebkit2gtk-4.1.so",- "libcurl.so",- "libnghttp2.so",- ):- assert library in script- assert "sudo apt install libayatana-appindicator3-1 libwebkit2gtk-4.1-0 libgtk-3-0" in script- assert "libayatana-appindicator3.so.1 libappindicator3.so.1" in script- assert "libayatana-appindicator3.so libappindicator3.so" in script- assert "zenity --error" in script- assert "xmessage -center" in script---def test_thin_appimage_rejects_a_bundled_host_library(tmp_path):- allowed = tmp_path / "allowed"- allowed.mkdir()- (allowed / "libunsloth-test.so").touch()+ # Run the finalizer regardless of linuxdeploy plugin order.+ assert tool_script.count('"$plugin_dir/finalize-complete-appimage.sh" "$APPDIR"') == 1+ assert "for plugin in linuxdeploy-plugin-gtk.sh linuxdeploy-plugin-gstreamer.sh" in tool_script+++def _compile_fixture_elf(path: Path, *, origin_runpath: bool) -> None:+ args = ["cc", "-x", "c", "-", "-o", path]+ if origin_runpath:+ args.insert(-2, "-Wl,-rpath,$ORIGIN/../lib")subprocess.run(- [PACKAGER, "--verify-appdir", allowed],+ args,+ input = "int main(void) { return 0; }\n",check = True,- capture_output = True,text = True,- )-- forbidden = tmp_path / "forbidden"- forbidden.mkdir()- (forbidden / "libglib-2.0.so.0").touch()- result = subprocess.run(- [PACKAGER, "--verify-appdir", forbidden],- check = False,capture_output = True,- text = True,)- assert result.returncode != 0- assert "libglib-2.0.so.0" in result.stderr+def _fake_complete_appdir(tmp_path: Path) -> Path:+ appdir = tmp_path / "AppDir"+ binary = appdir / "usr/bin/unsloth-studio"+ binary.parent.mkdir(parents = True)+ _compile_fixture_elf(binary, origin_runpath = True)-def _build_fake_appimage(- tmp_path,- *,- bundle_markers = 1,- check = True,-):- package_root = tmp_path / "package"- control_dir = package_root / "DEBIAN"- binary_dir = package_root / "usr" / "bin"- desktop_dir = package_root / "usr" / "share" / "applications"- icon_dir = package_root / "usr" / "share" / "icons" / "hicolor" / "128x128" / "apps"- for directory in (control_dir, binary_dir, desktop_dir, icon_dir):- directory.mkdir(parents = True, exist_ok = True)-- (control_dir / "control").write_text(- "Package: unsloth-test\nVersion: 1.0\nArchitecture: amd64\nDescription: test\n",+ (appdir / "Unsloth.png").touch()+ (appdir / ".DirIcon").symlink_to("Unsloth.png")+ apprun = appdir / "AppRun"+ apprun.write_text(+ "#!/bin/sh\n"+ '. "$APPDIR/apprun-hooks/linuxdeploy-plugin-gtk.sh"\n'+ "unset LD_LIBRARY_PATH\n"+ "exit 0\n",+ encoding = "utf-8",+ )+ apprun.chmod(0o755)+ hook = appdir / "apprun-hooks/linuxdeploy-plugin-gtk.sh"+ hook.parent.mkdir()+ hook.write_text(+ "unset GIO_EXTRA_MODULES\n"+ 'export GIO_MODULE_DIR="$APPDIR/usr/lib/gio/modules"\n'+ 'export GTK_PATH="$APPDIR/usr/lib/gtk-3.0"\n',encoding = "utf-8",)- shutil.copy2("/bin/sh", binary_dir / "unsloth-studio")- with (binary_dir / "unsloth-studio").open("ab") as binary:- binary.write(b"__TAURI_BUNDLE_TYPE_VAR_DEB" * bundle_markers)- (desktop_dir / "Unsloth.desktop").write_text("[Desktop Entry]\n", encoding = "utf-8")- (icon_dir / "unsloth-studio.png").write_bytes(b"test")+ runtime = appdir / "usr/lib"+ runtime.mkdir(parents = True)+ for name in (+ "libglib-2.0.so.0",+ "libgobject-2.0.so.0",+ "libgio-2.0.so.0",+ "libgtk-3.so.0",+ "libgdk-3.so.0",+ "libgdk_pixbuf-2.0.so.0",+ "libwebkit2gtk-4.1.so.0",+ "libjavascriptcoregtk-4.1.so.0",+ "libsoup-3.0.so.0",+ "libappindicator3.so.1",+ "WebKitNetworkProcess",+ "WebKitWebProcess",+ "libwebkit2gtkinjectedbundle.so",+ ):+ (runtime / name).touch()++ gio_modules = runtime / "gio/modules"+ gio_modules.mkdir(parents = True)+ (gio_modules / "libgiognutls.so").touch()++ # WebKit's media pipeline is the bundled GStreamer core plus these plugins.+ gst_plugins = runtime / "gstreamer-1.0"+ gst_plugins.mkdir()+ for name in (+ "coreelements",+ "playback",+ "pulseaudio",+ "typefindfunctions",+ "isomp4",+ "videoparsersbad",+ "libav",+ ):+ (gst_plugins / f"libgst{name}.so").touch()+ for index in range(60):+ (gst_plugins / f"libgstfixture{index}.so").touch()+ scanner = runtime / "gstreamer1.0/gstreamer-1.0/gst-plugin-scanner"+ scanner.parent.mkdir(parents = True)+ scanner.touch()+ return appdir- deb_path = tmp_path / "unsloth-test.deb"- subprocess.run(- ["dpkg-deb", "--build", "--root-owner-group", package_root, deb_path],++def _write_foreign_arch_elf(path: Path) -> None:+ """An i386 ELF header, the shape a multilib build host contributes."""++ header = bytearray(52)+ header[0:8] = b"\x7fELF\x01\x01\x01\x00"+ header[16:18] = (3).to_bytes(2, "little") # e_type = ET_DYN+ header[18:20] = (3).to_bytes(2, "little") # e_machine = EM_386+ header[20:24] = (1).to_bytes(4, "little") # e_version+ header[40:42] = (52).to_bytes(2, "little") # e_ehsize+ path.write_bytes(bytes(header))+++def test_complete_appimage_verifier_accepts_a_coherent_runtime(tmp_path):+ result = subprocess.run(+ [VERIFIER, "--appdir", _fake_complete_appdir(tmp_path)],check = True,capture_output = True,text = True,)+ assert "Verified complete x86_64 AppImage runtime" in result.stdout- appimagetool = tmp_path / "appimagetool"- appimagetool.write_text(- """#!/usr/bin/env bash-set -euo pipefail-while [[ $# -gt 2 ]]; do shift; done-app_dir="$1"-output_path="$2"-captured_app_dir="${output_path}.AppDir"-cp -a "$app_dir" "$captured_app_dir"-printf '#!/usr/bin/env bash\nset -euo pipefail\ncp -a %q squashfs-root\n' "$captured_app_dir" > "$output_path"-chmod +x "$output_path"-""",++def test_complete_appimage_verifier_rejects_host_gtk_module_directories(tmp_path):+ appdir = _fake_complete_appdir(tmp_path)+ hook = appdir / "apprun-hooks/linuxdeploy-plugin-gtk.sh"+ hook.write_text(+ hook.read_text(encoding = "utf-8").replace(+ 'export GTK_PATH="$APPDIR/usr/lib/gtk-3.0"',+ 'export GTK_PATH="$APPDIR/usr/lib/gtk-3.0:/usr/lib64/gtk-3.0"',+ ),encoding = "utf-8",)- appimagetool.chmod(0o755)- runtime = tmp_path / "runtime"- runtime.touch()-- relative_output = Path("artifacts") / "unsloth-test.AppImage"result = subprocess.run(- [PACKAGER, deb_path, appimagetool, runtime, relative_output],- cwd = tmp_path,- check = check,- capture_output = True,- text = True,+ [VERIFIER, "--appdir", appdir], check = False, capture_output = True, text = True)+ assert result.returncode != 0+ assert "/usr/lib64/gtk-3.0" in result.stderr- output_path = tmp_path / relative_output- return output_path, Path(f"{output_path}.AppDir"), result---def test_thin_appimage_resolves_a_relative_output_before_verification(tmp_path):- output_path, _, result = _build_fake_appimage(tmp_path)-- assert output_path.is_file()- assert f"Built thin AppImage: {output_path}" in result.stdout---def test_thin_appimage_stamps_the_copied_deb_binary_as_an_appimage(tmp_path):- _, app_dir, _ = _build_fake_appimage(tmp_path)- binary = (app_dir / "usr" / "bin" / "unsloth-studio").read_bytes()-- assert b"__TAURI_BUNDLE_TYPE_VAR_DEB" not in binary- assert binary.count(b"__TAURI_BUNDLE_TYPE_VAR_APP") == 1+def test_complete_appimage_verifier_rejects_a_foreign_architecture_object(tmp_path):+ appdir = _fake_complete_appdir(tmp_path)+ _write_foreign_arch_elf(appdir / "usr/lib/gio/modules/libgiognutls.so")+ result = subprocess.run(+ [VERIFIER, "--appdir", appdir], check = False, capture_output = True, text = True+ )+ assert result.returncode != 0+ assert "wrong architecture" in result.stderr-def test_thin_appimage_rejects_an_unexpected_tauri_bundle_marker(tmp_path):- for bundle_markers in (0, 2):- _, _, result = _build_fake_appimage(- tmp_path / str(bundle_markers),- bundle_markers = bundle_markers,- check = False,- )- assert result.returncode != 0- assert "Expected exactly one Tauri deb bundle marker" in result.stderr---def test_thin_appimage_preserves_host_xdg_data_dirs(tmp_path):- _, app_dir, _ = _build_fake_appimage(tmp_path)- apprun = app_dir / "AppRun"- command = [apprun, "-c", 'printf %s "$XDG_DATA_DIRS"']-- fake_bin = tmp_path / "fake-bin"- fake_bin.mkdir()- ldconfig = fake_bin / "ldconfig"- ldconfig.write_text("#!/bin/sh\nexit 0\n", encoding = "utf-8")- ldconfig.chmod(0o755)- host_libraries = tmp_path / "host-libraries"- host_libraries.mkdir()- (host_libraries / "libayatana-appindicator3.so.1").symlink_to("/bin/sh")-- default_env = os.environ.copy()- default_env.pop("XDG_DATA_DIRS", None)- default_env["PATH"] = f"{fake_bin}:{default_env['PATH']}"- default_env["LD_LIBRARY_PATH"] = str(host_libraries)- default_result = subprocess.run(- command,- env = default_env,- check = True,- capture_output = True,- text = True,+def test_complete_appimage_verifier_requires_the_bundled_media_pipeline(tmp_path):+ appdir = _fake_complete_appdir(tmp_path)+ for plugin in (appdir / "usr/lib/gstreamer-1.0").glob("libgstfixture*.so"):+ plugin.unlink()+ result = subprocess.run(+ [VERIFIER, "--appdir", appdir], check = False, capture_output = True, text = True)- assert default_result.stdout == f"{app_dir}/usr/share:/usr/local/share:/usr/share"+ assert result.returncode != 0+ assert "GStreamer plugins" in result.stderr- custom_env = {**default_env, "XDG_DATA_DIRS": "/opt/share:/srv/share"}- custom_result = subprocess.run(- command,- env = custom_env,- check = True,- capture_output = True,- text = True,+ missing_scanner = _fake_complete_appdir(tmp_path / "no-scanner")+ (missing_scanner / "usr/lib/gstreamer1.0/gstreamer-1.0/gst-plugin-scanner").unlink()+ result = subprocess.run(+ [VERIFIER, "--appdir", missing_scanner], check = False, capture_output = True, text = True)- assert custom_result.stdout == f"{app_dir}/usr/share:/opt/share:/srv/share"-+ assert result.returncode != 0+ assert "gst-plugin-scanner" in result.stderr-def _fake_library_host(tmp_path, ldconfig_lines = ()):- """Stub the tools AppRun probes so the build machine's own libraries don't count.- The AppImage binary always resolves; any other library resolves only when a- test planted it under tmp_path. Without this the default-directory search- would find the real AppIndicator on any developer or CI box.- """- fake_bin = tmp_path / "fake-bin"- fake_bin.mkdir()- ldd = fake_bin / "ldd"- ldd.write_text(- "#!/bin/sh\n"- 'case "$1" in\n'- " */usr/bin/unsloth-studio) exit 0 ;;\n"- ' ./*) [ -e "$1" ] && exit 0 || exit 1 ;;\n'- " " + str(tmp_path) + '/*) [ -e "$1" ] && exit 0 || exit 1 ;;\n'- " *) exit 1 ;;\n"- "esac\n",+def test_complete_appimage_verifier_rejects_global_library_path_and_missing_origin_runpath(+ tmp_path,+):+ global_path = _fake_complete_appdir(tmp_path / "global-path")+ (global_path / "AppRun").write_text(+ '#!/bin/sh\nexport LD_LIBRARY_PATH="$APPDIR/usr/lib:${LD_LIBRARY_PATH:-}"\n',encoding = "utf-8",)- cache = "".join(f"printf '%s\\n' {shlex.quote(line)}\n" for line in ldconfig_lines)- (fake_bin / "ldconfig").write_text(f"#!/bin/sh\n{cache}exit 0\n", encoding = "utf-8")- for program in ("zenity", "xmessage"):- (fake_bin / program).write_text("#!/bin/sh\nexit 0\n", encoding = "utf-8")- for stub in fake_bin.iterdir():- stub.chmod(0o755)- return fake_bin---def _run_apprun(- app_dir,- fake_bin,- library_path,- *,- path = None,-):- return subprocess.run(- [app_dir / "AppRun", "-c", "exit 0"],- env = {- **os.environ,- "APPDIR": str(app_dir),- "LD_LIBRARY_PATH": str(library_path),- "PATH": path or f"{fake_bin}:{os.environ['PATH']}",- },+ result = subprocess.run(+ [VERIFIER, "--appdir", global_path], check = False, capture_output = True, text = True+ )+ assert result.returncode != 0+ assert "LD_LIBRARY_PATH" in result.stderr++ missing_runpath = _fake_complete_appdir(tmp_path / "missing-runpath")+ _compile_fixture_elf(missing_runpath / "usr/lib/WebKitWebProcess", origin_runpath = False)+ result = subprocess.run(+ [VERIFIER, "--appdir", missing_runpath],check = False,capture_output = True,text = True,)+ assert result.returncode != 0+ assert "$ORIGIN-relative RUNPATH" in result.stderr-def test_thin_appimage_reports_a_missing_dynamic_tray_library(tmp_path):- _, app_dir, _ = _build_fake_appimage(tmp_path)- result = _run_apprun(app_dir, _fake_library_host(tmp_path), tmp_path / "missing-libraries")+def test_apprun_hands_an_inherited_library_path_to_children_only(tmp_path):+ """The loader reads LD_LIBRARY_PATH before the bundle's own $ORIGIN RUNPATHs."""- assert result.returncode == 127- assert "libayatana-appindicator3.so.1 or libappindicator3.so.1" in result.stderr- assert "sudo apt install libayatana-appindicator3-1" in result.stderr+ appdir = tmp_path / "AppDir"+ binary = appdir / "usr/bin/unsloth-studio"+ binary.parent.mkdir(parents = True)+ binary.write_text("#!/bin/sh\nexec /usr/bin/env\n", encoding = "utf-8")+ binary.chmod(0o755)+ apprun = appdir / "AppRun"+ apprun.write_bytes(APPRUN.read_bytes())+ apprun.chmod(0o755)+ result = subprocess.run(+ [apprun],+ check = True,+ capture_output = True,+ text = True,+ env = {"PATH": "/usr/bin:/bin", "LD_LIBRARY_PATH": "/opt/conda/lib:/opt/rocm/lib"},+ )+ printed = result.stdout.splitlines()+ assert not [line for line in printed if line.startswith("LD_LIBRARY_PATH=")]+ assert "UNSLOTH_HOST_LD_LIBRARY_PATH=/opt/conda/lib:/opt/rocm/lib" in printed-# libappindicator-sys falls back from the versioned sonames to the unversioned-# ones, so rejecting those two would refuse a host whose tray works.-def test_thin_appimage_accepts_every_tray_library_name_the_loader_tries(tmp_path):- _, app_dir, _ = _build_fake_appimage(tmp_path)- fake_bin = _fake_library_host(tmp_path)- for library_name in (- "libayatana-appindicator3.so.1",- "libappindicator3.so.1",- "libayatana-appindicator3.so",- "libappindicator3.so",- ):- library_dir = tmp_path / f"host-{library_name}"- library_dir.mkdir()- (library_dir / library_name).symlink_to("/bin/sh")+def test_complete_appimage_verifier_rejects_a_launcher_that_keeps_the_host_library_path(tmp_path):+ appdir = _fake_complete_appdir(tmp_path)+ apprun = appdir / "AppRun"+ apprun.write_text(+ apprun.read_text(encoding = "utf-8").replace("unset LD_LIBRARY_PATH\n", ""),+ encoding = "utf-8",+ )+ result = subprocess.run(+ [VERIFIER, "--appdir", appdir], check = False, capture_output = True, text = True+ )+ assert result.returncode != 0+ assert "inherited LD_LIBRARY_PATH" in result.stderr- result = _run_apprun(app_dir, fake_bin, library_dir)- assert result.returncode == 0, f"{library_name}: {result.stderr}"+def test_complete_appimage_verifier_rejects_additive_host_gio_modules(tmp_path):+ appdir = _fake_complete_appdir(tmp_path)+ hook = appdir / "apprun-hooks/linuxdeploy-plugin-gtk.sh"+ hook.write_text('export GIO_MODULE_DIR="$APPDIR/usr/lib/gio/modules"\n', encoding = "utf-8")+ result = subprocess.run(+ [VERIFIER, "--appdir", appdir], check = False, capture_output = True, text = True+ )+ assert result.returncode != 0+ assert "host GIO_EXTRA_MODULES" in result.stderr-def test_thin_appimage_matches_loader_library_path_separators_and_empty_components(tmp_path):- _, app_dir, _ = _build_fake_appimage(tmp_path)- fake_bin = _fake_library_host(tmp_path)- library_dir = tmp_path / "host-libraries"- library_dir.mkdir()- (library_dir / "libayatana-appindicator3.so.1").symlink_to("/bin/sh")+def test_complete_appimage_verifier_requires_webkit_and_rejects_host_abi_libraries(tmp_path):+ missing = _fake_complete_appdir(tmp_path / "missing")+ (missing / "usr/lib/libwebkit2gtk-4.1.so.0").unlink()+ result = subprocess.run(+ [VERIFIER, "--appdir", missing], check = False, capture_output = True, text = True+ )+ assert result.returncode != 0+ assert "libwebkit2gtk-4.1.so" in result.stderr- for library_path in (- f"{tmp_path / 'missing'};{library_dir}",- f"{tmp_path / 'missing'}::{library_dir}",- f"{tmp_path / 'missing'}:",+ for library in (+ "libc.so.6",+ "libwayland-client.so.0",+ "libwayland-cursor.so.0",+ "libwayland-egl.so.1",+ "libwayland-server.so.0",+ "libGLESv2.so.2",+ "libnghttp2.so.14",+ "libcurl-gnutls.so.4",+ "libstdc++.so.6",+ "libgcc_s.so.1",):- if library_path.endswith(":"):- working_dir = tmp_path / "working-directory"- working_dir.mkdir()- (working_dir / "libayatana-appindicator3.so.1").symlink_to("/bin/sh")- else:- working_dir = tmp_path-+ bundled = _fake_complete_appdir(tmp_path / library)+ (bundled / "usr/lib" / library).touch()result = subprocess.run(- [app_dir / "AppRun", "-c", "exit 0"],- cwd = working_dir,- env = {- **os.environ,- "APPDIR": str(app_dir),- "LD_LIBRARY_PATH": str(library_path),- "PATH": f"{fake_bin}:{os.environ['PATH']}",- },+ [VERIFIER, "--appdir", bundled],check = False,capture_output = True,text = True,)-- assert result.returncode == 0, f"{library_path}: {result.stderr}"---# The loader commits to the first file it finds for a name, so a broken copy-# ahead of a working one must fail rather than skip ahead.-def test_thin_appimage_stops_at_a_broken_library_path_candidate(tmp_path):- _, app_dir, _ = _build_fake_appimage(tmp_path)- fake_bin = _fake_library_host(tmp_path)-- broken_dir = tmp_path / "broken-libraries"- broken_dir.mkdir()- (broken_dir / "libayatana-appindicator3.so.1").symlink_to("/bin/sh")- working_dir = tmp_path / "working-libraries"- working_dir.mkdir()- (working_dir / "libayatana-appindicator3.so.1").symlink_to("/bin/sh")-- ldd = fake_bin / "ldd"- ldd.write_text(- "#!/bin/sh\n"- 'case "$1" in\n'- " */usr/bin/unsloth-studio) exit 0 ;;\n"- " " + str(broken_dir) + "/*) printf '\\tlibmissing.so.0 => not found\\n'; exit 0 ;;\n"- " " + str(tmp_path) + '/*) [ -e "$1" ] && exit 0 || exit 1 ;;\n'- " *) exit 1 ;;\n"- "esac\n",- encoding = "utf-8",- )- ldd.chmod(0o755)-- result = _run_apprun(app_dir, fake_bin, f"{broken_dir}:{working_dir}")-- assert result.returncode == 127- assert "libayatana-appindicator3.so.1 or libappindicator3.so.1" in result.stderr---def test_thin_appimage_accepts_a_readable_tray_library_when_ldd_is_unavailable(tmp_path):- _, app_dir, _ = _build_fake_appimage(tmp_path)- fake_bin = _fake_library_host(tmp_path)- (fake_bin / "ldd").unlink()- sed = fake_bin / "sed"- sed.write_text("#!/bin/sh\nexit 0\n", encoding = "utf-8")- sed.chmod(0o755)- library_dir = tmp_path / "host-libraries"- library_dir.mkdir()- (library_dir / "libayatana-appindicator3.so.1").symlink_to("/bin/sh")-- result = _run_apprun(app_dir, fake_bin, library_dir, path = str(fake_bin))-- assert result.returncode == 0, result.stderr---# The cache is how a library outside LD_LIBRARY_PATH and the default directories-# gets found, so keep the ldconfig -p parsing covered.-def test_thin_appimage_finds_a_tray_library_through_the_ldconfig_cache(tmp_path):- _, app_dir, _ = _build_fake_appimage(tmp_path)- cached_dir = tmp_path / "cached-libraries"- cached_dir.mkdir()- cached_library = cached_dir / "libappindicator3.so.1"- cached_library.symlink_to("/bin/sh")- fake_bin = _fake_library_host(- tmp_path,- ldconfig_lines = (- "\tlibunrelated.so.1 (libc6,x86-64) => /usr/lib/libunrelated.so.1",- f"\tlibappindicator3.so.1 (libc6,x86-64) => {cached_library}",- ),- )-- result = _run_apprun(app_dir, fake_bin, tmp_path / "missing-libraries")-- assert result.returncode == 0, result.stderr---def test_release_notes_keep_existing_appimage_guidance():- notes = _workflow()["env"]["DESKTOP_RELEASE_NOTES"]- assert "`.AppImage` is experimental." in notes- assert "libwebkit2gtk" not in notes- assert "Linux AppImage on Ubuntu 24.04+ may require: `sudo apt install libfuse2t64`" in notes- assert "--appimage-extract-and-run" not in notes+ assert result.returncode != 0+ assert "host runtime component" in result.stderr-def test_thin_appimage_preserves_host_libraries_and_scrubs_python_overrides():- source_root = REPO_ROOT / "studio" / "src-tauri" / "src"+def test_managed_appimage_children_preserve_host_library_paths():+ source_root = REPO_ROOT / "studio/src-tauri/src"process_source = (source_root / "process.rs").read_text(encoding = "utf-8")child_process_calls = {source_root / "commands.rs": ("scrub_appimage_python_env_tokio(&mut cmd)", 1),source_root / "desktop_auth.rs": ("scrub_appimage_python_env_tokio(&mut cmd)", 1),source_root / "install.rs": ("scrub_appimage_python_env(&mut cmd)", 1),- source_root / "preflight" / "managed.rs": (- "scrub_appimage_python_env_tokio(&mut cmd)",- 2,- ),- source_root / "process.rs": ("scrub_appimage_python_env(&mut cmd)", 1),+ source_root / "preflight/managed.rs": ("scrub_appimage_python_env_tokio(&mut cmd)", 2),+ # One spawn path plus the unit tests that live in the same file.+ source_root / "process.rs": ("scrub_appimage_python_env(&mut cmd)", 4),source_root / "update.rs": ("scrub_appimage_python_env(&mut cmd)", 1),}+ assert "scrub_appimage_library_path" in process_source+ assert "split_paths" in process_source+ assert "starts_with(&appdir)" in process_source+ assert 'cmd.env_remove("PYTHONHOME")' in process_source+ assert 'cmd.env_remove("PYTHONPATH")' in process_source++ # The AppRun parks the host value under the name process.rs restores it from.+ assert "UNSLOTH_HOST_LD_LIBRARY_PATH" in APPRUN.read_text(encoding = "utf-8")+ assert "UNSLOTH_HOST_LD_LIBRARY_PATH" in process_source++ # Cover std children, Tokio children, and host launchers.+ production_source = process_source.split('#[cfg(all(test, target_os = "linux"))]', 1)[0]+ assert production_source.count("for name in APPIMAGE_GUI_ONLY_VARS") == 3+ for source_path, (call, expected) in child_process_calls.items():+ assert source_path.read_text(encoding = "utf-8").count(call) == expected- assert process_source.count('cmd.env_remove("PYTHONHOME")') == 2- assert process_source.count('cmd.env_remove("PYTHONPATH")') == 2- for source_path, (call, expected) in child_process_calls.items():- source = source_path.read_text(encoding = "utf-8")- assert source.count(call) == expected, source_path- assert 'cmd.env_remove("LD_LIBRARY_PATH")' not in source, source_path+def test_release_notes_recommend_native_deb_without_claiming_universality():+ notes = _workflow()["env"]["DESKTOP_RELEASE_NOTES"]+ assert "`.AppImage` is experimental." in notes+ assert "use `.deb` when available" in notes+ assert "universal" not in notes.lower()diff --git a/tests/security/test_release_desktop_signing_simulation.py b/tests/security/test_release_desktop_signing_simulation.pyindex 529a0ae09f8..c9d99a1c403 100644--- a/tests/security/test_release_desktop_signing_simulation.py+++ b/tests/security/test_release_desktop_signing_simulation.py@@ -199,7 +199,7 @@ def test_every_signing_cli_step_stays_windows_only():def test_other_platform_integrity_paths_are_untouched():names = [s.get("name") for s in workflow()["jobs"]["build"]["steps"]]- assert "Pin thin AppImage toolchain" in names+ assert "Pin complete AppImage toolchain" in namesassert "Import Apple certificate" in namesdiff --git a/tests/studio/appimage_media_pipeline_probe.py b/tests/studio/appimage_media_pipeline_probe.pynew file mode 100644index 00000000000..d21698e0c48--- /dev/null+++ b/tests/studio/appimage_media_pipeline_probe.py@@ -0,0 +1,151 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Decode H.264 frames with the AppImage's GStreamer on the target host."""++from __future__ import annotations++import ctypes+import os+import re+import shutil+import subprocess+import tempfile+from pathlib import Path++WIDTH, HEIGHT, FRAMES = 320, 240, 12+I420_FRAME_BYTES = WIDTH * HEIGHT * 3 // 2+GST_STATE_NULL, GST_STATE_PLAYING = 1, 4+GST_MESSAGE_EOS, GST_MESSAGE_ERROR = 1 << 0, 1 << 11+EXPORT = re.compile(r'^export ([A-Z0-9_]+)="([^"]*)"$')++# Cover the formats used by the media galleries.+REQUIRED_ELEMENTS = (+ "playbin",+ "decodebin",+ "qtdemux",+ "h264parse",+ "openh264enc",+ "avdec_h264",+ "vp8dec",+ "opusdec",+ "wavparse",+)+# Dictation may use either host audio stack.+CAPTURE_ELEMENTS = ("pulsesrc", "alsasrc")+++def _extract(appimage: Path, workdir: Path) -> Path:+ subprocess.run(+ [str(appimage), "--appimage-extract"],+ cwd = workdir,+ check = True,+ stdout = subprocess.DEVNULL,+ )+ return workdir / "squashfs-root"+++def _hook_environment(appdir: Path) -> dict[str, str]:+ """The GStreamer and GIO variables AppRun exports, read from the hooks."""++ wanted = {"GIO_MODULE_DIR"}+ environment: dict[str, str] = {}+ for hook in sorted((appdir / "apprun-hooks").glob("*.sh")):+ for line in hook.read_text(encoding = "utf-8", errors = "replace").splitlines():+ match = EXPORT.match(line.strip())+ if not match:+ continue+ name, value = match.groups()+ if not (name.startswith("GST_") or name in wanted):+ continue+ environment[name] = value.replace("${APPDIR}", str(appdir)).replace(+ "$APPDIR", str(appdir)+ )+ missing = {"GST_PLUGIN_SYSTEM_PATH_1_0", "GST_PLUGIN_SCANNER_1_0"} - environment.keys()+ if missing:+ raise SystemExit(f"AppRun hooks export no {', '.join(sorted(missing))}")+ return environment+++def main() -> None:+ appimage_value = os.environ.get("APPIMAGE_PATH", "")+ if not appimage_value:+ raise SystemExit("APPIMAGE_PATH must name the AppImage under test")+ appimage = Path(appimage_value).resolve()+ if not appimage.is_file():+ raise SystemExit(f"AppImage does not exist: {appimage}")++ workdir = Path(tempfile.mkdtemp(prefix = "unsloth-appimage-media."))+ try:+ appdir = _extract(appimage, workdir)+ os.environ.update(_hook_environment(appdir))+ os.environ.pop("GIO_EXTRA_MODULES", None)++ gst = ctypes.CDLL(str(appdir / "usr/lib/libgstreamer-1.0.so.0"))+ gst.gst_init(None, None)+ gst.gst_version_string.restype = ctypes.c_char_p+ gst.gst_element_factory_find.restype = ctypes.c_void_p+ gst.gst_element_factory_find.argtypes = [ctypes.c_char_p]+ gst.gst_parse_launch.restype = ctypes.c_void_p+ gst.gst_parse_launch.argtypes = [ctypes.c_char_p, ctypes.c_void_p]+ gst.gst_element_set_state.restype = ctypes.c_int+ gst.gst_element_set_state.argtypes = [ctypes.c_void_p, ctypes.c_int]+ gst.gst_element_get_bus.restype = ctypes.c_void_p+ gst.gst_element_get_bus.argtypes = [ctypes.c_void_p]+ gst.gst_bus_timed_pop_filtered.restype = ctypes.c_void_p+ gst.gst_bus_timed_pop_filtered.argtypes = [+ ctypes.c_void_p,+ ctypes.c_uint64,+ ctypes.c_int,+ ]++ print(f"bundled core: {gst.gst_version_string().decode()}")+ absent = [+ name for name in REQUIRED_ELEMENTS if not gst.gst_element_factory_find(name.encode())+ ]+ if not any(gst.gst_element_factory_find(name.encode()) for name in CAPTURE_ELEMENTS):+ absent.append(" or ".join(CAPTURE_ELEMENTS))+ if absent:+ raise SystemExit(+ "The bundled GStreamer registry is missing "+ f"{', '.join(absent)}: a bundled plugin did not load on this host"+ )++ decoded = workdir / "decoded.i420"+ pipeline_description = (+ f"videotestsrc num-buffers={FRAMES} ! "+ f"video/x-raw,width={WIDTH},height={HEIGHT},framerate=30/1 ! "+ "videoconvert ! video/x-raw,format=I420 ! openh264enc ! h264parse ! "+ "avdec_h264 ! videoconvert ! video/x-raw,format=I420 ! "+ f"filesink location={decoded}"+ )+ error = ctypes.c_void_p()+ pipeline = gst.gst_parse_launch(pipeline_description.encode(), ctypes.byref(error))+ if not pipeline:+ raise SystemExit(f"Could not build the media pipeline: {pipeline_description}")+ if gst.gst_element_set_state(pipeline, GST_STATE_PLAYING) == 0:+ raise SystemExit("The bundled media pipeline refused to start")+ bus = gst.gst_element_get_bus(pipeline)+ finished = gst.gst_bus_timed_pop_filtered(bus, 60 * 1_000_000_000, GST_MESSAGE_EOS)+ failed = gst.gst_bus_timed_pop_filtered(bus, 0, GST_MESSAGE_ERROR)+ gst.gst_element_set_state(pipeline, GST_STATE_NULL)+ if failed or not finished:+ raise SystemExit("The bundled media pipeline errored or never finished")++ size = decoded.stat().st_size if decoded.is_file() else 0+ frames, remainder = divmod(size, I420_FRAME_BYTES)+ if remainder or frames < FRAMES:+ raise SystemExit(+ f"avdec_h264 produced {size} bytes, expected {FRAMES} frames of "+ f"{I420_FRAME_BYTES} bytes"+ )+ print(+ f"PASS bundled GStreamer decoded {frames} H.264 frames "+ f"({size} bytes of I420) on this host"+ )+ finally:+ shutil.rmtree(workdir, ignore_errors = True)+++if __name__ == "__main__":+ main()diff --git a/tests/studio/appimage_model_download_webdriver.py b/tests/studio/appimage_model_download_webdriver.pynew file mode 100644index 00000000000..face256d367--- /dev/null+++ b/tests/studio/appimage_model_download_webdriver.py@@ -0,0 +1,659 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Exercise model download and cancellation through the packaged WebKitGTK view."""++from __future__ import annotations++import base64+import hashlib+import json+import os+import re+import shutil+import signal+import socket+import subprocess+import sys+import textwrap+import time+import urllib.error+import urllib.request+from pathlib import Path+from typing import Any+++from appimage_test_support import assert_no_loader_errors+++REPO_ID = "unsloth/FLUX.2-klein-4B-GGUF"+FILENAME = "FLUX.2-klein-4B-Q4_K_M.gguf"+MODEL_BYTES = 1_048_576+REPO_ROOT = Path(__file__).resolve().parents[2]+ART_DIR = Path(os.environ.get("APPIMAGE_E2E_ART_DIR", "logs/appimage-model-download"))+++def _free_port() -> int:+ with socket.socket() as sock:+ sock.bind(("127.0.0.1", 0))+ return int(sock.getsockname()[1])+++def _request(+ base: str,+ method: str,+ path: str,+ payload: object | None = None,+ *,+ timeout: float = 30,+) -> dict[str, Any]:+ body = None if payload is None else json.dumps(payload).encode("utf-8")+ request = urllib.request.Request(+ f"{base}{path}",+ data = body,+ method = method,+ headers = {"Content-Type": "application/json"},+ )+ try:+ with urllib.request.urlopen(request, timeout = timeout) as response:+ return json.load(response)+ except urllib.error.HTTPError as error:+ detail = error.read().decode("utf-8", errors = "replace")+ raise RuntimeError(f"WebDriver {method} {path} returned {error.code}: {detail}") from error+++def _execute(base: str, session_id: str, script: str) -> Any:+ response = _request(+ base,+ "POST",+ f"/session/{session_id}/execute/sync",+ {"script": script, "args": []},+ )+ return response.get("value")+++def _wait_for(+ base: str,+ session_id: str,+ script: str,+ description: str,+ *,+ timeout: float = 90,+) -> Any:+ deadline = time.monotonic() + timeout+ last: Any = None+ while time.monotonic() < deadline:+ try:+ last = _execute(base, session_id, script)+ if last:+ return last+ except Exception as error: # The webview can reload while startup hands off.+ last = str(error)+ time.sleep(0.25)+ raise AssertionError(f"Timed out waiting for {description}; last result: {last!r}")+++def _minimum_backend_version() -> str:+ source = (REPO_ROOT / "studio/src-tauri/src/preflight/version.rs").read_text(encoding = "utf-8")+ match = re.search(r'MIN_DESKTOP_BACKEND_VERSION: &str = "([^"]+)"', source)+ if not match:+ raise RuntimeError("Could not read MIN_DESKTOP_BACKEND_VERSION")+ return match.group(1)+++def _write_backend_fixture(home: Path, request_log: Path) -> None:+ fixture_dir = ART_DIR / "fixture"+ fixture_dir.mkdir(parents = True, exist_ok = True)+ server = fixture_dir / "backend.py"+ server.write_text(+ textwrap.dedent(+ f"""\+ import ctypes+ import hashlib+ import json+ import os+ import signal+ import sys+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+ from urllib.parse import parse_qs, urlparse++ # Do not leave the fixture bound after the app exits.+ ctypes.CDLL("libc.so.6").prctl(1, signal.SIGTERM)+ if os.getppid() == 1:+ raise SystemExit(0)++ REPO_ID = {REPO_ID!r}+ FILENAME = {FILENAME!r}+ MODEL_BYTES = {MODEL_BYTES}+ REQUEST_LOG = {str(request_log.resolve())!r}+ token = os.environ.get("UNSLOTH_STUDIO_DESKTOP_OWNER_TOKEN", "")+ root_path = os.path.expanduser("~/.unsloth/studio/share/studio_install_id")+ with open(root_path, encoding="utf-8") as handle:+ studio_root_id = handle.read().strip()+ owner = {{+ "kind": "tauri",+ "token_sha256": hashlib.sha256(token.encode()).hexdigest(),+ }}+ state = {{"started": False, "cancelled": False}}++ def record(method, path, payload=None):+ with open(REQUEST_LOG, "a", encoding="utf-8") as handle:+ handle.write(json.dumps({{"method": method, "path": path, "body": payload}}) + "\\n")++ class Handler(BaseHTTPRequestHandler):+ def log_message(self, *_args):+ return++ def read_json(self):+ length = int(self.headers.get("content-length", "0"))+ raw = self.rfile.read(length) if length else b"{{}}"+ return json.loads(raw or b"{{}}")++ def send_json(self, payload, status=200):+ raw = json.dumps(payload).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(raw)))+ self.send_header("Access-Control-Allow-Origin", "tauri://localhost")+ self.send_header("Access-Control-Allow-Headers", "Authorization, Content-Type, X-HF-Token")+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")+ self.end_headers()+ self.wfile.write(raw)++ def do_OPTIONS(self):+ self.send_response(204)+ self.send_header("Access-Control-Allow-Origin", "tauri://localhost")+ self.send_header("Access-Control-Allow-Headers", "Authorization, Content-Type, X-HF-Token")+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")+ self.end_headers()++ def do_GET(self):+ parsed = urlparse(self.path)+ path = parsed.path+ query = parse_qs(parsed.query)+ record("GET", path)+ if path in ("/api/liveness", "/api/health"):+ return self.send_json({{+ "status": "alive",+ "service": "Unsloth UI Backend",+ "version": {_minimum_backend_version()!r},+ "desktop_protocol_version": 1,+ "desktop_manageability_version": 2,+ "supports_desktop_auth": True,+ "supports_desktop_backend_ownership": True,+ "studio_root_id": studio_root_id,+ "desktop_owner": owner,+ "device_type": "cuda",+ "chat_only": False,+ "hardware_detecting": False,+ }})+ if path == "/api/system":+ device = {{+ "index": 0, "index_kind": "physical", "name": "AppImage E2E GPU",+ "memory_total_gb": 24, "vram_free_gb": 22,+ }}+ return self.send_json({{+ "platform": "Linux", "python_version": "3.11", "device_backend": "cuda",+ "uptime_seconds": 1,+ "cpu": {{"logical_count": 8, "physical_count": 4, "usage_percent": 1, "frequency_mhz": 3000}},+ "memory": {{"total_gb": 32, "available_gb": 24, "percent_used": 25, "process_used_mb": 128}},+ "disk": {{"total_gb": 100, "free_gb": 80, "percent_used": 20}},+ "gpu": {{"available": True, "backend": "cuda", "devices": [device]}},+ "inference_gpu": {{"available": True, "backend": "cuda", "devices": [device]}},+ "ml_packages": {{}},+ }})+ if path == "/api/inference/images/status":+ return self.send_json({{+ "loaded": False, "repo_id": None, "family": None, "base_repo": None,+ "device": None, "dtype": None, "model_kind": None, "workflows": [],+ }})+ if path == "/api/inference/images/load-progress":+ return self.send_json({{"phase": None, "bytes_downloaded": 0, "bytes_total": 0, "error": None}})+ if path == "/api/inference/images/generate-progress":+ return self.send_json({{"active": False, "step": 0, "total_steps": 0, "eta_seconds": None}})+ if path == "/api/inference/images/info":+ return self.send_json({{"families": []}})+ if path == "/api/inference/images/gallery":+ return self.send_json({{"images": [], "has_more": False}})+ if path == "/api/inference/monitor":+ return self.send_json({{"status": "idle", "active_model": None, "active_requests": 0, "entries": []}})+ if path == "/api/models/diffusion-loras":+ return self.send_json({{"loras": []}})+ if path == "/api/models/diffusion-controlnets":+ return self.send_json({{"controlnets": []}})+ if path == "/api/models/list":+ return self.send_json({{"models": [], "default_models": []}})+ if path == "/api/models/loras":+ return self.send_json({{"loras": [], "outputs_dir": "/tmp/outputs"}})+ if path == "/api/hub/local":+ return self.send_json({{"models_dir": "/tmp/models", "lmstudio_dirs": [], "models": []}})+ if path in ("/api/hub/cached-gguf", "/api/hub/cached-models"):+ return self.send_json({{"cached": []}})+ if path == "/api/hub/hidden-models":+ return self.send_json({{"patterns": []}})+ if path in ("/api/hub/active-downloads", "/api/hub/datasets/active-downloads"):+ return self.send_json({{"downloads": []}})+ if path in ("/api/hub/gguf-variants", "/api/models/gguf-variants"):+ return self.send_json({{+ "repo_id": REPO_ID,+ "variants": [{{+ "filename": FILENAME, "quant": "Q4_K_M",+ "size_bytes": MODEL_BYTES, "download_size_bytes": MODEL_BYTES,+ "downloaded": False,+ }}],+ "has_vision": False, "default_variant": "Q4_K_M", "context_length": None,+ }})+ if path == "/api/hub/download-status":+ job_state = (+ "cancelled" if state["cancelled"]+ else "running" if state["started"]+ else "idle"+ )+ return self.send_json({{+ "state": job_state, "error": None,+ "generation": 1 if state["started"] else None,+ }})++ if path == "/api/studio/download-transport-capabilities":+ return self.send_json({{+ "http": {{"available": True, "reason": None}},+ "xet": {{"available": False, "reason": "AppImage E2E uses HTTP"}},+ "auto_resolves_to": "http", "auto_reason": "deterministic E2E",+ }})+ if path in ("/api/hub/gguf-download-progress", "/api/hub/download-progress"):+ downloaded = 262144+ return self.send_json({{+ "downloaded_bytes": downloaded, "completed_bytes": downloaded,+ "complete_on_disk": False, "expected_bytes": MODEL_BYTES,+ "progress": downloaded / MODEL_BYTES, "cache_path": "/tmp/model-cache",+ }})+ if path == "/api/hub/transport-status":+ return self.send_json({{"has_partial": False, "last_transport": None, "resumable": False}})+ if path == "/api/settings/personalization":+ return self.send_json({{+ "version": 1,+ "profile": {{"displayName": "", "nickname": "", "avatarDataUrl": None, "avatarShape": "circle", "showGreetingSloth": True}},+ "appearance": {{"theme": "dark", "palette": "standard", "language": None, "customization": {{}}}},+ "saved": False, "customizationSaved": False, "paletteSaved": False, "greetingSlothSaved": False,+ }})+ if path == "/api/export/status":+ return self.send_json({{"current_checkpoint": None, "is_vision": False, "is_peft": False, "is_export_active": False}})+ if path in ("/api/chat/threads", "/api/chat/projects"):+ return self.send_json({{"threads": []}} if path.endswith("threads") else {{"projects": []}})+ return self.send_json({{}})++ def do_POST(self):+ path = urlparse(self.path).path+ payload = self.read_json()+ record("POST", path, payload)+ if path == "/api/auth/desktop-login":+ if payload.get("secret") == "desktop-owner-adoption-invalid-secret":+ return self.send_json({{"detail": "invalid desktop secret"}}, 401)+ return self.send_json({{+ "access_token": "appimage-e2e-access", "refresh_token": "appimage-e2e-refresh",+ "token_type": "bearer", "must_change_password": False,+ }})+ if path == "/api/inference/images/download-plan":+ return self.send_json({{+ "entries": [{{"repo_id": REPO_ID, "files": [FILENAME], "bytes": MODEL_BYTES, "gguf_filename": FILENAME}}],+ "total_bytes": MODEL_BYTES, "required_bytes": MODEL_BYTES, "checkpoint_bytes": MODEL_BYTES,+ }})+ if path == "/api/hub/download":+ state["started"] = True+ state["cancelled"] = False+ return self.send_json({{+ "job_key": f"model:{{REPO_ID}}:Q4_K_M", "accepted": True,+ "state": "running", "generation": 1, "transport": "http", "cancel_transport": None,+ }}, 202)+ if path == "/api/hub/download/cancel":+ state["cancelled"] = True+ return self.send_json({{"job_key": f"model:{{REPO_ID}}:Q4_K_M", "state": "cancelled"}}, 202)+ return self.send_json({{}})++ requested_port = int(sys.argv[1])+ server = ThreadingHTTPServer(("127.0.0.1", requested_port), Handler)+ print(f"TAURI_PORT={{server.server_port}}", flush=True)+ server.serve_forever()+ """+ ),+ encoding = "utf-8",+ )++ managed_bin = home / ".unsloth/studio/unsloth_studio/bin/unsloth"+ managed_bin.parent.mkdir(parents = True, exist_ok = True)+ managed_bin.write_text(+ textwrap.dedent(+ f"""\+ #!/usr/bin/env bash+ set -euo pipefail+ if [[ "${{1:-}}" == "-h" ]]; then exit 0; fi+ if [[ "$*" == *"desktop-capabilities"* ]]; then+ printf '%s\\n' '{json.dumps({+ "desktop_protocol_version": 1,+ "desktop_manageability_version": 2,+ "supports_api_only": True,+ "supports_provision_desktop_auth": True,+ "supports_desktop_backend_ownership": True,+ "studio_install_ok": True,+ "version": _minimum_backend_version(),+ }, separators = (",", ":"))}'+ exit 0+ fi+ if [[ "$*" == *"provision-desktop-auth"* ]]; then+ mkdir -p "$HOME/.unsloth/studio/auth"+ printf 'appimage-e2e-secret' > "$HOME/.unsloth/studio/auth/.desktop_secret"+ chmod 600 "$HOME/.unsloth/studio/auth/.desktop_secret"+ exit 0+ fi+ if [[ "$*" == *"studio"*"--api-only"* ]]; then+ port=8888+ while [[ $# -gt 0 ]]; do+ if [[ "$1" == "-p" ]]; then port="$2"; break; fi+ shift+ done+ exec /usr/bin/python3 {str(server.resolve())!r} "$port"+ fi+ exit 1+ """+ ),+ encoding = "utf-8",+ )+ managed_bin.chmod(0o755)+++def _request_log_contains(request_log: Path, path: str) -> bool:+ if not request_log.is_file():+ return False+ return any(+ json.loads(line).get("method") == "POST" and json.loads(line).get("path") == path+ for line in request_log.read_text(encoding = "utf-8").splitlines()+ if line.strip()+ )+++def main() -> None:+ appimage_value = os.environ.get("APPIMAGE_PATH", "")+ if not appimage_value:+ raise SystemExit("APPIMAGE_PATH must name the AppImage under test")+ appimage = Path(appimage_value).resolve()+ if not appimage.is_file():+ raise SystemExit(f"AppImage does not exist: {appimage}")+ tauri_driver = shutil.which("tauri-driver")+ native_driver = shutil.which("WebKitWebDriver")+ if not tauri_driver or not native_driver:+ raise SystemExit("tauri-driver and WebKitWebDriver must both be on PATH")++ if ART_DIR.exists():+ shutil.rmtree(ART_DIR)+ ART_DIR.mkdir(parents = True)+ home = ART_DIR.resolve() / "home"+ runtime_dir = ART_DIR.resolve() / "runtime"+ config_dir = home / ".config"+ data_dir = home / ".local/share"+ cache_dir = home / ".cache"+ state_dir = home / ".local/state"+ runtime_dir.mkdir(parents = True)+ config_dir.mkdir(parents = True)+ data_dir.mkdir(parents = True)+ cache_dir.mkdir(parents = True)+ state_dir.mkdir(parents = True)+ request_log = ART_DIR.resolve() / "backend-requests.jsonl"+ _write_backend_fixture(home, request_log)++ driver_port = _free_port()+ native_port = _free_port()+ while native_port == driver_port:+ native_port = _free_port()+ base = f"http://127.0.0.1:{driver_port}"+ driver_log = (ART_DIR / "tauri-driver.log").open("wb")+ env = {+ **os.environ,+ "HOME": str(home),+ "XDG_CONFIG_HOME": str(config_dir),+ "XDG_DATA_HOME": str(data_dir),+ "XDG_CACHE_HOME": str(cache_dir),+ "XDG_STATE_HOME": str(state_dir),+ "XDG_RUNTIME_DIR": str(runtime_dir),+ "APPIMAGE_EXTRACT_AND_RUN": "1",+ "WEBKIT_DISABLE_DMABUF_RENDERER": "1",+ "G_MESSAGES_DEBUG": "all",+ }+ process = subprocess.Popen(+ [+ tauri_driver,+ "--port",+ str(driver_port),+ "--native-port",+ str(native_port),+ "--native-driver",+ native_driver,+ ],+ stdout = driver_log,+ stderr = subprocess.STDOUT,+ env = env,+ start_new_session = True,+ )+ session_id: str | None = None+ try:+ deadline = time.monotonic() + 30+ while time.monotonic() < deadline:+ if process.poll() is not None:+ raise RuntimeError(f"tauri-driver exited early with {process.returncode}")+ try:+ _request(base, "GET", "/status", timeout = 1)+ break+ except Exception:+ time.sleep(0.25)+ else:+ raise RuntimeError("tauri-driver did not open its HTTP port")++ capabilities = {+ "capabilities": {+ "alwaysMatch": {+ "browserName": "wry",+ "tauri:options": {"application": str(appimage)},+ }+ }+ }+ created = _request(base, "POST", "/session", capabilities, timeout = 60)+ session_id = str(created["value"]["sessionId"])++ _wait_for(+ base,+ session_id,+ "return document.body && document.body.innerText.includes('Starting Unsloth')",+ "the packaged frontend to render",+ )+ _wait_for(+ base,+ session_id,+ "return document.body && !document.body.innerText.includes('Starting Unsloth')",+ "the deterministic desktop backend handoff",+ )+ clicked = _wait_for(+ base,+ session_id,+ "const direct=document.querySelector('[data-testid=\"nav-row-images\"]'); if(direct){direct.click(); return 'direct';} const more=[...document.querySelectorAll('button')].find((e)=>(e.innerText||'').trim()==='More'); if(more){more.click(); return 'more';} return false;",+ "the rendered Images sidebar destination",+ )+ assert clicked, "Could not find the Images sidebar destination"+ if clicked == "more":+ clicked = _wait_for(+ base,+ session_id,+ "const e=[...document.querySelectorAll('[role=menuitem]')].find((x)=>(x.innerText||'').trim()==='Images'); if(e){e.click(); return true;} return false;",+ "the Images destination in the More menu",+ )+ assert clicked, "Could not click Images in the More menu"+ _wait_for(+ base,+ session_id,+ "return location.pathname === '/images'",+ "the Images route",+ )+ _wait_for(+ base,+ session_id,+ "return [...document.querySelectorAll('button')].some((b) => (b.innerText || b.getAttribute('aria-label') || '').includes('Select image model'))",+ "the Images model picker",+ )+ clicked = _execute(+ base,+ session_id,+ "const b=[...document.querySelectorAll('button')].find((e)=>(e.innerText||e.getAttribute('aria-label')||'').includes('Select image model')); if(b)b.click(); return !!b;",+ )+ assert clicked, "Could not click Select image model"+ _wait_for(+ base,+ session_id,+ "return document.querySelector('.unsloth-model-selector-menu')?.innerText.includes('FLUX.2')",+ "the seeded FLUX model row",+ )+ clicked = _execute(+ base,+ session_id,+ "const root=document.querySelector('.unsloth-model-selector-menu'); const rows=[...root.querySelectorAll('button')].filter((b)=>/FLUX\\.2[\\s-]klein[\\s-]4B/i.test(b.innerText||'')).sort((a,b)=>(a.innerText||'').length-(b.innerText||'').length); const row=rows[0]; if(row)row.click(); return row?.innerText||false;",+ )+ assert clicked, "Could not click the seeded FLUX model row"++ # Some catalog states show a format level before the quantization level.+ time.sleep(0.25)+ _execute(+ base,+ session_id,+ "const b=[...document.querySelectorAll('button')].find((e)=>(e.innerText||'').trim()==='GGUF'); if(b)b.click(); return !!b;",+ )+ _wait_for(+ base,+ session_id,+ "return [...document.querySelectorAll('button')].some((b)=>(b.innerText||'').includes('Q4_K_M'))",+ "the Q4_K_M quantization",+ timeout = 15,+ )+ clicked = _execute(+ base,+ session_id,+ "const b=[...document.querySelectorAll('button')].find((e)=>(e.innerText||'').includes('Q4_K_M')); if(b)b.click(); return !!b;",+ )+ assert clicked, "Could not click Q4_K_M"++ _wait_for(+ base,+ session_id,+ f"return {str(request_log)!r} && true",+ "the model download request",+ timeout = 1,+ )+ deadline = time.monotonic() + 30+ while time.monotonic() < deadline and not _request_log_contains(+ request_log, "/api/hub/download"+ ):+ time.sleep(0.25)+ assert _request_log_contains(+ request_log, "/api/hub/download"+ ), "The packaged webview never sent POST /api/hub/download"++ _wait_for(+ base,+ session_id,+ "return [...document.querySelectorAll('button')].some((b)=>(b.innerText||b.getAttribute('aria-label')||'').includes('Cancel download'))",+ "visible model download progress and its cancel button",+ timeout = 30,+ )+ clicked = _execute(+ base,+ session_id,+ "const b=[...document.querySelectorAll('button')].find((e)=>(e.innerText||e.getAttribute('aria-label')||'').includes('Cancel download')); if(b)b.click(); return !!b;",+ )+ assert clicked, "Could not click Cancel download"+ deadline = time.monotonic() + 15+ while time.monotonic() < deadline and not _request_log_contains(+ request_log, "/api/hub/download/cancel"+ ):+ time.sleep(0.25)+ assert _request_log_contains(+ request_log, "/api/hub/download/cancel"+ ), "The packaged webview never sent POST /api/hub/download/cancel"++ _wait_for(+ base,+ session_id,+ "return document.body?.innerText.includes('Cancelled. Partial files kept.')",+ "the packaged UI to confirm cancellation",+ timeout = 15,+ )++ # Verify the packaged WebKit view exposes the required media formats.+ media = json.loads(+ _execute(+ base,+ session_id,+ "const v=document.createElement('video'); const a=document.createElement('audio');"+ "return JSON.stringify({"+ "mp4:v.canPlayType('video/mp4'), webm:v.canPlayType('video/webm'),"+ "wav:a.canPlayType('audio/wav'),"+ "capture:!!(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia)});",+ )+ )+ (ART_DIR / "media-support.json").write_text(json.dumps(media, indent = 2), encoding = "utf-8")+ for media_type in ("mp4", "webm", "wav"):+ assert media[media_type], f"The packaged webview cannot play {media_type}: {media}"+ assert media["capture"], f"The packaged webview exposes no capture device API: {media}"++ screenshot = _request(base, "GET", f"/session/{session_id}/screenshot")+ (ART_DIR / "model-download-cancelled.png").write_bytes(+ base64.b64decode(screenshot["value"])+ )+ body = _execute(base, session_id, "return document.body.innerText")+ (ART_DIR / "webview-body.txt").write_text(str(body), encoding = "utf-8")+ assert_no_loader_errors(+ ART_DIR / "tauri-driver.log",+ home / ".unsloth/studio/tauri.log",+ )++ print("PASS packaged AppImage model picker sent download, rendered progress, and cancelled")+ except Exception:+ if session_id:+ try:+ screenshot = _request(base, "GET", f"/session/{session_id}/screenshot", timeout = 10)+ (ART_DIR / "failure.png").write_bytes(base64.b64decode(screenshot["value"]))+ snapshot = _execute(+ base,+ session_id,+ "return {url:location.href,title:document.title,body:document.body?.innerText||'',html:document.body?.innerHTML||''};",+ )+ (ART_DIR / "failure-webview.json").write_text(+ json.dumps(snapshot, indent = 2), encoding = "utf-8"+ )+ except Exception as evidence_error:+ (ART_DIR / "failure-evidence-error.txt").write_text(+ str(evidence_error), encoding = "utf-8"+ )+ raise++ finally:+ if session_id:+ try:+ _request(base, "DELETE", f"/session/{session_id}", timeout = 10)+ except Exception:+ pass+ if process.poll() is None:+ os.killpg(process.pid, signal.SIGTERM)+ try:+ process.wait(timeout = 10)+ except subprocess.TimeoutExpired:+ os.killpg(process.pid, signal.SIGKILL)+ process.wait(timeout = 10)+ driver_log.close()+ tauri_log = home / ".unsloth/studio/tauri.log"+ if tauri_log.is_file():+ shutil.copy2(tauri_log, ART_DIR / "tauri.log")+++if __name__ == "__main__":+ try:+ main()+ except Exception:+ # Preserve the rendered text whenever a late assertion fails.+ print(f"AppImage E2E evidence: {ART_DIR.resolve()}", file = sys.stderr)+ raisediff --git a/tests/studio/appimage_portability_smoke.py b/tests/studio/appimage_portability_smoke.pynew file mode 100644index 00000000000..b2a1a8c8263--- /dev/null+++ b/tests/studio/appimage_portability_smoke.py@@ -0,0 +1,318 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Reach desktop auth without a host GTK or WebKit runtime."""++from __future__ import annotations++import hashlib+import json+import os+import shutil+import signal+import subprocess+import sys+import textwrap+import time+from pathlib import Path++from appimage_test_support import assert_no_loader_errors++ROOT_ID = "a" * 64+DESKTOP_SECRET = "appimage-portability-secret"+++def _minimum_backend_version(repo_root: Path) -> str:+ source = (repo_root / "studio/src-tauri/src/preflight/version.rs").read_text(encoding = "utf-8")+ marker = 'MIN_DESKTOP_BACKEND_VERSION: &str = "'+ start = source.find(marker)+ if start < 0:+ raise RuntimeError("Could not read the minimum desktop backend version")+ start += len(marker)+ return source[start : source.index('"', start)]+++def _write_fixture(art_dir: Path, home: Path, version: str) -> Path:+ request_log = art_dir / "backend-requests.jsonl"+ backend = art_dir / "backend.py"+ backend.write_text(+ textwrap.dedent(+ f"""\+ import ctypes+ import hashlib+ import json+ import os+ import signal+ import sys+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++ # Do not leave the fixture bound after the app exits.+ ctypes.CDLL("libc.so.6").prctl(1, signal.SIGTERM)+ if os.getppid() == 1:+ raise SystemExit(0)++ LOG = {str(request_log)!r}+ ROOT_ID = {ROOT_ID!r}+ VERSION = {version!r}+ token = os.environ.get("UNSLOTH_STUDIO_DESKTOP_OWNER_TOKEN", "")+ owner = {{+ "kind": "tauri",+ "token_sha256": hashlib.sha256(token.encode()).hexdigest(),+ }}++ class Handler(BaseHTTPRequestHandler):+ def log_message(self, *_args):+ return++ def record(self, method):+ length = int(self.headers.get("content-length", "0"))+ body = self.rfile.read(length).decode(errors="replace") if length else ""+ with open(LOG, "a", encoding="utf-8") as handle:+ handle.write(json.dumps({{"method": method, "path": self.path, "body": body}}) + "\\n")++ def send_json(self, payload, status=200):+ raw = json.dumps(payload).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(raw)))+ self.send_header("Access-Control-Allow-Origin", "tauri://localhost")+ self.send_header("Access-Control-Allow-Headers", "Authorization, Content-Type")+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")+ self.end_headers()+ self.wfile.write(raw)++ def do_OPTIONS(self):+ self.send_json({{}}, 204)++ def do_GET(self):+ self.record("GET")+ if self.path.startswith(("/api/liveness", "/api/health")):+ return self.send_json({{+ "status": "alive",+ "service": "Unsloth UI Backend",+ "version": VERSION,+ "desktop_protocol_version": 1,+ "desktop_manageability_version": 2,+ "supports_desktop_auth": True,+ "supports_desktop_backend_ownership": True,+ "studio_root_id": ROOT_ID,+ "desktop_owner": owner,+ "chat_only": False,+ "hardware_detecting": False,+ }})+ if self.path.startswith("/api/system"):+ return self.send_json({{"device_type": "cpu", "chat_only": False}})+ return self.send_json({{}})++ def do_POST(self):+ self.record("POST")+ if self.path.startswith("/api/auth/desktop-login"):+ return self.send_json({{+ "access_token": "portability-access",+ "refresh_token": "portability-refresh",+ "token_type": "bearer",+ "must_change_password": False,+ }})+ return self.send_json({{}})++ port = int(sys.argv[1])+ server = ThreadingHTTPServer(("127.0.0.1", port), Handler)+ print(f"TAURI_PORT={{server.server_port}}", flush=True)+ server.serve_forever()+ """+ ),+ encoding = "utf-8",+ )++ managed_bin = home / ".unsloth/studio/unsloth_studio/bin/unsloth"+ managed_bin.parent.mkdir(parents = True, exist_ok = True)+ managed_bin.write_text(+ textwrap.dedent(+ f"""\+ #!/usr/bin/env bash+ set -euo pipefail+ if [[ "${{1:-}}" == "-h" ]]; then exit 0; fi+ if [[ "$*" == *"desktop-capabilities"* ]]; then+ printf '%s\\n' '{json.dumps({+ "desktop_protocol_version": 1,+ "desktop_manageability_version": 2,+ "supports_api_only": True,+ "supports_provision_desktop_auth": True,+ "supports_desktop_backend_ownership": True,+ "studio_install_ok": True,+ "version": version,+ }, separators = (",", ":"))}'+ exit 0+ fi+ if [[ "$*" == *"provision-desktop-auth"* ]]; then+ mkdir -p "$HOME/.unsloth/studio/auth"+ printf '%s' {DESKTOP_SECRET!r} > "$HOME/.unsloth/studio/auth/.desktop_secret"+ chmod 600 "$HOME/.unsloth/studio/auth/.desktop_secret"+ exit 0+ fi+ if [[ "$*" == *"studio"*"--api-only"* ]]; then+ port=8888+ while [[ $# -gt 0 ]]; do+ if [[ "$1" == "-p" ]]; then port="$2"; break; fi+ shift+ done+ exec /usr/bin/python3 {str(backend)!r} "$port"+ fi+ exit 1+ """+ ),+ encoding = "utf-8",+ )+ managed_bin.chmod(0o755)+ return request_log+++def main() -> None:+ repo_root = Path(__file__).resolve().parents[2]+ appimage_value = os.environ.get("APPIMAGE_PATH", "")+ if not appimage_value:+ raise SystemExit("APPIMAGE_PATH must name the AppImage under test")+ appimage = Path(appimage_value).resolve()+ if not appimage.is_file():+ raise SystemExit(f"AppImage does not exist: {appimage}")+ display_backend = os.environ.get("APPIMAGE_DISPLAY_BACKEND", "x11")+ if display_backend not in {"x11", "wayland"}:+ raise SystemExit(f"Unsupported APPIMAGE_DISPLAY_BACKEND: {display_backend}")+ display_tool = "weston" if display_backend == "wayland" else "xvfb-run"+ if not shutil.which(display_tool):+ raise SystemExit(f"{display_tool} is required for {display_backend} smoke")++ art_dir = Path(os.environ.get("APPIMAGE_SMOKE_ART_DIR", "logs/appimage-portability")).resolve()+ if art_dir.exists():+ shutil.rmtree(art_dir)+ art_dir.mkdir(parents = True)+ home = art_dir / "home"+ runtime = art_dir / "runtime"+ config = art_dir / "config"+ data = art_dir / "data"+ cache = art_dir / "cache"+ state = art_dir / "state"+ for directory in (runtime, config, data, cache, state):+ directory.mkdir(parents = True)+ runtime.chmod(0o700)+ install_id = home / ".unsloth/studio/share/studio_install_id"+ install_id.parent.mkdir(parents = True)+ install_id.write_text(ROOT_ID, encoding = "utf-8")+ request_log = _write_fixture(art_dir, home, _minimum_backend_version(repo_root))++ env = {+ **os.environ,+ "HOME": str(home),+ "XDG_CONFIG_HOME": str(config),+ "XDG_DATA_HOME": str(data),+ "XDG_CACHE_HOME": str(cache),+ "XDG_STATE_HOME": str(state),+ "XDG_RUNTIME_DIR": str(runtime),+ "APPIMAGE_EXTRACT_AND_RUN": "1",+ "NO_AT_BRIDGE": "1",+ "LIBGL_ALWAYS_SOFTWARE": "1",+ "GALLIUM_DRIVER": "llvmpipe",+ "G_MESSAGES_DEBUG": "all",+ }+ weston: subprocess.Popen[bytes] | None = None+ weston_log = None+ if display_backend == "wayland":+ env["GDK_BACKEND"] = "wayland"+ env["WAYLAND_DISPLAY"] = "wayland-ci"+ weston_log = (art_dir / "weston.log").open("wb")++ weston_help = subprocess.run(+ ["weston", "--help"], capture_output = True, check = False, text = True+ )+ help_text = weston_help.stdout + weston_help.stderr+ software_renderer = "--renderer=pixman" if "--renderer" in help_text else "--use-pixman"+ weston = subprocess.Popen(+ [+ "weston",+ "--backend=headless-backend.so",+ software_renderer,+ "--socket=wayland-ci",+ "--idle-time=0",+ ],+ stdout = weston_log,+ stderr = subprocess.STDOUT,+ env = env,+ start_new_session = True,+ )+ socket = runtime / "wayland-ci"+ deadline = time.monotonic() + 15+ while time.monotonic() < deadline and not socket.exists():+ if weston.poll() is not None:+ raise RuntimeError(f"Weston exited early with {weston.returncode}")+ time.sleep(0.1)+ if not socket.exists():+ raise RuntimeError("Weston did not create its Wayland socket")+ stdout = (art_dir / "app-stdout.log").open("wb")+ command = [str(appimage)]+ if display_backend == "x11":+ command = [+ "xvfb-run",+ "-a",+ "--server-args=-screen 0 1440x900x24",+ str(appimage),+ ]+ process = subprocess.Popen(+ command,+ stdout = stdout,+ stderr = subprocess.STDOUT,+ env = env,+ start_new_session = True,+ )+ try:+ deadline = time.monotonic() + 45+ while time.monotonic() < deadline:+ if process.poll() is not None:+ raise RuntimeError(f"AppImage exited early with {process.returncode}")+ if request_log.is_file():+ requests = request_log.read_text(encoding = "utf-8")+ if '"path": "/api/auth/desktop-login"' in requests:+ stdout.flush()+ assert_no_loader_errors(+ art_dir / "app-stdout.log",+ home / ".unsloth/studio/tauri.log",+ )+ print(+ "PASS complete AppImage rendered startup and completed desktop auth "+ f"on {display_backend}"+ )+ return+ time.sleep(0.25)+ raise RuntimeError("Packaged webview never completed desktop authentication")+ finally:+ if process.poll() is None:+ os.killpg(process.pid, signal.SIGTERM)+ try:+ process.wait(timeout = 10)+ except subprocess.TimeoutExpired:+ os.killpg(process.pid, signal.SIGKILL)+ process.wait(timeout = 10)+ stdout.close()++ if weston is not None and weston.poll() is None:+ os.killpg(weston.pid, signal.SIGTERM)+ try:+ weston.wait(timeout = 5)+ except subprocess.TimeoutExpired:+ os.killpg(weston.pid, signal.SIGKILL)+ weston.wait(timeout = 5)+ if weston_log is not None:+ weston_log.close()+ tauri_log = home / ".unsloth/studio/tauri.log"+ if tauri_log.is_file():+ shutil.copy2(tauri_log, art_dir / "tauri.log")+++if __name__ == "__main__":+ try:+ main()+ except Exception:+ print(+ f"AppImage portability evidence: {os.environ.get('APPIMAGE_SMOKE_ART_DIR', 'logs/appimage-portability')}",+ file = sys.stderr,+ )+ raisediff --git a/tests/studio/appimage_test_support.py b/tests/studio/appimage_test_support.pynew file mode 100644index 00000000000..accf175b03d--- /dev/null+++ b/tests/studio/appimage_test_support.py@@ -0,0 +1,30 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Shared assertions for packaged Linux AppImage smoke tests."""++from __future__ import annotations++from pathlib import Path+++LOADER_ERROR_MARKERS = (+ "Failed to load module:",+ "undefined symbol:",+)+++def assert_no_loader_errors(*logs: Path) -> None:+ """Reject mixed host/bundle loader failures even when the UI path succeeds."""++ failures: list[str] = []+ for log in logs:+ if not log.is_file():+ continue+ for line in log.read_text(encoding = "utf-8", errors = "replace").splitlines():+ if any(marker in line for marker in LOADER_ERROR_MARKERS):+ failures.append(f"{log.name}: {line}")+ if failures:+ raise RuntimeError(+ "AppImage mixed host and bundled runtime libraries:\n" + "\n".join(failures)+ )