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
Revert "Desktop: ship a complete Linux AppImage (#8695)" (#8823)
Wasim Yousef Said83e163f13c35
diff --git a/.github/workflows/desktop-app-clean-machine-ci.yml b/.github/workflows/desktop-app-clean-machine-ci.ymlindex 537d54caf04..9d046a2cb53 100644--- a/.github/workflows/desktop-app-clean-machine-ci.yml+++ b/.github/workflows/desktop-app-clean-machine-ci.yml@@ -25,17 +25,10 @@ on:pull_request:paths:- '.github/workflows/desktop-app-clean-machine-ci.yml'+- '.github/scripts/resolve-desktop-release.py'- '.github/scripts/clean-machine-env.sh'- '.github/scripts/clean-machine-assert.sh'- - '.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_model_download_webdriver.py'workflow_dispatch:inputs:release_tag:@@ -409,9 +402,8 @@ 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 libgles2 libgl1 libegl1 libgbm1 libwayland-client0 \- libharfbuzz0b libnghttp2-14 fontconfig libfribidi0+ sudo apt-get install -y -qq --no-install-recommends libfuse2 \+ libwebkit2gtk-4.1-0 libgtk-3-0 libayatana-appindicator3-1 || truechmod +x dl/*.AppImageBIN="$(ls dl/*.AppImage | head -1)"fi@@ -564,307 +556,6 @@ jobs:retention-days: 7if-no-files-found: warn- # Build the checked-out PR once without signing or release credentials. Every- # PR artifact test below consumes this exact file, including fork PRs.- 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- run: |- sudo apt-get update -qq- sudo apt-get install -y -qq \- libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev \- libxdo-dev libssl-dev patchelf xdg-utils-- - 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--- # Complete AppImage portability is separate from the native .deb lane above:- # these images deliberately have no host GTK/WebKitGTK/JavaScriptCore/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}- - {label: ubuntu-24.04-wayland, image: 'ubuntu:24.04', display_backend: wayland}- - {label: debian-12, image: 'debian:12', display_backend: x11}- - {label: fedora-44, image: 'fedora:44', display_backend: x11}-- steps:- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- with:- persist-credentials: false-- - name: Install only generic display and graphics prerequisites- run: |- set -euo pipefail- if command -v apt-get >/dev/null 2>&1; then- apt-get update -qq- DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \- ca-certificates python3 xvfb xauth binutils libgles2 libgl1 libegl1 libgbm1 \- libwayland-client0 libharfbuzz0b libnghttp2-14 fontconfig libfribidi0- 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-libGLES mesa-libEGL mesa-libgbm mesa-dri-drivers mesa-libGL \- libwayland-client libnghttp2 harfbuzz fontconfig fribidi procps-ng findutils- forbidden="$(rpm -qa | grep -Ei 'webkit|javascriptcore|appindicator|gtk3' || true)"- 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"- 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 needs the host's driver package. PR runs consume the same unsigned- # branch-built AppImage as the portability matrix; other events test the shipped artifact.- # a rendered window is not enough unless WebKit can start and cancel a model download.- 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- run: |- set -euo pipefail- sudo apt-get update -qq- sudo apt-get install -y -qq --no-install-recommends \- python3 xvfb xauth webkit2gtk-driver libgles2 libgl1 libegl1 libgbm1 \- libwayland-client0 libharfbuzz0b libnghttp2-14 fontconfig libfribidi0- 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 3ab0a254aab..1d14eaedcc7 100644--- a/.github/workflows/release-desktop.yml+++ b/.github/workflows/release-desktop.yml@@ -556,7 +556,7 @@ jobs:if: matrix.platform == 'ubuntu-22.04'run: |sudo apt-get update- sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf xdg-utils+ sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf# ── Node.js ──- name: Setup Node.js@@ -606,14 +606,14 @@ 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('Desktop release must build the complete Tauri AppImage target');+ 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 (config.bundle?.linux?.rpm) {throw new Error('bundle.linux.rpm must not be configured');}- if (config.bundle?.linux?.appimage?.bundleMediaFramework !== false) {- throw new Error('Linux AppImage bundleMediaFramework must stay false');+ if (config.bundle?.linux?.appimage) {+ throw new Error('bundle.linux.appimage must not be configured for the thin AppImage release path');}const workflow = readFileSync('.github/workflows/release-desktop.yml', 'utf8');@@ -626,32 +626,64 @@ jobs:if (!linuxInstallLines.some((line) => line.includes('libappindicator3-dev'))) {throw new Error('Desktop Linux release must install libappindicator3-dev');}- const requiredTools = [- 'AppRun-x86_64',- '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 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 !== requiredTools.length) {- throw new Error(`Expected ${requiredTools.length} digest-verified fetch calls, got ${fetchCalls.length}`);+ 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');}- for (const tool of requiredTools) {- if (!fetchedTools.includes(tool)) {- throw new Error(`Desktop Linux release must digest-verify its fetch of ${tool}`);+ // 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 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;}}+ 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');}@@ -896,44 +928,118 @@ jobs:exit 1}- # ── Linux: preseed every executable/script consumed by Tauri's AppImage bundler ──- - name: Pin complete AppImage toolchain+ # ── Linux: pin AppImage packaging toolchain ──+ - name: Pin thin 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: |- studio/src-tauri/linux/prepare-complete-appimage-tools.sh \- "$RUNNER_TEMP/tauri-tools-cache/tauri"-- # ── Linux: build and sign the native package and complete AppImage together ──- - name: Build Linux bundles+ 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 debid: 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,appimage+ args: >-+ -v --bundles deb+ --config '{"bundle":{"createUpdaterArtifacts":false}}'- - name: Verify complete Linux AppImage+ # ── Linux: wrap the deb payload without bundling the GTK/WebKit stack ──+ - name: Build and sign thin Linux AppImage+ id: package_linuxif: 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- 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')]+ 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')]if len(matches) != 1 or not matches[0].is_file():- sys.exit(f'Expected exactly one AppImage artifact, got {matches}')+ sys.exit(f'Expected exactly one Linux deb artifact, got {matches}')print(matches[0])PY)"- studio/src-tauri/linux/verify-complete-appimage.sh "$appimage"+ 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# ── macOS: build + sign + notarize ──- name: Build macOS app@@ -1442,7 +1548,7 @@ jobs:- name: Stage release assetsshell: bashenv:- ARTIFACT_PATHS: ${{ steps.build_linux.outputs.artifactPaths || steps.build_macos.outputs.artifactPaths || steps.build_windows.outputs.artifactPaths }}+ ARTIFACT_PATHS: ${{ steps.package_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/build-thin-appimage.sh b/studio/src-tauri/linux/build-thin-appimage.shnew file mode 100755index 00000000000..f222eb1629b--- /dev/null+++ b/studio/src-tauri/linux/build-thin-appimage.sh@@ -0,0 +1,259 @@+#!/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/prepare-complete-appimage-tools.sh b/studio/src-tauri/linux/prepare-complete-appimage-tools.shdeleted file mode 100755index cf5dbe8f316..00000000000--- a/studio/src-tauri/linux/prepare-complete-appimage-tools.sh+++ /dev/null@@ -1,78 +0,0 @@-#!/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"--APPRUN_URL="https://github.com/tauri-apps/binary-releases/releases/download/apprun-old/AppRun-x86_64"-APPRUN_SHA256="f30140a43a0a59e46db21bdefdf749b9e9f2c6946e92afabbacf98b8ae73fb4f"-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 "$APPRUN_URL" "$APPRUN_SHA256" AppRun-x86_64-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---# The pinned GTK plugin predates the repaired Wayland runtime boundary and-# unconditionally forces X11. Let GTK follow the session (or an explicit-# GDK_BACKEND) so the same artifact can run natively on Wayland and under X11.-sed -i '/export GDK_BACKEND=x11/d' "$tools_dir/linuxdeploy-plugin-gtk.sh"--# Keep host-loaded display, networking, and C++ libraries on the host side of-# the ABI boundary. Ubuntu 22.04 copies of these break Ubuntu 24.04/Mint 22 GIO,-# curl, and Mesa modules when the host loads them after bundled WebKitGTK.-cat >> "$tools_dir/linuxdeploy-plugin-gtk.sh" <<'SH'-rm -f \- "$APPDIR"/usr/lib/libwayland-client.so* \- "$APPDIR"/usr/lib/libnghttp2.so* \- "$APPDIR"/usr/lib/libcurl*.so* \- "$APPDIR"/usr/lib/libstdc++.so* \- "$APPDIR"/usr/lib/libgcc_s.so*--# GIO_EXTRA_MODULES is additive, so inherited host entries must be removed.-# Pin the default module directory to the bundled modules; otherwise host proxy-# and dconf modules can be loaded into the bundled GLib process.-gio_module_dir="$(find "$APPDIR"/usr/lib -type d -path '*/gio/modules' -print -quit)"-if [[ -z "$gio_module_dir" ]]; then- echo "Complete AppImage has no bundled GIO module directory" >&2- exit 1-fi-gio_module_rel="${gio_module_dir#"$APPDIR"/}"-cat >> "$HOOKFILE" <<EOF-unset GIO_EXTRA_MODULES-export GIO_MODULE_DIR="\$APPDIR/$gio_module_rel"-EOF--# Tauri writes .DirIcon as an absolute build-machine symlink, so it dangles on-# every user's machine and desktop integration shows no icon. Relink relative.-# Tauri points it at "$APPDIR/<product>.png", so the basename is the whole fix.-dir_icon_target="$(readlink "$APPDIR/.DirIcon" 2>/dev/null || true)"-if [[ "$dir_icon_target" == /* ]]; then- ln -sfn "${dir_icon_target##*/}" "$APPDIR/.DirIcon"-fi-SHdiff --git a/studio/src-tauri/linux/verify-complete-appimage.sh b/studio/src-tauri/linux/verify-complete-appimage.shdeleted file mode 100755index 1e2b42f825b..00000000000--- a/studio/src-tauri/linux/verify-complete-appimage.sh+++ /dev/null@@ -1,99 +0,0 @@-#!/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--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; }--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-# Desktop integration reads .DirIcon, so an absolute build-machine symlink-# there ships an iconless launcher.-[[ -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'; do- require_basename "$component"-done--# The bundle owns one coherent userspace web runtime, but glibc, the loader,-# Wayland client ABI, and graphics drivers must remain host-owned so an Ubuntu-# 22.04 build can use a newer distribution's coherent EGL/Mesa/Wayland stack.-for forbidden in \- 'libc.so*' 'libpthread.so*' 'libm.so*' 'libdl.so*' 'librt.so*' \- 'ld-linux*.so*' 'libGL.so*' 'libGLX*.so*' 'libEGL.so*' \- 'libwayland-client.so*' \- 'libnghttp2.so*' 'libcurl*.so*' 'libstdc++.so*' 'libgcc_s.so*' \- 'libdrm.so*' 'libgbm.so*' 'libvulkan.so*' 'libcuda.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--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 47f49b19ba5..6f5566e95f5 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| crate::process::open_detached(path))+ open_existing_dir_with(dir, |path| open::that_detached(path))}/// Open the Unsloth directory in the system file manager.diff --git a/studio/src-tauri/src/native_intents.rs b/studio/src-tauri/src/native_intents.rsindex b3ab4b792f0..ad1944cceaa 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);- crate::process::open_detached(target).map_err(|e| format!("Failed to reveal path: {e}"))+ open::that_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)?;- crate::process::open_detached(entry.canonical_path).map_err(|e| format!("Failed to open path: {e}"))+ open::that_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 a836f1ae78e..0c4b43f42ac 100644--- a/studio/src-tauri/src/process.rs+++ b/studio/src-tauri/src/process.rs@@ -12,282 +12,25 @@ use tauri::{AppHandle, Emitter, Manager};const MAX_LOG_LINES: usize = 1000;-// The complete AppImage's library path belongs only to its GTK/WebKit GUI.-// Never leak AppDir entries—or activated Python overrides—into the managed-// host Python environment. Caller-provided host paths remain available for-// CUDA and private runtime discovery.-#[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")?;- 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) {- match scrub_appimage_library_path() {- Some(library_path) => {- cmd.env("LD_LIBRARY_PATH", library_path);- }- None => {- cmd.env_remove("LD_LIBRARY_PATH");- }- }-}-+// 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.#[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);-- for name in APPIMAGE_GUI_ONLY_VARS {- cmd.env_remove(name);- }cmd.env_remove("PYTHONHOME");cmd.env_remove("PYTHONPATH");}}-// A host launcher hands the target to a host browser or file manager, so it-// must not inherit the bundle's GUI runtime: the host's own GLib/GTK binaries-// fail to load against Ubuntu 22.04 copies. Bundled tools stay reachable as a-// fallback because the AppDir PATH entries are demoted rather than dropped.-#[cfg(target_os = "linux")]-const APPIMAGE_GUI_ONLY_VARS: [&str; 12] = [- "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",- "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::that_detached`, with the launcher handed a host 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() {- match scrub_appimage_library_path() {- Some(library_path) => {- cmd.env("LD_LIBRARY_PATH", library_path);- }- None => {- cmd.env_remove("LD_LIBRARY_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");- 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",- );- 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"));- 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),- ] {- match old_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-";diff --git a/studio/src-tauri/tauri.conf.json b/studio/src-tauri/tauri.conf.jsonindex f6fdc02a20e..c8cc4b334d4 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", "appimage", "deb", "dmg", "nsis"],+ "targets": ["app", "deb", "dmg", "nsis"],"icon": ["icons/32x32.png","icons/128x128.png",@@ -81,12 +81,6 @@}},"linux": {- "appimage": {- "bundleMediaFramework": false,- "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 397fd1045cd..4b5caa94634 100644--- a/tests/security/test_desktop_release_resolver.py+++ b/tests/security/test_desktop_release_resolver.py@@ -57,10 +57,9 @@ 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")- # One lookup per shipped-asset lane: .dmg, .deb, .AppImage, .exe.- assert workflow.count("python3 .github/scripts/resolve-desktop-release.py") == 4+ assert workflow.count("python3 .github/scripts/resolve-desktop-release.py") == 3assert "'.github/scripts/resolve-desktop-release.py'" in workflow- assert workflow.count('if [ -z "$REL_TAG" ]; then') == 4+ assert workflow.count('if [ -z "$REL_TAG" ]; then') == 3assert '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 30e262d6cf7..3b5faba820a 100644--- a/tests/security/test_release_desktop_appimage.py+++ b/tests/security/test_release_desktop_appimage.py@@ -1,7 +1,7 @@-"""Contracts for the complete Linux AppImage release path."""+"""Contracts for the host-integrated Linux AppImage release path."""-import json-import re+import os+import shleximport shutilimport subprocessfrom pathlib import Path@@ -11,9 +11,7 @@ import yamlREPO_ROOT = Path(__file__).resolve().parents[2]WORKFLOW = REPO_ROOT / ".github" / "workflows" / "release-desktop.yml"--CLEAN_MACHINE_WORKFLOW = REPO_ROOT / ".github" / "workflows" / "desktop-app-clean-machine-ci.yml"-VERIFIER = REPO_ROOT / "studio" / "src-tauri" / "linux" / "verify-complete-appimage.sh"+PACKAGER = REPO_ROOT / "studio" / "src-tauri" / "linux" / "build-thin-appimage.sh"def _workflow():@@ -21,268 +19,436 @@ def _workflow():def _step(name: str):- return next(step for step in _workflow()["jobs"]["build"]["steps"] if step.get("name") == name)+ steps = _workflow()["jobs"]["build"]["steps"]+ return next(step for step in steps if step.get("name") == name)-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")+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"])- assert "appimage" in config["bundle"]["targets"]- appimage = config["bundle"]["linux"]["appimage"]- assert appimage["bundleMediaFramework"] is False- assert appimage["files"]["/usr/lib/libappindicator3.so.1"].endswith("/libappindicator3.so.1")+ assert len(step["env"]["APPIMAGE_RUNTIME_SHA256"]) == 64+ assert step["run"].count("sha256sum -c") == 2- 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"]- 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",- "libharfbuzz0b",- "libnghttp2-14",- ):- assert package in source- assert "weston" in source- assert "APPIMAGE_DISPLAY_BACKEND" in source- assert "wayland" 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- for package in ("libwayland-client", "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")- expected = {- "APPRUN": ("AppRun-x86_64", "AppRun-x86_64"),- "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")- for host_library in (- "libwayland-client.so*",- "libnghttp2.so*",- "libcurl*.so*",- "libstdc++.so*",- "libgcc_s.so*",- ):- assert host_library in tool_script- 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+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()+ subprocess.run(+ [PACKAGER, "--verify-appdir", allowed],+ check = True,+ capture_output = True,+ text = True,+ )-def _fake_complete_appdir(tmp_path: Path) -> Path:- appdir = tmp_path / "AppDir"- binary = appdir / "usr/bin/unsloth-studio"- binary.parent.mkdir(parents = True)- shutil.copy2("/bin/true", binary)+ 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,+ )- (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"\nexit 0\n',+ assert result.returncode != 0+ assert "libglib-2.0.so.0" in result.stderr+++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",encoding = "utf-8",)- apprun.chmod(0o755)- hook = appdir / "apprun-hooks/linuxdeploy-plugin-gtk.sh"- hook.parent.mkdir()- hook.write_text(- 'unset GIO_EXTRA_MODULES\nexport GIO_MODULE_DIR="$APPDIR/usr/lib/gio/modules"\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")++ deb_path = tmp_path / "unsloth-test.deb"+ subprocess.run(+ ["dpkg-deb", "--build", "--root-owner-group", package_root, deb_path],+ check = True,+ capture_output = True,+ text = True,)- 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()- return appdir+ 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"+""",+ encoding = "utf-8",+ )+ appimagetool.chmod(0o755)+ runtime = tmp_path / "runtime"+ runtime.touch()-def test_complete_appimage_verifier_accepts_a_coherent_runtime(tmp_path):+ relative_output = Path("artifacts") / "unsloth-test.AppImage"result = subprocess.run(- [VERIFIER, "--appdir", _fake_complete_appdir(tmp_path)],- check = True,+ [PACKAGER, deb_path, appimagetool, runtime, relative_output],+ cwd = tmp_path,+ check = check,capture_output = True,text = True,)- assert "Verified complete x86_64 AppImage runtime" in result.stdout+ output_path = tmp_path / relative_output+ return output_path, Path(f"{output_path}.AppDir"), result-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_resolves_a_relative_output_before_verification(tmp_path):+ output_path, _, result = _build_fake_appimage(tmp_path)-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 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_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,)- assert result.returncode != 0- assert "libwebkit2gtk-4.1.so" in result.stderr+ assert default_result.stdout == f"{app_dir}/usr/share:/usr/local/share:/usr/share"- for library in (- "libc.so.6",- "libwayland-client.so.0",- "libnghttp2.so.14",- "libcurl-gnutls.so.4",- "libstdc++.so.6",- "libgcc_s.so.1",+ 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,+ )+ assert custom_result.stdout == f"{app_dir}/usr/share:/opt/share:/srv/share"+++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",+ 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']}",+ },+ check = False,+ capture_output = True,+ text = True,+ )+++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")++ 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+++# 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")++ result = _run_apprun(app_dir, fake_bin, library_dir)++ assert result.returncode == 0, f"{library_name}: {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")++ for library_path in (+ f"{tmp_path / 'missing'};{library_dir}",+ f"{tmp_path / 'missing'}::{library_dir}",+ f"{tmp_path / 'missing'}:",):- bundled = _fake_complete_appdir(tmp_path / library)- (bundled / "usr/lib" / library).touch()+ 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+result = subprocess.run(- [VERIFIER, "--appdir", bundled],+ [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']}",+ },check = False,capture_output = True,text = True,)- assert result.returncode != 0- assert "host runtime component" in result.stderr+ 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")-def test_managed_appimage_children_preserve_host_library_paths():- source_root = REPO_ROOT / "studio/src-tauri/src"+ 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+++def test_thin_appimage_preserves_host_libraries_and_scrubs_python_overrides():+ 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)", 3),+ 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 / "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-- # One cleanup each for std managed children, Tokio managed 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-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()+ 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_pathdiff --git a/tests/security/test_release_desktop_signing_simulation.py b/tests/security/test_release_desktop_signing_simulation.pyindex c9d99a1c403..529a0ae09f8 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 complete AppImage toolchain" in names+ assert "Pin thin AppImage toolchain" in namesassert "Import Apple certificate" in namesdiff --git a/tests/studio/appimage_model_download_webdriver.py b/tests/studio/appimage_model_download_webdriver.pydeleted file mode 100644index cc3cd7aed4d..00000000000--- a/tests/studio/appimage_model_download_webdriver.py+++ /dev/null@@ -1,642 +0,0 @@-# SPDX-License-Identifier: AGPL-3.0-only-# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0--"""Drive the packaged Linux AppImage through its real WebKitGTK webview.--The backend is deterministic and serves no model bytes. The assertion is the-historical Linux Mint failure boundary: selecting a GGUF in the packaged model-picker must send POST /api/hub/download, paint progress, and send the cancel-request. A live window alone cannot prove that the bundled WebKit network-process works.-"""--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 hashlib- import json- import os- import sys- from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer- from urllib.parse import parse_qs, urlparse-- 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,- )-- 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.pydeleted file mode 100644index 103aca82f0e..00000000000--- a/tests/studio/appimage_portability_smoke.py+++ /dev/null@@ -1,317 +0,0 @@-# SPDX-License-Identifier: AGPL-3.0-only-# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0--"""Launch a shipped AppImage against a deterministic desktop backend fixture.--This deliberately does not install host GTK, WebKitGTK, JavaScriptCore, or an-AppIndicator implementation. Reaching desktop auth proves that the packaged-webview rendered and ran its startup JavaScript, not merely that AppRun stayed-alive.-"""--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 hashlib- import json- import os- import sys- from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer-- 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.pydeleted file mode 100644index accf175b03d..00000000000--- a/tests/studio/appimage_test_support.py+++ /dev/null@@ -1,30 +0,0 @@-# 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)- )