Skip to content

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.

Desktop: run the AppImage on the host's WebKitGTK 2.54+ when available (#15503)

Etherl05ede7c31e82
diff --git a/.github/workflows/desktop-app-clean-machine-ci.yml b/.github/workflows/desktop-app-clean-machine-ci.yml
index 902e73e1b39..eb800a20ab5 100644
--- a/.github/workflows/desktop-app-clean-machine-ci.yml
+++ b/.github/workflows/desktop-app-clean-machine-ci.yml
@@ -611,7 +611,9 @@ jobs:
if-no-files-found: error
- # These images deliberately omit host GTK, WebKitGTK, and AppIndicator.
+ # The plain images deliberately omit host GTK, WebKitGTK, and AppIndicator. host_webkit lanes
+ # install a host WebKitGTK and check which runtime AppRun picks; second_* relaunches the
+ # same AppImage with an override or a removed package to cover the other runtime.
appimage-portability:
needs: appimage-pr-build
if: >-
@@ -628,11 +630,18 @@ jobs:
fail-fast: false
matrix:
include:
- - {label: ubuntu-22.04, image: 'ubuntu:22.04', display_backend: x11, install_gles: true}
- - {label: ubuntu-22.04-no-gles, image: 'ubuntu:22.04', display_backend: x11, install_gles: false}
- - {label: ubuntu-24.04-wayland, image: 'ubuntu:24.04', display_backend: wayland, install_gles: true}
- - {label: debian-12, image: 'debian:12', display_backend: x11, install_gles: true}
- - {label: fedora-44, image: 'fedora:44', display_backend: x11, install_gles: true}
+ - {label: ubuntu-22.04, image: 'ubuntu:22.04', display_backend: x11, install_gles: true, host_webkit: false, expect_mode: bundled}
+ - {label: ubuntu-22.04-no-gles, image: 'ubuntu:22.04', display_backend: x11, install_gles: false, host_webkit: false, expect_mode: bundled}
+ - {label: ubuntu-24.04-wayland, image: 'ubuntu:24.04', display_backend: wayland, install_gles: true, host_webkit: false, expect_mode: bundled}
+ - {label: debian-12, image: 'debian:12', display_backend: x11, install_gles: true, host_webkit: false, expect_mode: bundled}
+ - {label: fedora-44, image: 'fedora:44', display_backend: x11, install_gles: true, host_webkit: false, expect_mode: bundled}
+ - {label: fedora-44-host-webkit, image: 'fedora:44', display_backend: x11, install_gles: true, host_webkit: true, webkit_min: '2.54', expect_mode: host,
+ second_override: bundled, second_remove: '', second_expect_mode: bundled}
+ # trixie-security carries 2.54; trixie itself is still 2.52.
+ - {label: debian-13-host-webkit, image: 'debian:13', display_backend: x11, install_gles: true, host_webkit: true, webkit_min: '2.54', expect_mode: host,
+ second_override: '', second_remove: libayatana-appindicator3-1, second_expect_mode: bundled}
+ - {label: ubuntu-24.04-host-webkit-old, image: 'ubuntu:24.04', display_backend: x11, install_gles: true, host_webkit: true, webkit_min: '2.52', expect_mode: bundled,
+ second_override: host, second_remove: '', second_expect_mode: host}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -665,9 +674,14 @@ jobs:
if [[ "${{ matrix.display_backend }}" == "wayland" ]]; then
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends weston
fi
+ if [[ "${{ matrix.host_webkit }}" == "true" ]]; then
+ DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \
+ libwebkit2gtk-4.1-0 libayatana-appindicator3-1 glib-networking
+ fi
'
forbidden="$(dpkg-query -W -f='${binary:Package}\n' 2>/dev/null | \
grep -Ei 'webkit|javascriptcore|appindicator|libgtk-3' || true)"
+ host_webkit_version="$(dpkg-query -W -f='${Version}' libwebkit2gtk-4.1-0 2>/dev/null || true)"
else
dnf install -y -q ca-certificates python3 binutils xorg-x11-server-Xvfb xorg-x11-xauth \
mesa-libEGL mesa-libgbm mesa-dri-drivers mesa-libGL \
@@ -678,7 +692,11 @@ jobs:
if [[ "${{ matrix.install_gles }}" == "true" ]]; then
dnf install -y -q mesa-libGLES
fi
+ if [[ "${{ matrix.host_webkit }}" == "true" ]]; then
+ dnf install -y -q webkit2gtk4.1 libayatana-appindicator-gtk3 glib-networking
+ fi
forbidden="$(rpm -qa | grep -Ei 'webkit|javascriptcore|appindicator|gtk3' || true)"
+ host_webkit_version="$(rpm -q --qf '%{VERSION}' webkit2gtk4.1 2>/dev/null || true)"
fi
if [[ "${{ matrix.install_gles }}" == "false" ]] && \
ldconfig -p | grep -q 'libGLESv2\.so\.2'; then
@@ -686,7 +704,16 @@ jobs:
exit 1
fi
- if [ -n "$forbidden" ]; then
+ if [[ "${{ matrix.host_webkit }}" == "true" ]]; then
+ # A silently older host would turn a host-mode lane into a second bundled lane.
+ host_webkit_version="${host_webkit_version#*:}"
+ echo "Host WebKitGTK ${host_webkit_version:-missing}; lane needs >= ${{ matrix.webkit_min }}"
+ if [[ ! "$host_webkit_version" =~ ^[0-9]+\.[0-9]+ ]] || \
+ ! printf '%s\n' "${{ matrix.webkit_min }}" "$host_webkit_version" | sort -V -C; then
+ echo "::error::host WebKitGTK ${host_webkit_version:-missing} is older than ${{ matrix.webkit_min }}"
+ exit 1
+ fi
+ elif [ -n "$forbidden" ]; then
echo "::error::portability image unexpectedly contains a host desktop runtime"
printf '%s\n' "$forbidden"
exit 1
@@ -767,6 +794,8 @@ jobs:
APPIMAGE_SMOKE_ART_DIR: ${{ github.workspace }}/logs/appimage-portability
APPIMAGE_DISPLAY_BACKEND: ${{ matrix.display_backend }}
+ # The shipped release has no host copy, so only the PR build is held to a mode.
+ APPIMAGE_EXPECTED_WEBKIT_MODE: ${{ github.event_name == 'pull_request' && matrix.expect_mode || '' }}
GALLIUM_DRIVER: llvmpipe
run: |
set -euo pipefail
@@ -774,6 +803,32 @@ jobs:
python3 tests/studio/appimage_media_pipeline_probe.py
python3 tests/studio/appimage_portability_smoke.py
+ - name: Relaunch with the other WebKitGTK runtime
+ if: github.event_name == 'pull_request' && matrix.host_webkit
+ env:
+ APPIMAGE_PATH: ${{ github.workspace }}/dl/Unsloth.AppImage
+ APPIMAGE_SMOKE_ART_DIR: ${{ github.workspace }}/logs/appimage-portability/second-run
+ APPIMAGE_DISPLAY_BACKEND: ${{ matrix.display_backend }}
+ APPIMAGE_EXPECTED_WEBKIT_MODE: ${{ github.event_name == 'pull_request' && matrix.second_expect_mode || '' }}
+ GALLIUM_DRIVER: llvmpipe
+ SECOND_OVERRIDE: ${{ matrix.second_override }}
+ SECOND_REMOVE: ${{ matrix.second_remove }}
+ run: |
+ set -euo pipefail
+ if [[ -n "$SECOND_REMOVE" ]]; then
+ # Without AppIndicator the probe exits 3, so auto must fall back to bundled.
+ DEBIAN_FRONTEND=noninteractive apt-get remove -y -qq "$SECOND_REMOVE"
+ if ldconfig -p | grep -Eq 'lib(ayatana-)?appindicator3\.so\.1'; then
+ echo "::error::an AppIndicator library is still installed after removing $SECOND_REMOVE"
+ exit 1
+ fi
+ fi
+ if [[ -n "$SECOND_OVERRIDE" ]]; then
+ export UNSLOTH_APPIMAGE_WEBKIT="$SECOND_OVERRIDE"
+ fi
+ echo "UNSLOTH_APPIMAGE_WEBKIT=${UNSLOTH_APPIMAGE_WEBKIT:-auto}; expecting $APPIMAGE_EXPECTED_WEBKIT_MODE"
+ python3 tests/studio/appimage_portability_smoke.py
+
- name: Upload portability evidence
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
diff --git a/.github/workflows/workflow-trigger-lint.yml b/.github/workflows/workflow-trigger-lint.yml
index e57dea00db8..610b487bfea 100644
--- a/.github/workflows/workflow-trigger-lint.yml
+++ b/.github/workflows/workflow-trigger-lint.yml
@@ -75,6 +75,7 @@ jobs:
run: |
python3 -m pytest -q -n 4 \
tests/studio/test_absorbed_lanes_still_run.py \
+ tests/studio/test_appimage_toolchain_contract.py \
tests/studio/test_lint_ci_scans_committed_files.py \
tests/studio/test_agent_guides_verdicts.py \
tests/studio/test_agent_guides_openclaw_node.py \
diff --git a/studio/src-tauri/linux/appimage-apprun.sh b/studio/src-tauri/linux/appimage-apprun.sh
index c3f02515b4a..362e34f455e 100755
--- a/studio/src-tauri/linux/appimage-apprun.sh
+++ b/studio/src-tauri/linux/appimage-apprun.sh
@@ -4,36 +4,159 @@
set -eu
+# The hooks ran with the runtime's APPDIR; keep it to undo their exports in host mode.
+unsloth_hook_appdir="${APPDIR:-}"
+
# Bundled ELF objects use $ORIGIN RUNPATHs; display and driver libraries stay host-owned.
APPDIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
PATH="$APPDIR/usr/bin:$APPDIR/usr/sbin:${PATH:-/usr/local/bin:/usr/bin:/bin}"
export APPDIR PATH
-# Keep Jammy's Skia off host COLRv1 fonts. Fontconfig 2.13 misresolves relative paths, so write
-# this mount's absolute path (XML/sed-encoded; the AppImage name is in it) into user state.
-unsloth_fonts_template="$APPDIR/usr/etc/fonts/unsloth-appimage.conf"
-unsloth_fonts_state="${XDG_RUNTIME_DIR:-${XDG_CACHE_HOME:-${HOME:-}/.cache}}/unsloth-studio"
-FONTCONFIG_FILE="$unsloth_fonts_template"
-if [ -r "$unsloth_fonts_template" ] &&
- mkdir -p "$unsloth_fonts_state" 2>/dev/null &&
- unsloth_fonts_appdir="$(printf '%s' "$APPDIR" | sed \
- -e 's,&,\&amp;,g' -e 's,<,\&lt;,g' -e 's,>,\&gt;,g' \
- -e 's,\\,\\\\,g' -e 's,&,\\&,g' -e 's,|,\\|,g')" &&
- sed "s|@APPDIR@|$unsloth_fonts_appdir|g" "$unsloth_fonts_template" \
- >"$unsloth_fonts_state/fonts-${APPDIR##*/}.conf" 2>/dev/null; then
- FONTCONFIG_FILE="$unsloth_fonts_state/fonts-${APPDIR##*/}.conf"
- for unsloth_stale in "$unsloth_fonts_state"/fonts-*.conf; do
- [ -f "$unsloth_stale" ] || continue
- [ "$unsloth_stale" != "$FONTCONFIG_FILE" ] || continue
- unsloth_stale_mount="$(sed -n 's|^[[:space:]]*<dir>\(.*\)/usr/share/unsloth/fonts</dir>.*|\1|p' \
- "$unsloth_stale" 2>/dev/null | head -1 |
- sed -e 's,&lt;,<,g' -e 's,&gt;,>,g' -e 's,&amp;,\&,g')"
- [ -n "$unsloth_stale_mount" ] && [ -d "$unsloth_stale_mount" ] || rm -f "$unsloth_stale"
+# Host mode runs a copy of the executable whose $ORIGIN/../lib RUNPATH reaches nothing, so the
+# whole GTK/WebKit stack comes from the host. Undo the gtk and gstreamer hook exports that pin
+# GTK, GIO, GSettings and GStreamer to the bundle; their inherited values are already gone.
+unsloth_host_env() {
+ unset GTK_DATA_PREFIX GTK_EXE_PREFIX GTK_PATH GTK_IM_MODULE_FILE GDK_PIXBUF_MODULE_FILE \
+ GSETTINGS_SCHEMA_DIR GIO_MODULE_DIR GIO_EXTRA_MODULES GST_REGISTRY_REUSE_PLUGIN_SCANNER \
+ GST_PLUGIN_SYSTEM_PATH_1_0 GST_PLUGIN_PATH_1_0 GST_PLUGIN_SCANNER_1_0 GST_PTP_HELPER_1_0
+ # The hook forces Adwaita unless the user asked for a theme through APPIMAGE_GTK_THEME.
+ [ "${APPIMAGE_GTK_THEME+x}" = x ] || unset GTK_THEME
+ # A bundled-mode parent relaunching (an in-app update) passes its Jammy font policy back in.
+ case "${FONTCONFIG_FILE:-}" in
+ */unsloth-studio/fonts-*.conf | */usr/etc/fonts/unsloth-appimage.conf) unset FONTCONFIG_FILE ;;
+ esac
+ [ "${XDG_DATA_DIRS+x}" = x ] || return 0
+ unsloth_hooked="${unsloth_hook_appdir:-$APPDIR}"
+ # Each pass through the hooks (a relaunch) prepends the same prefix again.
+ for unsloth_root in "$unsloth_hooked" "$APPDIR"; do
+ while :; do
+ case "$XDG_DATA_DIRS" in
+ "$unsloth_root/usr/share:/usr/share:"*)
+ XDG_DATA_DIRS="${XDG_DATA_DIRS#"$unsloth_root/usr/share:/usr/share:"}" ;;
+ *) break ;;
+ esac
+ done
+ done
+ unsloth_rest="$XDG_DATA_DIRS"
+ unsloth_kept=
+ unsloth_first=1
+ while :; do
+ unsloth_entry="${unsloth_rest%%:*}"
+ case "$unsloth_entry" in
+ "$APPDIR" | "$APPDIR"/* | "$unsloth_hooked" | "$unsloth_hooked"/*) ;;
+ *)
+ if [ -n "$unsloth_first" ]; then
+ unsloth_kept="$unsloth_entry"
+ unsloth_first=
+ else
+ unsloth_kept="$unsloth_kept:$unsloth_entry"
+ fi
+ ;;
+ esac
+ case "$unsloth_rest" in
+ *:*) unsloth_rest="${unsloth_rest#*:}" ;;
+ *) break ;;
+ esac
done
- unset unsloth_stale unsloth_stale_mount
+ # Empty or unset both give GLib's default /usr/local/share:/usr/share.
+ if [ -n "$unsloth_kept" ]; then
+ XDG_DATA_DIRS="$unsloth_kept"
+ else
+ unset XDG_DATA_DIRS
+ fi
+ unset unsloth_hooked unsloth_root unsloth_rest unsloth_kept unsloth_first unsloth_entry
+}
+
+# UNSLOTH_APPIMAGE_WEBKIT=auto (default) uses a host WebKitGTK >= 2.54 when the probe proves the
+# host stack and its appindicator load; host forces it; bundled, or anything else, keeps the bundle.
+unsloth_host_exe="$APPDIR/usr/bin/host/unsloth-studio"
+unsloth_webkit_request="${UNSLOTH_APPIMAGE_WEBKIT:-auto}"
+unsloth_webkit_mode=bundled
+unsloth_webkit_detail=
+if [ ! -f "$unsloth_host_exe" ] || [ ! -x "$unsloth_host_exe" ]; then
+ unsloth_webkit_detail="reason: no host copy"
+else
+ case "$unsloth_webkit_request" in
+ host)
+ unsloth_webkit_mode=host
+ unsloth_webkit_detail="override, UNSLOTH_APPIMAGE_WEBKIT=host"
+ ;;
+ bundled)
+ unsloth_webkit_detail="reason: override"
+ ;;
+ auto)
+ if ! command -v timeout >/dev/null 2>&1; then
+ unsloth_webkit_detail="reason: no timeout"
+ else
+ unsloth_probe_rc=0
+ unsloth_probe_out=$(
+ unsloth_host_env
+ unset LD_LIBRARY_PATH
+ cd / && exec timeout -k 1 5 "$unsloth_host_exe" --unsloth-webkit-probe </dev/null 2>/dev/null
+ ) || unsloth_probe_rc=$?
+ unsloth_probe_version=
+ case "$unsloth_probe_out" in
+ *'
+'*) ;;
+ *)
+ unsloth_probe_version="$(printf '%s\n' "$unsloth_probe_out" |
+ sed -n 's/^webkit=\([0-9]\{1,4\}\)\.\([0-9]\{1,4\}\)\.\([0-9]\{1,4\}\)$/\1.\2.\3/p')"
+ ;;
+ esac
+ if [ "$unsloth_probe_rc" -ne 0 ]; then
+ unsloth_webkit_detail="reason: probe exit $unsloth_probe_rc"
+ elif [ -z "$unsloth_probe_version" ]; then
+ unsloth_webkit_detail="reason: unrecognized probe output"
+ else
+ unsloth_probe_major="${unsloth_probe_version%%.*}"
+ unsloth_probe_minor="${unsloth_probe_version#*.}"
+ unsloth_probe_minor="${unsloth_probe_minor%%.*}"
+ if [ "$unsloth_probe_major" -gt 2 ] ||
+ { [ "$unsloth_probe_major" -eq 2 ] && [ "$unsloth_probe_minor" -ge 54 ]; }; then
+ unsloth_webkit_mode=host
+ unsloth_webkit_detail="host WebKitGTK $unsloth_probe_version, UNSLOTH_APPIMAGE_WEBKIT=auto"
+ else
+ unsloth_webkit_detail="reason: version $unsloth_probe_version < 2.54"
+ fi
+ unset unsloth_probe_major unsloth_probe_minor
+ fi
+ unset unsloth_probe_rc unsloth_probe_out unsloth_probe_version
+ fi
+ ;;
+ *)
+ unsloth_webkit_detail="reason: invalid override '$(printf '%s' "$unsloth_webkit_request" |
+ tr -c 'A-Za-z0-9._-' '?' | cut -c 1-32)'"
+ ;;
+ esac
+fi
+
+if [ "$unsloth_webkit_mode" = bundled ]; then
+ # Keep Jammy's Skia off host COLRv1 fonts. Fontconfig 2.13 misresolves relative paths, so write
+ # this mount's absolute path (XML/sed-encoded; the AppImage name is in it) into user state.
+ unsloth_fonts_template="$APPDIR/usr/etc/fonts/unsloth-appimage.conf"
+ unsloth_fonts_state="${XDG_RUNTIME_DIR:-${XDG_CACHE_HOME:-${HOME:-}/.cache}}/unsloth-studio"
+ FONTCONFIG_FILE="$unsloth_fonts_template"
+ if [ -r "$unsloth_fonts_template" ] &&
+ mkdir -p "$unsloth_fonts_state" 2>/dev/null &&
+ unsloth_fonts_appdir="$(printf '%s' "$APPDIR" | sed \
+ -e 's,&,\&amp;,g' -e 's,<,\&lt;,g' -e 's,>,\&gt;,g' \
+ -e 's,\\,\\\\,g' -e 's,&,\\&,g' -e 's,|,\\|,g')" &&
+ sed "s|@APPDIR@|$unsloth_fonts_appdir|g" "$unsloth_fonts_template" \
+ >"$unsloth_fonts_state/fonts-${APPDIR##*/}.conf" 2>/dev/null; then
+ FONTCONFIG_FILE="$unsloth_fonts_state/fonts-${APPDIR##*/}.conf"
+ for unsloth_stale in "$unsloth_fonts_state"/fonts-*.conf; do
+ [ -f "$unsloth_stale" ] || continue
+ [ "$unsloth_stale" != "$FONTCONFIG_FILE" ] || continue
+ unsloth_stale_mount="$(sed -n 's|^[[:space:]]*<dir>\(.*\)/usr/share/unsloth/fonts</dir>.*|\1|p' \
+ "$unsloth_stale" 2>/dev/null | head -1 |
+ sed -e 's,&lt;,<,g' -e 's,&gt;,>,g' -e 's,&amp;,\&,g')"
+ [ -n "$unsloth_stale_mount" ] && [ -d "$unsloth_stale_mount" ] || rm -f "$unsloth_stale"
+ done
+ unset unsloth_stale unsloth_stale_mount
+ fi
+ export FONTCONFIG_FILE
+ unset unsloth_fonts_appdir unsloth_fonts_template unsloth_fonts_state
fi
-export FONTCONFIG_FILE
-unset unsloth_fonts_appdir unsloth_fonts_template unsloth_fonts_state
# An inherited LD_LIBRARY_PATH would put host GLib/GTK/WebKit before the bundle's RUNPATHs.
# Managed children still get the saved value; the guard keeps a restart from erasing it.
@@ -43,8 +166,21 @@ if [ "${LD_LIBRARY_PATH+x}" = x ]; then
unset LD_LIBRARY_PATH
fi
+# Overwrite any inherited value so a relaunch re-decides; the app reads it to pick its plan.
+UNSLOTH_APPIMAGE_WEBKIT_MODE="$unsloth_webkit_mode"
+export UNSLOTH_APPIMAGE_WEBKIT_MODE
+printf 'unsloth-studio: AppImage WebKitGTK runtime=%s (%s)\n' \
+ "$unsloth_webkit_mode" "$unsloth_webkit_detail" >&2
+
# WebKitGTK resolves its helpers relative to its /usr prefix.
cd "$APPDIR/usr"
-
+if [ "$unsloth_webkit_mode" = host ]; then
+ unsloth_host_env
+ unset unsloth_hook_appdir unsloth_host_exe unsloth_webkit_request unsloth_webkit_mode \
+ unsloth_webkit_detail
+ exec "$APPDIR/usr/bin/host/unsloth-studio" "$@"
+fi
+unset unsloth_hook_appdir unsloth_host_exe unsloth_webkit_request unsloth_webkit_mode \
+ unsloth_webkit_detail
exec "$APPDIR/usr/bin/unsloth-studio" "$@"
diff --git a/studio/src-tauri/linux/finalize-complete-appimage.sh b/studio/src-tauri/linux/finalize-complete-appimage.sh
index 352884b4aeb..916f41a62b5 100755
--- a/studio/src-tauri/linux/finalize-complete-appimage.sh
+++ b/studio/src-tauri/linux/finalize-complete-appimage.sh
@@ -55,7 +55,9 @@ for pattern in "${host_patterns[@]}"; do
done < <(find "$appdir" \( -type f -o -type l \) -name "$pattern" -print0)
done
-# $ORIGIN RUNPATHs so host objects do not inherit bundled libraries.
+# $ORIGIN RUNPATHs so host objects do not inherit bundled libraries. The host-mode copy keeps
+# the main executable's $ORIGIN/../lib, which from usr/bin/host reaches no bundled library.
+host_copy="$appdir/usr/bin/host/unsloth-studio"
patched=0
while IFS= read -r -d '' object; do
[[ "$(head -c 4 "$object" 2>/dev/null || true)" == $'\177ELF' ]] || continue
@@ -68,7 +70,18 @@ while IFS= read -r -d '' object; do
fi
patchelf --set-rpath "$runpath" "$object"
((patched += 1))
-done < <(find "$appdir" -type f -print0)
+done < <(find "$appdir" -path "$appdir/usr/bin/host" -prune -o -type f -print0)
((patched > 0)) || { echo "AppDir contains no dynamic ELF objects" >&2; exit 1; }
+
+# AppRun runs this copy when the host has a complete WebKitGTK >= 2.54 stack.
+[[ ! -e "$appdir/usr/bin/lib" ]] || {
+ echo "AppDir has usr/bin/lib, which the host-mode executable's RUNPATH reaches" >&2
+ exit 1
+}
+[[ -f "$appdir/usr/bin/unsloth-studio" ]] || {
+ echo "AppDir has no usr/bin/unsloth-studio to copy for host mode" >&2
+ exit 1
+}
+install -D -m 755 "$appdir/usr/bin/unsloth-studio" "$host_copy"
printf 'Finalized AppImage runtime with %d $ORIGIN RUNPATHs: %s\n' "$patched" "$appdir"
diff --git a/studio/src-tauri/linux/verify-complete-appimage.sh b/studio/src-tauri/linux/verify-complete-appimage.sh
index 85d466f296c..1e3e8b845f5 100755
--- a/studio/src-tauri/linux/verify-complete-appimage.sh
+++ b/studio/src-tauri/linux/verify-complete-appimage.sh
@@ -244,6 +244,64 @@ done < <(find "$appdir" -type f -print0)
((dynamic_count > 0)) || { echo "Complete AppImage contains no dynamic ELF objects" >&2; exit 1; }
((runpath_failures == 0)) || exit 1
+# Releases before host mode ship no copy; a launcher that runs one needs all of it.
+if grep -aFq 'usr/bin/host/unsloth-studio' "${launchers[@]}"; then
+ host_copy="$appdir/usr/bin/host/unsloth-studio"
+ [[ -f "$host_copy" && -x "$host_copy" ]] || {
+ echo "Complete AppImage launcher runs a missing host-mode executable: $host_copy" >&2
+ exit 1
+ }
+ # Minimal images (fedora:44) ship no diffutils; sha256sum is coreutils. Fail closed.
+ same_bytes() {
+ if command -v cmp >/dev/null 2>&1; then
+ cmp -s "$1" "$2"
+ else
+ local left right
+ left="$(sha256sum <"$1")" && right="$(sha256sum <"$2")" &&
+ [[ -n "$left" && "$left" == "$right" ]]
+ fi
+ }
+ same_bytes "$appdir/usr/bin/unsloth-studio" "$host_copy" || {
+ echo "Complete AppImage host-mode executable differs from usr/bin/unsloth-studio" >&2
+ exit 1
+ }
+ [[ ! -e "$appdir/usr/bin/lib" ]] || {
+ echo "Complete AppImage has usr/bin/lib, which the host-mode executable reaches" >&2
+ exit 1
+ }
+ host_runpath="$(readelf -d "$host_copy" 2>/dev/null |
+ sed -n 's/.*\(RPATH\|RUNPATH\).*Library .*path: \[\(.*\)\].*/\2/p')"
+ IFS=':' read -ra host_entries <<<"$host_runpath"
+ for entry in "${host_entries[@]}"; do
+ resolved="${entry//\$ORIGIN/$appdir/usr/bin/host}"
+ [[ ! -e "$resolved" ]] || {
+ echo "Complete AppImage host-mode executable reaches bundled libraries: $entry" >&2
+ exit 1
+ }
+ done
+ grep -aFq -- '--unsloth-webkit-probe' "${launchers[@]}" || {
+ echo "Complete AppImage runs its host-mode executable without the WebKitGTK probe" >&2
+ exit 1
+ }
+ # Host mode undoes the hook exports by name; a plugin bump must not add one it misses.
+ host_env="$(sed -n '/^unsloth_host_env() {$/,/^}$/p' "${launchers[@]}")"
+ [[ -n "$host_env" ]] || {
+ echo "Complete AppImage launcher has no host-mode environment restore" >&2
+ exit 1
+ }
+ drift=0
+ while IFS= read -r name; do
+ [[ "$name" != APPDIR ]] || continue
+ grep -Eq "(^|[^A-Za-z0-9_])${name}([^A-Za-z0-9_]|\$)" <<<"$host_env" || {
+ echo "Complete AppImage hook pins $name to the bundle, and host mode does not undo it" >&2
+ ((drift += 1))
+ }
+ done < <(sed -n -E \
+ 's/^[[:space:]]*(export[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)=.*\$\{?APPDIR([^A-Za-z0-9_].*)?$/\2/p' \
+ "$appdir/apprun-hooks"/* 2>/dev/null | sort -u)
+ ((drift == 0)) || exit 1
+fi
+
max_glibc="$({ readelf --version-info "$binary" 2>/dev/null || true; } |
diff --git a/studio/src-tauri/src/appimage_webkit.rs b/studio/src-tauri/src/appimage_webkit.rs
new file mode 100644
index 00000000000..b527c5aaebc
--- /dev/null
+++ b/studio/src-tauri/src/appimage_webkit.rs
@@ -0,0 +1,146 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+//! Which WebKitGTK an AppImage runs on. `linux/appimage-apprun.sh` probes the host's
+//! GTK3/webkit2gtk-4.1 stack with [`PROBE_FLAG`] and, when it is complete and new enough,
+//! starts the app on it instead of the bundled copy, exporting [`MODE_ENV`]`=host`.
+
+use std::ffi::OsString;
+
+/// Run by AppRun on the unbundled copy of this binary: report the WebKitGTK that loaded.
+pub const PROBE_FLAG: &str = "--unsloth-webkit-probe";
+/// Set by AppRun to `host` or `bundled`.
+pub const MODE_ENV: &str = "UNSLOTH_APPIMAGE_WEBKIT_MODE";
+const APPIMAGE: &str = "APPIMAGE";
+/// No tray library: setup_tray would panic (libappindicator-sys dlopens one at startup).
+#[cfg(target_os = "linux")]
+const EXIT_NO_APPINDICATOR: i32 = 3;
+/// libappindicator-sys's own order.
+#[cfg(target_os = "linux")]
+const APPINDICATOR_LIBRARIES: [&[u8]; 2] = [
+ b"libayatana-appindicator3.so.1\0",
+ b"libappindicator3.so.1\0",
+];
+
+/// True when this AppImage runs on its own bundled libraries. A host-mode AppImage loads the
+/// system's stack, so renderer decisions treat it like a native install.
+pub fn bundled_runtime(env: impl Fn(&str) -> Option<OsString>) -> bool {
+ env(APPIMAGE).is_some() && env(MODE_ENV).as_deref() != Some("host".as_ref())
+}
+
+/// For diagnostics: never echoes the variable, so only these three values can appear.
+pub fn mode_label(env: impl Fn(&str) -> Option<OsString>) -> &'static str {
+ if env(APPIMAGE).is_none() {
+ "none"
+ } else if bundled_runtime(env) {
+ "bundled"
+ } else {
+ "host"
+ }
+}
+
+/// The probe: `Some(exit code)` when argv is exactly `[exe, PROBE_FLAG]`. Runs before any
+/// GTK or logging. The process only starts when every linked library and symbol resolved
+/// (the binary is linked BIND_NOW), so reaching this code already proves the stack loads.
+#[cfg(target_os = "linux")]
+pub fn run_probe() -> Option<i32> {
+ let mut args = std::env::args_os().skip(1);
+ if args.next().as_deref() != Some(PROBE_FLAG.as_ref()) || args.next().is_some() {
+ return None;
+ }
+ if !APPINDICATOR_LIBRARIES
+ .iter()
+ .any(|name| library_loads(name))
+ {
+ return Some(EXIT_NO_APPINDICATOR);
+ }
+ let (major, minor, micro) = linked_webkit_version();
+ println!("webkit={major}.{minor}.{micro}");
+ Some(0)
+}
+
+#[cfg(target_os = "linux")]
+fn library_loads(name: &[u8]) -> bool {
+ // SAFETY: a NUL-terminated name; the handle is closed straight away.
+ unsafe {
+ let handle = libc::dlopen(name.as_ptr().cast(), libc::RTLD_LAZY | libc::RTLD_LOCAL);
+ if handle.is_null() {
+ return false;
+ }
+ libc::dlclose(handle);
+ true
+ }
+}
+
+/// The version of the libwebkit2gtk that actually loaded.
+#[cfg(target_os = "linux")]
+pub fn linked_webkit_version() -> (u32, u32, u32) {
+ // SAFETY: plain getters with no preconditions; no GTK initialization needed.
+ unsafe {
+ (
+ webkit2gtk_sys::webkit_get_major_version(),
+ webkit2gtk_sys::webkit_get_minor_version(),
+ webkit2gtk_sys::webkit_get_micro_version(),
+ )
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
+ move |name| {
+ vars.iter()
+ .find(|(key, _)| *key == name)
+ .map(|(_, value)| OsString::from(value))
+ }
+ }
+
+ #[test]
+ fn only_an_exact_host_mode_leaves_the_bundled_runtime() {
+ assert!(!bundled_runtime(env(&[])));
+ assert!(!bundled_runtime(env(&[(MODE_ENV, "host")])));
+ for mode in [
+ None,
+ Some("bundled"),
+ Some("HOST"),
+ Some("host "),
+ Some(""),
+ Some("x"),
+ ] {
+ let mut vars = vec![(APPIMAGE, "/tmp/Unsloth.AppImage")];
+ if let Some(mode) = mode {
+ vars.push((MODE_ENV, mode));
+ }
+ assert!(bundled_runtime(env(&vars)), "{mode:?}");
+ }
+ assert!(!bundled_runtime(env(&[
+ (APPIMAGE, "/tmp/Unsloth.AppImage"),
+ (MODE_ENV, "host")
+ ])));
+ }
+
+ #[test]
+ fn the_diagnostics_label_is_one_of_three_values() {
+ assert_eq!(mode_label(env(&[])), "none");
+ assert_eq!(
+ mode_label(env(&[(APPIMAGE, "/a"), (MODE_ENV, "host")])),
+ "host"
+ );
+ for mode in ["bundled", "<script>", "host\nx"] {
+ assert_eq!(
+ mode_label(env(&[(APPIMAGE, "/a"), (MODE_ENV, mode)])),
+ "bundled"
+ );
+ }
+ }
+
+ #[cfg(target_os = "linux")]
+ #[test]
+ fn the_linked_webkit_reports_a_plausible_version() {
+ let (major, minor, _) = linked_webkit_version();
+ assert_eq!(major, 2);
+ assert!(minor >= 36, "{minor}");
+ }
+}
diff --git a/studio/src-tauri/src/diagnostics/report.rs b/studio/src-tauri/src/diagnostics/report.rs
index c738ca32915..bdad723d4d7 100644
--- a/studio/src-tauri/src/diagnostics/report.rs
+++ b/studio/src-tauri/src/diagnostics/report.rs
@@ -37,6 +37,10 @@ pub(crate) fn render_report(
"appimage={}\n",
std::env::var_os("APPIMAGE").is_some()
));
+ raw.push_str(&format!(
+ "appimage_webkit_mode={}\n",
+ crate::appimage_webkit::mode_label(|name| std::env::var_os(name))
+ ));
raw.push_str(&format!(
"cpu_logical_count={}\n",
std::thread::available_parallelism()
diff --git a/studio/src-tauri/src/linux_webkit.rs b/studio/src-tauri/src/linux_webkit.rs
index 71934a7eacc..317643922e0 100644
--- a/studio/src-tauri/src/linux_webkit.rs
+++ b/studio/src-tauri/src/linux_webkit.rs
@@ -244,7 +244,7 @@ fn rendering_plan(
.as_deref()
.is_some_and(force_dmabuf_requested);
- let is_appimage = env(APPIMAGE).is_some();
+ let is_appimage = crate::appimage_webkit::bundled_runtime(&env);
let wayland_session = session_is_wayland(&env, wayland_socket, x11_open);
let nvidia_x11 = nvidia_driver_loaded
&& !force_dmabuf
@@ -580,7 +580,8 @@ pub fn configure_renderer(
setting: GpuRendering,
unsafe_flag: impl FnOnce((u32, u32, u32), bool) -> bool,
) -> RendererDecision {
- let gles_usable = std::env::var_os(APPIMAGE).is_none() || gles_is_usable();
+ let gles_usable =
+ !crate::appimage_webkit::bundled_runtime(|name| std::env::var_os(name)) || gles_is_usable();
let env = |name: &str| std::env::var_os(name);
let webkit_version = runtime_webkit_version();
let nvidia = nvidia_driver_branch();
@@ -2272,4 +2273,51 @@ mod tests {
assert!(!decision(Some(GPU_ON_REASON), false).wants_supervision());
assert!(!decision(None, true).wants_supervision());
}
+
+ const HOST_MODE: (&str, &str) = (crate::appimage_webkit::MODE_ENV, "host");
+
+ #[test]
+ fn a_host_mode_appimage_on_wayland_gets_the_native_plan() {
+ let vars = [
+ (WAYLAND_DISPLAY, "wayland-0"),
+ (APPIMAGE, "/tmp/Unsloth.AppImage"),
+ HOST_MODE,
+ ];
+ assert_eq!(
+ plan(&vars),
+ RenderingPlan::Apply(RenderingWorkaround::ForceSharedMemory, WAYLAND_REASON)
+ );
+ // Bundled keeps the AppImage switch.
+ assert_eq!(
+ plan(&vars[..2]),
+ RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, WAYLAND_REASON)
+ );
+ }
+
+ #[test]
+ fn a_host_mode_appimage_on_nvidia_x11_reports_the_native_reason() {
+ assert_eq!(
+ plan_on_nvidia(&[
+ (APPIMAGE, "/tmp/Unsloth.AppImage"),
+ HOST_MODE,
+ (GDK_BACKEND, "x11")
+ ]),
+ RenderingPlan::Apply(
+ RenderingWorkaround::DisableCompositingOnNvidiaX11,
+ NVIDIA_REASON
+ )
+ );
+ }
+
+ #[test]
+ fn a_host_mode_appimage_is_not_held_to_the_bundled_gles_check() {
+ assert_eq!(
+ plan_with_version_and_gles(
+ &[(APPIMAGE, "/tmp/Unsloth.AppImage"), HOST_MODE],
+ MODERN_WEBKIT,
+ false
+ ),
+ RenderingPlan::PreserveEnvironment
+ );
+ }
}
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index 5971410b18e..58cabaf6f3d 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -2,6 +2,7 @@
mod app_layout;
mod app_menu;
+mod appimage_webkit;
mod browser_capture;
#[cfg(target_os = "macos")]
mod browser_context_downloads;
@@ -2260,6 +2261,11 @@ fn extend_csp_with_hf_endpoints<R: tauri::Runtime>(context: &mut tauri::Context<
}
fn main() {
+ // AppRun's host-stack probe: answer and exit before anything else loads or logs.
+ #[cfg(target_os = "linux")]
+ if let Some(code) = appimage_webkit::run_probe() {
+ std::process::exit(code);
+ }
#[cfg(target_os = "linux")]
if let Some(result) = debian_update::run_installer() {
match result {
@@ -2375,6 +2381,14 @@ fn main() {
setup_logging();
log_panics();
info!("Unsloth desktop app starting");
+ #[cfg(target_os = "linux")]
+ if std::env::var_os("APPIMAGE").is_some() {
+ let (major, minor, micro) = appimage_webkit::linked_webkit_version();
+ info!(
+ "AppImage WebKitGTK runtime: {}; WebKitGTK {major}.{minor}.{micro}",
+ appimage_webkit::mode_label(|name| std::env::var_os(name))
+ );
+ }
#[cfg(target_os = "macos")]
macos_event_guard::install();
diff --git a/tests/security/test_release_desktop_appimage.py b/tests/security/test_release_desktop_appimage.py
index 9855bc71de5..67bcae15f54 100644
--- a/tests/security/test_release_desktop_appimage.py
+++ b/tests/security/test_release_desktop_appimage.py
@@ -1,12 +1,15 @@
"""Contracts for the complete Linux AppImage release path."""
import json
+import os
import re
import shutil
import subprocess
+import time
from pathlib import Path
from xml.etree import ElementTree
+import pytest
import yaml
@@ -466,15 +469,121 @@ def test_complete_appimage_verifier_rejects_global_library_path_and_missing_orig
assert "$ORIGIN-relative RUNPATH" in result.stderr
-def _apprun_mount(tmp_path: Path, name: str = "AppDir") -> Path:
- """An AppDir holding just what AppRun itself touches."""
+# The pinned linuxdeploy plugins' hooks as shipped (gtk patched by prepare-complete-appimage-tools.sh).
+_GTK_HOOK = """#! /usr/bin/env bash
+case "${APPDIR:-}" in
+ /*) ;;
+ *) APPDIR="$(dirname "$(realpath "$0")")" ;;
+esac
+export APPDIR
+
+gsettings get org.gnome.desktop.interface gtk-theme 2> /dev/null | grep -qi "dark" && GTK_THEME_VARIANT="dark" || GTK_THEME_VARIANT="light"
+APPIMAGE_GTK_THEME="${APPIMAGE_GTK_THEME:-"Adwaita:$GTK_THEME_VARIANT"}" # Allow user to override theme (discouraged)
+
+export APPDIR="${APPDIR:-"$(dirname "$(realpath "$0")")"}" # Workaround to run extracted AppImage
+export GTK_DATA_PREFIX="$APPDIR"
+export GTK_THEME="$APPIMAGE_GTK_THEME" # Custom themes are broken
+export XDG_DATA_DIRS="$APPDIR/usr/share:/usr/share:$XDG_DATA_DIRS" # g_get_system_data_dirs() from GLib
+export GSETTINGS_SCHEMA_DIR="$APPDIR//usr/share/glib-2.0/schemas"
+export GTK_EXE_PREFIX="$APPDIR//usr"
+export GTK_PATH="$APPDIR//usr/lib/x86_64-linux-gnu/gtk-3.0:/usr/lib64/gtk-3.0:/usr/lib/x86_64-linux-gnu/gtk-3.0"
+export GTK_IM_MODULE_FILE="$APPDIR//usr/lib/x86_64-linux-gnu/gtk-3.0/3.0.0/immodules.cache"
+
+export GDK_PIXBUF_MODULE_FILE="$APPDIR//usr/lib/x86_64-linux-gnu/gdk-pixbuf-2.0/2.10.0/loaders.cache"
+export GIO_EXTRA_MODULES="$APPDIR/usr/lib/x86_64-linux-gnu/gio/modules"
+unset GIO_EXTRA_MODULES
+export GIO_MODULE_DIR="$APPDIR/usr/lib/x86_64-linux-gnu/gio/modules"
+export GTK_PATH="$APPDIR/usr/lib/x86_64-linux-gnu/gtk-3.0"
+"""
+
+_GST_HOOK = """#! /bin/bash
+
+export GST_REGISTRY_REUSE_PLUGIN_SCANNER="no"
+export GST_PLUGIN_SYSTEM_PATH_1_0="${APPDIR}/usr/lib/gstreamer-1.0"
+export GST_PLUGIN_PATH_1_0="${APPDIR}/usr/lib/gstreamer-1.0"
+
+export GST_PLUGIN_SCANNER_1_0="${APPDIR}/usr/lib/gstreamer1.0/gstreamer-1.0/gst-plugin-scanner"
+export GST_PTP_HELPER_1_0="${APPDIR}/usr/lib/gstreamer1.0/gstreamer-1.0/gst-ptp-helper"
+"""
+
+# AppRun.wrapped is #!/bin/sh, which is dash on Debian-family hosts; prefer dash where present.
+_POSIX_SH = shutil.which("dash")
+_SH = [_POSIX_SH] if _POSIX_SH else []
+
+_LINUXDEPLOY_APPRUN = f"""#! /usr/bin/env bash
+
+# autogenerated by linuxdeploy
+
+# make sure errors in sourced scripts will cause this script to stop
+set -e
+
+this_dir="$(readlink -f "$(dirname "$0")")"
+
+source "$this_dir"/apprun-hooks/"linuxdeploy-plugin-gtk.sh"
+source "$this_dir"/apprun-hooks/"linuxdeploy-plugin-gstreamer.sh"
+
+exec {_POSIX_SH or ""} "$this_dir"/AppRun.wrapped "$@"
+"""
+
+# The bundled stand-in reports its exec target, cwd and argv before its environment.
+_FAKE_BUNDLED_BINARY = (
+ "#!/bin/sh\n"
+ "echo EXE=bundled\n"
+ 'echo "CWD=$(pwd -P)"\n'
+ 'echo "ARGV=$*"\n'
+ "exec /usr/bin/env\n"
+)
+
+# The host-mode stand-in answers the WebKitGTK probe from FAKE_PROBE_* knobs and records that it
+# ran, with the probe's cwd and environment, in FAKE_PROBE_MARKER.
+_FAKE_HOST_BINARY = (
+ "#!/bin/sh\n"
+ 'if [ "$#" -eq 1 ] && [ "$1" = --unsloth-webkit-probe ]; then\n'
+ ' { echo "cwd=$(pwd -P)"; /usr/bin/env; } >"$FAKE_PROBE_MARKER"\n'
+ ' echo "probe noise on stderr" >&2\n'
+ ' [ -z "${FAKE_PROBE_SLEEP:-}" ] || sleep "$FAKE_PROBE_SLEEP"\n'
+ ' printf "%b" "${FAKE_PROBE_OUTPUT-webkit=2.54.2\\n}"\n'
+ ' exit "${FAKE_PROBE_EXIT:-0}"\n'
+ "fi\n"
+ "echo EXE=host\n"
+ 'echo "CWD=$(pwd -P)"\n'
+ 'echo "ARGV=$*"\n'
+ "exec /usr/bin/env\n"
+)
+
+
+def _apprun_mount(
+ tmp_path: Path,
+ name: str = "AppDir",
+ *,
+ host_copy: bool = False,
+ hooked: bool = False,
+) -> Path:
+ """An AppDir holding just what AppRun itself touches.
+
+ host_copy adds the usr/bin/host executable; hooked wraps AppRun the way linuxdeploy does,
+ sourcing the gtk then gstreamer hooks before it execs AppRun.wrapped.
+ """
appdir = tmp_path / name
binary = appdir / "usr/bin/unsloth-studio"
binary.parent.mkdir(parents = True)
- binary.write_text("#!/bin/sh\nexec /usr/bin/env\n", encoding = "utf-8")
+ binary.write_text(_FAKE_BUNDLED_BINARY, encoding = "utf-8")
binary.chmod(0o755)
- apprun = appdir / "AppRun"
+ if host_copy:
+ host = appdir / "usr/bin/host/unsloth-studio"
+ host.parent.mkdir()
+ host.write_text(_FAKE_HOST_BINARY, encoding = "utf-8")
+ host.chmod(0o755)
+ if hooked:
+ hooks = appdir / "apprun-hooks"
+ hooks.mkdir()
+ (hooks / "linuxdeploy-plugin-gtk.sh").write_text(_GTK_HOOK, encoding = "utf-8")
+ (hooks / "linuxdeploy-plugin-gstreamer.sh").write_text(_GST_HOOK, encoding = "utf-8")
+ wrapper = appdir / "AppRun"
+ wrapper.write_text(_LINUXDEPLOY_APPRUN, encoding = "utf-8")
+ wrapper.chmod(0o755)
+ apprun = appdir / ("AppRun.wrapped" if hooked else "AppRun")
apprun.write_bytes(APPRUN.read_bytes())
apprun.chmod(0o755)
template = appdir / "usr/etc/fonts/unsloth-appimage.conf"
@@ -727,3 +836,471 @@ def test_release_notes_recommend_native_deb_without_claiming_universality():
assert "`.AppImage` is experimental." in notes
assert "use `.deb` when available" in notes
assert "universal" not in notes.lower()
+
+
+# Every variable the hooks point into the bundle; host mode must not hand any of them to host GTK.
+_HOOK_PINNED = (
+ "GTK_DATA_PREFIX",
+ "GTK_EXE_PREFIX",
+ "GTK_PATH",
+ "GTK_IM_MODULE_FILE",
+ "GDK_PIXBUF_MODULE_FILE",
+ "GSETTINGS_SCHEMA_DIR",
+ "GIO_MODULE_DIR",
+ "GIO_EXTRA_MODULES",
+ "GST_REGISTRY_REUSE_PLUGIN_SCANNER",
+ "GST_PLUGIN_SYSTEM_PATH_1_0",
+ "GST_PLUGIN_PATH_1_0",
+ "GST_PLUGIN_SCANNER_1_0",
+ "GST_PTP_HELPER_1_0",
+)
+
+_MODE_LINE = re.compile(r"^unsloth-studio: AppImage WebKitGTK runtime=(host|bundled) \((.*)\)$")
+
+
+def _launch(
+ appdir: Path,
+ tmp_path: Path,
+ args = (),
+ **env,
+):
+ """Run the mount like the AppImage runtime does: APPDIR set, AppRun as the entry point."""
+
+ base = {
+ "PATH": "/usr/bin:/bin",
+ "APPDIR": str(appdir),
+ "XDG_RUNTIME_DIR": str(tmp_path / "state"),
+ "FAKE_PROBE_MARKER": str(tmp_path / "probe-ran"),
+ }
+ base.update({key: value for key, value in env.items() if value is not None})
+ for key, value in env.items():
+ if value is None:
+ base.pop(key, None)
+ entry = appdir / "AppRun"
+ hooked = (appdir / "AppRun.wrapped").exists()
+ command = [entry, *args] if hooked else [*_SH, entry, *args]
+ started = time.monotonic()
+ result = subprocess.run(command, check = True, capture_output = True, text = True, env = base)
+ lines = result.stdout.splitlines()
+ exe = lines[0].removeprefix("EXE=")
+ cwd = lines[1].removeprefix("CWD=")
+ argv = lines[2].removeprefix("ARGV=")
+ child_env = dict(line.split("=", 1) for line in lines[3:] if "=" in line)
+ mode_lines = [line for line in result.stderr.splitlines() if _MODE_LINE.match(line)]
+ return {
+ "exe": exe,
+ "cwd": cwd,
+ "argv": argv,
+ "env": child_env,
+ "stderr": result.stderr,
+ "mode": _MODE_LINE.match(mode_lines[0]).groups() if len(mode_lines) == 1 else None,
+ "elapsed": time.monotonic() - started,
+ "probed": (tmp_path / "probe-ran").exists(),
+ }
+
+
+def _assert_host_env_restored(run, appdir: Path):
+ env = run["env"]
+ for name in _HOOK_PINNED:
+ assert name not in env, f"host mode kept the bundle's {name}={env[name]}"
+ for name, value in env.items():
+ if str(appdir) in value:
+ assert name in {"APPDIR", "PATH", "PWD", "OLDPWD"}, f"{name}={value} names the mount"
+ assert "FONTCONFIG_FILE" not in env, "host mode pinned the Jammy fontconfig policy"
+ assert env["UNSLOTH_APPIMAGE_WEBKIT_MODE"] == "host"
+
+
+ ("inherited", "restored"),
+ [(None, None), ("/a:/b", "/a:/b")],
+ ids = ["xdg-unset", "xdg-set"],
+)
+def test_apprun_runs_the_host_copy_with_the_hook_environment_undone(tmp_path, inherited, restored):
+ appdir = _apprun_mount(tmp_path, host_copy = True, hooked = True)
+ run = _launch(
+ appdir, tmp_path, ["--flag", "x"], XDG_DATA_DIRS = inherited, LD_LIBRARY_PATH = "/opt/lib"
+ )
+
+ assert run["mode"] == ("host", "host WebKitGTK 2.54.2, UNSLOTH_APPIMAGE_WEBKIT=auto")
+ assert run["exe"] == "host"
+ assert run["cwd"] == str(appdir.resolve() / "usr")
+ assert run["argv"] == "--flag x"
+ assert "probe noise" not in run["stderr"]
+ _assert_host_env_restored(run, appdir)
+ assert run["env"].get("XDG_DATA_DIRS") == restored
+ # The hook forced Adwaita; nobody asked for it, so host GTK follows the desktop's theme.
+ assert "GTK_THEME" not in run["env"]
+ assert "LD_LIBRARY_PATH" not in run["env"]
+ assert run["env"]["UNSLOTH_HOST_LD_LIBRARY_PATH"] == "/opt/lib"
+ assert not (tmp_path / "state/unsloth-studio").exists()
+
+ # The probe saw the same cleaned environment from /, with no library path.
+ probe = (tmp_path / "probe-ran").read_text(encoding = "utf-8").splitlines()
+ assert probe[0] == "cwd=/"
+ probe_env = dict(line.split("=", 1) for line in probe[1:] if "=" in line)
+ assert "LD_LIBRARY_PATH" not in probe_env
+ for name in (*_HOOK_PINNED, "GTK_THEME"):
+ assert name not in probe_env
+ assert probe_env.get("XDG_DATA_DIRS") == restored
+
+
+def test_apprun_host_mode_keeps_an_explicit_theme_and_survives_a_relaunch(tmp_path):
+ appdir = _apprun_mount(tmp_path, host_copy = True, hooked = True)
+ # A bundled-mode parent restarting through $APPIMAGE passes its hooked XDG_DATA_DIRS back in.
+ relaunched = f"{appdir}/usr/share:/usr/share:/a:/b"
+ run = _launch(
+ appdir,
+ tmp_path,
+ XDG_DATA_DIRS = relaunched,
+ APPIMAGE_GTK_THEME = "Breeze:dark",
+ UNSLOTH_APPIMAGE_WEBKIT_MODE = "bundled",
+ )
+ assert run["mode"][0] == "host"
+ _assert_host_env_restored(run, appdir)
+ assert run["env"]["XDG_DATA_DIRS"] == "/a:/b"
+ assert run["env"]["GTK_THEME"] == "Breeze:dark"
+
+ stray = _launch(appdir, tmp_path, XDG_DATA_DIRS = f"/a:{appdir}/usr/share/extra:/b:{appdir}")
+ assert stray["env"]["XDG_DATA_DIRS"] == "/a:/b"
+
+
+ "policy",
+ [
+ "{state}/unsloth-studio/fonts-.mount_UnslotOLD.conf",
+ "/tmp/.mount_UnslotOLD/usr/etc/fonts/unsloth-appimage.conf",
+ ],
+ ids = ["written", "template"],
+)
+def test_apprun_host_mode_drops_a_bundled_parents_font_policy(tmp_path, policy):
+ # The updater's relaunch inherits the bundled-mode parent's FONTCONFIG_FILE.
+ appdir = _apprun_mount(tmp_path, host_copy = True, hooked = True)
+ inherited = policy.format(state = tmp_path / "state")
+ run = _launch(
+ appdir, tmp_path, FONTCONFIG_FILE = inherited, UNSLOTH_APPIMAGE_WEBKIT_MODE = "bundled"
+ )
+ assert run["mode"][0] == "host"
+ _assert_host_env_restored(run, appdir)
+
+ operator = _launch(appdir, tmp_path, FONTCONFIG_FILE = "/etc/fonts/custom.conf")
+ assert operator["env"]["FONTCONFIG_FILE"] == "/etc/fonts/custom.conf"
+
+
+ ("knobs", "reason"),
+ [
+ ({"FAKE_PROBE_OUTPUT": "webkit=2.52.6\\n"}, "reason: version 2.52.6 < 2.54"),
+ ({"FAKE_PROBE_OUTPUT": "webkit=1.99.0\\n"}, "reason: version 1.99.0 < 2.54"),
+ ({"FAKE_PROBE_EXIT": "3"}, "reason: probe exit 3"),
+ ({"FAKE_PROBE_OUTPUT": "", "FAKE_PROBE_EXIT": "127"}, "reason: probe exit 127"),
+ ({"FAKE_PROBE_OUTPUT": "webkit=2.54\\n"}, "reason: unrecognized probe output"),
+ ({"FAKE_PROBE_OUTPUT": "webkit=2.54.2x\\n"}, "reason: unrecognized probe output"),
+ ({"FAKE_PROBE_OUTPUT": "webkit=12345.0.0\\n"}, "reason: unrecognized probe output"),
+ ({"FAKE_PROBE_OUTPUT": "WebKit 2.54.2\\n"}, "reason: unrecognized probe output"),
+ (
+ {"FAKE_PROBE_OUTPUT": "webkit=2.54.2\\nwebkit=2.54.2\\n"},
+ "reason: unrecognized probe output",
+ ),
+ ({"FAKE_PROBE_OUTPUT": ""}, "reason: unrecognized probe output"),
+ ],
+ ids = [
+ "2.52.6",
+ "1.x",
+ "exit-3",
+ "exit-127",
+ "two-part",
+ "suffix",
+ "huge",
+ "garbage",
+ "two-lines",
+ "empty",
+ ],
+)
+def test_apprun_falls_back_to_the_bundle_when_the_probe_does_not_prove_the_host(
+ tmp_path, knobs, reason
+):
+ appdir = _apprun_mount(tmp_path, host_copy = True, hooked = True)
+ run = _launch(appdir, tmp_path, **knobs)
+ assert run["probed"]
+ assert run["mode"] == ("bundled", reason)
+ assert run["exe"] == "bundled"
+ assert run["env"]["UNSLOTH_APPIMAGE_WEBKIT_MODE"] == "bundled"
+ assert run["env"]["GTK_PATH"].startswith(str(appdir))
+
+
+def test_apprun_gives_a_hung_probe_five_seconds(tmp_path):
+ appdir = _apprun_mount(tmp_path, host_copy = True, hooked = True)
+ run = _launch(appdir, tmp_path, FAKE_PROBE_SLEEP = "30")
+ assert run["mode"] == ("bundled", "reason: probe exit 124")
+ assert run["exe"] == "bundled"
+ assert run["elapsed"] < 7
+
+
+def test_apprun_needs_a_host_copy_whatever_the_override(tmp_path):
+ appdir = _apprun_mount(tmp_path, hooked = True)
+ for request in (None, "auto", "host", "bundled"):
+ run = _launch(appdir, tmp_path, UNSLOTH_APPIMAGE_WEBKIT = request)
+ assert run["mode"] == ("bundled", "reason: no host copy")
+ assert run["exe"] == "bundled"
+
+
+def test_apprun_overrides_skip_the_probe(tmp_path):
+ appdir = _apprun_mount(tmp_path, host_copy = True, hooked = True)
+
+ bundled = _launch(appdir, tmp_path, UNSLOTH_APPIMAGE_WEBKIT = "bundled")
+ assert bundled["mode"] == ("bundled", "reason: override")
+ assert bundled["exe"] == "bundled"
+ assert not bundled["probed"]
+
+ # Forced host runs the host copy even where auto would refuse it.
+ forced = _launch(
+ appdir,
+ tmp_path,
+ UNSLOTH_APPIMAGE_WEBKIT = "host",
+ FAKE_PROBE_OUTPUT = "webkit=2.52.6\\n",
+ LD_LIBRARY_PATH = "/opt/lib",
+ )
+ assert forced["mode"] == ("host", "override, UNSLOTH_APPIMAGE_WEBKIT=host")
+ assert forced["exe"] == "host"
+ assert not forced["probed"]
+ _assert_host_env_restored(forced, appdir)
+ assert "LD_LIBRARY_PATH" not in forced["env"]
+
+ empty = _launch(appdir, tmp_path, UNSLOTH_APPIMAGE_WEBKIT = "")
+ assert empty["mode"][0] == "host" and empty["probed"]
+
+
[email protected]("request_value", ["HOST", "x", "host\nruntime=host", "$(id)"])
+def test_apprun_treats_an_unknown_override_as_bundled(tmp_path, request_value):
+ appdir = _apprun_mount(tmp_path, host_copy = True, hooked = True)
+ run = _launch(appdir, tmp_path, UNSLOTH_APPIMAGE_WEBKIT = request_value)
+ assert run["exe"] == "bundled"
+ assert not run["probed"]
+ mode, detail = run["mode"]
+ assert mode == "bundled"
+ assert re.fullmatch(r"reason: invalid override '[A-Za-z0-9._?-]*'", detail)
+ assert run["stderr"].count("\n") == 1
+
+
+def test_apprun_overwrites_an_inherited_mode_in_bundled_mode(tmp_path):
+ appdir = _apprun_mount(tmp_path)
+ run = _launch(appdir, tmp_path, UNSLOTH_APPIMAGE_WEBKIT_MODE = "host")
+ assert run["mode"] == ("bundled", "reason: no host copy")
+ assert run["env"]["UNSLOTH_APPIMAGE_WEBKIT_MODE"] == "bundled"
+
+
+MAIN_APPRUN_REVISION = "a1064bb8e6dbbd527761436605c20cdb59cb2a94"
+
+
+ ("host_copy", "knobs", "reason"),
+ [
+ (False, {}, "reason: no host copy"),
+ (True, {"FAKE_PROBE_OUTPUT": "", "FAKE_PROBE_EXIT": "127"}, "reason: probe exit 127"),
+ (True, {"FAKE_PROBE_OUTPUT": "webkit=2.52.6\\n"}, "reason: version 2.52.6 < 2.54"),
+ (True, {"UNSLOTH_APPIMAGE_WEBKIT": "bundled"}, "reason: override"),
+ (True, {"UNSLOTH_APPIMAGE_WEBKIT": "x"}, "reason: invalid override 'x'"),
+ ],
+ ids = ["no-copy", "probe-127", "2.52", "override", "invalid"],
+)
+def test_bundled_mode_matches_the_launcher_before_host_mode(tmp_path, host_copy, knobs, reason):
+ """Bundled mode adds only UNSLOTH_APPIMAGE_WEBKIT_MODE and its one stderr line."""
+
+ shown = subprocess.run(
+ [
+ "git",
+ "-C",
+ REPO_ROOT,
+ "show",
+ f"{MAIN_APPRUN_REVISION}:studio/src-tauri/linux/appimage-apprun.sh",
+ ],
+ capture_output = True,
+ )
+ if shown.returncode != 0:
+ pytest.skip(f"{MAIN_APPRUN_REVISION} is not in this clone")
+ appdir = _apprun_mount(tmp_path, host_copy = host_copy, hooked = True)
+ knobs = {"LD_LIBRARY_PATH": "/opt/lib", "XDG_DATA_DIRS": "/a:/b", **knobs}
+
+ current = _launch(appdir, tmp_path, ["--x", "y z"], **knobs)
+ (appdir / "AppRun.wrapped").write_bytes(shown.stdout)
+ before = _launch(appdir, tmp_path, ["--x", "y z"], **knobs)
+
+ assert current["mode"] == ("bundled", reason)
+ assert current["stderr"].splitlines() == [
+ f"unsloth-studio: AppImage WebKitGTK runtime=bundled ({reason})"
+ ]
+ assert before["stderr"] == ""
+ for key in ("exe", "cwd", "argv"):
+ assert current[key] == before[key]
+ added = {k: v for k, v in current["env"].items() if before["env"].get(k) != v}
+ removed = set(before["env"]) - set(current["env"])
+ assert added == {"UNSLOTH_APPIMAGE_WEBKIT_MODE": "bundled"}
+ assert not removed
+
+
+def _host_capable_appdir(tmp_path: Path) -> Path:
+ """A verifier fixture whose real launcher can run a host-mode copy."""
+
+ appdir = _fake_complete_appdir(tmp_path)
+ (appdir / "AppRun.wrapped").write_bytes(APPRUN.read_bytes())
+ host = appdir / "usr/bin/host/unsloth-studio"
+ host.parent.mkdir()
+ shutil.copy2(appdir / "usr/bin/unsloth-studio", host)
+ return appdir
+
+
+def _verify(appdir: Path):
+ return subprocess.run(
+ [VERIFIER, "--appdir", appdir], check = False, capture_output = True, text = True
+ )
+
+
+def _path_without(tmp_path: Path, missing: str) -> str:
+ """A PATH holding every executable on the current one except ``missing``."""
+ shadow = tmp_path / f"path-without-{missing}"
+ shadow.mkdir()
+ for directory in os.environ.get("PATH", "").split(os.pathsep):
+ if not directory or not os.path.isdir(directory):
+ continue
+ for entry in os.scandir(directory):
+ target = shadow / entry.name
+ if entry.name == missing or target.exists():
+ continue
+ if entry.is_file() and os.access(entry.path, os.X_OK):
+ target.symlink_to(entry.path)
+ return str(shadow)
+
+
+def test_complete_appimage_verifier_compares_the_host_copy_without_cmp(tmp_path):
+ # fedora:44 has no diffutils, so cmp is absent there.
+ env = {**os.environ, "PATH": _path_without(tmp_path, "cmp")}
+ appdir = _host_capable_appdir(tmp_path / "same")
+ result = subprocess.run(
+ [VERIFIER, "--appdir", appdir], check = False, capture_output = True, text = True, env = env
+ )
+ assert result.returncode == 0, result.stderr
+ assert "cmp: command not found" not in result.stderr
+
+ differing = _host_capable_appdir(tmp_path / "differs")
+ with open(differing / "usr/bin/host/unsloth-studio", "ab") as handle:
+ handle.write(b"x")
+ result = subprocess.run(
+ [VERIFIER, "--appdir", differing], check = False, capture_output = True, text = True, env = env
+ )
+ assert result.returncode != 0
+ assert "differs from usr/bin/unsloth-studio" in result.stderr
+
+
+def test_complete_appimage_verifier_accepts_a_host_capable_runtime_and_the_shipped_layout(tmp_path):
+ result = _verify(_host_capable_appdir(tmp_path / "host"))
+ assert result.returncode == 0, result.stderr
+
+ # Shipped releases have neither the copy nor a launcher that runs it.
+ shipped = _fake_complete_appdir(tmp_path / "shipped")
+ assert "usr/bin/host" not in (shipped / "AppRun").read_text(encoding = "utf-8")
+ result = _verify(shipped)
+ assert result.returncode == 0, result.stderr
+
+
+def test_complete_appimage_verifier_rejects_an_incoherent_host_copy(tmp_path):
+ differs = _host_capable_appdir(tmp_path / "differs")
+ with open(differs / "usr/bin/host/unsloth-studio", "ab") as host:
+ host.write(b"\0")
+ result = _verify(differs)
+ assert result.returncode != 0
+ assert "differs from usr/bin/unsloth-studio" in result.stderr
+
+ reaches = _host_capable_appdir(tmp_path / "reaches")
+ (reaches / "usr/bin/lib").mkdir()
+ result = _verify(reaches)
+ assert result.returncode != 0
+ assert "usr/bin/lib" in result.stderr
+
+ missing = _host_capable_appdir(tmp_path / "missing")
+ shutil.rmtree(missing / "usr/bin/host")
+ result = _verify(missing)
+ assert result.returncode != 0
+ assert "missing host-mode executable" in result.stderr
+
+ unprobed = _host_capable_appdir(tmp_path / "unprobed")
+ launcher = unprobed / "AppRun.wrapped"
+ launcher.write_text(
+ launcher.read_text(encoding = "utf-8").replace("--unsloth-webkit-probe", "--no-probe"),
+ encoding = "utf-8",
+ )
+ result = _verify(unprobed)
+ assert result.returncode != 0
+ assert "without the WebKitGTK probe" in result.stderr
+
+
+def test_complete_appimage_verifier_rejects_a_hook_export_host_mode_does_not_undo(tmp_path):
+ appdir = _host_capable_appdir(tmp_path)
+ hook = appdir / "apprun-hooks/linuxdeploy-plugin-gstreamer.sh"
+ hook.write_text(
+ 'export GST_REGISTRY_REUSE_PLUGIN_SCANNER="no"\n'
+ 'export GST_PLUGIN_PATH_1_0="${APPDIR}/usr/lib/gstreamer-1.0"\n'
+ 'export GST_PLUGIN_FEATURE_RANK_PATH="${APPDIR}/usr/lib/ranks"\n',
+ encoding = "utf-8",
+ )
+ result = _verify(appdir)
+ assert result.returncode != 0
+ assert "GST_PLUGIN_FEATURE_RANK_PATH" in result.stderr
+ assert "GST_PLUGIN_PATH_1_0" not in result.stderr
+
+
+def _finalizer_tools(tmp_path: Path) -> Path:
+ """The finalizer beside the assets prepare-complete-appimage-tools.sh stages next to it."""
+
+ tools = tmp_path / "tools"
+ tools.mkdir()
+ shutil.copy2(FINALIZER, tools / FINALIZER.name)
+ (tools / "UnslothSafeEmoji.ttf").write_bytes(b"fixture CBDT CBLC")
+ (tools / "UnslothSafeEmoji.LICENSE").write_text("fixture\n", encoding = "utf-8")
+ shutil.copy2(FONTCONFIG, tools / "unsloth-appimage-fonts.conf")
+ return tools / FINALIZER.name
+
+
+def _runpath(path: Path) -> str:
+ dynamic = subprocess.run(
+ ["readelf", "-d", path], check = True, capture_output = True, text = True
+ ).stdout
+ return re.search(r"\((?:RUNPATH|RPATH)\).*\[(.*)\]", dynamic).group(1)
+
+
[email protected](shutil.which("patchelf") is None, reason = "the finalizer needs patchelf")
+def test_finalizer_adds_an_identical_host_copy_and_stays_idempotent(tmp_path):
+ finalizer = _finalizer_tools(tmp_path)
+ appdir = tmp_path / "AppDir"
+ binary = appdir / "usr/bin/unsloth-studio"
+ binary.parent.mkdir(parents = True)
+ _compile_fixture_elf(binary, origin_runpath = False)
+ (appdir / "usr/lib").mkdir()
+ _compile_fixture_elf(appdir / "usr/lib/WebKitWebProcess", origin_runpath = False)
+ host = appdir / "usr/bin/host/unsloth-studio"
+
+ # linuxdeploy runs the finalizer once from each of the gtk and gstreamer plugins.
+ for _ in range(2):
+ subprocess.run([finalizer, appdir], check = True, capture_output = True, text = True)
+ assert host.read_bytes() == binary.read_bytes()
+ assert os.access(host, os.X_OK)
+ assert _runpath(host) == "$ORIGIN/../lib"
+ assert _runpath(binary) == "$ORIGIN/../lib"
+ assert _runpath(appdir / "usr/lib/WebKitWebProcess") == "$ORIGIN"
+ assert not (appdir / "usr/bin/lib").exists()
+
+ (appdir / "usr/bin/lib").mkdir()
+ result = subprocess.run([finalizer, appdir], check = False, capture_output = True, text = True)
+ assert result.returncode != 0
+ assert "usr/bin/lib" in result.stderr
+
+
+def test_apprun_never_probes_without_a_timeout(tmp_path):
+ tools = tmp_path / "bin"
+ tools.mkdir()
+ for tool in ("dirname", "sed", "mkdir", "head", "rm", "tr", "cut"):
+ (tools / tool).symlink_to(shutil.which(tool))
+ appdir = _apprun_mount(tmp_path, host_copy = True)
+ run = _launch(appdir, tmp_path, PATH = str(tools))
+ assert run["mode"] == ("bundled", "reason: no timeout")
+ assert run["exe"] == "bundled"
+ assert not run["probed"]
diff --git a/tests/studio/appimage_portability_smoke.py b/tests/studio/appimage_portability_smoke.py
index cb4f5c82a92..20dd6c52d9a 100644
--- a/tests/studio/appimage_portability_smoke.py
+++ b/tests/studio/appimage_portability_smoke.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import hashlib
import json
import os
+import re
import shutil
import signal
import subprocess
@@ -52,6 +53,164 @@ def _abandoned_reason(tauri_log: Path) -> str | None:
return detail or "preflight abandoned the fixture backend; see tauri.log"
+# /proc/<pid>/comm keeps 15 bytes, so WebKit's helpers appear truncated.
+_WEBKIT_COMMS = {"unsloth-studio", "WebKitWebProces", "WebKitNetworkPr"}
+_MODE_LINE = re.compile(r"AppImage WebKitGTK runtime=(\w+)")
+_EXPECTED_MODES = ("host", "bundled")
+
+
+def _proc_tree(root_pid: int) -> list[int]:
+ """The launch's descendants plus its process group; the WebKit sandbox may call setsid."""
+ parents: dict[int, int] = {}
+ groups: dict[int, int] = {}
+ for entry in Path("/proc").iterdir():
+ if not entry.name.isdigit():
+ continue
+ try:
+ stat = (entry / "stat").read_text(encoding = "utf-8", errors = "replace")
+ except OSError:
+ continue
+ fields = stat.rsplit(")", 1)[-1].split()
+ if len(fields) < 3:
+ continue
+ parents[int(entry.name)] = int(fields[1])
+ groups[int(entry.name)] = int(fields[2])
+ found = {pid for pid, group in groups.items() if group == root_pid}
+ found.add(root_pid)
+ grew = True
+ while grew:
+ grew = False
+ for pid, parent in parents.items():
+ if parent in found and pid not in found:
+ found.add(pid)
+ grew = True
+ return sorted(found)
+
+
+def _read_proc(pid: int) -> dict[str, object] | None:
+ base = Path("/proc") / str(pid)
+ try:
+ comm = (base / "comm").read_text(encoding = "utf-8", errors = "replace").strip()
+ except OSError:
+ return None
+ if comm not in _WEBKIT_COMMS:
+ return None
+ # An unreadable process is reported, never silently skipped: it could hide a mixed stack.
+ try:
+ exe = os.readlink(base / "exe")
+ maps = (base / "maps").read_text(encoding = "utf-8", errors = "replace")
+ except OSError as error:
+ return {"pid": pid, "comm": comm, "error": str(error), "exe": "", "maps": []}
+ try:
+ environ = (base / "environ").read_bytes()
+ except OSError:
+ environ = b""
+ paths = sorted(
+ {
+ fields[5].removesuffix(" (deleted)")
+ for fields in (line.split(maxsplit = 5) for line in maps.splitlines())
+ if len(fields) == 6 and fields[5].startswith("/")
+ }
+ )
+ env = dict(
+ item.split("=", 1) for item in environ.decode(errors = "replace").split("\0") if "=" in item
+ )
+ return {
+ "pid": pid,
+ "comm": comm,
+ "exe": exe,
+ "appdir": env.get("APPDIR", ""),
+ "mode_env": env.get("UNSLOTH_APPIMAGE_WEBKIT_MODE"),
+ "maps": paths,
+ }
+
+
+def _assert_webkit_runtime(
+ expected: str, root_pid: int, app_log: Path, tauri_log: Path, art_dir: Path
+) -> None:
+ """Prove which WebKitGTK stack the session really loaded, from the processes themselves."""
+ text = app_log.read_text(encoding = "utf-8", errors = "replace")
+ modes = _MODE_LINE.findall(text)
+ if not modes:
+ raise RuntimeError("AppRun printed no 'AppImage WebKitGTK runtime=' line")
+ if set(modes) != {expected}:
+ raise RuntimeError(f"AppRun chose WebKitGTK runtime={modes}, expected {expected}")
+ logged = ""
+ if tauri_log.is_file():
+ logged = tauri_log.read_text(encoding = "utf-8", errors = "replace")
+ if f"AppImage WebKitGTK runtime: {expected}" not in logged:
+ raise RuntimeError(f"tauri.log does not record 'AppImage WebKitGTK runtime: {expected}'")
+
+ # The web process can trail the login request by a moment.
+ deadline = time.monotonic() + 10
+ while True:
+ processes = [info for pid in _proc_tree(root_pid) if (info := _read_proc(pid))]
+ if any(info["comm"] == "WebKitWebProces" for info in processes) or (
+ time.monotonic() >= deadline
+ ):
+ break
+ time.sleep(0.25)
+ (art_dir / "webkit-runtime.json").write_text(
+ json.dumps({"expected": expected, "mode_lines": modes, "processes": processes}, indent = 2),
+ encoding = "utf-8",
+ )
+
+ unreadable = [
+ f"{info['comm']}[{info['pid']}]: {info['error']}" for info in processes if "error" in info
+ ]
+ if unreadable:
+ raise RuntimeError("could not inspect session processes: " + ", ".join(unreadable))
+ apps = [info for info in processes if info["comm"] == "unsloth-studio"]
+ if not apps:
+ raise RuntimeError("no unsloth-studio process found in the launched session")
+ appdir = next((str(info["appdir"]) for info in apps if info["appdir"]), "")
+ if not appdir:
+ raise RuntimeError("unsloth-studio has no APPDIR in its environment")
+ # exe and maps report resolved paths.
+ appdir = os.path.realpath(appdir)
+ bundled_lib = appdir.rstrip("/") + "/usr/lib/"
+ for info in apps:
+ if info["mode_env"] != expected:
+ raise RuntimeError(
+ f"unsloth-studio {info['pid']} has "
+ f"UNSLOTH_APPIMAGE_WEBKIT_MODE={info['mode_env']!r}, expected {expected}"
+ )
+
+ if expected == "host":
+ host_exe = appdir.rstrip("/") + "/usr/bin/host/unsloth-studio"
+ wrong = [f"{info['pid']}: {info['exe']}" for info in apps if info["exe"] != host_exe]
+ if wrong:
+ raise RuntimeError(f"host mode did not exec {host_exe}: " + ", ".join(wrong))
+ if not any(info["comm"] == "WebKitWebProces" for info in processes):
+ raise RuntimeError("host mode session has no WebKitWebProcess to inspect")
+ mixed = [
+ f"{info['comm']}[{info['pid']}]: {path}"
+ for info in processes
+ for path in info["maps"]
+ if str(path).startswith(bundled_lib)
+ ]
+ if mixed:
+ raise RuntimeError(
+ "host mode mapped bundled libraries (mixed stack):\n" + "\n".join(mixed[:40])
+ )
+ else:
+ bundled_exe = appdir.rstrip("/") + "/usr/bin/unsloth-studio"
+ wrong = [f"{info['pid']}: {info['exe']}" for info in apps if info["exe"] != bundled_exe]
+ if wrong:
+ raise RuntimeError(f"bundled mode did not exec {bundled_exe}: " + ", ".join(wrong))
+ webkit = [
+ path for info in apps for path in info["maps"] if "libwebkit2gtk-4.1" in str(path)
+ ]
+ if not any(str(path).startswith(bundled_lib) for path in webkit):
+ raise RuntimeError(
+ f"bundled mode did not map libwebkit2gtk-4.1 from {bundled_lib}: {webkit}"
+ )
+ print(
+ f"PASS AppImage WebKitGTK runtime={expected} across "
+ + ", ".join(f"{info['comm']}[{info['pid']}]" for info in processes)
+ )
+
+
def _write_fixture(art_dir: Path, home: Path, version: str) -> Path:
request_log = art_dir / "backend-requests.jsonl"
backend = art_dir / "backend.py"
@@ -201,6 +360,9 @@ def main() -> None:
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")
+ expected_mode = os.environ.get("APPIMAGE_EXPECTED_WEBKIT_MODE", "")
+ if expected_mode and expected_mode not in _EXPECTED_MODES:
+ raise SystemExit(f"Unsupported APPIMAGE_EXPECTED_WEBKIT_MODE: {expected_mode}")
art_dir = Path(os.environ.get("APPIMAGE_SMOKE_ART_DIR", "logs/appimage-portability")).resolve()
if art_dir.exists():
@@ -297,6 +459,14 @@ def main() -> None:
art_dir / "app-stdout.log",
home / ".unsloth/studio/tauri.log",
)
+ if expected_mode:
+ _assert_webkit_runtime(
+ expected_mode,
+ process.pid,
+ art_dir / "app-stdout.log",
+ home / ".unsloth/studio/tauri.log",
+ art_dir,
+ )
print(
"PASS complete AppImage rendered startup and completed desktop auth "
f"on {display_backend}"
diff --git a/tests/studio/test_appimage_toolchain_contract.py b/tests/studio/test_appimage_toolchain_contract.py
index e62e1e7e4ee..5adcd2dc919 100644
--- a/tests/studio/test_appimage_toolchain_contract.py
+++ b/tests/studio/test_appimage_toolchain_contract.py
@@ -63,3 +63,121 @@ fetch "$APPIMAGE_PLUGIN_URL" "$APPIMAGE_PLUGIN_SHA256" linuxdeploy-plugin-appima
"""
with pytest.raises(AssertionError, match = "APPIMAGE_PLUGIN_URL"):
_assert_no_rolling_release_aliases(former_pin)
+
+
+APPRUN = REPO / "studio/src-tauri/linux/appimage-apprun.sh"
+FINALIZER = REPO / "studio/src-tauri/linux/finalize-complete-appimage.sh"
+CLEAN_MACHINE_CI = REPO / ".github/workflows/desktop-app-clean-machine-ci.yml"
+PROBE_FLAG = "--unsloth-webkit-probe"
+HOST_EXE = "usr/bin/host/unsloth-studio"
+# Every variable the pinned gtk and gstreamer hooks point into the bundle.
+HOOK_VARIABLES = (
+ "GTK_DATA_PREFIX",
+ "GTK_EXE_PREFIX",
+ "GTK_PATH",
+ "GTK_IM_MODULE_FILE",
+ "GDK_PIXBUF_MODULE_FILE",
+ "GSETTINGS_SCHEMA_DIR",
+ "GIO_MODULE_DIR",
+ "GIO_EXTRA_MODULES",
+ "GST_REGISTRY_REUSE_PLUGIN_SCANNER",
+ "GST_PLUGIN_SYSTEM_PATH_1_0",
+ "GST_PLUGIN_PATH_1_0",
+ "GST_PLUGIN_SCANNER_1_0",
+ "GST_PTP_HELPER_1_0",
+)
+
+
+def _code_lines(path: Path) -> list[str]:
+ """Shell lines without comments, with backslash continuations joined."""
+ joined = path.read_text(encoding = "utf-8").replace("\\\n", " ")
+ return [
+ line.strip()
+ for line in joined.splitlines()
+ if line.strip() and not line.strip().startswith("#")
+ ]
+
+
+def _unset_names(lines: list[str]) -> set[str]:
+ names: set[str] = set()
+ for line in lines:
+ for statement in re.split(r"[;&|]+", line):
+ words = statement.split()
+ if words[:1] == ["unset"]:
+ names.update(word for word in words[1:] if not word.startswith("-"))
+ return names
+
+
+def test_apprun_probes_the_host_copy_only_under_a_timeout() -> None:
+ lines = _code_lines(APPRUN)
+ probes = [line for line in lines if PROBE_FLAG in line]
+ assert probes, f"AppRun must probe the host copy with {PROBE_FLAG}"
+ for line in probes:
+ assert "timeout -k 1 5" in line, f"probe runs without `timeout -k 1 5`: {line}"
+ assert "</dev/null" in line, f"probe must not read the caller's stdin: {line}"
+ assert any(HOST_EXE in line for line in lines), f"AppRun never names {HOST_EXE}"
+
+
+def test_apprun_restores_every_hook_variable_in_host_mode() -> None:
+ lines = _code_lines(APPRUN)
+ missing = sorted(set(HOOK_VARIABLES) - _unset_names(lines))
+ assert not missing, "host mode leaves bundle paths set: " + ", ".join(missing)
+ text = "\n".join(lines)
+ assert "APPIMAGE_GTK_THEME" in text and "GTK_THEME" in _unset_names(lines)
+ assert "XDG_DATA_DIRS" in text
+ # Both modes keep the loader guard the verifier requires.
+ assert "LD_LIBRARY_PATH" in _unset_names(lines)
+ assert "UNSLOTH_HOST_LD_LIBRARY_PATH" in text
+ assert re.search(r"export\s+(\w+\s+)*UNSLOTH_APPIMAGE_WEBKIT_MODE\b", text) or re.search(
+ r"export\s+UNSLOTH_APPIMAGE_WEBKIT_MODE=", text
+ ), "AppRun must export UNSLOTH_APPIMAGE_WEBKIT_MODE"
+ assert "AppImage WebKitGTK runtime=" in text, "AppRun must log the chosen runtime"
+
+
+def test_apprun_has_exactly_one_exec_per_mode() -> None:
+ launches = [
+ line
+ for line in _code_lines(APPRUN)
+ if re.match(r"exec\s", line) and '"$@"' in line and "timeout" not in line
+ ]
+ host = [line for line in launches if HOST_EXE in line]
+ bundled = [line for line in launches if re.search(r"usr/bin/unsloth-studio\b", line)]
+ assert len(host) == 1, f"expected one host-mode exec, got {host}"
+ assert len(bundled) == 1, f"expected one bundled-mode exec, got {bundled}"
+ assert len(launches) == 2, f"unexpected app exec lines: {launches}"
+
+
+def test_finalizer_keeps_the_host_copy_out_of_the_runpath_loop() -> None:
+ text = FINALIZER.read_text(encoding = "utf-8")
+ loop_start = text.index("patched=0")
+ loop_end = text.index("((patched > 0))")
+ assert (
+ "usr/bin/host" in text[loop_start:loop_end]
+ ), "the RUNPATH loop must skip usr/bin/host so the copy keeps $ORIGIN/../lib"
+ shell_vars = dict(re.findall(r'^\s*([a-z_][a-z0-9_]*)="([^"]*)"', text, re.MULTILINE))
+
+ def expand(word: str) -> str:
+ return re.sub(r"\$\{?([a-z_][a-z0-9_]*)\}?", lambda m: shell_vars.get(m[1], m[0]), word)
+
+ install = next(
+ (
+ match
+ for match in re.finditer(r"install -D -m 755 (\S+) (\S+)", text)
+ if "usr/bin/unsloth-studio" in match[1] and HOST_EXE in expand(match[2])
+ ),
+ None,
+ )
+ assert install, "finalizer must install the host copy of the main binary"
+ assert install.start() > text.index(
+ "patchelf --set-rpath"
+ ), "the host copy must be made after the RUNPATH loop"
+ assert "usr/bin/lib" in text, "finalizer must reject a usr/bin/lib the host copy would reach"
+
+
+def test_portability_mode_assertions_run_only_against_the_pr_build() -> None:
+ """Scheduled runs test the shipped release, which has no host copy."""
+ text = CLEAN_MACHINE_CI.read_text(encoding = "utf-8")
+ assignments = re.findall(r"APPIMAGE_EXPECTED_WEBKIT_MODE:\s*(.+)", text)
+ assert assignments, "the portability smoke must receive APPIMAGE_EXPECTED_WEBKIT_MODE"
+ for value in assignments:
+ assert "github.event_name == 'pull_request'" in value, value