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.

Uninstaller: reject unrecognized arguments instead of uninstalling (#7631)

oobaboogaa1dcd94846a4
diff --git a/.github/workflows/studio-windows-update-smoke.yml b/.github/workflows/studio-windows-update-smoke.yml
index 0dcc828e6b9..45ecd95a4df 100644
--- a/.github/workflows/studio-windows-update-smoke.yml
+++ b/.github/workflows/studio-windows-update-smoke.yml
@@ -24,6 +24,7 @@ on:
paths:
- 'install.ps1'
- 'scripts/uninstall.ps1'
+ - 'tests/studio/test_uninstall_*.ps1'
- 'studio/setup.ps1'
- 'studio/setup.bat'
- 'studio/install_python_stack.py'
@@ -62,6 +63,17 @@ jobs:
with:
persist-credentials: false
+ # This workflow triggers on uninstall.ps1, so run both uninstaller unit
+ # tests here. The guard test cannot perform a real uninstall.
+ - name: uninstall.ps1 unit tests (argument guard, dual-install icon preserve)
+ shell: pwsh
+ run: |
+ # Propagate each child test's failure before continuing.
+ pwsh -NoProfile -File tests/studio/test_uninstall_arg_guard.ps1
+ if ($LASTEXITCODE) { exit $LASTEXITCODE }
+ pwsh -NoProfile -File tests/studio/test_uninstall_dual_install_icon.ps1
+ if ($LASTEXITCODE) { exit $LASTEXITCODE }
+
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
node-version: '22'
diff --git a/scripts/uninstall.ps1 b/scripts/uninstall.ps1
index 9b6e6ebb866..b524b129689 100644
--- a/scripts/uninstall.ps1
+++ b/scripts/uninstall.ps1
@@ -1,11 +1,10 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
#
-# Unsloth Studio uninstaller for Windows PowerShell.
-# Stops running servers and removes install dir, launcher data, CLI shim,
-# desktop and Start Menu shortcuts, the user PATH entry, and the PathBackup
-# registry key. Honors custom roots set via UNSLOTH_STUDIO_HOME / STUDIO_HOME
-# at install time (read back from share\studio.conf).
+# Unsloth Studio uninstaller for Windows PowerShell. Run -Help for removal
+# details and options.
+# Custom roots set via UNSLOTH_STUDIO_HOME / STUDIO_HOME at install time are
+# read back from share\studio.conf.
#
# Usage: irm https://raw.githubusercontent.com/unslothai/unsloth/main/scripts/uninstall.ps1 | iex
# Local: Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass; .\scripts\uninstall.ps1
@@ -13,6 +12,40 @@
function Uninstall-UnslothStudio {
$ErrorActionPreference = "Continue"
+ function _Usage {
+ Write-Host @'
+Unsloth Studio uninstaller (Windows PowerShell).
+
+Usage:
+ irm https://raw.githubusercontent.com/unslothai/unsloth/main/scripts/uninstall.ps1 | iex
+ Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass; .\scripts\uninstall.ps1
+
+Stops running Unsloth Studio servers, then removes the install dir, launcher
+data, CLI shim, desktop and Start Menu shortcuts, the user PATH entry and the
+PathBackup registry key. The Hugging Face cache is left in place.
+
+Options:
+ -Help, -h, --help, -?, /? Print this message and exit without removing anything.
+
+Run with no arguments to uninstall. Unrecognized arguments never trigger
+removal.
+
+Environment:
+ UNSLOTH_STUDIO_HOME Also remove this custom install root. Set it to the value
+ used at install time.
+ STUDIO_HOME Alias for the above, ignored when both are set.
+'@
+ }
+
+ # Reject unknown arguments before destructive work. Use throw so embedded
+ # invocations report failure without exiting the caller's PowerShell session.
+ foreach ($arg in $args) {
+ if ($arg -in @('-h', '-help', '--help', '-?', '/?')) { _Usage; return }
+ Write-Host "uninstall.ps1: unrecognized argument: $arg" -ForegroundColor Red
+ Write-Host "Nothing was removed. Re-run with no arguments to uninstall, or -Help."
+ throw "uninstall.ps1: unrecognized argument: $arg"
+ }
+
function _Step { param([string]$Msg) Write-Host $Msg }
function _Substep { param([string]$Msg, [string]$Color = "Gray") Write-Host " $Msg" -ForegroundColor $Color }
diff --git a/scripts/uninstall.sh b/scripts/uninstall.sh
index 957d2b7af28..92ecfa48104 100755
--- a/scripts/uninstall.sh
+++ b/scripts/uninstall.sh
@@ -2,16 +2,46 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
#
-# Unsloth Studio uninstaller (macOS / Linux / WSL).
-# Stops running servers and removes install dir, launcher data,
-# CLI shim, desktop shortcut, .app bundle, and Launch Services entry.
-# Honors custom roots set via UNSLOTH_STUDIO_HOME / STUDIO_HOME at
-# install time (read back from studio.conf).
+# Unsloth Studio uninstaller (macOS / Linux / WSL). Run --help for removal
+# details and options.
+# Custom roots set via UNSLOTH_STUDIO_HOME / STUDIO_HOME at install time are
+# read back from studio.conf.
#
# Usage: curl -fsSL https://raw.githubusercontent.com/unslothai/unsloth/main/scripts/uninstall.sh | sh
set -e
+_usage() {
+ cat <<'EOF'
+Unsloth Studio uninstaller (macOS / Linux / WSL).
+
+Usage:
+ curl -fsSL https://raw.githubusercontent.com/unslothai/unsloth/main/scripts/uninstall.sh | sh
+ sh scripts/uninstall.sh
+
+Stops running Unsloth Studio servers, then removes the install dir, launcher
+data dir, CLI shim, desktop shortcut, macOS .app bundle and Launch Services
+entry. The Hugging Face cache at ~/.cache/huggingface is left in place.
+
+On WSL it also removes this distro's Windows-side shortcuts under /mnt/*/Users,
+strips the Unsloth block from ~/.bashrc, and uses sudo to delete
+/etc/profile.d/unsloth-rocm-wsl.sh.
+
+Options:
+ -h, --help Print this message and exit without removing anything.
+
+Run with no arguments to uninstall. Unrecognized arguments never trigger
+removal.
+
+Environment:
+ UNSLOTH_STUDIO_HOME Also remove this custom install root. Pass the value
+ used at install time.
+ STUDIO_HOME Alias for the above, ignored when both are set.
+ UNSLOTH_UNINSTALL_ROCM=1 Also remove system ROCm (WSL only). Off by default
+ because ROCm is a shared prerequisite.
+EOF
+}
+
# Stop an Unsloth server via its PID file (written by install.sh's _spawn_terminal).
_kill_pid_file() {
_pid_file="$1"
@@ -190,238 +220,258 @@ _remove_cli_shim() {
esac
}
-_uid=$(id -u 2>/dev/null || echo 0)
-_os=$(uname 2>/dev/null || echo unknown)
-_is_wsl=0
-[ "$_os" = "Linux" ] && grep -qi microsoft /proc/version 2>/dev/null && _is_wsl=1
-
-echo "Stopping any running Unsloth Studio servers..."
-_pkill_studio
+_unsloth_uninstall_main() {
+ # Reject unknown arguments before destructive work.
+ for _arg in "$@"; do
+ case "$_arg" in
+ -h|--help) _usage; return 0 ;;
+ *)
+ echo "uninstall.sh: unrecognized argument: $_arg" >&2
+ echo "Nothing was removed. Re-run with no arguments to uninstall, or --help." >&2
+ return 2
+ ;;
+ esac
+ done
-echo "Removing data and install directories..."
-_custom_studio_roots | while IFS= read -r _custom_root; do
- [ -n "$_custom_root" ] || continue
- if _is_unsafe_root "$_custom_root"; then
- echo " refusing to remove unsafe path: $_custom_root" >&2
- continue
- fi
- if ! _is_studio_root "$_custom_root"; then
- echo " refusing to remove non-Unsloth path: $_custom_root" >&2
- continue
- fi
- _remove_path "$_custom_root"
-done
-_remove_path "$HOME/.unsloth/studio"
-# Default-mode shared llama.cpp build + cache are siblings of studio (not removed
-# by deleting it). No-op in env/custom mode (they nest under the custom root) and
-# when absent. A user-set UNSLOTH_LLAMA_CPP_PATH is intentionally kept.
-_remove_path "$HOME/.unsloth/llama.cpp"
-_remove_path "$HOME/.unsloth/.cache"
-# Isolated Node.js runtime (install_node_prebuilt.py), a sibling of studio in
-# default mode. No-op in env/custom mode (nested under the custom root) and absent.
-_remove_path "$HOME/.unsloth/node"
-# llama.cpp atomic-install staging root (install_llama_prebuilt.py .staging).
-# Normally pruned after activate, but an interrupted build can leave it behind;
-# removing it lets the rmdir below succeed. No-op in env/custom mode and absent.
-_remove_path "$HOME/.unsloth/.staging"
-# llama.cpp install lock (serializes the shared build); a stray one keeps ~/.unsloth
-# from being pruned below. No-op in env/custom mode and when absent.
-_remove_path "$HOME/.unsloth/.llama.cpp.install.lock"
-# ROCm-on-WSL helper artifacts (librocdxg build clone + smoke-test venv). No-op
-# where they don't exist; removing them lets the rmdir below succeed.
-_remove_path "$HOME/.unsloth/librocdxg"
-_remove_path "$HOME/.unsloth/rocm-smoketest"
-# Drop ~/.unsloth only if now empty (rmdir refuses non-empty, so user content is kept).
-rmdir "$HOME/.unsloth" 2>/dev/null || true
-_remove_path "$HOME/.local/share/unsloth"
-# CLI shim: only the symlink Unsloth created, never a pip-installed file.
-_remove_cli_shim
+ _uid=$(id -u 2>/dev/null || echo 0)
+ _os=$(uname 2>/dev/null || echo unknown)
+ _is_wsl=0
+ [ "$_os" = "Linux" ] && grep -qi microsoft /proc/version 2>/dev/null && _is_wsl=1
-echo "Removing desktop shortcut and launcher lock..."
-# install.sh creates Desktop/Unsloth Studio as a symlink. If the user has an
-# unrelated regular directory by that name, leave it alone.
-_desktop_link="$HOME/Desktop/Unsloth Studio"
-if [ -L "$_desktop_link" ] || [ ! -e "$_desktop_link" ]; then
- _remove_path "$_desktop_link"
-else
- echo " refusing to remove non-symlink Desktop path: $_desktop_link" >&2
-fi
-_remove_path "$HOME/Desktop/unsloth-studio.desktop"
-# Locks are namespaced per-uid; env-mode adds an extra suffix.
-_lock_glob="${XDG_RUNTIME_DIR:-/tmp}/unsloth-studio-launcher-${_uid}"
-for _lock in "$_lock_glob".lock "$_lock_glob"-*.lock; do
- [ -e "$_lock" ] && _remove_path "$_lock"
-done
+ echo "Stopping any running Unsloth Studio servers..."
+ _pkill_studio
-case "$_os" in
- Darwin)
- echo "Removing macOS .app bundle and Launch Services entry..."
- _remove_path "$HOME/Applications/Unsloth Studio.app"
- _lsr="/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister"
- if [ -x "$_lsr" ]; then
- "$_lsr" -u "$HOME/Applications/Unsloth Studio.app" 2>/dev/null || true
+ echo "Removing data and install directories..."
+ _custom_studio_roots | while IFS= read -r _custom_root; do
+ [ -n "$_custom_root" ] || continue
+ if _is_unsafe_root "$_custom_root"; then
+ echo " refusing to remove unsafe path: $_custom_root" >&2
+ continue
fi
- ;;
- Linux)
- if [ "$_is_wsl" = "1" ]; then
- echo "Removing WSL Windows-side shortcuts..."
- # install.sh creates per-distro 'Unsloth Studio (WSL - <distro>).lnk'
- # on the Windows Desktop + Start Menu via powershell.exe. Scope removal
- # to THIS distro (passed as $args[0]) so a multi-distro install keeps the
- # other distros' launchers; the TARGET=wsl.exe check still spares a
- # native install's "Unsloth Studio.lnk". Prefer powershell.exe; test it
- # can EXECUTE (`command -v` succeeds even with interop OFF -- .exe then
- # fails "Exec format error", common on systemd-enabled distros).
- _wsl_distro="${WSL_DISTRO_NAME:-}"
- _ps_ran=0
- if command -v powershell.exe >/dev/null 2>&1 && \
- powershell.exe -NoProfile -Command "exit 0" >/dev/null 2>&1; then
- _ps_ran=1
- # Inject the distro into the command: a -Command string does not
- # receive trailing tokens as $args. WSL distro names are safe to
- # embed (no quotes/$/backtick).
- # shellcheck disable=SC2016
- powershell.exe -NoProfile -Command '$distro = "'"$_wsl_distro"'";
- $dirs = @(
- [Environment]::GetFolderPath("Desktop"),
- (Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs")
- );
- $ws = New-Object -ComObject WScript.Shell;
- foreach ($d in $dirs) {
- if (-not $d -or -not (Test-Path -LiteralPath $d)) { continue }
- Get-ChildItem -LiteralPath $d -Filter "Unsloth Studio*.lnk" -ErrorAction SilentlyContinue | ForEach-Object {
- try {
- $sc = $ws.CreateShortcut($_.FullName);
- if ("$($sc.TargetPath) $($sc.Arguments)" -notmatch "wsl\.exe") { return }
- # When the distro is known, require the per-distro
- # name for this distro or its -d "<distro>" argument
- # so launchers for other distros are not removed.
- if ($distro) {
- $nameMatch = ($_.Name -eq "Unsloth Studio (WSL - $distro).lnk");
- $argMatch = ($sc.Arguments -match ("-d\s+`"?" + [regex]::Escape($distro) + "`"?"));
- if (-not ($nameMatch -or $argMatch)) { return }
- }
- Remove-Item -LiteralPath $_.FullName -Force -ErrorAction SilentlyContinue
- } catch { }
- }
- }
- # Keep the shared icon while any Unsloth shortcut still uses it (native
- # install or another WSL distro); drop it only with the last one.
- $iconInUse = $false;
- foreach ($d in $dirs) {
- if (-not $d -or -not (Test-Path -LiteralPath $d)) { continue }
- if (Get-ChildItem -LiteralPath $d -Filter "Unsloth Studio*.lnk" -ErrorAction SilentlyContinue) { $iconInUse = $true; break }
- }
- # Guard LOCALAPPDATA: empty on a service/SYSTEM account makes
- # Join-Path throw, aborting the icon cleanup (mirror uninstall.ps1).
- if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
- $iconDir = Join-Path $env:LOCALAPPDATA "Unsloth Studio";
- $ico = Join-Path $iconDir "unsloth.ico";
- if ((-not $iconInUse) -and (Test-Path -LiteralPath $ico)) { Remove-Item -LiteralPath $ico -Force -ErrorAction SilentlyContinue }
- if ((Test-Path -LiteralPath $iconDir) -and -not (Get-ChildItem -LiteralPath $iconDir -Force -ErrorAction SilentlyContinue)) { Remove-Item -LiteralPath $iconDir -Recurse -Force -ErrorAction SilentlyContinue }
- }' >/dev/null 2>&1 || true
+ if ! _is_studio_root "$_custom_root"; then
+ echo " refusing to remove non-Unsloth path: $_custom_root" >&2
+ continue
+ fi
+ _remove_path "$_custom_root"
+ done
+ _remove_path "$HOME/.unsloth/studio"
+ # Default-mode shared llama.cpp build + cache are siblings of studio (not removed
+ # by deleting it). No-op in env/custom mode (they nest under the custom root) and
+ # when absent. A user-set UNSLOTH_LLAMA_CPP_PATH is intentionally kept.
+ _remove_path "$HOME/.unsloth/llama.cpp"
+ _remove_path "$HOME/.unsloth/.cache"
+ # Isolated Node.js runtime (install_node_prebuilt.py), a sibling of studio in
+ # default mode. No-op in env/custom mode (nested under the custom root) and absent.
+ _remove_path "$HOME/.unsloth/node"
+ # llama.cpp atomic-install staging root (install_llama_prebuilt.py .staging).
+ # Normally pruned after activate, but an interrupted build can leave it behind;
+ # removing it lets the rmdir below succeed. No-op in env/custom mode and absent.
+ _remove_path "$HOME/.unsloth/.staging"
+ # llama.cpp install lock (serializes the shared build); a stray one keeps ~/.unsloth
+ # from being pruned below. No-op in env/custom mode and when absent.
+ _remove_path "$HOME/.unsloth/.llama.cpp.install.lock"
+ # ROCm-on-WSL helper artifacts (librocdxg build clone + smoke-test venv). No-op
+ # where they don't exist; removing them lets the rmdir below succeed.
+ _remove_path "$HOME/.unsloth/librocdxg"
+ _remove_path "$HOME/.unsloth/rocm-smoketest"
+ # Drop ~/.unsloth only if now empty (rmdir refuses non-empty, so user content is kept).
+ rmdir "$HOME/.unsloth" 2>/dev/null || true
+ _remove_path "$HOME/.local/share/unsloth"
+ # CLI shim: only the symlink Unsloth created, never a pip-installed file.
+ _remove_cli_shim
+
+ echo "Removing desktop shortcut and launcher lock..."
+ # install.sh creates Desktop/Unsloth Studio as a symlink. If the user has an
+ # unrelated regular directory by that name, leave it alone.
+ _desktop_link="$HOME/Desktop/Unsloth Studio"
+ if [ -L "$_desktop_link" ] || [ ! -e "$_desktop_link" ]; then
+ _remove_path "$_desktop_link"
+ else
+ echo " refusing to remove non-symlink Desktop path: $_desktop_link" >&2
+ fi
+ _remove_path "$HOME/Desktop/unsloth-studio.desktop"
+ # Locks are namespaced per-uid; env-mode adds an extra suffix.
+ _lock_glob="${XDG_RUNTIME_DIR:-/tmp}/unsloth-studio-launcher-${_uid}"
+ for _lock in "$_lock_glob".lock "$_lock_glob"-*.lock; do
+ [ -e "$_lock" ] && _remove_path "$_lock"
+ done
+
+ case "$_os" in
+ Darwin)
+ echo "Removing macOS .app bundle and Launch Services entry..."
+ _remove_path "$HOME/Applications/Unsloth Studio.app"
+ _lsr="/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister"
+ if [ -x "$_lsr" ]; then
+ "$_lsr" -u "$HOME/Applications/Unsloth Studio.app" 2>/dev/null || true
fi
- # Remove $1's shared unsloth.ico only if no Unsloth shortcut (native install
- # or another WSL distro) still uses it, then drop the dir if empty. Reciprocal
- # of uninstall.ps1's _RemoveDataDirKeepingWslIcon (keeps the icon for a
- # surviving WSL shortcut when the native side is removed).
- _drop_shared_icon_if_unused() {
- _du="$1"
- _icodir="$_du/AppData/Local/Unsloth Studio"
- _icon_in_use=0
- for _sd in \
- "$_du/Desktop" \
- "$_du/OneDrive/Desktop" \
- "$_du"/OneDrive*/Desktop \
- "$_du/AppData/Roaming/Microsoft/Windows/Start Menu/Programs"; do
- [ -d "$_sd" ] || continue
- for _any in "$_sd"/"Unsloth Studio"*.lnk; do
- [ -e "$_any" ] && { _icon_in_use=1; break; }
- done
- [ "$_icon_in_use" = "1" ] && break
- done
- if [ "$_icon_in_use" = "0" ]; then
- [ -f "$_icodir/unsloth.ico" ] && rm -f "$_icodir/unsloth.ico" 2>/dev/null || true
+ ;;
+ Linux)
+ if [ "$_is_wsl" = "1" ]; then
+ echo "Removing WSL Windows-side shortcuts..."
+ # install.sh creates per-distro 'Unsloth Studio (WSL - <distro>).lnk'
+ # on the Windows Desktop + Start Menu via powershell.exe. Scope removal
+ # to THIS distro (passed as $args[0]) so a multi-distro install keeps the
+ # other distros' launchers; the TARGET=wsl.exe check still spares a
+ # native install's "Unsloth Studio.lnk". Prefer powershell.exe; test it
+ # can EXECUTE (`command -v` succeeds even with interop OFF -- .exe then
+ # fails "Exec format error", common on systemd-enabled distros).
+ _wsl_distro="${WSL_DISTRO_NAME:-}"
+ _ps_ran=0
+ if command -v powershell.exe >/dev/null 2>&1 && \
+ powershell.exe -NoProfile -Command "exit 0" >/dev/null 2>&1; then
+ _ps_ran=1
+ # Inject the distro into the command: a -Command string does not
+ # receive trailing tokens as $args. WSL distro names are safe to
+ # embed (no quotes/$/backtick).
+ # shellcheck disable=SC2016
+ powershell.exe -NoProfile -Command '$distro = "'"$_wsl_distro"'";
+ $dirs = @(
+ [Environment]::GetFolderPath("Desktop"),
+ (Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs")
+ );
+ $ws = New-Object -ComObject WScript.Shell;
+ foreach ($d in $dirs) {
+ if (-not $d -or -not (Test-Path -LiteralPath $d)) { continue }
+ Get-ChildItem -LiteralPath $d -Filter "Unsloth Studio*.lnk" -ErrorAction SilentlyContinue | ForEach-Object {
+ try {
+ $sc = $ws.CreateShortcut($_.FullName);
+ if ("$($sc.TargetPath) $($sc.Arguments)" -notmatch "wsl\.exe") { return }
+ # When the distro is known, require the per-distro
+ # name for this distro or its -d "<distro>" argument
+ # so launchers for other distros are not removed.
+ if ($distro) {
+ $nameMatch = ($_.Name -eq "Unsloth Studio (WSL - $distro).lnk");
+ $argMatch = ($sc.Arguments -match ("-d\s+`"?" + [regex]::Escape($distro) + "`"?"));
+ if (-not ($nameMatch -or $argMatch)) { return }
+ }
+ Remove-Item -LiteralPath $_.FullName -Force -ErrorAction SilentlyContinue
+ } catch { }
+ }
+ }
+ # Keep the shared icon while any Unsloth shortcut still uses it (native
+ # install or another WSL distro); drop it only with the last one.
+ $iconInUse = $false;
+ foreach ($d in $dirs) {
+ if (-not $d -or -not (Test-Path -LiteralPath $d)) { continue }
+ if (Get-ChildItem -LiteralPath $d -Filter "Unsloth Studio*.lnk" -ErrorAction SilentlyContinue) { $iconInUse = $true; break }
+ }
+ # Guard LOCALAPPDATA: empty on a service/SYSTEM account makes
+ # Join-Path throw, aborting the icon cleanup (mirror uninstall.ps1).
+ if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
+ $iconDir = Join-Path $env:LOCALAPPDATA "Unsloth Studio";
+ $ico = Join-Path $iconDir "unsloth.ico";
+ if ((-not $iconInUse) -and (Test-Path -LiteralPath $ico)) { Remove-Item -LiteralPath $ico -Force -ErrorAction SilentlyContinue }
+ if ((Test-Path -LiteralPath $iconDir) -and -not (Get-ChildItem -LiteralPath $iconDir -Force -ErrorAction SilentlyContinue)) { Remove-Item -LiteralPath $iconDir -Recurse -Force -ErrorAction SilentlyContinue }
+ }' >/dev/null 2>&1 || true
fi
- [ -d "$_icodir" ] && rmdir "$_icodir" 2>/dev/null || true
- }
- # Fallback when powershell.exe can't run (interop disabled): remove WSL .lnk
- # files via drvfs. The "Unsloth Studio (WSL..." name is WSL-specific, so a
- # native install's "Unsloth Studio.lnk" never matches.
- if [ "$_ps_ran" = "0" ]; then
- for _drive in /mnt/c /mnt/d /mnt/e; do
- [ -d "$_drive/Users" ] || continue
- for _udir in "$_drive"/Users/*; do
- [ -d "$_udir" ] || continue
- for _scdir in \
- "$_udir/Desktop" \
- "$_udir/OneDrive/Desktop" \
- "$_udir"/OneDrive*/Desktop \
- "$_udir/AppData/Roaming/Microsoft/Windows/Start Menu/Programs"; do
- [ -d "$_scdir" ] || continue
- if [ -n "$_wsl_distro" ]; then
- # Exact per-distro name (no glob) so other distros survive.
- _lnk="$_scdir/Unsloth Studio (WSL - ${_wsl_distro}).lnk"
- [ -e "$_lnk" ] && rm -f "$_lnk" 2>/dev/null && echo " removed: $_lnk" || true
- else
- # Distro unknown: fall back to the broad WSL prefix.
- for _lnk in "$_scdir"/"Unsloth Studio (WSL"*.lnk; do
+ # Remove $1's shared unsloth.ico only if no Unsloth shortcut (native install
+ # or another WSL distro) still uses it, then drop the dir if empty. Reciprocal
+ # of uninstall.ps1's _RemoveDataDirKeepingWslIcon (keeps the icon for a
+ # surviving WSL shortcut when the native side is removed).
+ _drop_shared_icon_if_unused() {
+ _du="$1"
+ _icodir="$_du/AppData/Local/Unsloth Studio"
+ _icon_in_use=0
+ for _sd in \
+ "$_du/Desktop" \
+ "$_du/OneDrive/Desktop" \
+ "$_du"/OneDrive*/Desktop \
+ "$_du/AppData/Roaming/Microsoft/Windows/Start Menu/Programs"; do
+ [ -d "$_sd" ] || continue
+ for _any in "$_sd"/"Unsloth Studio"*.lnk; do
+ [ -e "$_any" ] && { _icon_in_use=1; break; }
+ done
+ [ "$_icon_in_use" = "1" ] && break
+ done
+ if [ "$_icon_in_use" = "0" ]; then
+ [ -f "$_icodir/unsloth.ico" ] && rm -f "$_icodir/unsloth.ico" 2>/dev/null || true
+ fi
+ [ -d "$_icodir" ] && rmdir "$_icodir" 2>/dev/null || true
+ }
+ # Fallback when powershell.exe can't run (interop disabled): remove WSL .lnk
+ # files via drvfs. The "Unsloth Studio (WSL..." name is WSL-specific, so a
+ # native install's "Unsloth Studio.lnk" never matches.
+ if [ "$_ps_ran" = "0" ]; then
+ for _drive in /mnt/c /mnt/d /mnt/e; do
+ [ -d "$_drive/Users" ] || continue
+ for _udir in "$_drive"/Users/*; do
+ [ -d "$_udir" ] || continue
+ for _scdir in \
+ "$_udir/Desktop" \
+ "$_udir/OneDrive/Desktop" \
+ "$_udir"/OneDrive*/Desktop \
+ "$_udir/AppData/Roaming/Microsoft/Windows/Start Menu/Programs"; do
+ [ -d "$_scdir" ] || continue
+ if [ -n "$_wsl_distro" ]; then
+ # Exact per-distro name (no glob) so other distros survive.
+ _lnk="$_scdir/Unsloth Studio (WSL - ${_wsl_distro}).lnk"
[ -e "$_lnk" ] && rm -f "$_lnk" 2>/dev/null && echo " removed: $_lnk" || true
- done
- fi
+ else
+ # Distro unknown: fall back to the broad WSL prefix.
+ for _lnk in "$_scdir"/"Unsloth Studio (WSL"*.lnk; do
+ [ -e "$_lnk" ] && rm -f "$_lnk" 2>/dev/null && echo " removed: $_lnk" || true
+ done
+ fi
+ done
+ # Drop the shared icon only when no shortcut still needs it.
+ _drop_shared_icon_if_unused "$_udir"
done
- # Drop the shared icon only when no shortcut still needs it.
- _drop_shared_icon_if_unused "$_udir"
done
- done
- fi
- # ── ROCm-on-WSL config (install_rocm_wsl_strixhalo.sh) ──
- # Remove Unsloth's own ROCDXG config (the env it persisted). The system
- # ROCm userspace is a shared prereq (like CUDA) and is LEFT IN PLACE by
- # default; set UNSLOTH_UNINSTALL_ROCM=1 to remove it too.
- echo "Removing ROCm-on-WSL config..."
- _sudo=""
- if [ "$_uid" != "0" ] && command -v sudo >/dev/null 2>&1; then _sudo="sudo"; fi
- $_sudo rm -f /etc/profile.d/unsloth-rocm-wsl.sh 2>/dev/null || true
- if [ -f "$HOME/.bashrc" ] && grep -q "Unsloth ROCm-on-WSL" "$HOME/.bashrc" 2>/dev/null; then
- _bk=$(mktemp 2>/dev/null || echo "$HOME/.bashrc.unsloth.tmp")
- if sed '/# >>> Unsloth ROCm-on-WSL/,/# <<< Unsloth ROCm-on-WSL/d' "$HOME/.bashrc" > "$_bk" 2>/dev/null; then
- cat "$_bk" > "$HOME/.bashrc" 2>/dev/null || true
- echo " cleaned ROCm-on-WSL block from ~/.bashrc"
fi
- rm -f "$_bk" 2>/dev/null || true
+ # ── ROCm-on-WSL config (install_rocm_wsl_strixhalo.sh) ──
+ # Remove Unsloth's own ROCDXG config (the env it persisted). The system
+ # ROCm userspace is a shared prereq (like CUDA) and is LEFT IN PLACE by
+ # default; set UNSLOTH_UNINSTALL_ROCM=1 to remove it too.
+ echo "Removing ROCm-on-WSL config..."
+ _sudo=""
+ if [ "$_uid" != "0" ] && command -v sudo >/dev/null 2>&1; then _sudo="sudo"; fi
+ $_sudo rm -f /etc/profile.d/unsloth-rocm-wsl.sh 2>/dev/null || true
+ if [ -f "$HOME/.bashrc" ] && grep -q "Unsloth ROCm-on-WSL" "$HOME/.bashrc" 2>/dev/null; then
+ _bk=$(mktemp 2>/dev/null || echo "$HOME/.bashrc.unsloth.tmp")
+ if sed '/# >>> Unsloth ROCm-on-WSL/,/# <<< Unsloth ROCm-on-WSL/d' "$HOME/.bashrc" > "$_bk" 2>/dev/null; then
+ cat "$_bk" > "$HOME/.bashrc" 2>/dev/null || true
+ echo " cleaned ROCm-on-WSL block from ~/.bashrc"
+ fi
+ rm -f "$_bk" 2>/dev/null || true
+ fi
+ if [ "${UNSLOTH_UNINSTALL_ROCM:-0}" = "1" ]; then
+ echo " removing system ROCm (UNSLOTH_UNINSTALL_ROCM=1)..."
+ $_sudo rm -f /etc/apt/sources.list.d/rocm.list /etc/apt/preferences.d/rocm-pin-600 \
+ /etc/apt/keyrings/rocm.gpg /etc/ld.so.conf.d/rocm.conf 2>/dev/null || true
+ $_sudo sh -c 'rm -rf /opt/rocm /opt/rocm-*' 2>/dev/null || true
+ if command -v ldconfig >/dev/null 2>&1; then $_sudo ldconfig 2>/dev/null || true; fi
+ elif [ -d /opt/rocm ]; then
+ echo " Note: ROCm userspace (/opt/rocm*) left in place (shared prereq)."
+ echo " Remove it by re-running with UNSLOTH_UNINSTALL_ROCM=1, or manually:"
+ echo " sudo rm -rf /opt/rocm /opt/rocm-* && sudo ldconfig"
+ fi
fi
- if [ "${UNSLOTH_UNINSTALL_ROCM:-0}" = "1" ]; then
- echo " removing system ROCm (UNSLOTH_UNINSTALL_ROCM=1)..."
- $_sudo rm -f /etc/apt/sources.list.d/rocm.list /etc/apt/preferences.d/rocm-pin-600 \
- /etc/apt/keyrings/rocm.gpg /etc/ld.so.conf.d/rocm.conf 2>/dev/null || true
- $_sudo sh -c 'rm -rf /opt/rocm /opt/rocm-*' 2>/dev/null || true
- if command -v ldconfig >/dev/null 2>&1; then $_sudo ldconfig 2>/dev/null || true; fi
- elif [ -d /opt/rocm ]; then
- echo " Note: ROCm userspace (/opt/rocm*) left in place (shared prereq)."
- echo " Remove it by re-running with UNSLOTH_UNINSTALL_ROCM=1, or manually:"
- echo " sudo rm -rf /opt/rocm /opt/rocm-* && sudo ldconfig"
+ echo "Removing Linux .desktop entry..."
+ _remove_path "$HOME/.local/share/applications/unsloth-studio.desktop"
+ if command -v update-desktop-database >/dev/null 2>&1; then
+ update-desktop-database "$HOME/.local/share/applications" 2>/dev/null || true
fi
- fi
- echo "Removing Linux .desktop entry..."
- _remove_path "$HOME/.local/share/applications/unsloth-studio.desktop"
- if command -v update-desktop-database >/dev/null 2>&1; then
- update-desktop-database "$HOME/.local/share/applications" 2>/dev/null || true
- fi
- ;;
-esac
+ ;;
+ esac
-echo ""
-echo "Unsloth Studio uninstalled."
-echo "Note: Hugging Face model cache at ~/.cache/huggingface was left in place."
-echo "Remove it manually with 'rm -rf ~/.cache/huggingface/hub' if desired."
-# Env-mode installs leave no breadcrumb in $HOME, so a custom root can
-# only be located if the user re-exports the variable. Print a hint when
-# neither var is set so the bare `curl | sh` flow doesn't silently miss.
-if [ -z "${UNSLOTH_STUDIO_HOME:-}" ] && [ -z "${STUDIO_HOME:-}" ]; then
echo ""
- echo "If you installed Unsloth Studio with UNSLOTH_STUDIO_HOME or STUDIO_HOME"
- echo "pointing at a custom directory, re-run this script with the same variable"
- echo "set to also remove that install tree, e.g.:"
- echo " UNSLOTH_STUDIO_HOME=/your/path sh -c \"\$(curl -fsSL https://raw.githubusercontent.com/unslothai/unsloth/main/scripts/uninstall.sh)\""
-fi
+ echo "Unsloth Studio uninstalled."
+ echo "Note: Hugging Face model cache at ~/.cache/huggingface was left in place."
+ echo "Remove it manually with 'rm -rf ~/.cache/huggingface/hub' if desired."
+ # Env-mode installs leave no breadcrumb in $HOME, so a custom root can
+ # only be located if the user re-exports the variable. Print a hint when
+ # neither var is set so the bare `curl | sh` flow doesn't silently miss.
+ if [ -z "${UNSLOTH_STUDIO_HOME:-}" ] && [ -z "${STUDIO_HOME:-}" ]; then
+ echo ""
+ echo "If you installed Unsloth Studio with UNSLOTH_STUDIO_HOME or STUDIO_HOME"
+ echo "pointing at a custom directory, re-run this script with the same variable"
+ echo "set to also remove that install tree, e.g.:"
+ echo " UNSLOTH_STUDIO_HOME=/your/path sh -c \"\$(curl -fsSL https://raw.githubusercontent.com/unslothai/unsloth/main/scripts/uninstall.sh)\""
+ fi
+}
+
+# Parse the entire script before running destructive work. This keeps piped help
+# from closing the writer early and makes a truncated download inert.
+{
+ _unsloth_uninstall_main "$@"
+}
diff --git a/tests/sh/test_uninstall_arg_guard.sh b/tests/sh/test_uninstall_arg_guard.sh
new file mode 100755
index 00000000000..64f32a55aa4
--- /dev/null
+++ b/tests/sh/test_uninstall_arg_guard.sh
@@ -0,0 +1,240 @@
+#!/bin/bash
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+#
+# Argument and pipe-safety tests for scripts/uninstall.sh.
+#
+# Behavioral cases use an instrumented copy that aborts before uninstalling.
+# The real no-argument case is skipped on WSL because it reaches host state.
+set -e
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+SOURCE_UNINSTALL_SH="$SCRIPT_DIR/../../scripts/uninstall.sh"
+PASS=0
+FAIL=0
+BODY_MARKER="__UNSLOTH_TEST_BODY_REACHED__"
+
+_TMP_ROOT=$(mktemp -d)
+trap 'rm -rf "$_TMP_ROOT"' EXIT
+
+# Abort the test copy immediately before the first uninstall action.
+_body_entries=$(grep -c '^[[:space:]]*echo "Stopping any running Unsloth Studio servers\.\.\."$' "$SOURCE_UNINSTALL_SH" || true)
+[ "$_body_entries" = "1" ] || {
+ echo "FATAL: expected one uninstall body entry, found $_body_entries" >&2
+ exit 1
+}
+UNINSTALL_SH="$_TMP_ROOT/uninstall.sh"
+sed 's/^[[:space:]]*echo "Stopping any running Unsloth Studio servers\.\.\."$/ echo "__UNSLOTH_TEST_BODY_REACHED__"; return 99/' \
+ "$SOURCE_UNINSTALL_SH" > "$UNINSTALL_SH"
+
+# Isolate every environment-controlled removal path.
+unset UNSLOTH_STUDIO_HOME STUDIO_HOME UNSLOTH_UNINSTALL_ROCM
+XDG_RUNTIME_DIR="$_TMP_ROOT/run"
+export XDG_RUNTIME_DIR
+mkdir -p "$XDG_RUNTIME_DIR"
+
+ok() { echo " PASS: $1"; PASS=$((PASS + 1)); }
+nope() { echo " FAIL: $1"; FAIL=$((FAIL + 1)); }
+
+check() {
+ if [ "$3" = "$2" ]; then ok "$1"; else nope "$1 (expected '$2', got '$3')"; fi
+}
+
+assert_says() {
+ case "$3" in
+ *"$2"*) ok "$1" ;;
+ *) nope "$1 (no '$2' in: $(printf '%s' "$3" | head -n1))" ;;
+ esac
+}
+
+assert_not_says() {
+ case "$3" in
+ *"$2"*) nope "$1 (unexpected '$2')" ;;
+ *) ok "$1" ;;
+ esac
+}
+
+# Check the fixture as a unit.
+FIXTURE_PATHS=".unsloth/studio .unsloth/studio/auth/.desktop_secret .local/bin/unsloth .local/share/unsloth"
+
+# assert_fixture <label> <home> present|gone
+assert_fixture() {
+ _missing=""
+ for _rel in $FIXTURE_PATHS; do
+ if [ -e "$2/$_rel" ] || [ -L "$2/$_rel" ]; then
+ [ "$3" = "gone" ] && _missing="$_missing $_rel"
+ else
+ [ "$3" = "present" ] && _missing="$_missing $_rel"
+ fi
+ done
+ if [ -z "$_missing" ]; then ok "$1"; else nope "$1 (wrong state:$_missing)"; fi
+}
+
+# Publish a validated fixture path. A global keeps setup failures from being
+# hidden by command-substitution errexit behavior.
+FIXTURE_HOME=""
+make_home() {
+ FIXTURE_HOME=$(TMPDIR="$_TMP_ROOT" mktemp -d) || FIXTURE_HOME=""
+ case "$FIXTURE_HOME" in
+ "$_TMP_ROOT"/*) ;;
+ *) echo "FATAL: no fixture home under $_TMP_ROOT (got '$FIXTURE_HOME')" >&2; exit 1 ;;
+ esac
+ mkdir -p "$FIXTURE_HOME/.unsloth/studio/unsloth_studio/bin" \
+ "$FIXTURE_HOME/.unsloth/studio/auth" \
+ "$FIXTURE_HOME/.local/share/unsloth" \
+ "$FIXTURE_HOME/.local/bin"
+ : > "$FIXTURE_HOME/.unsloth/studio/unsloth_studio/bin/unsloth"
+ : > "$FIXTURE_HOME/.unsloth/studio/auth/.desktop_secret"
+ ln -s "$FIXTURE_HOME/.unsloth/studio/unsloth_studio/bin/unsloth" "$FIXTURE_HOME/.local/bin/unsloth"
+}
+
+RC=0
+OUT=""
+run_script() {
+ _script="$1"
+ _fake_home="$2"
+ shift 2
+ OUT=$(HOME="$_fake_home" sh "$_script" "$@" 2>&1) && RC=0 || RC=$?
+}
+
+run_uninstall() {
+ run_script "$UNINSTALL_SH" "$@"
+}
+
+echo "=== structure: the wrapper that makes an early exit pipe-safe ==="
+
+# Portable structural checks complement the Linux-only pipe test.
+if grep -q '^_unsloth_uninstall_main() {' "$SOURCE_UNINSTALL_SH"; then
+ ok "_unsloth_uninstall_main is defined at top level"
+else
+ nope "uninstall.sh is not wrapped in _unsloth_uninstall_main -- curl-pipe safety is gone"
+fi
+_tail="$(grep -vE '^[[:space:]]*(#|$)' "$SOURCE_UNINSTALL_SH" | tail -3)"
+_expected_tail='{
+ _unsloth_uninstall_main "$@"
+}'
+check "final entry is a complete compound block" "$_expected_tail" "$_tail"
+
+echo "=== help: prints usage, removes nothing ==="
+
+for _flag in --help -h; do
+ make_home
+ run_uninstall "$FIXTURE_HOME" "$_flag"
+ check "$_flag exits 0" "0" "$RC"
+ assert_says "$_flag prints usage" "Unsloth Studio uninstaller" "$OUT"
+done
+assert_fixture "help keeps the install" "$FIXTURE_HOME" present
+
+echo "=== unknown arguments: abort before touching anything ==="
+
+make_home
+run_uninstall "$FIXTURE_HOME" --dry-run
+check "'--dry-run' exits 2" "2" "$RC"
+assert_says "the rejected argument is named" "unrecognized argument: --dry-run" "$OUT"
+assert_says "the error states nothing was removed" "Nothing was removed" "$OUT"
+assert_fixture "a rejected option keeps the install" "$FIXTURE_HOME" present
+
+make_home
+run_uninstall "$FIXTURE_HOME" uninstall
+check "a positional argument exits 2" "2" "$RC"
+assert_fixture "a rejected positional argument keeps the install" "$FIXTURE_HOME" present
+
+make_home
+run_uninstall "$FIXTURE_HOME" --dry-run --help
+check "'--dry-run --help' exits 2" "2" "$RC"
+
+make_home
+run_uninstall "$FIXTURE_HOME" --help --dry-run
+check "'--help --dry-run' exits 0" "0" "$RC"
+
+echo "=== no arguments: the guard must not have broken the uninstall ==="
+
+make_home
+run_uninstall "$FIXTURE_HOME"
+check "no arguments reach the instrumented body" "99" "$RC"
+assert_says "the instrumented body announces itself" "$BODY_MARKER" "$OUT"
+assert_fixture "instrumentation keeps the install" "$FIXTURE_HOME" present
+
+# The body reaches host state on WSL, so do not run it there.
+if grep -qi microsoft /proc/version 2>/dev/null; then
+ echo " SKIP: WSL -- the uninstall body reaches Windows-side state outside the fixture"
+else
+ make_home
+ run_script "$SOURCE_UNINSTALL_SH" "$FIXTURE_HOME"
+ check "no arguments still uninstalls (exit 0)" "0" "$RC"
+ assert_fixture "no arguments removes the install" "$FIXTURE_HOME" gone
+fi
+
+echo "=== behaviour: a piped --help must not break the writer ==="
+
+# Shrink the pipe so an unread script tail produces a broken writer. Skip where
+# Linux F_SETPIPE_SZ is unavailable.
+if python3 -c 'import fcntl, sys; sys.exit(0 if sys.platform.startswith("linux") else 1)' 2>/dev/null; then
+ make_home
+ verdict=$(UNINSTALL_SH="$UNINSTALL_SH" FAKE_HOME="$FIXTURE_HOME" python3 - <<'PY'
+import fcntl, os, subprocess
+F_SETPIPE_SZ, F_GETPIPE_SZ = 1031, 1032
+with open(os.environ["UNINSTALL_SH"], "rb") as fh:
+ src = fh.read()
+r, w = os.pipe()
+try:
+ fcntl.fcntl(w, F_SETPIPE_SZ, 4096)
+except OSError as exc:
+ print(f"skip: cannot resize the pipe ({exc})")
+ raise SystemExit(0)
+# Reject a pipe size large enough to make the test vacuous.
+if len(src) <= fcntl.fcntl(w, F_GETPIPE_SZ):
+ print("vacuous: uninstall.sh now fits in one pipe buffer, re-derive this test")
+ raise SystemExit(0)
+proc = subprocess.Popen(
+ ["sh", "-s", "--", "--help"], stdin = r,
+ stdout = subprocess.PIPE, stderr = subprocess.STDOUT,
+ env = dict(os.environ, HOME = os.environ["FAKE_HOME"]),
+)
+os.close(r)
+try:
+ with os.fdopen(w, "wb") as pipe:
+ pipe.write(src)
+ writer = "ok"
+except BrokenPipeError:
+ writer = "epipe"
+out = proc.communicate(timeout = 60)[0]
+body = "body" if b"__UNSLOTH_TEST_BODY_REACHED__" in out else "guarded"
+print(f"{writer}:{proc.returncode}:{body}")
+PY
+ )
+ case "$verdict" in
+ skip:*|vacuous:*) echo " SKIP: ${verdict#*: }" ;;
+ *)
+ # Check both the writer and script exit codes.
+ check "piped --help stays guarded" "ok:0:guarded" "$verdict"
+ ;;
+ esac
+else
+ echo " SKIP: pipe-buffer case needs Linux F_SETPIPE_SZ"
+fi
+
+echo "=== behaviour: the vulnerable final-call prefix is inert ==="
+
+# Drop the closing brace and truncate the call immediately after its function
+# name. Without the compound block this is a valid no-argument uninstall.
+_tail_prefix="$_TMP_ROOT/tail-after-function-name.sh"
+sed '$d' "$UNINSTALL_SH" | sed '$s/ "\$@"$//' > "$_tail_prefix"
+make_home
+OUT=$(HOME="$FIXTURE_HOME" sh -s -- --help < "$_tail_prefix" 2>&1) || true
+assert_not_says "the incomplete final call never reaches the body" "$BODY_MARKER" "$OUT"
+assert_fixture "tail truncation keeps the install" "$FIXTURE_HOME" present
+
+echo "=== behaviour: a truncated download must remove nothing ==="
+
+# One generic near-complete truncation complements the exact final-call boundary.
+make_home
+_bytes=$(wc -c < "$UNINSTALL_SH")
+OUT=$(head -c "$((_bytes * 99 / 100))" "$UNINSTALL_SH" \
+ | HOME="$FIXTURE_HOME" sh 2>&1) || true
+assert_not_says "a 99% download never reaches the body" "$BODY_MARKER" "$OUT"
+assert_fixture "a 99% download removes nothing" "$FIXTURE_HOME" present
+
+echo ""
+echo "Results: $PASS passed, $FAIL failed"
+[ "$FAIL" = 0 ]
diff --git a/tests/sh/test_uninstall_shared_icon.sh b/tests/sh/test_uninstall_shared_icon.sh
index e9dca15d5e9..71eea7106d8 100644
--- a/tests/sh/test_uninstall_shared_icon.sh
+++ b/tests/sh/test_uninstall_shared_icon.sh
@@ -28,9 +28,9 @@ assert_nofile() { _l="$1"; [ -f "$2" ] && { echo " FAIL: $_l (unexpected $2)";
assert_dir() { _l="$1"; [ -d "$2" ] && { echo " PASS: $_l"; PASS=$((PASS+1)); } || { echo " FAIL: $_l (missing dir $2)"; FAIL=$((FAIL+1)); }; }
assert_nodir() { _l="$1"; [ -d "$2" ] && { echo " FAIL: $_l (unexpected dir $2)"; FAIL=$((FAIL+1)); } || { echo " PASS: $_l"; PASS=$((PASS+1)); }; }
-# Extract just the function definition (12-space indented in the WSL branch).
+# Match the function's closing brace without depending on its nesting depth.
FUNC_FILE=$(mktemp -p "$_TMP_ROOT")
-sed -n '/_drop_shared_icon_if_unused() {/,/^ }/p' "$UNINSTALL_SH" > "$FUNC_FILE"
+sed -n '/_drop_shared_icon_if_unused() {/,/^[[:space:]]*}$/p' "$UNINSTALL_SH" > "$FUNC_FILE"
# shellcheck disable=SC1090
. "$FUNC_FILE"
diff --git a/tests/studio/test_uninstall_arg_guard.ps1 b/tests/studio/test_uninstall_arg_guard.ps1
new file mode 100644
index 00000000000..55cfb753b99
--- /dev/null
+++ b/tests/studio/test_uninstall_arg_guard.ps1
@@ -0,0 +1,107 @@
+#!/usr/bin/env pwsh
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+# Argument contract for scripts/uninstall.ps1.
+#
+# Tests run against a temporary copy that aborts before the first uninstall
+# action, so a broken guard cannot perform a real uninstall.
+#
+# Run: pwsh -NoProfile -File tests/studio/test_uninstall_arg_guard.ps1
+
+$ErrorActionPreference = "Stop"
+$sourceUninstallPath = [System.IO.Path]::Combine($PSScriptRoot, "..", "..", "scripts", "uninstall.ps1")
+$sourceUninstallPath = (Resolve-Path $sourceUninstallPath).Path
+$pwshPath = (Get-Process -Id $PID).Path
+$bodyEntry = ' _Step "Stopping any running Unsloth Studio servers..."'
+$bodyMarker = "__UNSLOTH_TEST_BODY_REACHED__"
+
+$source = Get-Content -Raw -LiteralPath $sourceUninstallPath
+$entryMatches = [regex]::Matches($source, [regex]::Escape($bodyEntry))
+if ($entryMatches.Count -ne 1) {
+ throw "Expected exactly one uninstall body entry point, found $($entryMatches.Count)"
+}
+$safeSource = $source.Replace($bodyEntry, " throw `"$bodyMarker`"")
+$tempRoot = Join-Path ([System.IO.Path]::GetTempPath()) ("unsloth-uninstall-guard-" + [guid]::NewGuid().ToString("N"))
+$uninstallPath = Join-Path $tempRoot "uninstall.ps1"
+New-Item -ItemType Directory -Path $tempRoot | Out-Null
+try {
+ [System.IO.File]::WriteAllText(
+ $uninstallPath,
+ $safeSource,
+ [System.Text.UTF8Encoding]::new($false)
+ )
+} catch {
+ Remove-Item -LiteralPath $tempRoot -Recurse -Force -ErrorAction SilentlyContinue
+ throw
+}
+
+$failures = 0
+function Check($name, $cond) {
+ if ($cond) { Write-Host " PASS $name" }
+ else { Write-Host " FAIL $name" -ForegroundColor Red; $script:failures++ }
+}
+
+# Run the instrumented uninstaller in a child pwsh.
+function Invoke-Uninstaller([string[]]$ScriptArgs) {
+ $argv = @("-NoProfile", "-File", $uninstallPath) + $ScriptArgs
+ $out = & $pwshPath @argv 2>&1 | Out-String
+ return [pscustomobject]@{ Code = $LASTEXITCODE; Output = $out }
+}
+
+try {
+ # Both the source and instrumented copy must parse.
+ foreach ($parseCase in @(
+ @{ Name = "source uninstall.ps1"; Path = $sourceUninstallPath },
+ @{ Name = "instrumented uninstall.ps1"; Path = $uninstallPath }
+ )) {
+ $parsePath = $parseCase.Path
+ $tokens = $null; $errors = $null
+ [System.Management.Automation.Language.Parser]::ParseFile($parsePath, [ref]$tokens, [ref]$errors) | Out-Null
+ Check "$($parseCase.Name) parses" (-not $errors)
+ if ($errors) { $errors | ForEach-Object { $_.ToString() }; throw "uninstall.ps1 has parse errors" }
+ }
+
+ # Prove instrumentation did not break the normal entry path.
+ $r = Invoke-Uninstaller @()
+ Check "no arguments reach the instrumented body" ($r.Output -match $bodyMarker)
+ Check "the instrumented body aborts" ($r.Code -ne 0)
+
+ Write-Host "help flags print usage and start nothing"
+ foreach ($flag in @("-Help", "-h", "-help", "--help", "-?", "/?")) {
+ $r = Invoke-Uninstaller @($flag)
+ Check "$flag exits 0" ($r.Code -eq 0)
+ Check "$flag prints usage" ($r.Output -match "Unsloth Studio uninstaller")
+ Check "$flag never starts the uninstall" ($r.Output -notmatch $bodyMarker)
+ }
+
+ Write-Host "unknown arguments abort before the body runs"
+ foreach ($bad in @("--dry-run", "-n", "--version", "uninstall")) {
+ $r = Invoke-Uninstaller @($bad)
+ Check "'$bad' exits nonzero" ($r.Code -ne 0)
+ Check "'$bad' never starts the uninstall" ($r.Output -notmatch $bodyMarker)
+ Check "'$bad' is named in the error" ($r.Output -match [regex]::Escape("unrecognized argument: $bad"))
+ }
+
+ $r = Invoke-Uninstaller @("--dry-run")
+ Check "the error states nothing was removed" ($r.Output -match "Nothing was removed")
+
+ $r = Invoke-Uninstaller @("--dry-run", "--help")
+ Check "'--dry-run --help' exits nonzero" ($r.Code -ne 0)
+ Check "'--dry-run --help' never starts the uninstall" ($r.Output -notmatch $bodyMarker)
+
+ # Embedded invocation must report failure without exiting the caller.
+ $probe = @'
+$s = Get-Content -Raw '__PATH__'
+try { & ([scriptblock]::Create($s)) --dry-run } catch { Write-Host $_.Exception.Message }
+Write-Host 'SESSION SURVIVED'
+'@ -replace '__PATH__', $uninstallPath
+ $out = & $pwshPath -NoProfile -Command $probe 2>&1 | Out-String
+ Check "a bad argument does not kill the caller's session" ($out -match "SESSION SURVIVED")
+ Check "the scriptblock flow never starts the uninstall" ($out -notmatch $bodyMarker)
+} finally {
+ Remove-Item -LiteralPath $tempRoot -Recurse -Force -ErrorAction SilentlyContinue
+}
+
+Write-Host ""
+if ($failures -gt 0) { Write-Host "$failures check(s) failed" -ForegroundColor Red; exit 1 }
+Write-Host "All checks passed" -ForegroundColor Green