Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Setup: clear stale WebView caches on install and update, keep user settings and data (#7361)
Michael Han6f4cce68d118
diff --git a/studio/setup.ps1 b/studio/setup.ps1index d65eb6dceb1..356d4b026ee 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -1679,6 +1679,36 @@ if ($script:StudioVtOk -and -not $env:NO_COLOR) {Write-Host " $Rule" -ForegroundColor DarkGray}+# WebView2 caches keyed by the bundle id can keep serving the previous frontend+# after an update. Cache-only: storage, cookies, settings, models and the studio+# database are untouched. Called only once the UNSLOTH_STUDIO_HOME / STUDIO_HOME+# override is validated, so a mistyped override cannot wipe the cache and then abort.+function Clear-WebViewCaches {+ if (-not $env:LOCALAPPDATA) { return }+ $wvDefault = Join-Path $env:LOCALAPPDATA "ai.unsloth.studio\EBWebView\Default"+ # Drop the version stamp first. The old WebView still holds these files, which is+ # why the removals below can fail; the app's own clear is the retry, and it is+ # skipped while the stamp matches the running version. Unconditional, since a+ # repair or a local rebuild leaves the version unchanged and a redundant clear on+ # the next launch is the cheap side of the trade.+ Remove-Item -LiteralPath (Join-Path $env:LOCALAPPDATA "ai.unsloth.studio\.webview-cache-cleared") `+ -Force -ErrorAction SilentlyContinue+ $wvCleared = $false+ foreach ($wvSub in @("Cache", "Code Cache", "GPUCache", "Service Worker")) {+ $wvPath = Join-Path $wvDefault $wvSub+ # Get-Item -Force, not Test-Path: the probe throws on an ACL denial under+ # "Stop", and a reparse point must be unlinked, not recursed into.+ $wvItem = Get-Item -LiteralPath $wvPath -Force -ErrorAction SilentlyContinue+ if (-not $wvItem) { continue }+ try {+ if ($wvItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint) { $wvItem.Delete() }+ else { Remove-Item -LiteralPath $wvPath -Recurse -Force -ErrorAction Stop }+ $wvCleared = $true+ } catch { }+ }+ if ($wvCleared) { substep "cleared stale WebView caches (ai.unsloth.studio); settings and data kept" }+}+# Back up User PATH under HKCU\Software\Unsloth before any modifications.try {$envKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false)@@ -3464,8 +3494,17 @@ if ($_studioOverride) {} else {$StudioHome = Join-Path $env:USERPROFILE ".unsloth\studio"}+$VenvDir = Join-Path $StudioHome "unsloth_studio"+# The override is validated, so a typo can no longer cost the cache. Venv-gated because+# a writable-but-empty override still fails at the venv check below, and clearing first+# would cost the cache for a run that then does nothing; a fresh install has neither venv+# nor cache. Still before any install work.+if (Test-Path -LiteralPath (Join-Path $VenvDir "Scripts\python.exe") -PathType Leaf) {+ Clear-WebViewCaches+}+# why: in env-override mode $StudioHome is user-chosen; require the# ownership marker before Remove-Item so unrelated dirs survive. Gated on# the canonical comparison so an override pointing at the legacy defaultdiff --git a/studio/setup.sh b/studio/setup.shindex 6a1a08e0cb7..0e43221c428 100755--- a/studio/setup.sh+++ b/studio/setup.sh@@ -831,6 +831,65 @@ rm -rf "$REPO_ROOT/unsloth_compiled_cache"rm -rf "$SCRIPT_DIR/backend/unsloth_compiled_cache"rm -rf "$SCRIPT_DIR/tmp/unsloth_compiled_cache"+# WebView caches keyed by the bundle id can keep serving the previous frontend+# after an update. Cache-only: storage, cookies, settings, models and the studio+# database are untouched.+_clear_webview_caches() {+ # No HOME: bail rather than let `set -u` abort or "" expand to /Library and /.cache.+ [ -n "${HOME:-}" ] || return 0+ _wvc_bid="ai.unsloth.studio"+ _wvc_paths=()+ # The app's version stamp dir (main.rs webview_profile_root), which on macOS+ # is not the cache dir, so it is tracked separately.+ _wvc_root=""+ case "$(uname -s 2>/dev/null)" in+ Darwin)+ # WKWebView keeps every cache-typed store under Library/Caches/<bid>;+ # Library/WebKit/<bid> is user storage and is left alone.+ _wvc_paths=("$HOME/Library/Caches/$_wvc_bid")+ _wvc_root="$HOME/Library/Application Support/$_wvc_bid"+ ;;+ Linux)+ # wry points WebKitGTK's base-cache dir at the app data dir, so the+ # caches sit beside localstorage/, databases/ and cookies, which stay.+ # A relative XDG_DATA_HOME is invalid per the XDG spec and dropped by+ # dirs, so match Tauri and use the default rather than rm -rf under+ # whatever directory the installer runs from.+ _wvc_data="${XDG_DATA_HOME:-$HOME/.local/share}"+ case "$_wvc_data" in /*) ;; *) _wvc_data="$HOME/.local/share" ;; esac+ _wvc_data="$_wvc_data/$_wvc_bid"+ _wvc_paths=(+ "$_wvc_data/WebKitCache"+ "$_wvc_data/CacheStorage"+ "$_wvc_data/serviceworkers"+ )+ _wvc_root="$_wvc_data"+ ;;+ *) return 0 ;;+ esac+ # Drop the version stamp first. An update runs while the old WebView still holds+ # these files, so the rm below can fail; the app's own clear is the retry, and it+ # is skipped while the stamp matches the running version. Unconditional, since a+ # repair or a local rebuild leaves the version unchanged and a redundant clear on+ # the next launch is the cheap side. An `if`, not `[ ... ] && rm`: under `set -e`+ # that compound returns 1 when the guard is false and would abort the install.+ if [ -n "$_wvc_root" ]; then+ rm -f "$_wvc_root/.webview-cache-cleared" 2>/dev/null || true+ fi+ _wvc_cleared=false+ for _wvc_p in "${_wvc_paths[@]}"; do+ # -L too: a dangling symlink still occupies the path.+ [ -e "$_wvc_p" ] || [ -L "$_wvc_p" ] || continue+ rm -rf "$_wvc_p" 2>/dev/null && _wvc_cleared=true || true+ done+ if [ "$_wvc_cleared" = true ]; then+ substep "cleared stale WebView caches ($_wvc_bid); settings and data kept"+ fi+ return 0+}+# Not called here: under `set -e` with no trap, clearing before the UNSLOTH_STUDIO_HOME+# / STUDIO_HOME override is validated lets a typo'd override delete the cache, then abort.+# ── Detect Colab ──IS_COLAB=falsekeynames=$'\n'$(printenv | cut -d= -f1)@@ -875,11 +934,20 @@ if [ -n "$_studio_override" ]; thenelseSTUDIO_HOME="$HOME/.unsloth/studio"fi+VENV_DIR="$STUDIO_HOME/unsloth_studio"VENV_T5_530_DIR="$STUDIO_HOME/.venv_t5_530"VENV_T5_550_DIR="$STUDIO_HOME/.venv_t5_550"VENV_T5_510_DIR="$STUDIO_HOME/.venv_t5_510"+# The override is validated, so a typo can no longer cost the cache. Venv-gated because+# a writable-but-empty override still aborts at the venv check below, and clearing first+# would cost the cache for a run that then does nothing; a fresh install has neither venv+# nor cache. Still before any install work, while the old frontend is the one on disk.+if [ -x "$VENV_DIR/bin/python" ]; then+ _clear_webview_caches+fi+_STUDIO_OWNED_MARKER=".unsloth-studio-owned"_LEGACY_STUDIO_HOME="$HOME/.unsloth/studio"_studio_home_canon="$STUDIO_HOME"diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rsindex 35464942497..55bb48e08d1 100644--- a/studio/src-tauri/src/main.rs+++ b/studio/src-tauri/src/main.rs@@ -873,6 +873,89 @@ fn setup_tray(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {Ok(())}+// Root shared by the WebView profile and the version stamp below. dirs::data_local_dir+// is the call Tauri's PathResolver makes for LocalData/<bid>, and it falls back to the+// passwd database and the Windows known folder where a raw env read cannot.+fn webview_profile_root(bundle_id: &str) -> Option<std::path::PathBuf> {+ dirs::data_local_dir().map(|d| d.join(bundle_id))+}++// Clear WebView caches after an update: the in-app update runs setup.sh/setup.ps1 while+// the old WebView still holds these files, so its clear fails and a relaunch serves the+// previous frontend. Version-stamped so an ordinary launch does not discard the Windows+// compiled-JS cache. Cache-only (storage and cookies kept), mirroring setup.sh+// _clear_webview_caches / setup.ps1. The caller runs after single-instance, so a duplicate+// launch has exited; the returned lock covers the no-session-bus case, where it has not.+#[must_use]+fn clear_webview_caches(bundle_id: &str, version: &str) -> Option<fs::File> {+ let root = webview_profile_root(bundle_id)?;+ // Claim the profile BEFORE reading the stamp, and keep the lock even when it+ // matches: a stamped launch holding nothing would let a newer executable started+ // alongside it delete this instance's live profile. The OS drops the lock if we+ // crash, so a dead process never blocks a clear.+ let _ = fs::create_dir_all(&root);+ let lock = fs::File::create(root.join(".webview-cache-lock")).ok()?;+ lock.try_lock().ok()?;+ let stamp = root.join(".webview-cache-cleared");+ if fs::read_to_string(&stamp).is_ok_and(|v| v.trim() == version) {+ return Some(lock);+ }++ let mut paths: Vec<std::path::PathBuf> = Vec::new();+ #[cfg(target_os = "windows")]+ {+ let profile = root.join("EBWebView").join("Default");+ for sub in ["Cache", "Code Cache", "GPUCache", "Service Worker"] {+ paths.push(profile.join(sub));+ }+ }+ #[cfg(target_os = "macos")]+ if let Some(caches) = dirs::cache_dir() {+ // WKWebView keeps every cache-typed store under Library/Caches/<bid>;+ // Library/WebKit/<bid> is user storage and is left alone.+ paths.push(caches.join(bundle_id));+ }+ #[cfg(target_os = "linux")]+ for sub in ["WebKitCache", "CacheStorage", "serviceworkers"] {+ paths.push(root.join(sub));+ }++ let mut cleared = true;+ for p in &paths {+ // Absent is normal; anything else is the silent failure that shows up+ // as a stale frontend, so log it.+ if let Err(e) = fs::remove_dir_all(p) {+ if e.kind() != std::io::ErrorKind::NotFound {+ warn!("could not clear WebView cache {}: {e}", p.display());+ cleared = false;+ }+ }+ }+ // Stamping a partial clear (an update can still hold a cache file open)+ // would make every later launch skip the retry and keep the stale cache.+ if cleared {+ let _ = fs::write(&stamp, version);+ }+ Some(lock)+}++// Never dropped: the lock has to outlive the clear (see the function).+static WEBVIEW_PROFILE_LOCK: std::sync::OnceLock<Option<fs::File>> = std::sync::OnceLock::new();++// Register directly after tauri_plugin_single_instance: setup hooks run in registration+// order inside Builder::build(), while the config window (and its WebView, which locks+// these files) is only created later, from App::run().+fn webview_cache_plugin<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {+ tauri::plugin::Builder::new("unsloth-webview-cache")+ .setup(|app, _api| {+ let version = app.package_info().version.to_string();+ let _ = WEBVIEW_PROFILE_LOCK+ .set(clear_webview_caches(&app.config().identifier, &version));+ Ok(())+ })+ .build()+}+fn main() {// Must precede any Xlib call: GTK3 never calls XInitThreads and this// process drives X from several threads. See x11_threads for the crash.@@ -897,10 +980,13 @@ fn main() {}windows_job::initialize();+ let context = tauri::generate_context!();+tauri::Builder::default().plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {show_main_window(app);}))+ .plugin(webview_cache_plugin()).plugin(tauri_plugin_deep_link::init()).plugin(tauri_plugin_autostart::init(tauri_plugin_autostart::MacosLauncher::LaunchAgent,@@ -1019,7 +1105,7 @@ fn main() {}}})- .build(tauri::generate_context!())+ .build(context).expect("error while building tauri application").run(|app, event| match event {#[cfg(target_os = "macos")]@@ -1113,6 +1199,116 @@ mod tests {assert!(!in_app_relaunch_marker_path(dir.path()).exists());}+ #[cfg(target_os = "linux")]+ const BID: &str = "ai.unsloth.studio";++ // Only XDG_DATA_HOME is swapped, and nothing else in the crate reads it, so the+ // tests running beside these stay clear. HOME is left alone for the same reason:+ // `dirs::home_dir` is all over this crate.+ #[cfg(target_os = "linux")]+ fn with_xdg_data_home<T>(value: &str, f: impl FnOnce() -> T) -> T {+ static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());+ let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let saved = std::env::var_os("XDG_DATA_HOME");+ std::env::set_var("XDG_DATA_HOME", value);+ let out = f();+ match saved {+ Some(v) => std::env::set_var("XDG_DATA_HOME", v),+ None => std::env::remove_var("XDG_DATA_HOME"),+ }+ out+ }++ #[test]+ #[cfg(target_os = "linux")]+ fn a_relative_xdg_data_home_resolves_like_tauri_does() {+ // dirs, which resolves the LocalData dir Tauri hands the WebView, drops a+ // relative XDG_DATA_HOME; following one would leave the real cache in+ // place and rm -rf under the working directory.+ let (got, expected) = with_xdg_data_home("reldata", || {+ (+ webview_profile_root(BID),+ dirs::data_local_dir().map(|d| d.join(BID)),+ )+ });+ assert_eq!(got, expected, "diverged from the resolver Tauri uses");+ assert!(+ got.is_none_or(|p| p.is_absolute()),+ "resolved a deletion target relative to the working directory"+ );++ // An absolute override is still honoured.+ let dir = tempfile::tempdir().unwrap();+ let got = with_xdg_data_home(dir.path().to_str().unwrap(), || webview_profile_root(BID));+ assert_eq!(got, Some(dir.path().join(BID)));+ }++ #[test]+ #[cfg(target_os = "linux")]+ fn a_partial_clear_is_not_stamped_and_retries() {+ let dir = tempfile::tempdir().unwrap();+ let xdg = dir.path().to_str().unwrap();+ let root = dir.path().join(BID);+ fs::create_dir_all(root.join("CacheStorage")).unwrap();+ // A plain file where a cache dir belongs fails remove_dir_all with something+ // other than NotFound, exactly as a locked directory does.+ fs::write(root.join("WebKitCache"), b"still open").unwrap();++ let lock = with_xdg_data_home(xdg, || clear_webview_caches(BID, "1.0.0"));+ assert!(!root.join("CacheStorage").exists(), "the deletable cache stayed");+ assert!(+ !root.join(".webview-cache-cleared").exists(),+ "stamping a partial clear makes every later launch skip the retry"+ );+ drop(lock);++ // The next launch, with the obstruction gone, clears and stamps.+ fs::remove_file(root.join("WebKitCache")).unwrap();+ fs::create_dir_all(root.join("WebKitCache")).unwrap();+ let lock = with_xdg_data_home(xdg, || clear_webview_caches(BID, "1.0.0"));+ assert!(!root.join("WebKitCache").exists(), "the retry did not run");+ assert!(root.join(".webview-cache-cleared").exists(), "the retry did not stamp");+ drop(lock);+ }++ #[test]+ #[cfg(target_os = "linux")]+ fn a_live_instance_lock_excludes_a_duplicate_launch() {+ let dir = tempfile::tempdir().unwrap();+ let xdg = dir.path().to_str().unwrap();+ let root = dir.path().join(BID);+ fs::create_dir_all(root.join("WebKitCache")).unwrap();++ // The first launch clears and holds the lock, as main() does.+ let live = with_xdg_data_home(xdg, || clear_webview_caches(BID, "1.0.0"));+ assert!(live.is_some(), "the clearing instance must get the lock");+ assert!(!root.join("WebKitCache").exists(), "the first launch did not clear");++ // A second launch past single-instance (no session bus) must leave it alone.+ fs::create_dir_all(root.join("WebKitCache")).unwrap();+ let second = with_xdg_data_home(xdg, || clear_webview_caches(BID, "1.0.1"));+ assert!(second.is_none(), "a duplicate launch took the lock");+ assert!(root.join("WebKitCache").exists(), "deleted a live instance's cache");++ // Exit or crash drops the lock, so the next launch clears.+ drop(live);++ // A launch whose stamp already matches must still TAKE the lock, or a+ // newer executable started alongside it could delete the live profile.+ fs::create_dir_all(root.join("WebKitCache")).unwrap();+ let stamped = with_xdg_data_home(xdg, || clear_webview_caches(BID, "1.0.0"));+ assert!(stamped.is_some(), "a stamped launch dropped the profile lock");+ assert!(root.join("WebKitCache").exists(), "a stamped launch cleared anyway");+ let racer = with_xdg_data_home(xdg, || clear_webview_caches(BID, "1.0.1"));+ assert!(racer.is_none(), "a newer launch took the lock from a stamped instance");+ assert!(root.join("WebKitCache").exists(), "deleted a stamped instance's cache");+ drop(stamped);++ let next = with_xdg_data_home(xdg, || clear_webview_caches(BID, "1.0.1"));+ assert!(!root.join("WebKitCache").exists(), "a released lock still blocked the clear");+ drop(next);+ }+// One test, not three: `QUIT_IN_PROGRESS` is process-global and cargo tests run in parallel.#[test]fn quit_guard_admits_one_quit_and_always_re_arms() {diff --git a/tests/sh/test_setup_webview_cache_clear.sh b/tests/sh/test_setup_webview_cache_clear.shnew file mode 100755index 00000000000..5b56e0e0833--- /dev/null+++ b/tests/sh/test_setup_webview_cache_clear.sh@@ -0,0 +1,266 @@+#!/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+# Unit tests for _clear_webview_caches() from studio/setup.sh.+#+# WebView caches keyed by the bundle id (ai.unsloth.studio) hold copies of the+# previous frontend, so an install/update must clear them or the app keeps+# rendering old styles. Cache-only: LocalStorage, IndexedDB, app data and+# unrelated apps' caches stay intact.+#+# Follows the extract-via-sed pattern of test_uninstall_shared_icon.sh; uname+# is overridden per test with a shell function to select the OS branch.+# shellcheck disable=SC2329 # uname stubs are invoked inside the extracted function+set -e++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+SETUP_SH="$SCRIPT_DIR/../../studio/setup.sh"+BID="ai.unsloth.studio"+PASS=0+FAIL=0++_TMP_ROOT=$(mktemp -d)+trap 'rm -rf "$_TMP_ROOT"' EXIT++# -e || -L, matching the production guard: -e alone is false for a dangling+# symlink, so assert_gone would pass on one that was never removed.+assert_gone() { _l="$1"; if [ -e "$2" ] || [ -L "$2" ]; then echo " FAIL: $_l (still present: $2)"; FAIL=$((FAIL+1)); else echo " PASS: $_l"; PASS=$((PASS+1)); fi; }+assert_present() { _l="$1"; if [ -e "$2" ] || [ -L "$2" ]; then echo " PASS: $_l"; PASS=$((PASS+1)); else echo " FAIL: $_l (missing: $2)"; FAIL=$((FAIL+1)); fi; }++# Explicit template: -p is GNU-only (BSD got it in macOS 14) and a bare+# mktemp -d implies -t, landing outside _TMP_ROOT on macOS.+new_home() { mktemp -d "$_TMP_ROOT/home.XXXXXX"; }++# Extract just the function definition (top-level, closes at column 0).+FUNC_FILE=$(mktemp "$_TMP_ROOT/fn.XXXXXX")+sed -n '/^_clear_webview_caches() {/,/^}/p' "$SETUP_SH" > "$FUNC_FILE"+# shellcheck disable=SC1090+. "$FUNC_FILE"+substep() { :; } # stub the setup.sh logger++# ── 1. macOS: cache-typed stores hang off Library/Caches/<bid>/WebKit;+# Library/WebKit/<bid> is user storage only ──+H=$(new_home)+mkdir -p "$H/Library/Caches/$BID/WebKit/NetworkCache/Version 17" \+ "$H/Library/Caches/$BID/WebKit/CacheStorage" \+ "$H/Library/Caches/$BID/WebKit/ServiceWorkers" \+ "$H/Library/WebKit/$BID/WebsiteData/Default" \+ "$H/Library/WebKit/$BID/WebsiteData/LocalStorage" \+ "$H/Library/WebKit/$BID/WebsiteData/IndexedDB" \+ "$H/Library/Application Support/$BID" \+ "$H/Library/Caches/com.other.app"+uname() { echo Darwin; }+HOME="$H" _clear_webview_caches+assert_gone "macOS: Caches/$BID removed" "$H/Library/Caches/$BID"+assert_present "macOS: origin-keyed storage kept" "$H/Library/WebKit/$BID/WebsiteData/Default"+assert_present "macOS: LocalStorage kept" "$H/Library/WebKit/$BID/WebsiteData/LocalStorage"+assert_present "macOS: IndexedDB kept" "$H/Library/WebKit/$BID/WebsiteData/IndexedDB"+assert_present "macOS: Application Support kept" "$H/Library/Application Support/$BID"+assert_present "macOS: unrelated app cache kept" "$H/Library/Caches/com.other.app"++# ── 2. Linux: wry points the base-cache dir at the app data dir, so caches+# sit beside user storage under ~/.local/share/<bid> ──+H=$(new_home)+D="$H/.local/share/$BID"+mkdir -p "$D/WebKitCache" "$D/CacheStorage" "$D/serviceworkers" \+ "$D/localstorage" "$D/databases/indexeddb" "$H/.config/$BID" \+ "$H/.local/share/${BID}2/WebKitCache" "$H/.cache/other.app"+: > "$D/cookies"+uname() { echo Linux; }+HOME="$H" XDG_CACHE_HOME="" XDG_DATA_HOME="" _clear_webview_caches+assert_gone "linux: data-dir WebKitCache removed" "$D/WebKitCache"+assert_gone "linux: data-dir CacheStorage removed" "$D/CacheStorage"+assert_gone "linux: data-dir serviceworkers removed" "$D/serviceworkers"+assert_present "linux: localstorage kept" "$D/localstorage"+assert_present "linux: indexeddb kept" "$D/databases/indexeddb"+assert_present "linux: cookies kept" "$D/cookies"+assert_present "linux: ~/.config/$BID kept" "$H/.config/$BID"+assert_present "linux: prefix-decoy bundle id kept" "$H/.local/share/${BID}2/WebKitCache"+assert_present "linux: unrelated app cache kept" "$H/.cache/other.app"++# ── 3. Linux: XDG_DATA_HOME override honored ──+H=$(new_home)+XDG=$(mktemp -d "$_TMP_ROOT/xdg.XXXXXX")+mkdir -p "$XDG/data/$BID/WebKitCache" "$XDG/data/$BID/localstorage" "$H/.local/share/$BID/WebKitCache"+HOME="$H" XDG_CACHE_HOME="" XDG_DATA_HOME="$XDG/data" _clear_webview_caches+assert_gone "linux: XDG_DATA_HOME WebKitCache removed" "$XDG/data/$BID/WebKitCache"+assert_present "linux: XDG_DATA_HOME localstorage kept" "$XDG/data/$BID/localstorage"+assert_present "linux: default data dir kept under override" "$H/.local/share/$BID/WebKitCache"++# ── 3a. A relative XDG_DATA_HOME is invalid per the XDG spec, so dirs (and Tauri)+# ignores it. Following it would rm -rf under the installer's cwd and leave the+# cache Tauri actually uses in place ──+H=$(new_home)+W=$(mktemp -d "$_TMP_ROOT/work.XXXXXX")+mkdir -p "$W/reldata/$BID/WebKitCache" "$H/.local/share/$BID/WebKitCache"+uname() { echo Linux; }+( cd "$W" && HOME="$H" XDG_CACHE_HOME="" XDG_DATA_HOME="reldata" _clear_webview_caches )+assert_present "linux: relative XDG_DATA_HOME not followed under cwd" "$W/reldata/$BID/WebKitCache"+assert_gone "linux: relative XDG_DATA_HOME uses the default" "$H/.local/share/$BID/WebKitCache"++# ── 3b. A dangling cache symlink still occupies the path, so it must go ──+H=$(new_home)+mkdir -p "$H/.local/share/$BID"+ln -s "$_TMP_ROOT/does-not-exist" "$H/.local/share/$BID/WebKitCache"+HOME="$H" XDG_CACHE_HOME="" XDG_DATA_HOME="" _clear_webview_caches+assert_gone "linux: dangling cache symlink removed" "$H/.local/share/$BID/WebKitCache"++# ── 4. Nothing to clear is a clean no-op ──+H=$(new_home)+uname() { echo Darwin; }+if HOME="$H" _clear_webview_caches; then+ echo " PASS: empty HOME -> no-op exit 0"; PASS=$((PASS+1))+else+ echo " FAIL: empty HOME -> nonzero exit"; FAIL=$((FAIL+1))+fi++# ── 5. Unknown OS is a no-op ──+H=$(new_home)+mkdir -p "$H/Library/Caches/$BID"+uname() { echo SunOS; }+HOME="$H" _clear_webview_caches+assert_present "unknown OS: nothing removed" "$H/Library/Caches/$BID"++# ── 6. No HOME is a no-op, not a delete under /Library or /.cache. Unset, not empty:+# `set -u` fires on unset only, and the empty case passes even without the guard ──+uname() { echo Darwin; }+_wvc_rc=0+# `|| _wvc_rc=$?` keeps the abort we are testing for off `set -e`'s exit path.+_wvc_out=$( set -u; unset HOME; _clear_webview_caches 2>&1 ) || _wvc_rc=$?+if [ "$_wvc_rc" = 0 ] && [ -z "$_wvc_out" ]; then+ echo " PASS: unset HOME -> silent no-op"; PASS=$((PASS+1))+else+ echo " FAIL: unset HOME -> rc=$_wvc_rc out=$_wvc_out"; FAIL=$((FAIL+1))+fi++# ── 6b. The clear must invalidate the app's version stamp. ──+# The app skips its own clear whenever .webview-cache-cleared matches the running+# version (main.rs), and that clear is the retry for an rm here that failed. A repair+# or a local rebuild leaves the version unchanged, so a surviving stamp suppresses the+# retry and the cache we could not remove stays forever.+_st_home=$(new_home)+_st_data="$_st_home/.local/share/$BID"+mkdir -p "$_st_data/WebKitCache"+: > "$_st_data/WebKitCache/asset.js"+printf '2026.4.8' > "$_st_data/.webview-cache-cleared"+uname() { echo Linux; }+( HOME="$_st_home" _clear_webview_caches >/dev/null 2>&1 )+assert_gone "linux: version stamp invalidated so the app retries" \+ "$_st_data/.webview-cache-cleared"++# The stamp must go even when nothing was removable, which is the case that matters:+# an unremovable cache plus a surviving stamp is what makes the staleness permanent.+_st_home=$(new_home)+_st_data="$_st_home/.local/share/$BID"+mkdir -p "$_st_data"+printf '2026.4.8' > "$_st_data/.webview-cache-cleared"+( HOME="$_st_home" _clear_webview_caches >/dev/null 2>&1 )+assert_gone "linux: stamp dropped even with no cache dirs present" \+ "$_st_data/.webview-cache-cleared"++# macOS keeps the stamp under Application Support, not Caches, so the two paths differ.+_st_home=$(new_home)+mkdir -p "$_st_home/Library/Caches/$BID" "$_st_home/Library/Application Support/$BID"+: > "$_st_home/Library/Caches/$BID/stale.js"+printf '2026.4.8' > "$_st_home/Library/Application Support/$BID/.webview-cache-cleared"+uname() { echo Darwin; }+( HOME="$_st_home" _clear_webview_caches >/dev/null 2>&1 )+assert_gone "macos: stamp under Application Support invalidated" \+ "$_st_home/Library/Application Support/$BID/.webview-cache-cleared"+assert_gone "macos: Caches/<bid> still cleared" "$_st_home/Library/Caches/$BID/stale.js"+unset -f uname++# ── 7. setup.sh still calls it (the sed extract above cannot prove that) ──+if grep -qE '^[[:space:]]*_clear_webview_caches[[:space:]]*$' "$SETUP_SH"; then+ echo " PASS: setup.sh invokes _clear_webview_caches"; PASS=$((PASS+1))+else+ echo " FAIL: setup.sh never calls _clear_webview_caches"; FAIL=$((FAIL+1))+fi++# ── 7b. setup.ps1 is not driven here, so assert on source order: the call must come+# after the override validation, or a mistyped override wipes the cache and then aborts ──+SETUP_PS1="$SCRIPT_DIR/../../studio/setup.ps1"+if [ ! -f "$SETUP_PS1" ]; then+ echo " FAIL: setup.ps1 not found"; FAIL=$((FAIL+1))+else+ _ps_call=$(grep -n '^[[:space:]]*Clear-WebViewCaches[[:space:]]*$' "$SETUP_PS1" | head -n1 | cut -d: -f1)+ _ps_validate=$(grep -n 'does not exist"$' "$SETUP_PS1" | tail -n1 | cut -d: -f1)+ if [ -z "$_ps_call" ]; then+ echo " FAIL: setup.ps1 never calls Clear-WebViewCaches"; FAIL=$((FAIL+1))+ elif [ -z "$_ps_validate" ]; then+ echo " FAIL: could not find the setup.ps1 override validation"; FAIL=$((FAIL+1))+ elif [ "$_ps_call" -gt "$_ps_validate" ]; then+ echo " PASS: setup.ps1 clears after validating the override"; PASS=$((PASS+1))+ else+ echo " FAIL: setup.ps1 clears at line $_ps_call, before validation at $_ps_validate"+ FAIL=$((FAIL+1))+ fi+fi++# ── 7c. An override that exists and is writable but holds no Studio install: setup+# aborts later at the venv check, so clearing first would cost the cache for nothing ──+_novenv_home=$(new_home)+_novenv_root="$_TMP_ROOT/exists-but-empty.$$"+mkdir -p "$_novenv_root"+mkdir -p "$_novenv_home/.local/share/$BID/WebKitCache"+: > "$_novenv_home/.local/share/$BID/WebKitCache/asset.js"+# Stub node/npm as failing and opt out of the isolated install so setup.sh reaches the+# venv check without provisioning Node or building the frontend.+_novenv_bin="$_TMP_ROOT/no-node.$$"+mkdir -p "$_novenv_bin"+for _stub in node npm; do+ printf '#!/bin/sh\nexit 1\n' > "$_novenv_bin/$_stub"+ chmod +x "$_novenv_bin/$_stub"+done+_novenv_out=$(+ cd "$(dirname "$SETUP_SH")" &&+ env -u XDG_DATA_HOME -u STUDIO_HOME \+ HOME="$_novenv_home" UNSLOTH_STUDIO_HOME="$_novenv_root" \+ PATH="$_novenv_bin:$PATH" UNSLOTH_SKIP_NODE_INSTALL=1 SKIP_STUDIO_FRONTEND=1 \+ UNSLOTH_TAURI_MODE=0 bash "$SETUP_SH" 2>&1+) && _novenv_rc=0 || _novenv_rc=$?+if [ "$_novenv_rc" = 0 ]; then+ echo " FAIL: override without a venv did not abort"; FAIL=$((FAIL+1))+else+ echo " PASS: override without a venv aborts (rc=$_novenv_rc)"; PASS=$((PASS+1))+fi+# Or the cache survived for an unrelated reason.+case "$_novenv_out" in+ *"venv not found at"*) echo " PASS: the abort is the venv check"; PASS=$((PASS+1)) ;;+ *) echo " FAIL: aborted before the venv check"; FAIL=$((FAIL+1)) ;;+esac+case "$_novenv_out" in+ *"no suitable Node"*) echo " PASS: reached it without provisioning Node"; PASS=$((PASS+1)) ;;+ *) echo " FAIL: the fixture is not hermetic (Node/npm ran)"; FAIL=$((FAIL+1)) ;;+esac+assert_present "existing-but-empty override leaves the cache alone" \+ "$_novenv_home/.local/share/$BID/WebKitCache/asset.js"++# ── 8. a bad override must not cost the user their cache ──+# The cases above extract the function, so none sees where the call sits; driven in situ.+# Under `set -euo pipefail` with no trap, clearing before the UNSLOTH_STUDIO_HOME+# validation turns a typo into cache loss plus the same abort.+_ord_home=$(new_home)+mkdir -p "$_ord_home/.local/share/$BID/WebKitCache" "$_ord_home/.local/share/$BID/CacheStorage"+: > "$_ord_home/.local/share/$BID/WebKitCache/asset.js"+_ord_out=$(+ cd "$(dirname "$SETUP_SH")" &&+ env -u XDG_DATA_HOME -u STUDIO_HOME \+ HOME="$_ord_home" UNSLOTH_STUDIO_HOME="$_ord_home/typo-not-a-real-dir" \+ UNSLOTH_TAURI_MODE=0 bash "$SETUP_SH" 2>&1+) && _ord_rc=0 || _ord_rc=$?+if [ "$_ord_rc" = 0 ]; then+ echo " FAIL: bad override did not abort (rc=0)"; FAIL=$((FAIL+1))+else+ echo " PASS: bad override still aborts (rc=$_ord_rc)"; PASS=$((PASS+1))+fi+case "$_ord_out" in+ *"does not exist"*) echo " PASS: abort names the bad override"; PASS=$((PASS+1)) ;;+ *) echo " FAIL: abort message missing: $_ord_out"; FAIL=$((FAIL+1)) ;;+esac+assert_present "bad override leaves the cache alone" \+ "$_ord_home/.local/share/$BID/WebKitCache/asset.js"++echo ""+echo "Results: $PASS passed, $FAIL failed"+[ "$FAIL" = 0 ]