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.

Fix Studio desktop tray installer and titlebar and bux fixes (#5179)

Wasim Yousef Said507417579f01
diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml
index 2d1c6f51f26..ea827399684 100644
--- a/.github/workflows/release-desktop.yml
+++ b/.github/workflows/release-desktop.yml
@@ -54,10 +54,43 @@ jobs:
with:
node-version: 24
+ - name: Install pinned Tauri CLI
+ run: npm install --save-dev --prefix studio @tauri-apps/[email protected]
+
+ - name: Verify pinned Tauri CLI
+ shell: bash
+ run: |
+ out="$(npx --prefix studio tauri --version)"
+ echo "$out"
+ if [ "$out" != "tauri-cli 2.10.1" ]; then
+ echo "Expected tauri-cli 2.10.1, got $out" >&2
+ exit 1
+ fi
+
- name: Install frontend dependencies
working-directory: studio/frontend
run: npm install
+ - name: Verify backend package is published
+ shell: bash
+ run: |
+ node <<'JS'
+ const { readFileSync } = require('node:fs');
+
+ (async () => {
+ const cargo = readFileSync('studio/src-tauri/Cargo.toml', 'utf8');
+ const match = cargo.match(/^version\s*=\s*"([^"]+)"/m);
+ if (!match) throw new Error('Could not read desktop app version');
+
+ const appVersion = match[1];
+ const response = await fetch(`https://pypi.org/pypi/unsloth/${appVersion}/json`);
+ if (!response.ok) {
+ const message = 'Publish unsloth=={app_version} to PyPI before the desktop release';
+ throw new Error(`${message.replace('{app_version}', appVersion)} (HTTP ${response.status})`);
+ }
+ })();
+ JS
+
# ── Rust ──
- name: Install Rust stable
uses: dtolnay/rust-toolchain@stable
@@ -105,13 +138,14 @@ jobs:
# ── Linux: build + sign + upload ──
- name: Build Linux app
if: matrix.platform == 'ubuntu-22.04'
- uses: tauri-apps/tauri-action@fce9c6108b31ea247710505d3aaaa893ee6768d4
+ uses: tauri-apps/tauri-action@84b9d35b5fc46c1e45415bdb6144030364f7ebc5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
with:
projectPath: studio
+ tauriScript: npx --prefix . tauri
tagName: desktop-v__VERSION__
releaseName: 'Unsloth Studio (Desktop) v__VERSION__'
releaseBody: |
@@ -123,6 +157,7 @@ jobs:
> Linux in-app updates are AppImage-oriented. Package installs should update by downloading a new package.
> Linux AppImage on Ubuntu 24.04+ may require: `sudo apt install libfuse2t64`
+ > First-run system dependency elevation is supported on Ubuntu/Debian. Other Linux distributions should install system packages manually.
releaseDraft: ${{ inputs.draft }}
prerelease: false
args: -v ${{ matrix.args }}
@@ -130,7 +165,7 @@ jobs:
# ── macOS: build + sign + notarize + upload ──
- name: Build macOS app
if: matrix.platform == 'macos-latest'
- uses: tauri-apps/tauri-action@fce9c6108b31ea247710505d3aaaa893ee6768d4
+ uses: tauri-apps/tauri-action@84b9d35b5fc46c1e45415bdb6144030364f7ebc5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
@@ -141,6 +176,7 @@ jobs:
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
with:
projectPath: studio
+ tauriScript: npx --prefix . tauri
tagName: desktop-v__VERSION__
releaseName: 'Unsloth Studio (Desktop) v__VERSION__'
releaseBody: |
@@ -152,6 +188,7 @@ jobs:
> Linux in-app updates are AppImage-oriented. Package installs should update by downloading a new package.
> Linux AppImage on Ubuntu 24.04+ may require: `sudo apt install libfuse2t64`
+ > First-run system dependency elevation is supported on Ubuntu/Debian. Other Linux distributions should install system packages manually.
releaseDraft: ${{ inputs.draft }}
prerelease: false
args: -v ${{ matrix.args }}
@@ -159,7 +196,7 @@ jobs:
# ── Windows: build + sign + upload ──
- name: Build Windows app
if: matrix.platform == 'windows-latest'
- uses: tauri-apps/tauri-action@fce9c6108b31ea247710505d3aaaa893ee6768d4
+ uses: tauri-apps/tauri-action@84b9d35b5fc46c1e45415bdb6144030364f7ebc5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
@@ -171,6 +208,7 @@ jobs:
AZURE_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_CERTIFICATE_PROFILE_NAME }}
with:
projectPath: studio
+ tauriScript: npx --prefix . tauri
tagName: desktop-v__VERSION__
releaseName: 'Unsloth Studio (Desktop) v__VERSION__'
releaseBody: |
@@ -182,6 +220,7 @@ jobs:
> Linux in-app updates are AppImage-oriented. Package installs should update by downloading a new package.
> Linux AppImage on Ubuntu 24.04+ may require: `sudo apt install libfuse2t64`
+ > First-run system dependency elevation is supported on Ubuntu/Debian. Other Linux distributions should install system packages manually.
releaseDraft: ${{ inputs.draft }}
prerelease: false
args: -v ${{ matrix.args }}
diff --git a/install.ps1 b/install.ps1
index 2544eaf78a5..dcd86eb0197 100644
--- a/install.ps1
+++ b/install.ps1
@@ -8,6 +8,79 @@ function Install-UnslothStudio {
$ErrorActionPreference = "Stop"
$script:UnslothVerbose = ($env:UNSLOTH_VERBOSE -eq "1")
+ # ── Tauri structured output ──
+ function Write-TauriLog {
+ param([string]$Tag, [string]$Message)
+ if ($TauriMode) {
+ Write-Host "[TAURI:$Tag] $Message"
+ }
+ }
+
+ function Format-TauriDiagBool {
+ param([bool]$Value)
+ if ($Value) { return "true" }
+ return "false"
+ }
+
+ function Get-TauriDiagArch {
+ $arch = [string]$env:PROCESSOR_ARCHITECTURE
+ if ([string]::IsNullOrWhiteSpace($arch)) {
+ try { $arch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() } catch { $arch = "unknown" }
+ }
+ $arch = $arch.ToLowerInvariant()
+ switch ($arch) {
+ "amd64" { return "x86_64" }
+ "x64" { return "x86_64" }
+ "arm64" { return "arm64" }
+ "x86" { return "x86" }
+ default { return ($arch -replace '[^a-z0-9_.-]', '_') }
+ }
+ }
+
+ function Get-TauriTorchIndexFamily {
+ param([string]$TorchIndexUrl)
+ if ($SkipTorch) { return "none" }
+ if ([string]::IsNullOrWhiteSpace($TorchIndexUrl)) { return "none" }
+ $leaf = ($TorchIndexUrl.TrimEnd('/') -split '/')[-1].ToLowerInvariant()
+ if (@("cpu", "cu118", "cu124", "cu126", "cu128", "cu130") -contains $leaf) { return $leaf }
+ if ($leaf -match '^rocm[0-9]+\.[0-9]+$') { return $leaf }
+ return "auto"
+ }
+
+ function Get-TauriGpuBranch {
+ param([string]$TorchIndexFamily)
+ if ($SkipTorch) { return "no_torch" }
+ if ($TorchIndexFamily -like "cu*") { return "cuda" }
+ if ($TorchIndexFamily -like "rocm*") { return "rocm" }
+ if ($TorchIndexFamily -eq "cpu") { return "cpu" }
+ return "unknown"
+ }
+
+ function Write-TauriDiag {
+ param(
+ [string]$GpuBranch = "unknown",
+ [string]$TorchIndexFamily = "none",
+ [string]$PythonVersionForDiag = $PythonVersion
+ )
+ if ([string]::IsNullOrWhiteSpace($PythonVersionForDiag)) { $PythonVersionForDiag = "unknown" }
+ Write-TauriLog "DIAG" "diag_schema=1 platform=windows arch=$(Get-TauriDiagArch) python_version=$($PythonVersionForDiag.ToLowerInvariant()) skip_torch=$(Format-TauriDiagBool $SkipTorch) mac_intel=false gpu_branch=$GpuBranch torch_index_family=$TorchIndexFamily"
+ }
+
+ function Exit-InstallFailure {
+ param(
+ [Parameter(Mandatory = $true)][string]$Message,
+ [int]$Code = 1
+ )
+ if ($Code -eq 0) { $Code = 1 }
+ Write-TauriLog "ERROR" $Message
+ if (Get-Command Restore-StudioVenvRollback -CommandType Function -ErrorAction SilentlyContinue) {
+ Restore-StudioVenvRollback
+ }
+ if ($TauriMode) {
+ exit $Code
+ }
+ }
+
# ── Parse flags ──
$StudioLocalInstall = $false
$PackageName = "unsloth"
@@ -26,7 +99,7 @@ function Install-UnslothStudio {
$i++
if ($i -ge $argList.Count) {
Write-Host "[ERROR] --package requires an argument." -ForegroundColor Red
- return
+ return (Exit-InstallFailure "--package requires an argument.")
}
$PackageName = $argList[$i]
}
@@ -42,22 +115,14 @@ function Install-UnslothStudio {
$RepoRoot = (Resolve-Path (Split-Path -Parent $PSCommandPath)).Path
if (-not (Test-Path (Join-Path $RepoRoot "pyproject.toml"))) {
Write-Host "[ERROR] --local must be run from the unsloth repo root (pyproject.toml not found at $RepoRoot)" -ForegroundColor Red
- return
+ return (Exit-InstallFailure "--local must be run from the unsloth repo root")
}
}
# Validate --package to prevent injection into shell/Python commands
if ($PackageName -notmatch '^[a-zA-Z0-9][a-zA-Z0-9._-]*$') {
Write-Host "[ERROR] --package name contains invalid characters (allowed: a-z A-Z 0-9 . _ -)" -ForegroundColor Red
- return
- }
-
- # ── Tauri structured output ──
- function Write-TauriLog {
- param([string]$Tag, [string]$Message)
- if ($TauriMode) {
- Write-Host "[TAURI:$Tag] $Message"
- }
+ return (Exit-InstallFailure "--package name contains invalid characters")
}
$PythonVersion = "3.13"
@@ -630,7 +695,7 @@ shell.Run cmd, 0, False
step "winget" "not available" "Red"
substep "Install it from https://aka.ms/getwinget" "Yellow"
substep "or install Python $PythonVersion and uv manually, then re-run." "Yellow"
- return
+ return (Exit-InstallFailure "winget is not available")
}
# ── Helper: detect a working Python 3.11-3.13 on the system ──
@@ -749,9 +814,14 @@ shell.Run cmd, 0, False
Write-Host " Please install Python $PythonVersion manually from https://www.python.org/downloads/" -ForegroundColor Yellow
Write-Host " Make sure to check 'Add Python to PATH' during installation." -ForegroundColor Yellow
Write-Host " Then re-run this installer." -ForegroundColor Yellow
- return
+ return (Exit-InstallFailure "Python installation failed")
}
}
+ $DiagPythonVersion = $PythonVersion
+ if ($DetectedPython) { $DiagPythonVersion = $DetectedPython.Version }
+ $InitialGpuBranch = "unknown"
+ if ($SkipTorch) { $InitialGpuBranch = "no_torch" }
+ Write-TauriDiag -GpuBranch $InitialGpuBranch -TorchIndexFamily "none" -PythonVersionForDiag $DiagPythonVersion
# ── Install uv if not present ──
Write-TauriLog "STEP" "Installing uv package manager"
@@ -773,7 +843,7 @@ shell.Run cmd, 0, False
if (-not (Get-Command uv -ErrorAction SilentlyContinue)) {
step "uv" "could not be installed" "Red"
substep "Install it from https://docs.astral.sh/uv/" "Yellow"
- return
+ return (Exit-InstallFailure "uv could not be installed")
}
# ── Create venv (migrate old layout if possible, otherwise fresh) ──
@@ -786,11 +856,68 @@ shell.Run cmd, 0, False
$VenvPython = Join-Path $VenvDir "Scripts\python.exe"
$_Migrated = $false
+ $script:StudioVenvRollbackDir = $null
+ $script:StudioVenvRollbackTarget = $VenvDir
+ $script:StudioVenvRollbackActive = $false
+
+ function Start-StudioVenvRollback {
+ param([Parameter(Mandatory = $true)][string]$ExistingDir)
+ $stamp = Get-Date -Format "yyyyMMddHHmmss"
+ $candidate = Join-Path $StudioHome "unsloth_studio.rollback.$stamp.$PID"
+ $suffix = 0
+ while (Test-Path $candidate) {
+ $suffix++
+ $candidate = Join-Path $StudioHome "unsloth_studio.rollback.$stamp.$PID.$suffix"
+ }
+ Move-Item -Path $ExistingDir -Destination $candidate -ErrorAction Stop
+ $script:StudioVenvRollbackDir = $candidate
+ $script:StudioVenvRollbackTarget = $ExistingDir
+ $script:StudioVenvRollbackActive = $true
+ substep "previous environment preserved for rollback"
+ }
+
+ function Restore-StudioVenvRollback {
+ if (-not $script:StudioVenvRollbackActive) { return }
+ $backup = $script:StudioVenvRollbackDir
+ $target = $script:StudioVenvRollbackTarget
+ if (-not $backup -or -not (Test-Path $backup)) {
+ $script:StudioVenvRollbackActive = $false
+ return
+ }
+ substep "restoring previous environment after failed install..." "Yellow"
+ try {
+ if (Test-Path $target) {
+ Remove-Item -Recurse -Force $target -ErrorAction SilentlyContinue
+ }
+ Move-Item -Path $backup -Destination $target -Force -ErrorAction Stop
+ substep "restored previous environment"
+ $script:StudioVenvRollbackActive = $false
+ $script:StudioVenvRollbackDir = $null
+ } catch {
+ Write-Host "[WARN] Could not restore previous environment from $backup to $target" -ForegroundColor Yellow
+ Write-Host " $($_.Exception.Message)" -ForegroundColor Yellow
+ }
+ }
+
+ function Complete-StudioVenvRollback {
+ if (-not $script:StudioVenvRollbackActive) { return }
+ $backup = $script:StudioVenvRollbackDir
+ if ($backup -and (Test-Path $backup)) {
+ Remove-Item -Recurse -Force $backup -ErrorAction SilentlyContinue
+ }
+ $script:StudioVenvRollbackActive = $false
+ $script:StudioVenvRollbackDir = $null
+ }
if (Test-Path $VenvPython) {
- # New layout already exists -- nuke for fresh install
- substep "removing existing environment for fresh install..."
- Remove-Item -Recurse -Force $VenvDir
+ # New layout already exists -- replace only after preserving rollback copy.
+ substep "preserving existing environment for rollback..."
+ try {
+ Start-StudioVenvRollback -ExistingDir $VenvDir
+ } catch {
+ Write-Host "[ERROR] Could not prepare existing environment for reinstall: $($_.Exception.Message)" -ForegroundColor Red
+ return (Exit-InstallFailure "Could not prepare existing environment for reinstall")
+ }
} elseif (Test-Path (Join-Path $StudioHome ".venv\Scripts\python.exe")) {
# Old layout (~/.unsloth/studio/.venv) exists -- validate before migrating
$OldVenv = Join-Path $StudioHome ".venv"
@@ -799,18 +926,23 @@ shell.Run cmd, 0, False
$prevEAP2 = $ErrorActionPreference
$ErrorActionPreference = "Continue"
try {
- & $OldPy -c "import torch; A = torch.ones((2,2)); B = A + A" 2>$null | Out-Null
- $torchOk = ($LASTEXITCODE -eq 0)
- } catch { $torchOk = $false }
+ if ($SkipTorch) {
+ & $OldPy -c "import sys; print(sys.executable)" 2>$null | Out-Null
+ } else {
+ & $OldPy -c "import torch; A = torch.ones((2,2)); B = A + A" 2>$null | Out-Null
+ }
+ $legacyOk = ($LASTEXITCODE -eq 0)
+ } catch { $legacyOk = $false }
$ErrorActionPreference = $prevEAP2
- if ($torchOk) {
+ if ($legacyOk) {
substep "legacy environment is healthy -- migrating..."
Move-Item -Path $OldVenv -Destination $VenvDir -Force
substep "moved .venv -> unsloth_studio"
$_Migrated = $true
} else {
substep "legacy environment failed validation -- creating fresh environment" "Yellow"
- Remove-Item -Recurse -Force $OldVenv -ErrorAction SilentlyContinue
+ $invalidVenv = Join-Path $StudioHome (".venv.invalid.{0}.{1}" -f (Get-Date -Format "yyyyMMddHHmmss"), $PID)
+ Move-Item -Path $OldVenv -Destination $invalidVenv -Force -ErrorAction SilentlyContinue
}
} elseif (Test-Path (Join-Path $env:USERPROFILE "unsloth_studio\Scripts\python.exe")) {
# CWD-relative venv from old install.ps1 -- migrate to absolute path
@@ -826,9 +958,8 @@ shell.Run cmd, 0, False
substep "$VenvDir"
$venvExit = Invoke-InstallCommand { uv venv $VenvDir --python "$($DetectedPython.Path)" }
if ($venvExit -ne 0) {
- Write-TauriLog "ERROR" "Failed to create virtual environment (exit code $venvExit)"
Write-Host "[ERROR] Failed to create virtual environment (exit code $venvExit)" -ForegroundColor Red
- return
+ return (Exit-InstallFailure "Failed to create virtual environment (exit code $venvExit)" $venvExit)
}
} else {
step "venv" "using migrated environment"
@@ -886,6 +1017,9 @@ shell.Run cmd, 0, False
return "$baseUrl/cu126"
}
$TorchIndexUrl = Get-TorchIndexUrl
+ $TorchIndexFamily = Get-TauriTorchIndexFamily $TorchIndexUrl
+ $GpuBranch = Get-TauriGpuBranch $TorchIndexFamily
+ Write-TauriDiag -GpuBranch $GpuBranch -TorchIndexFamily $TorchIndexFamily -PythonVersionForDiag $DetectedPython.Version
# ── Print CPU-only hint when no GPU detected ──
if (-not $SkipTorch -and $TorchIndexUrl -like "*/cpu") {
@@ -946,14 +1080,14 @@ shell.Run cmd, 0, False
}
if ($baseInstallExit -ne 0) {
Write-Host "[ERROR] Failed to install unsloth (exit code $baseInstallExit)" -ForegroundColor Red
- return
+ return (Exit-InstallFailure "Failed to install unsloth (exit code $baseInstallExit)" $baseInstallExit)
}
if ($StudioLocalInstall) {
substep "overlaying local repo (editable)..."
$overlayExit = Invoke-InstallCommand { uv pip install --python $VenvPython -e $RepoRoot --no-deps }
if ($overlayExit -ne 0) {
Write-Host "[ERROR] Failed to overlay local repo (exit code $overlayExit)" -ForegroundColor Red
- return
+ return (Exit-InstallFailure "Failed to overlay local repo (exit code $overlayExit)" $overlayExit)
}
}
} elseif ($TorchIndexUrl) {
@@ -964,9 +1098,8 @@ shell.Run cmd, 0, False
substep "installing PyTorch ($TorchIndexUrl)..."
$torchInstallExit = Invoke-InstallCommand { uv pip install --python $VenvPython "torch>=2.4,<2.11.0" torchvision torchaudio --index-url $TorchIndexUrl }
if ($torchInstallExit -ne 0) {
- Write-TauriLog "ERROR" "Failed to install PyTorch (exit code $torchInstallExit)"
Write-Host "[ERROR] Failed to install PyTorch (exit code $torchInstallExit)" -ForegroundColor Red
- return
+ return (Exit-InstallFailure "Failed to install PyTorch (exit code $torchInstallExit)" $torchInstallExit)
}
}
@@ -988,9 +1121,8 @@ shell.Run cmd, 0, False
$baseInstallExit = Invoke-InstallCommand { uv pip install --python $VenvPython --upgrade-package unsloth -- "$PackageName" }
}
if ($baseInstallExit -ne 0) {
- Write-TauriLog "ERROR" "Failed to install unsloth (exit code $baseInstallExit)"
Write-Host "[ERROR] Failed to install unsloth (exit code $baseInstallExit)" -ForegroundColor Red
- return
+ return (Exit-InstallFailure "Failed to install unsloth (exit code $baseInstallExit)" $baseInstallExit)
}
if ($StudioLocalInstall) {
@@ -998,7 +1130,7 @@ shell.Run cmd, 0, False
$overlayExit = Invoke-InstallCommand { uv pip install --python $VenvPython -e $RepoRoot --no-deps }
if ($overlayExit -ne 0) {
Write-Host "[ERROR] Failed to overlay local repo (exit code $overlayExit)" -ForegroundColor Red
- return
+ return (Exit-InstallFailure "Failed to overlay local repo (exit code $overlayExit)" $overlayExit)
}
}
} else {
@@ -1009,20 +1141,19 @@ shell.Run cmd, 0, False
$baseInstallExit = Invoke-InstallCommand { uv pip install --python $VenvPython unsloth-zoo "unsloth>=2026.4.8" --torch-backend=auto }
if ($baseInstallExit -ne 0) {
Write-Host "[ERROR] Failed to install unsloth (exit code $baseInstallExit)" -ForegroundColor Red
- return
+ return (Exit-InstallFailure "Failed to install unsloth (exit code $baseInstallExit)" $baseInstallExit)
}
substep "overlaying local repo (editable)..."
$overlayExit = Invoke-InstallCommand { uv pip install --python $VenvPython -e $RepoRoot --no-deps }
if ($overlayExit -ne 0) {
Write-Host "[ERROR] Failed to overlay local repo (exit code $overlayExit)" -ForegroundColor Red
- return
+ return (Exit-InstallFailure "Failed to overlay local repo (exit code $overlayExit)" $overlayExit)
}
} else {
$baseInstallExit = Invoke-InstallCommand { uv pip install --python $VenvPython --torch-backend=auto -- "$PackageName" }
if ($baseInstallExit -ne 0) {
- Write-TauriLog "ERROR" "Failed to install unsloth (exit code $baseInstallExit)"
Write-Host "[ERROR] Failed to install unsloth (exit code $baseInstallExit)" -ForegroundColor Red
- return
+ return (Exit-InstallFailure "Failed to install unsloth (exit code $baseInstallExit)" $baseInstallExit)
}
}
}
@@ -1077,12 +1208,11 @@ shell.Run cmd, 0, False
step "setup" "running unsloth studio setup..."
$UnslothExe = Join-Path $VenvDir "Scripts\unsloth.exe"
if (-not (Test-Path $UnslothExe)) {
- Write-TauriLog "ERROR" "unsloth CLI was not installed correctly"
Write-Host "[ERROR] unsloth CLI was not installed correctly." -ForegroundColor Red
Write-Host " Expected: $UnslothExe" -ForegroundColor Yellow
Write-Host " This usually means an older unsloth version was installed that does not include the Studio CLI." -ForegroundColor Yellow
Write-Host " Try re-running the installer or see: https://github.com/unslothai/unsloth?tab=readme-ov-file#-quickstart" -ForegroundColor Yellow
- return
+ return (Exit-InstallFailure "unsloth CLI was not installed correctly")
}
# Tell setup.ps1 to skip base package installation (install.ps1 already did it)
$env:SKIP_STUDIO_BASE = "1"
@@ -1104,12 +1234,16 @@ shell.Run cmd, 0, False
# and bypass the fast-path version check from PR #4667.
$studioArgs = @('studio', 'setup')
if ($script:UnslothVerbose) { $studioArgs += '--verbose' }
- & $UnslothExe @studioArgs
- $setupExit = $LASTEXITCODE
+ $env:UNSLOTH_INSTALL_ROLLBACK_MANAGED = "1"
+ try {
+ & $UnslothExe @studioArgs
+ $setupExit = $LASTEXITCODE
+ } finally {
+ Remove-Item Env:UNSLOTH_INSTALL_ROLLBACK_MANAGED -ErrorAction SilentlyContinue
+ }
if ($setupExit -ne 0) {
- Write-TauriLog "ERROR" "unsloth studio setup failed (exit code $setupExit)"
Write-Host "[ERROR] unsloth studio setup failed (exit code $setupExit)" -ForegroundColor Red
- return
+ return (Exit-InstallFailure "unsloth studio setup failed (exit code $setupExit)" $setupExit)
}
# ── Expose `unsloth` via a shim dir containing only unsloth.exe ──
@@ -1182,6 +1316,7 @@ shell.Run cmd, 0, False
step "path" "added unsloth launcher to PATH"
}
Refresh-SessionPath # sync current session with registry
+ Complete-StudioVenvRollback
# ── Tauri mode: done, skip shortcuts and auto-launch ──
if ($TauriMode) {
diff --git a/install.sh b/install.sh
index 6c28b6eda4c..18c6bba5891 100755
--- a/install.sh
+++ b/install.sh
@@ -162,9 +162,119 @@ tauri_log() {
fi
}
+tauri_diag_marker() {
+ _diag_gpu_branch="${1:-unknown}"
+ _diag_torch_index_family="${2:-none}"
+ tauri_log "DIAG" "diag_schema=1 platform=${OS:-unknown} arch=${_ARCH:-unknown} python_version=${PYTHON_VERSION:-unknown} skip_torch=${SKIP_TORCH:-false} mac_intel=${MAC_INTEL:-false} gpu_branch=${_diag_gpu_branch} torch_index_family=${_diag_torch_index_family}"
+}
+
+_tauri_torch_index_family() {
+ if [ "${SKIP_TORCH:-false}" = true ]; then
+ echo "none"
+ return
+ fi
+ _diag_url="${1:-}"
+ case "$_diag_url" in
+ */cu118) echo "cu118" ;;
+ */cu124) echo "cu124" ;;
+ */cu126) echo "cu126" ;;
+ */cu128) echo "cu128" ;;
+ */cu130) echo "cu130" ;;
+ */cpu) echo "cpu" ;;
+ */rocm[0-9]*.[0-9]*)
+ _diag_family=${_diag_url##*/}
+ case "$_diag_family" in
+ rocm[0-9]*.[0-9]*) echo "$_diag_family" ;;
+ *) echo "auto" ;;
+ esac ;;
+ "") echo "none" ;;
+ *) echo "auto" ;;
+ esac
+}
+
+_tauri_gpu_branch() {
+ _diag_family="${1:-unknown}"
+ _diag_radeon="${2:-false}"
+ if [ "${SKIP_TORCH:-false}" = true ]; then
+ echo "no_torch"
+ return
+ fi
+ if [ "${OS:-}" = "macos" ]; then
+ echo "mac"
+ return
+ fi
+ case "$_diag_family" in
+ cu*) echo "cuda" ;;
+ rocm*)
+ if [ "$_diag_radeon" = true ]; then
+ echo "rocm_radeon"
+ else
+ echo "rocm"
+ fi ;;
+ radeon) echo "rocm_radeon" ;;
+ cpu) echo "cpu" ;;
+ none) echo "no_torch" ;;
+ *) echo "unknown" ;;
+ esac
+}
+
PYTHON_VERSION="" # resolved after platform detection
STUDIO_HOME="$HOME/.unsloth/studio"
VENV_DIR="$STUDIO_HOME/unsloth_studio"
+_VENV_ROLLBACK_DIR=""
+_VENV_ROLLBACK_TARGET="$VENV_DIR"
+_VENV_ROLLBACK_ACTIVE=false
+
+_start_studio_venv_replacement() {
+ _existing_dir="$1"
+ _stamp=$(date +%Y%m%d%H%M%S 2>/dev/null || echo "time")
+ _candidate="$STUDIO_HOME/unsloth_studio.rollback.$_stamp.$$"
+ _suffix=0
+ while [ -e "$_candidate" ]; do
+ _suffix=$((_suffix + 1))
+ _candidate="$STUDIO_HOME/unsloth_studio.rollback.$_stamp.$$.$_suffix"
+ done
+ mv "$_existing_dir" "$_candidate"
+ _VENV_ROLLBACK_DIR="$_candidate"
+ _VENV_ROLLBACK_TARGET="$_existing_dir"
+ _VENV_ROLLBACK_ACTIVE=true
+ substep "previous environment preserved for rollback"
+}
+
+_restore_studio_venv_replacement() {
+ [ "$_VENV_ROLLBACK_ACTIVE" = true ] || return 0
+ [ -n "$_VENV_ROLLBACK_DIR" ] && [ -d "$_VENV_ROLLBACK_DIR" ] || {
+ _VENV_ROLLBACK_ACTIVE=false
+ return 0
+ }
+ substep "restoring previous environment after failed install..." "$C_WARN"
+ rm -rf "$_VENV_ROLLBACK_TARGET"
+ if mv "$_VENV_ROLLBACK_DIR" "$_VENV_ROLLBACK_TARGET"; then
+ substep "restored previous environment"
+ _VENV_ROLLBACK_ACTIVE=false
+ _VENV_ROLLBACK_DIR=""
+ else
+ echo "⚠️ Could not restore previous environment from $_VENV_ROLLBACK_DIR to $_VENV_ROLLBACK_TARGET" >&2
+ fi
+}
+
+_commit_studio_venv_replacement() {
+ [ "$_VENV_ROLLBACK_ACTIVE" = true ] || return 0
+ if [ -n "$_VENV_ROLLBACK_DIR" ] && [ -d "$_VENV_ROLLBACK_DIR" ]; then
+ rm -rf "$_VENV_ROLLBACK_DIR" || true
+ fi
+ _VENV_ROLLBACK_ACTIVE=false
+ _VENV_ROLLBACK_DIR=""
+}
+
+_on_install_exit() {
+ _status=$?
+ if [ "$_status" -ne 0 ]; then
+ _restore_studio_venv_replacement
+ fi
+ exit "$_status"
+}
+trap _on_install_exit EXIT
# ── Helper: download a URL to a file (supports curl and wget) ──
download() {
@@ -828,6 +938,14 @@ if [ "$_NO_TORCH_FLAG" = true ] || [ "$MAC_INTEL" = true ]; then
SKIP_TORCH=true
fi
+_TAURI_INITIAL_GPU_BRANCH="unknown"
+if [ "$SKIP_TORCH" = true ]; then
+ _TAURI_INITIAL_GPU_BRANCH="no_torch"
+elif [ "$OS" = "macos" ]; then
+ _TAURI_INITIAL_GPU_BRANCH="mac"
+fi
+tauri_diag_marker "$_TAURI_INITIAL_GPU_BRANCH" "none"
+
# ── Check system dependencies ──
# cmake and git are needed by unsloth studio setup to build the GGUF inference
# engine (llama.cpp). build-essential and libcurl-dev are also needed on Linux.
@@ -883,9 +1001,15 @@ if [ -n "$MISSING" ]; then
if command -v apt-get >/dev/null 2>&1; then
_smart_apt_install $MISSING
else
- echo " apt-get is not available. Please install with your package manager:"
+ echo " Automatic system package installation is supported on apt-based"
+ echo " Linux distributions (Ubuntu/Debian) only. Please install the"
+ echo " missing dependencies with your package manager, then re-run setup:"
echo " $MISSING"
- echo " Then re-run Unsloth Studio setup."
+ echo ""
+ echo " Examples:"
+ echo " Fedora/RHEL: sudo dnf install cmake git gcc gcc-c++ make libcurl-devel"
+ echo " Arch: sudo pacman -S --needed cmake git base-devel curl"
+ echo " openSUSE: sudo zypper install cmake git gcc gcc-c++ make libcurl-devel"
exit 1
fi
;;
@@ -957,12 +1081,19 @@ mkdir -p "$STUDIO_HOME"
_MIGRATED=false
if [ -x "$VENV_DIR/bin/python" ]; then
- # New layout already exists — nuke for fresh install
- rm -rf "$VENV_DIR"
+ # New layout already exists — replace only after preserving rollback copy.
+ substep "preserving existing environment for rollback..."
+ _start_studio_venv_replacement "$VENV_DIR"
elif [ -x "$STUDIO_HOME/.venv/bin/python" ]; then
- # Old layout exists — validate before migrating
+ # Old layout exists — validate before migrating.
+ # In no-torch mode, a missing torch package is expected; validate Python only.
substep "found legacy Studio environment, validating..."
- if "$STUDIO_HOME/.venv/bin/python" -c "
+ _legacy_ok=false
+ if [ "$SKIP_TORCH" = true ]; then
+ if "$STUDIO_HOME/.venv/bin/python" -c "import sys; print(sys.executable)" >/dev/null 2>&1; then
+ _legacy_ok=true
+ fi
+ elif "$STUDIO_HOME/.venv/bin/python" -c "
import torch
device = 'cuda' if torch.cuda.is_available() else 'cpu'
A = torch.ones((10, 10), device=device)
@@ -972,13 +1103,17 @@ D = A + B
E = D @ C
torch.testing.assert_close(torch.unique(E), torch.tensor((20,), device=E.device, dtype=E.dtype))
" >/dev/null 2>&1; then
+ _legacy_ok=true
+ fi
+ if [ "$_legacy_ok" = true ]; then
echo "✅ Legacy environment is healthy — migrating..."
mv "$STUDIO_HOME/.venv" "$VENV_DIR"
echo " Moved ~/.unsloth/studio/.venv → $VENV_DIR"
_MIGRATED=true
else
echo "⚠️ Legacy environment failed validation — creating fresh environment"
- rm -rf "$STUDIO_HOME/.venv"
+ _invalid_venv="$STUDIO_HOME/.venv.invalid.$(date +%Y%m%d%H%M%S 2>/dev/null || echo time).$$"
+ mv "$STUDIO_HOME/.venv" "$_invalid_venv" 2>/dev/null || true
fi
fi
@@ -1308,6 +1443,12 @@ case "$TORCH_INDEX_URL" in
fi
;;
esac
+_TAURI_TORCH_INDEX_FAMILY=$(_tauri_torch_index_family "$TORCH_INDEX_URL")
+if [ "$_amd_gpu_radeon" = true ] && [ "$SKIP_TORCH" = false ]; then
+ _TAURI_TORCH_INDEX_FAMILY="radeon"
+fi
+_TAURI_GPU_BRANCH=$(_tauri_gpu_branch "$_TAURI_TORCH_INDEX_FAMILY" "$_amd_gpu_radeon")
+tauri_diag_marker "$_TAURI_GPU_BRANCH" "$_TAURI_TORCH_INDEX_FAMILY"
# ── Print CPU-only hint when no GPU detected ──
case "$TORCH_INDEX_URL" in
@@ -1679,6 +1820,8 @@ if [ "$_SETUP_EXIT" -ne 0 ]; then
exit "$_SETUP_EXIT"
fi
+_commit_studio_venv_replacement
+
# ── Tauri mode: done, skip shortcuts and auto-launch ──
if [ "$TAURI_MODE" = true ]; then
tauri_log "DONE" ""
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 9212404b300..aec335fad37 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -187,6 +187,8 @@ if _api_only:
"tauri://localhost", # Linux/macOS Tauri webview
"http://tauri.localhost", # Windows Tauri webview
"http://localhost", # dev fallback
+ "http://localhost:5173", # Tauri dev/Vite
+ "http://127.0.0.1:5173", # Tauri dev/Vite fallback
]
_cors_origin_regex = None
else:
diff --git a/studio/frontend/package.json b/studio/frontend/package.json
index 7bea824071a..3adc7ed0c80 100644
--- a/studio/frontend/package.json
+++ b/studio/frontend/package.json
@@ -43,6 +43,7 @@
"@tanstack/react-router": "^1.159.10",
"@tanstack/react-table": "^8.21.3",
"@tauri-apps/api": "^2.10.1",
+ "@tauri-apps/plugin-clipboard-manager": "^2.3.2",
"@tauri-apps/plugin-opener": "^2.5.3",
"@tauri-apps/plugin-process": "^2.3.1",
"@tauri-apps/plugin-updater": "^2.10.1",
diff --git a/studio/frontend/src/app/auth-guards.ts b/studio/frontend/src/app/auth-guards.ts
index 509b8f61afc..52230f0b6f1 100644
--- a/studio/frontend/src/app/auth-guards.ts
+++ b/studio/frontend/src/app/auth-guards.ts
@@ -9,7 +9,6 @@ import {
hasRefreshToken,
mustChangePassword,
refreshSession,
- tauriAutoAuth,
} from "@/features/auth";
async function hasActiveSession(): Promise<boolean> {
@@ -39,7 +38,7 @@ function authRedirect(to: "/login" | "/change-password"): never {
export async function requireAuth(): Promise<void> {
if (isTauri) {
- await tauriAutoAuth();
+ // AppProvider owns backend startup + desktop auth; route guards run before it mounts.
return;
}
@@ -59,7 +58,6 @@ export async function requireAuth(): Promise<void> {
export async function requireGuest(): Promise<void> {
if (isTauri) {
- await tauriAutoAuth();
throw redirect({ to: "/chat" });
}
if (!(await hasActiveSession())) return;
@@ -68,7 +66,6 @@ export async function requireGuest(): Promise<void> {
export async function requirePasswordChangeFlow(): Promise<void> {
if (isTauri) {
- await tauriAutoAuth();
throw redirect({ to: "/chat" });
}
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsx
index b75998a169e..e82f6115526 100644
--- a/studio/frontend/src/app/provider.tsx
+++ b/studio/frontend/src/app/provider.tsx
@@ -4,12 +4,18 @@
import { StartupScreen } from "@/components/tauri/startup-screen";
import { UpdateBanner } from "@/components/tauri/update-banner";
import { UpdateScreen } from "@/components/tauri/update-screen";
+import {
+ WindowTitlebar,
+ shouldUseCustomWindowTitlebar,
+} from "@/components/tauri/window-titlebar";
import { Toaster } from "@/components/ui/sonner";
+import { getTauriAuthFailure, tauriAutoAuth } from "@/features/auth";
import { useTauriBackend } from "@/hooks/use-tauri-backend";
import { useTauriUpdate } from "@/hooks/use-tauri-update";
import { isTauri } from "@/lib/api-base";
+import { useRouterState } from "@tanstack/react-router";
import { ThemeProvider } from "next-themes";
-import { useEffect, useRef, type ReactNode } from "react";
+import { useEffect, useRef, useState, type ReactNode } from "react";
interface AppProviderProps {
children: ReactNode;
@@ -103,6 +109,7 @@ function TauriUpdateLayer({ isExternalServer }: { isExternalServer: boolean }) {
error={update.error}
onRetry={update.retryUpdate}
onSkipRestart={update.skipAndRestart}
+ onCopyDiagnostics={update.copyDiagnostics}
/>
);
}
@@ -112,22 +119,34 @@ function TauriUpdateLayer({ isExternalServer }: { isExternalServer: boolean }) {
status={update.status}
info={update.info}
dismissed={update.dismissed}
+ lastFailure={update.lastFailure}
isExternalServer={isExternalServer}
onInstall={update.installUpdate}
onDismiss={update.dismiss}
+ onCopyDiagnostics={update.copyDiagnostics}
/>
);
}
+const HIDDEN_TITLEBAR_SIDEBAR_ROUTES = new Set([
+ "/onboarding",
+ "/login",
+ "/change-password",
+ "/signup",
+]);
+
function TauriWrapper({ children }: { children: ReactNode }) {
+ const pathname = useRouterState({ select: (s) => s.location.pathname });
const {
status, logs, error, isExternalServer,
currentStepIndex, progressDetail, elevationPackages,
- startInstall, retry, retryInstall, approveElevation,
+ startInstall, retry, retryInstall, approveElevation, copyDiagnostics,
} = useTauriBackend();
const hasResized = useRef(false);
const abortRef = useRef(false);
+ const [desktopAuthReady, setDesktopAuthReady] = useState(!isTauri);
+ const [desktopAuthRetry, setDesktopAuthRetry] = useState(0);
// Show the window once the frontend mounts (for pre-running states)
useEffect(() => {
@@ -150,24 +169,79 @@ function TauriWrapper({ children }: { children: ReactNode }) {
return () => { abortRef.current = true; };
}, [status]);
+ useEffect(() => {
+ if (!isTauri) {
+ setDesktopAuthReady(true);
+ return;
+ }
+ if (status !== "running") {
+ setDesktopAuthReady(false);
+ setDesktopAuthRetry(0);
+ return;
+ }
+
+ let disposed = false;
+ setDesktopAuthReady(false);
+ tauriAutoAuth({ force: true }).then((authenticated) => {
+ if (disposed) return;
+ if (authenticated) {
+ setDesktopAuthReady(true);
+ return;
+ }
+ if (!getTauriAuthFailure()) {
+ window.setTimeout(() => {
+ if (!disposed) setDesktopAuthRetry((value) => value + 1);
+ }, 500);
+ }
+ });
+
+ return () => { disposed = true; };
+ }, [status, desktopAuthRetry]);
+
if (!isTauri) return <>{children}</>;
- if (status === "running") return <><TauriUpdateLayer isExternalServer={isExternalServer} />{children}</>;
- return (
+ const showApp = status === "running" && desktopAuthReady;
+ const startupStatus = status === "running" ? "starting" : status;
+ const startupProgressDetail =
+ status === "running" && !desktopAuthReady
+ ? "Signing in to desktop session..."
+ : progressDetail;
+
+ const content = showApp ? (
+ <>
+ <TauriUpdateLayer isExternalServer={isExternalServer} />
+ {children}
+ </>
+ ) : (
<StartupScreen
- status={status}
+ status={startupStatus}
logs={logs}
error={error}
currentStepIndex={currentStepIndex}
- progressDetail={progressDetail}
+ progressDetail={startupProgressDetail}
elevationPackages={elevationPackages}
onInstall={startInstall}
onRetry={retry}
onRetryInstall={retryInstall}
onApproveElevation={approveElevation}
onStartServer={retry}
+ onCopyDiagnostics={copyDiagnostics}
/>
);
+
+ if (!shouldUseCustomWindowTitlebar()) return content;
+
+ const showSidebarSurface =
+ showApp && !HIDDEN_TITLEBAR_SIDEBAR_ROUTES.has(pathname);
+
+ return (
+ <div className="flex h-dvh min-h-0 flex-col overflow-hidden bg-background [--studio-titlebar-height:34px]">
+ <WindowTitlebar showSidebarSurface={showSidebarSurface} />
+ <div className="min-h-0 flex-1 overflow-hidden">
+ {content}
+ </div>
+ </div>
+ );
}
export function AppProvider({ children }: AppProviderProps) {
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index 19b57635578..22d149473ce 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -81,7 +81,7 @@ function RootLayout() {
pinned={pinned}
setPinned={setPinned}
togglePinned={togglePinned}
- className="!min-h-0 h-dvh overflow-hidden"
+ className="!min-h-0 h-[calc(100dvh-var(--studio-titlebar-height,0px))] overflow-hidden"
>
<AppSidebar />
<SidebarInset className={isChatRoute ? "overflow-hidden" : "overflow-y-auto"}>
diff --git a/studio/frontend/src/components/tauri/startup-screen.tsx b/studio/frontend/src/components/tauri/startup-screen.tsx
index af5f2414169..1eb3f81d10e 100644
--- a/studio/frontend/src/components/tauri/startup-screen.tsx
+++ b/studio/frontend/src/components/tauri/startup-screen.tsx
@@ -3,7 +3,9 @@
import { ShimmerButton } from "@/components/ui/shimmer-button";
import type { BackendStatus } from "@/hooks/use-tauri-backend";
+import type { CopySupportDiagnosticsResult } from "@/lib/tauri-diagnostics";
import { AnimatePresence, motion } from "motion/react";
+import { useState } from "react";
interface StartupScreenProps {
status: BackendStatus;
@@ -17,6 +19,63 @@ interface StartupScreenProps {
onRetryInstall: () => void;
onApproveElevation: () => void;
onStartServer: () => void;
+ onCopyDiagnostics: () => Promise<CopySupportDiagnosticsResult>;
+}
+
+function DiagnosticsCopyActions({
+ onCopyDiagnostics,
+ children,
+}: {
+ onCopyDiagnostics: () => Promise<CopySupportDiagnosticsResult>;
+ children: React.ReactNode;
+}) {
+ const [copying, setCopying] = useState(false);
+ const [manualReport, setManualReport] = useState<string | null>(null);
+ const [manualMessage, setManualMessage] = useState<string | null>(null);
+
+ async function handleCopyDiagnostics() {
+ setCopying(true);
+ try {
+ const result = await onCopyDiagnostics();
+ if (result.ok) {
+ setManualReport(null);
+ setManualMessage(null);
+ } else {
+ setManualReport(result.report);
+ setManualMessage(result.error ?? "Clipboard copy failed. Select and copy the diagnostics below.");
+ }
+ } catch (error) {
+ setManualReport(null);
+ setManualMessage(`Diagnostics copy failed: ${String(error)}`);
+ } finally {
+ setCopying(false);
+ }
+ }
+
+ return (
+ <div className="mt-4 flex w-full flex-col items-center gap-3">
+ <div className="flex gap-3">
+ <ActionButton
+ variant="secondary"
+ onClick={() => void handleCopyDiagnostics()}
+ >
+ {copying ? "Copying..." : "Copy Diagnostics"}
+ </ActionButton>
+ {children}
+ </div>
+ {manualMessage && (
+ <p className="max-w-md text-center text-xs text-destructive">{manualMessage}</p>
+ )}
+ {manualReport && (
+ <textarea
+ readOnly
+ value={manualReport}
+ onFocus={(event) => event.currentTarget.select()}
+ className="h-32 w-full max-w-md resize-none rounded-lg border border-border/50 bg-muted/30 p-2 font-mono text-[10px] text-muted-foreground"
+ />
+ )}
+ </div>
+ );
}
// ---------------------------------------------------------------------------
@@ -180,12 +239,12 @@ function RepairingContent({
function InstallErrorContent({
error,
- logs,
onRetryInstall,
+ onCopyDiagnostics,
}: {
error: string | null;
- logs: string[];
onRetryInstall: () => void;
+ onCopyDiagnostics: () => Promise<CopySupportDiagnosticsResult>;
}) {
return (
<>
@@ -195,15 +254,9 @@ function InstallErrorContent({
{error && (
<p className="max-w-xs text-center text-xs text-muted-foreground">{error}</p>
)}
- <div className="mt-4 flex gap-3">
- <ActionButton
- variant="secondary"
- onClick={() => void navigator.clipboard.writeText(logs.join("\n"))}
- >
- Copy Logs
- </ActionButton>
+ <DiagnosticsCopyActions onCopyDiagnostics={onCopyDiagnostics}>
<ActionButton onClick={onRetryInstall}>Try Again</ActionButton>
- </div>
+ </DiagnosticsCopyActions>
</div>
</>
);
@@ -211,12 +264,12 @@ function InstallErrorContent({
function RepairErrorContent({
error,
- logs,
onRetry,
+ onCopyDiagnostics,
}: {
error: string | null;
- logs: string[];
onRetry: () => void;
+ onCopyDiagnostics: () => Promise<CopySupportDiagnosticsResult>;
}) {
return (
<>
@@ -226,15 +279,9 @@ function RepairErrorContent({
{error && (
<p className="max-w-md text-center text-xs text-muted-foreground">{error}</p>
)}
- <div className="mt-4 flex gap-3">
- <ActionButton
- variant="secondary"
- onClick={() => void navigator.clipboard.writeText(logs.join("\n"))}
- >
- Copy Logs
- </ActionButton>
+ <DiagnosticsCopyActions onCopyDiagnostics={onCopyDiagnostics}>
<ActionButton onClick={onRetry}>Retry</ActionButton>
- </div>
+ </DiagnosticsCopyActions>
</div>
</>
);
@@ -301,12 +348,12 @@ function StoppedContent({ onStartServer }: { onStartServer: () => void }) {
function ErrorContent({
error,
- logs,
onRetry,
+ onCopyDiagnostics,
}: {
error: string | null;
- logs: string[];
onRetry: () => void;
+ onCopyDiagnostics: () => Promise<CopySupportDiagnosticsResult>;
}) {
return (
<>
@@ -316,15 +363,9 @@ function ErrorContent({
{error && (
<p className="max-w-md text-center text-xs text-muted-foreground">{error}</p>
)}
- <div className="mt-4 flex gap-3">
- <ActionButton
- variant="secondary"
- onClick={() => void navigator.clipboard.writeText(logs.join("\n"))}
- >
- Copy Logs
- </ActionButton>
+ <DiagnosticsCopyActions onCopyDiagnostics={onCopyDiagnostics}>
<ActionButton onClick={onRetry}>Retry</ActionButton>
- </div>
+ </DiagnosticsCopyActions>
</div>
</>
);
@@ -346,6 +387,7 @@ export function StartupScreen({
onRetryInstall,
onApproveElevation,
onStartServer,
+ onCopyDiagnostics,
}: StartupScreenProps) {
function renderContent() {
switch (status) {
@@ -356,11 +398,23 @@ export function StartupScreen({
case "installing":
return <InstallingContent currentStepIndex={currentStepIndex} progressDetail={progressDetail} />;
case "install-error":
- return <InstallErrorContent error={error} logs={logs} onRetryInstall={onRetryInstall} />;
+ return (
+ <InstallErrorContent
+ error={error}
+ onRetryInstall={onRetryInstall}
+ onCopyDiagnostics={onCopyDiagnostics}
+ />
+ );
case "repairing":
return <RepairingContent logs={logs} progressDetail={progressDetail} />;
case "repair-error":
- return <RepairErrorContent error={error} logs={logs} onRetry={onRetry} />;
+ return (
+ <RepairErrorContent
+ error={error}
+ onRetry={onRetry}
+ onCopyDiagnostics={onCopyDiagnostics}
+ />
+ );
case "needs-elevation":
return (
<NeedsElevationContent
@@ -376,12 +430,18 @@ export function StartupScreen({
case "stopped":
return <StoppedContent onStartServer={onStartServer} />;
case "error":
- return <ErrorContent error={error} logs={logs} onRetry={onRetry} />;
+ return (
+ <ErrorContent
+ error={error}
+ onRetry={onRetry}
+ onCopyDiagnostics={onCopyDiagnostics}
+ />
+ );
}
}
return (
- <div className="flex h-screen w-full flex-col items-center bg-background">
+ <div className="flex h-full w-full flex-col items-center bg-background">
<div className="flex flex-1 w-full max-w-md items-center justify-center px-6">
<AnimatePresence mode="wait">
<motion.div
diff --git a/studio/frontend/src/components/tauri/update-banner.tsx b/studio/frontend/src/components/tauri/update-banner.tsx
index 98652c4db11..79fbae6bb7d 100644
--- a/studio/frontend/src/components/tauri/update-banner.tsx
+++ b/studio/frontend/src/components/tauri/update-banner.tsx
@@ -2,16 +2,20 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { Button } from "@/components/ui/button";
-import type { UpdateInfo, UpdateStatus } from "@/hooks/use-tauri-update";
+import type { RetainedUpdateFailure, UpdateInfo, UpdateStatus } from "@/hooks/use-tauri-update";
+import type { CopySupportDiagnosticsResult } from "@/lib/tauri-diagnostics";
import { AnimatePresence, motion } from "motion/react";
+import { useState } from "react";
interface UpdateBannerProps {
status: UpdateStatus;
info: UpdateInfo | null;
dismissed: boolean;
+ lastFailure: RetainedUpdateFailure | null;
isExternalServer?: boolean;
onInstall: () => void;
onDismiss: () => void;
+ onCopyDiagnostics: () => Promise<CopySupportDiagnosticsResult>;
}
const EASE_OUT_QUART: [number, number, number, number] = [0.165, 0.84, 0.44, 1];
@@ -20,16 +24,41 @@ export function UpdateBanner({
status,
info,
dismissed,
+ lastFailure,
isExternalServer = false,
onInstall,
onDismiss,
+ onCopyDiagnostics,
}: UpdateBannerProps) {
- const visible = status === "available";
- const show = visible && !dismissed;
+ const [copying, setCopying] = useState(false);
+ const [manualReport, setManualReport] = useState<string | null>(null);
+ const [manualMessage, setManualMessage] = useState<string | null>(null);
+ const showFailure = Boolean(lastFailure) && !dismissed;
+ const showAvailable = status === "available" && !dismissed && !showFailure;
+ const show = showFailure || (showAvailable && Boolean(info));
+
+ async function handleCopyDiagnostics() {
+ setCopying(true);
+ try {
+ const result = await onCopyDiagnostics();
+ if (result.ok) {
+ setManualReport(null);
+ setManualMessage(null);
+ } else {
+ setManualReport(result.report);
+ setManualMessage(result.error ?? "Clipboard copy failed. Select and copy the diagnostics below.");
+ }
+ } catch (error) {
+ setManualReport(null);
+ setManualMessage(`Diagnostics copy failed: ${String(error)}`);
+ } finally {
+ setCopying(false);
+ }
+ }
return (
<AnimatePresence>
- {show && info && (
+ {show && (
<motion.div
initial={{ opacity: 0, y: -12, scale: 0.96 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
@@ -54,28 +83,61 @@ export function UpdateBanner({
<span className="text-lg">🦥</span>
<div>
<p className="text-sm font-semibold text-foreground">
- New version: v{info.version}
+ {showFailure ? "App update failed" : `New version: v${info?.version}`}
</p>
<p className="text-xs text-muted-foreground">
- {isExternalServer
- ? "Run `unsloth studio update` from your terminal"
- : "A new app update is available"}
+ {showFailure
+ ? "Backend recovered. Diagnostics are still available."
+ : isExternalServer
+ ? "Run `unsloth studio update` from your terminal"
+ : "A new app update is available"}
</p>
</div>
</div>
+ {/* Retained failure */}
+ {showFailure && lastFailure && (
+ <p className="mt-3 line-clamp-2 text-xs text-destructive">
+ {lastFailure.error}
+ </p>
+ )}
+
{/* Actions */}
<div className="mt-3 flex items-center gap-2">
- <Button size="sm" className="corner-squircle" onClick={onInstall} disabled={isExternalServer}>
- Update Now
- </Button>
- <Button size="sm" variant="outline" className="corner-squircle" disabled>
- Release Notes
- </Button>
+ {showFailure ? (
+ <>
+ <Button size="sm" variant="outline" className="corner-squircle" onClick={() => void handleCopyDiagnostics()}>
+ {copying ? "Copying..." : "Copy Diagnostics"}
+ </Button>
+ <Button size="sm" className="corner-squircle" onClick={onInstall} disabled={isExternalServer}>
+ Retry Update
+ </Button>
+ </>
+ ) : (
+ <>
+ <Button size="sm" className="corner-squircle" onClick={onInstall} disabled={isExternalServer}>
+ Update Now
+ </Button>
+ <Button size="sm" variant="outline" className="corner-squircle" disabled>
+ Release Notes
+ </Button>
+ </>
+ )}
<Button size="sm" variant="ghost" className="corner-squircle" onClick={onDismiss}>
Later
</Button>
</div>
+ {manualMessage && (
+ <p className="mt-3 text-xs text-destructive">{manualMessage}</p>
+ )}
+ {manualReport && (
+ <textarea
+ readOnly
+ value={manualReport}
+ onFocus={(event) => event.currentTarget.select()}
+ className="mt-2 h-28 w-full resize-none rounded-lg border border-border/50 bg-muted/30 p-2 font-mono text-[10px] text-muted-foreground"
+ />
+ )}
</div>
</motion.div>
)}
diff --git a/studio/frontend/src/components/tauri/update-screen.tsx b/studio/frontend/src/components/tauri/update-screen.tsx
index a8b77ab1faf..53e39612c0a 100644
--- a/studio/frontend/src/components/tauri/update-screen.tsx
+++ b/studio/frontend/src/components/tauri/update-screen.tsx
@@ -2,8 +2,9 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import type { UpdateStatus } from "@/hooks/use-tauri-update";
+import type { CopySupportDiagnosticsResult } from "@/lib/tauri-diagnostics";
import { AnimatePresence, motion } from "motion/react";
-import { useEffect, useRef } from "react";
+import { useEffect, useRef, useState } from "react";
interface UpdateScreenProps {
status: UpdateStatus;
@@ -12,6 +13,7 @@ interface UpdateScreenProps {
error: string | null;
onRetry: () => void;
onSkipRestart: () => void;
+ onCopyDiagnostics: () => Promise<CopySupportDiagnosticsResult>;
}
const EASE_OUT_QUART: [number, number, number, number] = [0.165, 0.84, 0.44, 1];
@@ -96,11 +98,34 @@ export function UpdateScreen({
error,
onRetry,
onSkipRestart,
+ onCopyDiagnostics,
}: UpdateScreenProps) {
const isError = status === "error";
+ const [copying, setCopying] = useState(false);
+ const [manualReport, setManualReport] = useState<string | null>(null);
+ const [manualMessage, setManualMessage] = useState<string | null>(null);
+
+ async function handleCopyDiagnostics() {
+ setCopying(true);
+ try {
+ const result = await onCopyDiagnostics();
+ if (result.ok) {
+ setManualReport(null);
+ setManualMessage(null);
+ } else {
+ setManualReport(result.report);
+ setManualMessage(result.error ?? "Clipboard copy failed. Select and copy the diagnostics below.");
+ }
+ } catch (copyError) {
+ setManualReport(null);
+ setManualMessage(`Diagnostics copy failed: ${String(copyError)}`);
+ } finally {
+ setCopying(false);
+ }
+ }
return (
- <div className="flex h-screen w-full items-center justify-center bg-background">
+ <div className="flex h-full w-full items-center justify-center bg-background">
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
@@ -148,6 +173,13 @@ export function UpdateScreen({
{/* Error actions */}
{isError && (
<div className="mt-4 flex items-center gap-2">
+ <button
+ type="button"
+ className="rounded-lg bg-muted px-5 py-2.5 text-sm font-medium text-foreground transition-colors hover:bg-muted/80"
+ onClick={() => void handleCopyDiagnostics()}
+ >
+ {copying ? "Copying..." : "Copy Diagnostics"}
+ </button>
<button
type="button"
className="rounded-lg bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/80"
@@ -165,6 +197,18 @@ export function UpdateScreen({
</div>
)}
+ {manualMessage && (
+ <p className="mt-3 max-w-xl text-center text-xs text-destructive">{manualMessage}</p>
+ )}
+ {manualReport && (
+ <textarea
+ readOnly
+ value={manualReport}
+ onFocus={(event) => event.currentTarget.select()}
+ className="mt-2 h-32 w-full max-w-xl resize-none rounded-lg border border-border/50 bg-muted/30 p-2 font-mono text-[10px] text-muted-foreground"
+ />
+ )}
+
{/* Log viewer */}
<LogViewer logs={logs} />
</motion.div>
diff --git a/studio/frontend/src/components/tauri/window-titlebar.tsx b/studio/frontend/src/components/tauri/window-titlebar.tsx
new file mode 100644
index 00000000000..b3180e6663b
--- /dev/null
+++ b/studio/frontend/src/components/tauri/window-titlebar.tsx
@@ -0,0 +1,329 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { useSidebarPin } from "@/hooks/use-sidebar-pin";
+import { isTauri } from "@/lib/api-base";
+import { cn } from "@/lib/utils";
+import type { Window as TauriWindow } from "@tauri-apps/api/window";
+import {
+ type MouseEvent,
+ type ReactElement,
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useState,
+} from "react";
+
+const CUSTOM_TITLEBAR_PLATFORMS = ["win", "linux", "x11"] as const;
+
+type WindowResizeDirection =
+ | "East"
+ | "North"
+ | "NorthEast"
+ | "NorthWest"
+ | "South"
+ | "SouthEast"
+ | "SouthWest"
+ | "West";
+
+type NavigatorWithUserAgentData = Navigator & {
+ userAgentData?: {
+ platform?: string;
+ };
+};
+
+function getClientPlatform(): string {
+ if (typeof navigator === "undefined") {
+ return "";
+ }
+ const nav = navigator as NavigatorWithUserAgentData;
+ return (
+ nav.userAgentData?.platform ??
+ navigator.platform ??
+ navigator.userAgent
+ ).toLowerCase();
+}
+
+export function shouldUseCustomWindowTitlebar(): boolean {
+ if (!isTauri) {
+ return false;
+ }
+ const platform = getClientPlatform();
+ if (!platform || platform.includes("mac")) {
+ return false;
+ }
+ return CUSTOM_TITLEBAR_PLATFORMS.some((token) => platform.includes(token));
+}
+
+async function getAppWindow(): Promise<TauriWindow> {
+ const { getCurrentWindow } = await import("@tauri-apps/api/window");
+ return getCurrentWindow();
+}
+
+function WindowControlButton({
+ label,
+ className,
+ onClick,
+ children,
+}: {
+ label: string;
+ className?: string;
+ onClick: () => void;
+ children: ReactNode;
+}): ReactElement {
+ return (
+ <button
+ type="button"
+ aria-label={label}
+ title={label}
+ onClick={onClick}
+ className={cn(
+ "relative z-[80] inline-flex size-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted/80 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ className,
+ )}
+ >
+ {children}
+ </button>
+ );
+}
+
+function MinimizeGlyph(): ReactElement {
+ return (
+ <span aria-hidden="true" className="h-px w-3.5 rounded-full bg-current" />
+ );
+}
+
+function MaximizeGlyph(): ReactElement {
+ return (
+ <span
+ aria-hidden="true"
+ className="size-3 rounded-[2px] border border-current"
+ />
+ );
+}
+
+function RestoreGlyph(): ReactElement {
+ return (
+ <span aria-hidden="true" className="relative size-3.5">
+ <span className="absolute left-0.5 top-0 size-2.5 rounded-[2px] border border-current" />
+ <span className="absolute bottom-0 right-0 size-2.5 rounded-[2px] border border-current bg-muted" />
+ </span>
+ );
+}
+
+function CloseGlyph(): ReactElement {
+ return (
+ <span aria-hidden="true" className="relative size-3.5">
+ <span className="absolute left-1/2 top-0 h-3.5 w-px -translate-x-1/2 rotate-45 rounded-full bg-current" />
+ <span className="absolute left-1/2 top-0 h-3.5 w-px -translate-x-1/2 -rotate-45 rounded-full bg-current" />
+ </span>
+ );
+}
+
+export function WindowTitlebar({
+ showSidebarSurface = false,
+}: {
+ showSidebarSurface?: boolean;
+}): ReactElement | null {
+ const [enabled] = useState(shouldUseCustomWindowTitlebar);
+ const [maximized, setMaximized] = useState(false);
+ const { pinned } = useSidebarPin();
+
+ const refreshMaximized = useCallback(async () => {
+ if (!enabled) {
+ return;
+ }
+ try {
+ const appWindow = await getAppWindow();
+ setMaximized(await appWindow.isMaximized());
+ } catch {
+ // If a window permission is not ready yet, keep the previous visual state.
+ }
+ }, [enabled]);
+
+ useEffect(() => {
+ if (!enabled) {
+ return;
+ }
+ let mounted = true;
+ let unlistenResize: (() => void) | undefined;
+ let unlistenFocus: (() => void) | undefined;
+
+ const setupWindowListeners = async () => {
+ try {
+ const appWindow = await getAppWindow();
+ if (!mounted) {
+ return;
+ }
+ setMaximized(await appWindow.isMaximized());
+ unlistenResize = await appWindow.onResized(() => {
+ refreshMaximized().catch(() => undefined);
+ });
+ unlistenFocus = await appWindow.onFocusChanged(() => {
+ refreshMaximized().catch(() => undefined);
+ });
+ } catch {
+ // Missing capabilities should not break the rest of the app shell.
+ }
+ };
+
+ setupWindowListeners().catch(() => undefined);
+
+ return () => {
+ mounted = false;
+ unlistenResize?.();
+ unlistenFocus?.();
+ };
+ }, [enabled, refreshMaximized]);
+
+ const runWindowAction = useCallback(
+ (action: (appWindow: TauriWindow) => Promise<void>) => {
+ const runAction = async () => {
+ try {
+ const appWindow = await getAppWindow();
+ await action(appWindow);
+ await refreshMaximized();
+ } catch {
+ // Keep custom chrome inert rather than throwing into React on denied commands.
+ }
+ };
+
+ runAction().catch(() => undefined);
+ },
+ [refreshMaximized],
+ );
+
+ const handleDragMouseDown = useCallback(
+ (event: MouseEvent<HTMLDivElement>) => {
+ if (event.button !== 0 || event.detail > 1) {
+ return;
+ }
+ runWindowAction((appWindow) => appWindow.startDragging());
+ },
+ [runWindowAction],
+ );
+
+ const handleDragDoubleClick = useCallback(
+ (event: MouseEvent<HTMLDivElement>) => {
+ if (event.button !== 0) {
+ return;
+ }
+ runWindowAction((appWindow) => appWindow.toggleMaximize());
+ },
+ [runWindowAction],
+ );
+
+ const handleResizeMouseDown = useCallback(
+ (direction: WindowResizeDirection) =>
+ (event: MouseEvent<HTMLDivElement>) => {
+ if (event.button !== 0) {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ runWindowAction(async (appWindow) => {
+ if (!(await appWindow.isResizable())) {
+ return;
+ }
+ await appWindow.startResizeDragging(direction);
+ });
+ },
+ [runWindowAction],
+ );
+
+ if (!enabled) {
+ return null;
+ }
+
+ return (
+ <>
+ <header
+ className="relative z-[60] flex h-[var(--studio-titlebar-height)] shrink-0 select-none items-center text-foreground"
+ aria-label="Window titlebar"
+ >
+ {showSidebarSurface && (
+ <div
+ className="h-full shrink-0 border-r border-sidebar-border bg-sidebar"
+ style={{ width: pinned ? "16rem" : "3rem" }}
+ onMouseDown={handleDragMouseDown}
+ onDoubleClick={handleDragDoubleClick}
+ aria-hidden="true"
+ />
+ )}
+ <div
+ className="h-full min-w-0 flex-1 border-b border-border/35 bg-muted/35"
+ onMouseDown={handleDragMouseDown}
+ onDoubleClick={handleDragDoubleClick}
+ aria-hidden="true"
+ />
+ <div
+ className="flex h-full shrink-0 items-center gap-0.5 border-b border-border/35 bg-muted/35 px-1"
+ role="toolbar"
+ aria-label="Window controls"
+ >
+ <WindowControlButton
+ label="Minimize window"
+ onClick={() => runWindowAction((appWindow) => appWindow.minimize())}
+ >
+ <MinimizeGlyph />
+ </WindowControlButton>
+ <WindowControlButton
+ label={maximized ? "Restore window" : "Maximize window"}
+ onClick={() =>
+ runWindowAction((appWindow) => appWindow.toggleMaximize())
+ }
+ >
+ {maximized ? <RestoreGlyph /> : <MaximizeGlyph />}
+ </WindowControlButton>
+ <WindowControlButton
+ label="Close window"
+ onClick={() => runWindowAction((appWindow) => appWindow.close())}
+ className="hover:bg-destructive hover:text-destructive-foreground focus-visible:ring-destructive/70"
+ >
+ <CloseGlyph />
+ </WindowControlButton>
+ </div>
+ </header>
+ <div
+ aria-hidden="true"
+ className="fixed inset-x-2 top-0 z-[70] h-1 cursor-n-resize"
+ onMouseDown={handleResizeMouseDown("North")}
+ />
+ <div
+ aria-hidden="true"
+ className="fixed inset-x-2 bottom-0 z-[70] h-1 cursor-s-resize"
+ onMouseDown={handleResizeMouseDown("South")}
+ />
+ <div
+ aria-hidden="true"
+ className="fixed inset-y-2 left-0 z-[70] w-1 cursor-w-resize"
+ onMouseDown={handleResizeMouseDown("West")}
+ />
+ <div
+ aria-hidden="true"
+ className="fixed inset-y-2 right-0 z-[70] w-1 cursor-e-resize"
+ onMouseDown={handleResizeMouseDown("East")}
+ />
+ <div
+ aria-hidden="true"
+ className="fixed left-0 top-0 z-[70] size-3 cursor-nw-resize"
+ onMouseDown={handleResizeMouseDown("NorthWest")}
+ />
+ <div
+ aria-hidden="true"
+ className="fixed right-0 top-0 z-[70] size-3 cursor-ne-resize"
+ onMouseDown={handleResizeMouseDown("NorthEast")}
+ />
+ <div
+ aria-hidden="true"
+ className="fixed bottom-0 left-0 z-[70] size-3 cursor-sw-resize"
+ onMouseDown={handleResizeMouseDown("SouthWest")}
+ />
+ <div
+ aria-hidden="true"
+ className="fixed bottom-0 right-0 z-[70] size-3 cursor-se-resize"
+ onMouseDown={handleResizeMouseDown("SouthEast")}
+ />
+ </>
+ );
+}
diff --git a/studio/frontend/src/features/auth/api.ts b/studio/frontend/src/features/auth/api.ts
index 97d815950d6..8f52c2187c2 100644
--- a/studio/frontend/src/features/auth/api.ts
+++ b/studio/frontend/src/features/auth/api.ts
@@ -18,6 +18,32 @@ type RefreshResponse = {
let isRedirecting = false;
+const TAURI_FETCH_RETRY_DELAYS_MS = [250, 750, 1500] as const;
+
+function wait(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+async function fetchWithTauriNetworkRetry(
+ input: RequestInfo | URL,
+ init?: RequestInit,
+): Promise<Response> {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ return await fetch(input, init);
+ } catch (error) {
+ if (
+ !isTauri ||
+ !(error instanceof TypeError) ||
+ attempt >= TAURI_FETCH_RETRY_DELAYS_MS.length
+ ) {
+ throw error;
+ }
+ await wait(TAURI_FETCH_RETRY_DELAYS_MS[attempt]);
+ }
+ }
+}
+
async function isPasswordChangeRequiredResponse(response: Response): Promise<boolean> {
if (response.status !== 403) return false;
@@ -54,7 +80,7 @@ async function retryWithCurrentToken(
const retryHeaders = new Headers(init?.headers);
const token = getAuthToken();
if (token) retryHeaders.set("Authorization", `Bearer ${token}`);
- return fetch(input, { ...init, headers: retryHeaders });
+ return fetchWithTauriNetworkRetry(input, { ...init, headers: retryHeaders });
}
async function retryWithTauriAutoAuth(
@@ -72,11 +98,14 @@ export async function refreshSession(): Promise<boolean> {
if (!refreshToken) return false;
try {
- const response = await fetch(apiUrl("/api/auth/refresh"), {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ refresh_token: refreshToken }),
- });
+ const response = await fetchWithTauriNetworkRetry(
+ apiUrl("/api/auth/refresh"),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ refresh_token: refreshToken }),
+ },
+ );
if (!response.ok) {
clearAuthTokens();
@@ -108,7 +137,10 @@ export async function authFetch(
let response: Response;
try {
- response = await fetch(resolvedInput, { ...init, headers });
+ response = await fetchWithTauriNetworkRetry(resolvedInput, {
+ ...init,
+ headers,
+ });
} catch (err) {
if (err instanceof TypeError) {
throw new Error("Studio isn't running -- please relaunch it.");
diff --git a/studio/frontend/src/features/auth/change-password-page.tsx b/studio/frontend/src/features/auth/change-password-page.tsx
index dd4ba711e0b..96ee8dd1a86 100644
--- a/studio/frontend/src/features/auth/change-password-page.tsx
+++ b/studio/frontend/src/features/auth/change-password-page.tsx
@@ -7,7 +7,7 @@ import { AuthForm } from "./components/auth-form";
export function ChangePasswordPage() {
return (
- <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-8 sm:px-6 sm:py-10 md:px-10">
+ <div className="relative flex min-h-[calc(100dvh-var(--studio-titlebar-height,0px))] items-center justify-center overflow-hidden bg-background px-4 py-8 sm:px-6 sm:py-10 md:px-10">
<LightRays
count={6}
color="rgba(34, 197, 94, 0.25)"
diff --git a/studio/frontend/src/features/auth/login-page.tsx b/studio/frontend/src/features/auth/login-page.tsx
index 502b35d22a9..6f4d03f1a1a 100644
--- a/studio/frontend/src/features/auth/login-page.tsx
+++ b/studio/frontend/src/features/auth/login-page.tsx
@@ -7,7 +7,7 @@ import { AuthForm } from "./components/auth-form";
export function LoginPage() {
return (
- <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-8 sm:px-6 sm:py-10 md:px-10">
+ <div className="relative flex min-h-[calc(100dvh-var(--studio-titlebar-height,0px))] items-center justify-center overflow-hidden bg-background px-4 py-8 sm:px-6 sm:py-10 md:px-10">
<LightRays
count={6}
color="rgba(34, 197, 94, 0.25)"
diff --git a/studio/frontend/src/features/auth/tauri-auto-auth.ts b/studio/frontend/src/features/auth/tauri-auto-auth.ts
index d67730d2d66..a0199f9ac39 100644
--- a/studio/frontend/src/features/auth/tauri-auto-auth.ts
+++ b/studio/frontend/src/features/auth/tauri-auto-auth.ts
@@ -15,9 +15,13 @@ type DesktopAuthResponse = {
refresh_token: string;
};
+type TauriAutoAuthOptions = {
+ force?: boolean;
+};
+
// Concurrency guard: multiple route guards can call tauriAutoAuth simultaneously.
// Without this, the first-launch password-change could race with itself.
-let pending: Promise<boolean> | null = null;
+let pending: { promise: Promise<boolean>; force: boolean } | null = null;
let lastTauriAuthFailure: string | null = null;
const TAURI_AUTH_FAILURE_FALLBACK =
@@ -49,15 +53,15 @@ function isBackendNotReady(error: unknown): boolean {
return authFailureMessage(error).includes(BACKEND_NOT_READY_MESSAGE);
}
-async function doTauriAutoAuth(): Promise<boolean> {
+async function doTauriAutoAuth(options: TauriAutoAuthOptions): Promise<boolean> {
// Desktop must handle password-change state internally in Rust.
- if (hasAuthToken() && !mustChangePassword()) {
+ if (!options.force && hasAuthToken() && !mustChangePassword()) {
clearTauriAuthFailure();
return true;
}
// Try refreshing existing session
- if (hasRefreshToken()) {
+ if (!options.force && hasRefreshToken()) {
const refreshed = await refreshSession();
if (refreshed && hasAuthToken() && !mustChangePassword()) {
clearTauriAuthFailure();
@@ -86,10 +90,17 @@ async function doTauriAutoAuth(): Promise<boolean> {
* Returns true if authentication succeeded.
* Concurrent calls are coalesced into a single in-flight attempt.
*/
-export function tauriAutoAuth(): Promise<boolean> {
+export function tauriAutoAuth(
+ options: TauriAutoAuthOptions = {},
+): Promise<boolean> {
if (!isTauri) return Promise.resolve(false);
- if (!pending) {
- pending = doTauriAutoAuth().finally(() => { pending = null; });
+ const force = options.force === true;
+ if (!pending || (force && !pending.force)) {
+ let promise: Promise<boolean>;
+ promise = doTauriAutoAuth({ force }).finally(() => {
+ if (pending?.promise === promise) pending = null;
+ });
+ pending = { promise, force };
}
- return pending;
+ return pending.promise;
}
diff --git a/studio/frontend/src/features/chat/utils/delete-thread-message.ts b/studio/frontend/src/features/chat/utils/delete-thread-message.ts
index 9901ccf80ef..204c0d00646 100644
--- a/studio/frontend/src/features/chat/utils/delete-thread-message.ts
+++ b/studio/frontend/src/features/chat/utils/delete-thread-message.ts
@@ -9,7 +9,9 @@ import type {
/**
* assistant-ui does not expose a public `deleteMessage` on `ThreadRuntime` / `MessageRuntime`
* in our version, but it already implements branch-safe deletion inside `MessageRepository`.
- * We import that helper from an **internal** package path (`runtime/utils/message-repository`).
+ * We import that helper from `@assistant-ui/core/internal`, the package's exported internal
+ * surface. Avoid importing the deeper `runtime/utils/message-repository` path directly: newer
+ * `@assistant-ui/core` releases no longer export arbitrary deep paths.
*
* **Maintainability:** treat this file as the only place that imports `MessageRepository` from
* `@assistant-ui/core`. When bumping `@assistant-ui/react` / `@assistant-ui/core`, re-run chat
diff --git a/studio/frontend/src/features/data-recipes/pages/data-recipes-page.tsx b/studio/frontend/src/features/data-recipes/pages/data-recipes-page.tsx
index 0a51f9df701..79566f21bfe 100644
--- a/studio/frontend/src/features/data-recipes/pages/data-recipes-page.tsx
+++ b/studio/frontend/src/features/data-recipes/pages/data-recipes-page.tsx
@@ -399,7 +399,7 @@ export function DataRecipesPage(): ReactElement {
const isBusy = creatingRecipe || Boolean(loadingTemplateId);
return (
- <div className="min-h-screen bg-background">
+ <div className="min-h-[calc(100dvh-var(--studio-titlebar-height,0px))] bg-background">
<main className="mx-auto w-full max-w-7xl px-6 py-8">
<div className="flex items-center justify-between gap-4">
<div>
diff --git a/studio/frontend/src/features/data-recipes/pages/edit-recipe-page.tsx b/studio/frontend/src/features/data-recipes/pages/edit-recipe-page.tsx
index 8ade8a34af3..ae87f92a531 100644
--- a/studio/frontend/src/features/data-recipes/pages/edit-recipe-page.tsx
+++ b/studio/frontend/src/features/data-recipes/pages/edit-recipe-page.tsx
@@ -28,7 +28,7 @@ function RecipeLoadState({
onBack: () => void;
}): ReactElement {
return (
- <div className="min-h-screen bg-background">
+ <div className="min-h-[calc(100dvh-var(--studio-titlebar-height,0px))] bg-background">
<main className="mx-auto flex min-h-[70vh] w-full max-w-4xl items-center justify-center px-6 py-8">
<div className="w-full rounded-2xl border bg-card p-8 text-center">
<h1 className="text-lg font-semibold">{title}</h1>
diff --git a/studio/frontend/src/features/export/export-page.tsx b/studio/frontend/src/features/export/export-page.tsx
index 454ce40772e..0d5d9c813c9 100644
--- a/studio/frontend/src/features/export/export-page.tsx
+++ b/studio/frontend/src/features/export/export-page.tsx
@@ -523,7 +523,7 @@ export function ExportPage() {
// ---- Render ----
return (
- <div className="min-h-screen bg-background">
+ <div className="min-h-[calc(100dvh-var(--studio-titlebar-height,0px))] bg-background">
<main className="mx-auto max-w-7xl px-4 py-4 sm:px-6">
<GuidedTour {...tour.tourProps} />
diff --git a/studio/frontend/src/features/onboarding/components/wizard-layout.tsx b/studio/frontend/src/features/onboarding/components/wizard-layout.tsx
index 6df873ffd3c..22274c5d7d8 100644
--- a/studio/frontend/src/features/onboarding/components/wizard-layout.tsx
+++ b/studio/frontend/src/features/onboarding/components/wizard-layout.tsx
@@ -73,7 +73,7 @@ export function WizardLayout() {
}, [isFinalStep]);
return (
- <div className="relative min-h-screen flex items-center justify-center overflow-hidden bg-gradient-to-br from-primary/5 via-background to-primary/3 p-4 sm:p-6 md:p-8">
+ <div className="relative flex min-h-[calc(100dvh-var(--studio-titlebar-height,0px))] items-center justify-center overflow-hidden bg-gradient-to-br from-primary/5 via-background to-primary/3 p-4 sm:p-6 md:p-8">
{showSplash && (
<SplashScreen
onStartOnboarding={() => setShowSplash(false)}
diff --git a/studio/frontend/src/features/recipe-studio/recipe-studio-page.tsx b/studio/frontend/src/features/recipe-studio/recipe-studio-page.tsx
index 5dbc004ffde..c1001c03225 100644
--- a/studio/frontend/src/features/recipe-studio/recipe-studio-page.tsx
+++ b/studio/frontend/src/features/recipe-studio/recipe-studio-page.tsx
@@ -776,7 +776,7 @@ export function RecipeStudioPage({
}
return (
- <div className="min-h-screen bg-background">
+ <div className="min-h-[calc(100dvh-var(--studio-titlebar-height,0px))] bg-background">
<main className="w-full px-6 py-8">
<div
className="relative w-full overflow-hidden rounded-2xl corner-squircle border"
diff --git a/studio/frontend/src/features/studio/studio-page.tsx b/studio/frontend/src/features/studio/studio-page.tsx
index 5c5e11907c2..5018dc3baab 100644
--- a/studio/frontend/src/features/studio/studio-page.tsx
+++ b/studio/frontend/src/features/studio/studio-page.tsx
@@ -127,7 +127,7 @@ export function StudioPage(): ReactElement {
})();
return (
- <div className="relative min-h-screen bg-background">
+ <div className="relative min-h-[calc(100dvh-var(--studio-titlebar-height,0px))] bg-background">
<main className="relative z-10 mx-auto max-w-7xl px-4 py-4 sm:px-6">
<GuidedTour {...tour.tourProps} celebrate={isConfigTour} />
diff --git a/studio/frontend/src/hooks/use-tauri-backend.ts b/studio/frontend/src/hooks/use-tauri-backend.ts
index ed697fe31e8..6bbbdb91f94 100644
--- a/studio/frontend/src/hooks/use-tauri-backend.ts
+++ b/studio/frontend/src/hooks/use-tauri-backend.ts
@@ -3,6 +3,10 @@
import { useEffect, useState, useCallback, useRef } from "react";
import { isTauri, setApiBase } from "@/lib/api-base";
+import {
+ copySupportDiagnostics,
+ type CopySupportDiagnosticsResult,
+} from "@/lib/tauri-diagnostics";
import {
clearTauriAuthFailure,
getTauriAuthFailure,
@@ -35,6 +39,54 @@ interface DesktopPreflightResult {
managed_bin: string | null;
}
+const MANAGED_STARTUP_TIMEOUT_MS = 5 * 60_000;
+const MANAGED_STARTUP_POLL_MS = 500;
+
+type TauriInvoke = typeof import("@tauri-apps/api/core").invoke;
+type ManagedStartupResult =
+ | { status: "ready"; port: number }
+ | { status: "aborted" }
+ | { status: "missing-port" }
+ | { status: "unhealthy" };
+
+function wait(ms: number) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+async function waitForManagedServerReady(
+ invoke: TauriInvoke,
+ getPort: () => number | null,
+ shouldContinue: () => boolean,
+): Promise<ManagedStartupResult> {
+ const deadline = Date.now() + MANAGED_STARTUP_TIMEOUT_MS;
+
+ while (Date.now() < deadline) {
+ if (!shouldContinue()) {
+ return { status: "aborted" };
+ }
+
+ const port = getPort();
+ if (port === null) {
+ await wait(MANAGED_STARTUP_POLL_MS);
+ continue;
+ }
+
+ const healthy = await invoke<boolean>("check_health", { port });
+ if (!shouldContinue()) {
+ return { status: "aborted" };
+ }
+ if (healthy && getPort() === port) {
+ return { status: "ready", port };
+ }
+
+ await wait(MANAGED_STARTUP_POLL_MS);
+ }
+
+ return getPort() === null
+ ? { status: "missing-port" }
+ : { status: "unhealthy" };
+}
+
export function useTauriBackend() {
const [status, setStatus] = useState<BackendStatus>("checking");
const statusRef = useRef<BackendStatus>(status);
@@ -181,8 +233,11 @@ export function useTauriBackend() {
async function startManagedServer() {
// Prevent double-start race condition
- if (startingRef.current) return;
+ if (startingRef.current) {
+ return;
+ }
startingRef.current = true;
+ portRef.current = null;
try {
const { invoke } = await import("@tauri-apps/api/core");
@@ -192,23 +247,27 @@ export function useTauriBackend() {
// Wait for the owned backend's server-port event. Do not attach to an
// external backend if the managed start does not report a port.
- for (let i = 0; i < 120; i++) {
- if (portRef.current) {
- const healthy = await invoke<boolean>("check_health", {
- port: portRef.current,
- });
- if (healthy) {
- setApiBase(portRef.current);
- setRunningStatus();
- startingRef.current = false;
- return;
- }
- }
- await new Promise((r) => setTimeout(r, 500));
+ const startupResult = await waitForManagedServerReady(
+ invoke,
+ () => portRef.current,
+ () => startingRef.current,
+ );
+
+ if (startupResult.status === "ready") {
+ setApiBase(startupResult.port);
+ setRunningStatus();
+ startingRef.current = false;
+ return;
}
- const message = !portRef.current
- ? "Managed server started without reporting a port. Check the logs for details."
- : "Server started but is not responding. Check the logs for details.";
+
+ if (startupResult.status === "aborted") {
+ return;
+ }
+
+ const message =
+ startupResult.status === "missing-port"
+ ? "Managed server started without reporting a port. Check the logs for details."
+ : "Server started but is not responding. Check the logs for details.";
setBackendError(message);
} catch (e) {
const msg = String(e);
@@ -283,9 +342,11 @@ export function useTauriBackend() {
const { invoke } = await import("@tauri-apps/api/core");
try {
await invoke("start_install");
- // Install completed — this is the ONLY path that starts the server
- // after install. The install-complete event listener does NOT call
- // startServer() to avoid a double-start race condition.
+ // Install completed — start the managed backend we just installed.
+ // Do not run the general preflight here: it can attach to an unrelated
+ // already-running CLI/backend server before launching our managed one.
+ // The install-complete event listener does NOT call startServer() to
+ // avoid a double-start race condition.
setBackendStatus("starting");
elevationResumeRef.current = null;
await startServer();
@@ -315,8 +376,16 @@ export function useTauriBackend() {
checkInstallAndStart();
}, []);
- const retryInstall = useCallback(() => {
+ const retryInstall = useCallback(async () => {
const resume = elevationResumeRef.current;
+ if (resume) {
+ try {
+ const { invoke } = await import("@tauri-apps/api/core");
+ await invoke("cancel_pending_elevation");
+ } catch (error) {
+ console.warn("Failed to record elevation cancellation", error);
+ }
+ }
elevationResumeRef.current = null;
clearBackendError();
setLogs([]);
@@ -347,6 +416,31 @@ export function useTauriBackend() {
}
}, [elevationPackages]);
+ const copyDiagnostics = useCallback((): Promise<CopySupportDiagnosticsResult> => {
+ const currentStatus = statusRef.current;
+ const flow =
+ currentStatus === "repairing" ||
+ currentStatus === "repair-error" ||
+ (currentStatus === "needs-elevation" && elevationResumeRef.current === "repair")
+ ? "repair"
+ : currentStatus === "installing" ||
+ currentStatus === "install-error" ||
+ currentStatus === "not-installed" ||
+ currentStatus === "needs-elevation"
+ ? "install"
+ : "backend";
+
+ return copySupportDiagnostics({
+ status: currentStatus,
+ error,
+ currentStepIndex,
+ progressDetail,
+ elevationPackages,
+ lastUiLogLines: logs,
+ flow,
+ });
+ }, [currentStepIndex, elevationPackages, error, logs, progressDetail]);
+
// Initial check on mount (guarded against Strict Mode double-mount)
useEffect(() => {
if (mountedRef.current) return;
@@ -482,6 +576,6 @@ export function useTauriBackend() {
status, logs, error, isExternalServer,
currentStepIndex, progressDetail, elevationPackages,
startServer, stopServer, startInstall,
- retry, retryInstall, approveElevation,
+ retry, retryInstall, approveElevation, copyDiagnostics,
};
}
diff --git a/studio/frontend/src/hooks/use-tauri-update.ts b/studio/frontend/src/hooks/use-tauri-update.ts
index 5863ef7aa5b..67f9bf4c77a 100644
--- a/studio/frontend/src/hooks/use-tauri-update.ts
+++ b/studio/frontend/src/hooks/use-tauri-update.ts
@@ -3,6 +3,10 @@
import { useEffect, useRef, useState } from "react";
import { isTauri } from "@/lib/api-base";
+import {
+ copySupportDiagnostics,
+ type CopySupportDiagnosticsResult,
+} from "@/lib/tauri-diagnostics";
import { toast } from "sonner";
export type UpdateStatus =
@@ -21,19 +25,74 @@ export interface UpdateInfo {
date?: string;
}
+export type UpdatePhase =
+ | "backend"
+ | "shell_download"
+ | "shell_install"
+ | "recovered_after_shell_failure";
+
+export interface RetainedUpdateFailure {
+ error: string;
+ phase: UpdatePhase;
+ progress: number;
+ logs: string[];
+}
+
export function useTauriUpdate(isExternalServer = false) {
const [status, setStatus] = useState<UpdateStatus>("idle");
const [info, setInfo] = useState<UpdateInfo | null>(null);
const [progress, setProgress] = useState(0);
+ const progressRef = useRef(0);
const [logs, setLogs] = useState<string[]>([]);
+ const logsRef = useRef<string[]>([]);
+ const [phase, setPhase] = useState<UpdatePhase | null>(null);
+ const phaseRef = useRef<UpdatePhase | null>(null);
const [dismissed, setDismissed] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const [lastFailure, setLastFailure] = useState<RetainedUpdateFailure | null>(null);
const updateRef = useRef<Awaited<
ReturnType<typeof import("@tauri-apps/plugin-updater").check>
> | null>(null);
const checkedRef = useRef(false);
const updatingRef = useRef(false);
+ function replaceLogs(nextLogs: string[]) {
+ logsRef.current = nextLogs;
+ setLogs(nextLogs);
+ }
+
+ function appendLog(line: string) {
+ setLogs((prev) => {
+ const next = [...prev.slice(-499), line];
+ logsRef.current = next;
+ return next;
+ });
+ }
+
+ function setUpdateProgress(nextProgress: number) {
+ progressRef.current = nextProgress;
+ setProgress(nextProgress);
+ }
+
+ function setUpdatePhase(nextPhase: UpdatePhase | null) {
+ phaseRef.current = nextPhase;
+ setPhase(nextPhase);
+ }
+
+ function retainFailure(
+ nextError: string,
+ nextPhase: UpdatePhase = phaseRef.current ?? "backend",
+ ) {
+ const failure = {
+ error: nextError,
+ phase: nextPhase,
+ progress: progressRef.current,
+ logs: logsRef.current,
+ };
+ setLastFailure(failure);
+ return failure;
+ }
+
useEffect(() => {
if (!isTauri || checkedRef.current) return;
checkedRef.current = true;
@@ -71,13 +130,15 @@ export function useTauriUpdate(isExternalServer = false) {
updatingRef.current = true;
const cleanups: (() => void)[] = [];
- let phase: "backend" | "shell" = "backend";
try {
// ── Step 1: Backend update ──
+ setUpdatePhase("backend");
setStatus("updating-backend");
- setLogs([]);
+ replaceLogs([]);
+ setUpdateProgress(0);
setError(null);
+ setLastFailure(null);
setDismissed(false);
const { listen } = await import("@tauri-apps/api/event");
@@ -87,7 +148,7 @@ export function useTauriUpdate(isExternalServer = false) {
const unlistenProgress = await listen<string>(
"update-progress",
(e) => {
- setLogs((prev) => [...prev.slice(-499), e.payload]);
+ appendLog(e.payload);
},
);
cleanups.push(unlistenProgress);
@@ -107,6 +168,7 @@ export function useTauriUpdate(isExternalServer = false) {
);
if (backendResult !== "complete") {
+ retainFailure(backendResult, "backend");
setError(backendResult);
setStatus("error");
updatingRef.current = false;
@@ -115,9 +177,9 @@ export function useTauriUpdate(isExternalServer = false) {
}
// ── Step 2: Shell update ──
- phase = "shell";
+ setUpdatePhase("shell_download");
setStatus("downloading");
- setProgress(0);
+ setUpdateProgress(0);
let downloaded = 0;
let contentLength = 0;
@@ -129,10 +191,11 @@ export function useTauriUpdate(isExternalServer = false) {
case "Progress":
downloaded += event.data.chunkLength;
if (contentLength > 0) {
- setProgress(Math.round((downloaded / contentLength) * 100));
+ setUpdateProgress(Math.round((downloaded / contentLength) * 100));
}
break;
case "Finished":
+ setUpdatePhase("shell_install");
setStatus("installing");
break;
}
@@ -146,21 +209,26 @@ export function useTauriUpdate(isExternalServer = false) {
const msg = String(e);
// Shell update failed — restart backend on updated code
- if (phase === "shell") {
+ if (phaseRef.current === "shell_download" || phaseRef.current === "shell_install") {
try {
const { invoke } = await import("@tauri-apps/api/core");
await invoke("start_server", { port: 8888 });
+ retainFailure(msg, "recovered_after_shell_failure");
toast.error("App update failed", {
description:
- "Backend was updated. The app update will be retried on next launch.",
+ "Backend was updated. Copy diagnostics from the update banner if you need support.",
});
+ setError(null);
setStatus("idle");
- setDismissed(true);
+ setDismissed(false);
+ setUpdatePhase("recovered_after_shell_failure");
} catch {
+ retainFailure(msg, phaseRef.current ?? "shell_install");
setError(msg);
setStatus("error");
}
} else {
+ retainFailure(msg, phaseRef.current ?? "backend");
setError(msg);
setStatus("error");
}
@@ -176,15 +244,23 @@ export function useTauriUpdate(isExternalServer = false) {
}
async function skipAndRestart() {
+ const skippedError = error;
try {
const { invoke } = await import("@tauri-apps/api/core");
await invoke("start_server", { port: 8888 });
+ if (skippedError) {
+ retainFailure(skippedError, phaseRef.current ?? "recovered_after_shell_failure");
+ setDismissed(false);
+ } else {
+ setDismissed(true);
+ }
setStatus("idle");
setError(null);
- setLogs([]);
- setDismissed(true);
+ replaceLogs([]);
} catch (e) {
- setError(String(e));
+ const msg = String(e);
+ retainFailure(msg, phaseRef.current ?? "backend");
+ setError(msg);
setStatus("error");
}
}
@@ -193,6 +269,18 @@ export function useTauriUpdate(isExternalServer = false) {
setDismissed(true);
}
+ function copyDiagnostics(): Promise<CopySupportDiagnosticsResult> {
+ const failure = lastFailure;
+ return copySupportDiagnostics({
+ status: failure ? "error" : status,
+ error: failure?.error ?? error,
+ lastUiLogLines: failure?.logs ?? logs,
+ flow: "update",
+ updatePhase: failure?.phase ?? phase,
+ updateProgress: failure?.progress ?? progress,
+ });
+ }
+
return {
status,
info,
@@ -200,11 +288,14 @@ export function useTauriUpdate(isExternalServer = false) {
logs,
dismissed,
error,
+ phase,
+ lastFailure,
isExternalServer,
installUpdate,
retryUpdate,
skipAndRestart,
dismiss,
+ copyDiagnostics,
};
}
diff --git a/studio/frontend/src/lib/tauri-diagnostics.ts b/studio/frontend/src/lib/tauri-diagnostics.ts
new file mode 100644
index 00000000000..5c07931a86c
--- /dev/null
+++ b/studio/frontend/src/lib/tauri-diagnostics.ts
@@ -0,0 +1,176 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { isTauri } from "@/lib/api-base";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
+
+export interface FrontendSupportSnapshot {
+ status?: string | null;
+ error?: string | null;
+ currentStepIndex?: number | null;
+ progressDetail?: string | null;
+ elevationPackages?: string[];
+ lastUiLogLines?: string[];
+ flow?: string | null;
+ updatePhase?: string | null;
+ updateProgress?: number | null;
+}
+
+export interface CopySupportDiagnosticsResult {
+ ok: boolean;
+ report: string;
+ error?: string;
+ source: "tauri" | "frontend-fallback";
+}
+
+const FALLBACK_LOG_LINE_LIMIT = 200;
+
+const ANSI_ESCAPE_PATTERN = new RegExp(
+ `${String.fromCharCode(27)}(?:[@-Z\\-_]|\\[[0-?]*[ -/]*[@-~])`,
+ "g",
+);
+
+function stripAnsi(text: string): string {
+ return text.replace(ANSI_ESCAPE_PATTERN, "");
+}
+
+export function redactDiagnosticsText(text: string): string {
+ let redacted = stripAnsi(text);
+
+ redacted = redacted.replace(
+ /-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/gi,
+ "<redacted-private-key>",
+ );
+ redacted = redacted.replace(
+ /([a-z][a-z0-9+.-]*:\/\/)([^/\s@]+)@/gi,
+ "$1<redacted>@",
+ );
+ redacted = redacted.replace(
+ /\b(authorization\s*[:=]\s*)(bearer|basic)\s+[^\s,;]+/gi,
+ "$1$2 <redacted>",
+ );
+ redacted = redacted.replace(/\bhf_[A-Za-z0-9]{20,}\b/g, "hf_<redacted>");
+ redacted = redacted.replace(/\bghp_[A-Za-z0-9_]{20,}\b/g, "ghp_<redacted>");
+ redacted = redacted.replace(/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g, "github_pat_<redacted>");
+ redacted = redacted.replace(/\bsk-[A-Za-z0-9_-]{20,}\b/g, "sk-<redacted>");
+ redacted = redacted.replace(
+ /\b(cookie|set-cookie)\s*[:=]\s*[^\n\r]+/gi,
+ "$1=<redacted>",
+ );
+ redacted = redacted.replace(
+ /(^|[\s;])((?:[A-Z0-9]+_)*(?:TOKEN|KEY|SECRET|PASSWORD)(?:_[A-Z0-9]+)*\s*=\s*)[^\s]+/gi,
+ "$1$2<redacted>",
+ );
+
+ // Redact Studio paths before broader home-directory paths.
+ redacted = redacted.replace(
+ /(?:\/Users|\/home)\/[^\s/]+\/\.unsloth\/studio/gi,
+ "<studio_home>",
+ );
+ redacted = redacted.replace(
+ /[A-Z]:\\Users\\[^\s\\]+\\\.unsloth\\studio/gi,
+ "<studio_home>",
+ );
+ redacted = redacted.replace(/(?:\/Users|\/home)\/[^\s/]+/gi, "$HOME");
+ redacted = redacted.replace(/[A-Z]:\\Users\\[^\s\\]+/gi, "%USERPROFILE%");
+ redacted = redacted.replace(
+ /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,
+ "<redacted-email>",
+ );
+
+ return redacted;
+}
+
+function safeLines(lines: string[] | undefined): string[] {
+ return (lines ?? [])
+ .filter((line): line is string => typeof line === "string")
+ .slice(-FALLBACK_LOG_LINE_LIMIT);
+}
+
+function buildFrontendFallbackReport(
+ snapshot: FrontendSupportSnapshot,
+ invokeError: unknown,
+): string {
+ const lines = safeLines(snapshot.lastUiLogLines);
+ const report = [
+ "DEGRADED FRONTEND-ONLY DIAGNOSTICS",
+ "DEGRADED_FRONTEND_ONLY=true",
+ `createdAt=${new Date().toISOString()}`,
+ "reason=collect_support_diagnostics invoke failed",
+ `invokeError=${String(invokeError)}`,
+ `status=${snapshot.status ?? "unavailable"}`,
+ `flow=${snapshot.flow ?? "unknown"}`,
+ `error=${snapshot.error ?? ""}`,
+ `currentStepIndex=${snapshot.currentStepIndex ?? ""}`,
+ `progressDetail=${snapshot.progressDetail ?? ""}`,
+ `elevationPackages=${(snapshot.elevationPackages ?? []).join(",")}`,
+ `updatePhase=${snapshot.updatePhase ?? ""}`,
+ `updateProgress=${snapshot.updateProgress ?? ""}`,
+ "",
+ "lastUiLogLines:",
+ ...lines,
+ "",
+ "redaction=frontend_minimal_js_redaction_applied",
+ "collectionWarnings=Rust diagnostics command was unavailable; this fallback contains only bounded UI state/log lines.",
+ ].join("\n");
+
+ return redactDiagnosticsText(report);
+}
+
+async function collectDiagnosticsReport(
+ snapshot: FrontendSupportSnapshot,
+): Promise<{ report: string; source: CopySupportDiagnosticsResult["source"] }> {
+ if (!isTauri) {
+ return {
+ report: buildFrontendFallbackReport(snapshot, "not running in Tauri"),
+ source: "frontend-fallback",
+ };
+ }
+
+ try {
+ const { invoke } = await import("@tauri-apps/api/core");
+ const report = await invoke<string>("collect_support_diagnostics", {
+ snapshot,
+ });
+ return { report, source: "tauri" };
+ } catch (error) {
+ console.warn("collect_support_diagnostics failed; using frontend-only diagnostics", error);
+ return {
+ report: buildFrontendFallbackReport(snapshot, error),
+ source: "frontend-fallback",
+ };
+ }
+}
+
+async function copyWithTauriClipboard(text: string): Promise<boolean> {
+ if (!isTauri) return false;
+ try {
+ const { writeText } = await import("@tauri-apps/plugin-clipboard-manager");
+ await writeText(text);
+ return true;
+ } catch (error) {
+ console.warn("Tauri clipboard-manager writeText failed", error);
+ return false;
+ }
+}
+
+export async function copySupportDiagnostics(
+ snapshot: FrontendSupportSnapshot,
+): Promise<CopySupportDiagnosticsResult> {
+ const { report, source } = await collectDiagnosticsReport(snapshot);
+
+ if (await copyWithTauriClipboard(report)) {
+ return { ok: true, report, source };
+ }
+
+ if (await copyToClipboard(report)) {
+ return { ok: true, report, source };
+ }
+
+ return {
+ ok: false,
+ report,
+ source,
+ error: "Unable to write diagnostics to the clipboard. Select and copy the text manually.",
+ };
+}
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index 0da30c92296..3d082aa70d6 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -1497,8 +1497,14 @@ substep "Using $PythonCmd ($(& $PythonCmd --version 2>&1))"
$VenvDir = Join-Path $env:USERPROFILE ".unsloth\studio\unsloth_studio"
# Stale-venv detection: if the venv exists but its torch flavor no longer
-# matches the current machine, wipe it so we get a clean install.
-if (Test-Path $VenvDir -PathType Container) {
+# matches the current machine, repair according to invocation context.
+# - install.ps1 sets UNSLOTH_INSTALL_ROLLBACK_MANAGED=1 so setup can delegate
+# to the installer-level rollback that restores the previous environment.
+# - direct `unsloth studio update` keeps the pre-existing self-repair behavior.
+# In no-torch mode, a missing torch package is expected.
+$NoTorchMode = $env:UNSLOTH_NO_TORCH -match '^(?i:true|1|yes)$'
+$InstallerManagedSetup = $env:UNSLOTH_INSTALL_ROLLBACK_MANAGED -match '^(?i:true|1|yes)$'
+if ((Test-Path $VenvDir -PathType Container) -and -not $NoTorchMode) {
$VenvPyExe = Join-Path $VenvDir "Scripts\python.exe"
$installedTorchTag = $null
$shouldRebuild = $false
@@ -1545,6 +1551,12 @@ if (Test-Path $VenvDir -PathType Container) {
if ($shouldRebuild) {
$reason = if ($installedTorchTag) { "torch $installedTorchTag != required $expectedTorchTag" } else { "torch could not be imported" }
+ if ($InstallerManagedSetup) {
+ substep "Stale venv detected ($reason)." "Yellow"
+ Write-Host " [ERROR] The existing Studio environment needs repair." -ForegroundColor Red
+ Write-Host " Re-run install.ps1 so it can replace the environment safely with rollback." -ForegroundColor Yellow
+ exit 1
+ }
substep "Stale venv detected ($reason) -- rebuilding..." "Yellow"
try {
Remove-Item $VenvDir -Recurse -Force -ErrorAction Stop
diff --git a/studio/src-tauri/Cargo.lock b/studio/src-tauri/Cargo.lock
index 62d520437cb..e491ee534ab 100644
--- a/studio/src-tauri/Cargo.lock
+++ b/studio/src-tauri/Cargo.lock
@@ -56,6 +56,27 @@ dependencies = [
"derive_arbitrary",
]
+[[package]]
+name = "arboard"
+version = "3.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf"
+dependencies = [
+ "clipboard-win",
+ "image",
+ "log",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-foundation",
+ "parking_lot",
+ "percent-encoding",
+ "windows-sys 0.60.2",
+ "wl-clipboard-rs",
+ "x11rb",
+]
+
[[package]]
name = "async-broadcast"
version = "0.7.2"
@@ -334,6 +355,12 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
+[[package]]
+name = "byteorder-lite"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
+
[[package]]
name = "bytes"
version = "1.11.1"
@@ -482,6 +509,15 @@ dependencies = [
"windows-link 0.2.1",
]
+[[package]]
+name = "clipboard-win"
+version = "5.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4"
+dependencies = [
+ "error-code",
+]
+
[[package]]
name = "combine"
version = "4.6.7"
@@ -609,6 +645,12 @@ version = "0.8.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
+[[package]]
+name = "crunchy"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+
[[package]]
name = "crypto-common"
version = "0.1.7"
@@ -850,6 +892,12 @@ dependencies = [
"tendril 0.5.0",
]
+[[package]]
+name = "downcast-rs"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
+
[[package]]
name = "dpi"
version = "0.1.2"
@@ -983,6 +1031,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "error-code"
+version = "3.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dea2df4cf52843e0452895c455a1a2cfbb842a1e7329671acf418fdc53ed4c59"
+
[[package]]
name = "event-listener"
version = "5.4.1"
@@ -1010,6 +1064,12 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
+[[package]]
+name = "fax"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a"
+
[[package]]
name = "fdeflate"
version = "0.3.7"
@@ -1056,6 +1116,12 @@ dependencies = [
"thiserror 1.0.69",
]
+[[package]]
+name = "fixedbitset"
+version = "0.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
+
[[package]]
name = "flate2"
version = "1.1.9"
@@ -1347,6 +1413,16 @@ dependencies = [
"version_check",
]
+[[package]]
+name = "gethostname"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
+dependencies = [
+ "rustix",
+ "windows-link 0.2.1",
+]
+
[[package]]
name = "getrandom"
version = "0.1.16"
@@ -1562,6 +1638,17 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "half"
+version = "2.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
+dependencies = [
+ "cfg-if",
+ "crunchy",
+ "zerocopy",
+]
+
[[package]]
name = "hashbrown"
version = "0.12.3"
@@ -1787,7 +1874,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e795dff5605e0f04bff85ca41b51a96b83e80b281e96231bcaaf1ac35103371"
dependencies = [
"byteorder",
- "png",
+ "png 0.17.16",
]
[[package]]
@@ -1904,6 +1991,20 @@ dependencies = [
"icu_properties",
]
+[[package]]
+name = "image"
+version = "0.25.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
+dependencies = [
+ "bytemuck",
+ "byteorder-lite",
+ "moxcms",
+ "num-traits",
+ "png 0.18.1",
+ "tiff",
+]
+
[[package]]
name = "indexmap"
version = "1.9.3"
@@ -2280,6 +2381,16 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "moxcms"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
+dependencies = [
+ "num-traits",
+ "pxfm",
+]
+
[[package]]
name = "muda"
version = "0.17.1"
@@ -2295,7 +2406,7 @@ dependencies = [
"objc2-core-foundation",
"objc2-foundation",
"once_cell",
- "png",
+ "png 0.17.16",
"serde",
"thiserror 2.0.18",
"windows-sys 0.60.2",
@@ -2372,6 +2483,15 @@ version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb"
+[[package]]
+name = "nom"
+version = "8.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "num-conv"
version = "0.2.0"
@@ -2438,6 +2558,7 @@ dependencies = [
"block2",
"objc2",
"objc2-core-foundation",
+ "objc2-core-graphics",
"objc2-foundation",
]
@@ -2632,6 +2753,16 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "os_pipe"
+version = "1.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "osakit"
version = "0.3.1"
@@ -2712,6 +2843,17 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+[[package]]
+name = "petgraph"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"
+dependencies = [
+ "fixedbitset",
+ "hashbrown 0.15.5",
+ "indexmap 2.13.0",
+]
+
[[package]]
name = "phf"
version = "0.8.0"
@@ -2942,7 +3084,7 @@ checksum = "740ebea15c5d1428f910cd1a5f52cebf8d25006245ed8ade92702f4943d91e07"
dependencies = [
"base64 0.22.1",
"indexmap 2.13.0",
- "quick-xml",
+ "quick-xml 0.38.4",
"serde",
"time",
]
@@ -2960,6 +3102,19 @@ dependencies = [
"miniz_oxide",
]
+[[package]]
+name = "png"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
+dependencies = [
+ "bitflags 2.11.0",
+ "crc32fast",
+ "fdeflate",
+ "flate2",
+ "miniz_oxide",
+]
+
[[package]]
name = "polling"
version = "3.11.0"
@@ -3094,6 +3249,18 @@ dependencies = [
"windows 0.62.2",
]
+[[package]]
+name = "pxfm"
+version = "0.1.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e0c5ccf5294c6ccd63a74f1565028353830a9c2f5eb0c682c355c471726a6e3f"
+
+[[package]]
+name = "quick-error"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
+
[[package]]
name = "quick-xml"
version = "0.38.4"
@@ -3103,6 +3270,15 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "quick-xml"
+version = "0.39.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "958f21e8e7ceb5a1aa7fa87fab28e7c75976e0bfe7e23ff069e0a260f894067d"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "quote"
version = "1.0.45"
@@ -4275,7 +4451,7 @@ dependencies = [
"ico",
"json-patch",
"plist",
- "png",
+ "png 0.17.16",
"proc-macro2",
"quote",
"semver",
@@ -4322,6 +4498,21 @@ dependencies = [
"walkdir",
]
+[[package]]
+name = "tauri-plugin-clipboard-manager"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "206dc20af4ed210748ba945c2774e60fd0acd52b9a73a028402caf809e9b6ecf"
+dependencies = [
+ "arboard",
+ "log",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "thiserror 2.0.18",
+]
+
[[package]]
name = "tauri-plugin-opener"
version = "2.5.3"
@@ -4585,6 +4776,20 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "tiff"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52"
+dependencies = [
+ "fax",
+ "flate2",
+ "half",
+ "quick-error",
+ "weezl",
+ "zune-jpeg",
+]
+
[[package]]
name = "time"
version = "0.3.47"
@@ -4886,12 +5091,23 @@ dependencies = [
"objc2-core-graphics",
"objc2-foundation",
"once_cell",
- "png",
+ "png 0.17.16",
"serde",
"thiserror 2.0.18",
"windows-sys 0.60.2",
]
+[[package]]
+name = "tree_magic_mini"
+version = "3.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"
+dependencies = [
+ "memchr",
+ "nom",
+ "petgraph",
+]
+
[[package]]
name = "try-lock"
version = "0.2.5"
@@ -4982,7 +5198,7 @@ checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "unsloth-studio"
-version = "2026.4.7"
+version = "2026.4.8"
dependencies = [
"dirs",
"elevated-command",
@@ -4999,6 +5215,7 @@ dependencies = [
"simplelog",
"tauri",
"tauri-build",
+ "tauri-plugin-clipboard-manager",
"tauri-plugin-opener",
"tauri-plugin-process",
"tauri-plugin-single-instance",
@@ -5265,6 +5482,76 @@ dependencies = [
"semver",
]
+[[package]]
+name = "wayland-backend"
+version = "0.3.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2857dd20b54e916ec7253b3d6b4d5c4d7d4ca2c33c2e11c6c76a99bd8744755d"
+dependencies = [
+ "cc",
+ "downcast-rs",
+ "rustix",
+ "smallvec",
+ "wayland-sys",
+]
+
+[[package]]
+name = "wayland-client"
+version = "0.31.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "645c7c96bb74690c3189b5c9cb4ca1627062bb23693a4fad9d8c3de958260144"
+dependencies = [
+ "bitflags 2.11.0",
+ "rustix",
+ "wayland-backend",
+ "wayland-scanner",
+]
+
+[[package]]
+name = "wayland-protocols"
+version = "0.32.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "563a85523cade2429938e790815fd7319062103b9f4a2dc806e9b53b95982d8f"
+dependencies = [
+ "bitflags 2.11.0",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-scanner",
+]
+
+[[package]]
+name = "wayland-protocols-wlr"
+version = "0.3.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234"
+dependencies = [
+ "bitflags 2.11.0",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-scanner",
+]
+
+[[package]]
+name = "wayland-scanner"
+version = "0.31.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c324a910fd86ebdc364a3e61ec1f11737d3b1d6c273c0239ee8ff4bc0d24b4a"
+dependencies = [
+ "proc-macro2",
+ "quick-xml 0.39.2",
+ "quote",
+]
+
+[[package]]
+name = "wayland-sys"
+version = "0.31.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be"
+dependencies = [
+ "pkg-config",
+]
+
[[package]]
name = "web-sys"
version = "0.3.91"
@@ -5376,6 +5663,12 @@ dependencies = [
"windows-core 0.61.2",
]
+[[package]]
+name = "weezl"
+version = "0.1.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
+
[[package]]
name = "winapi"
version = "0.3.9"
@@ -6016,6 +6309,24 @@ dependencies = [
"wasmparser",
]
+[[package]]
+name = "wl-clipboard-rs"
+version = "0.9.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e9651471a32e87d96ef3a127715382b2d11cc7c8bb9822ded8a7cc94072eb0a3"
+dependencies = [
+ "libc",
+ "log",
+ "os_pipe",
+ "rustix",
+ "thiserror 2.0.18",
+ "tree_magic_mini",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-protocols-wlr",
+]
+
[[package]]
name = "writeable"
version = "0.6.2"
@@ -6087,6 +6398,23 @@ dependencies = [
"pkg-config",
]
+[[package]]
+name = "x11rb"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"
+dependencies = [
+ "gethostname",
+ "rustix",
+ "x11rb-protocol",
+]
+
+[[package]]
+name = "x11rb-protocol"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
+
[[package]]
name = "xattr"
version = "1.6.1"
@@ -6279,6 +6607,21 @@ version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
+[[package]]
+name = "zune-core"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb8a0807f7c01457d0379ba880ba6322660448ddebc890ce29bb64da71fb40f9"
+
+[[package]]
+name = "zune-jpeg"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
+dependencies = [
+ "zune-core",
+]
+
[[package]]
name = "zvariant"
version = "5.10.0"
diff --git a/studio/src-tauri/Cargo.toml b/studio/src-tauri/Cargo.toml
index ccb07cb9e22..269bb7a92a9 100644
--- a/studio/src-tauri/Cargo.toml
+++ b/studio/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "unsloth-studio"
-version = "2026.4.7"
+version = "2026.4.8"
description = "Unsloth Studio Desktop App"
authors = ["Unsloth AI"]
edition = "2021"
@@ -22,6 +22,7 @@ process-wrap = { version = "9", features = ["std"] }
fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs" }
tauri-plugin-opener = "2.5.3"
tauri-plugin-updater = "2"
+tauri-plugin-clipboard-manager = "2"
rand = "0.10.0"
[target.'cfg(unix)'.dependencies]
diff --git a/studio/src-tauri/capabilities/default.json b/studio/src-tauri/capabilities/default.json
index 7b6033c721d..b624369abdd 100644
--- a/studio/src-tauri/capabilities/default.json
+++ b/studio/src-tauri/capabilities/default.json
@@ -13,12 +13,18 @@
"core:window:allow-set-size-constraints",
"core:window:allow-center",
"core:window:allow-current-monitor",
+ "core:window:allow-start-dragging",
+ "core:window:allow-start-resize-dragging",
+ "core:window:allow-minimize",
+ "core:window:allow-toggle-maximize",
+ "core:window:allow-close",
"core:tray:default",
"process:default",
{
"identifier": "opener:allow-open-url",
"allow": [{ "url": "https://*" }, { "url": "http://*" }, { "url": "mailto:*" }]
},
- "updater:default"
+ "updater:default",
+ "clipboard-manager:allow-write-text"
]
}
diff --git a/studio/src-tauri/src/commands.rs b/studio/src-tauri/src/commands.rs
index f2acb92e09a..48a0af6e487 100644
--- a/studio/src-tauri/src/commands.rs
+++ b/studio/src-tauri/src/commands.rs
@@ -1,9 +1,19 @@
+use crate::diagnostics::{self, DiagnosticsState};
use crate::install;
use crate::process::{self, BackendState, ShutdownFlag};
use crate::update;
use log::{error, info, warn};
+use std::time::{Duration, Instant};
use tauri::{AppHandle, Emitter};
+const BACKEND_STARTUP_GRACE_PERIOD: Duration = Duration::from_secs(5 * 60);
+const HEALTH_WATCHDOG_INTERVAL: Duration = Duration::from_secs(15);
+const HEALTH_WATCHDOG_MAX_FAILURES: u32 = 3;
+
+fn should_count_watchdog_failure(has_seen_healthy: bool, elapsed_since_start: Duration) -> bool {
+ has_seen_healthy || elapsed_since_start >= BACKEND_STARTUP_GRACE_PERIOD
+}
+
async fn managed_install_ready_after_repair() -> bool {
crate::preflight::managed_install_ready().await
}
@@ -13,8 +23,12 @@ fn should_emit_repair_failed(msg: &str) -> bool {
}
#[tauri::command]
-pub async fn desktop_preflight() -> crate::preflight::DesktopPreflightResult {
- crate::preflight::desktop_preflight_result().await
+pub async fn desktop_preflight(
+ diagnostics: tauri::State<'_, DiagnosticsState>,
+) -> Result<crate::preflight::DesktopPreflightResult, String> {
+ let result = crate::preflight::desktop_preflight_result().await;
+ diagnostics::record_preflight(&diagnostics, &result);
+ Ok(result)
}
/// Check if unsloth is installed AND functional.
@@ -82,11 +96,13 @@ pub async fn start_server(
app: AppHandle,
state: tauri::State<'_, BackendState>,
shutdown: tauri::State<'_, ShutdownFlag>,
+ diagnostics: tauri::State<'_, DiagnosticsState>,
port: u16,
) -> Result<(), String> {
info!("start_server command called with port {}", port);
- process::start_backend(&app, &state, port, &shutdown)?;
+ let diagnostics_state = diagnostics.inner().clone();
+ let generation = process::start_backend(&app, &state, port, &shutdown, &diagnostics_state)?;
// Spawn health watchdog for the owned backend — detects
// deadlocks and hangs that stdout-based crash detection misses.
@@ -94,7 +110,14 @@ pub async fn start_server(
let watchdog_shutdown = shutdown.inner().clone();
let watchdog_app = app.clone();
tokio::spawn(async move {
- health_watchdog(watchdog_app, watchdog_state, watchdog_shutdown).await;
+ health_watchdog(
+ watchdog_app,
+ watchdog_state,
+ watchdog_shutdown,
+ diagnostics_state,
+ generation,
+ )
+ .await;
});
Ok(())
@@ -106,16 +129,25 @@ pub async fn start_managed_server(
app: AppHandle,
state: tauri::State<'_, BackendState>,
shutdown: tauri::State<'_, ShutdownFlag>,
+ diagnostics: tauri::State<'_, DiagnosticsState>,
port: u16,
) -> Result<(), String> {
info!("start_managed_server command called with port {}", port);
- process::start_backend(&app, &state, port, &shutdown)?;
+ let diagnostics_state = diagnostics.inner().clone();
+ let generation = process::start_backend(&app, &state, port, &shutdown, &diagnostics_state)?;
let watchdog_state = state.inner().clone();
let watchdog_shutdown = shutdown.inner().clone();
let watchdog_app = app.clone();
tokio::spawn(async move {
- health_watchdog(watchdog_app, watchdog_state, watchdog_shutdown).await;
+ health_watchdog(
+ watchdog_app,
+ watchdog_state,
+ watchdog_shutdown,
+ diagnostics_state,
+ generation,
+ )
+ .await;
});
Ok(())
@@ -128,9 +160,10 @@ pub async fn start_managed_server(
pub fn stop_server(
state: tauri::State<'_, BackendState>,
shutdown: tauri::State<'_, ShutdownFlag>,
+ diagnostics: tauri::State<'_, DiagnosticsState>,
) -> Result<(), String> {
info!("stop_server command called");
- process::stop_backend(&state, &shutdown)
+ process::stop_backend(&state, &shutdown, Some(diagnostics.inner()))
}
/// Check if a healthy Unsloth backend is running on the given port.
@@ -201,13 +234,25 @@ pub fn open_logs_dir() -> Result<(), String> {
pub async fn start_install(
app: AppHandle,
state: tauri::State<'_, install::InstallState>,
+ diagnostics: tauri::State<'_, DiagnosticsState>,
) -> Result<(), String> {
let state = state.inner().clone();
- tokio::task::spawn_blocking(move || install::run_install(app, state))
+ let diagnostics_state = diagnostics.inner().clone();
+ tokio::task::spawn_blocking(move || install::run_install(app, state, diagnostics_state))
.await
.map_err(|e| format!("Install task panicked: {e}"))?
}
+/// Record that the user canceled a pending system-package elevation flow.
+#[tauri::command]
+pub fn cancel_pending_elevation(
+ state: tauri::State<'_, install::InstallState>,
+ diagnostics: tauri::State<'_, DiagnosticsState>,
+) -> Result<(), String> {
+ let _ = install::record_pending_elevation_canceled(&state, diagnostics.inner());
+ Ok(())
+}
+
/// Install system packages with elevated permissions (Linux only).
/// Called by frontend after user approves the elevation dialog.
/// Only allows packages that the install script reported as needed.
@@ -216,6 +261,7 @@ pub async fn start_install(
pub fn install_system_packages(
packages: Vec<String>,
state: tauri::State<'_, install::InstallState>,
+ diagnostics: tauri::State<'_, DiagnosticsState>,
) -> Result<(), String> {
// Cross-check against the packages the install script actually reported
let allowed = state
@@ -230,7 +276,7 @@ pub fn install_system_packages(
));
}
}
- install::install_system_packages(&packages)
+ install::install_system_packages(&packages, &state, diagnostics.inner())
}
/// Stub for non-Linux platforms — elevation is handled by the scripts themselves.
@@ -239,6 +285,7 @@ pub fn install_system_packages(
pub fn install_system_packages(
_packages: Vec<String>,
_state: tauri::State<'_, install::InstallState>,
+ _diagnostics: tauri::State<'_, DiagnosticsState>,
) -> Result<(), String> {
Err("Elevated package install is only supported on Linux".to_string())
}
@@ -252,6 +299,7 @@ pub async fn start_backend_update(
shutdown: tauri::State<'_, ShutdownFlag>,
update_state: tauri::State<'_, update::UpdateState>,
install_state: tauri::State<'_, install::InstallState>,
+ diagnostics: tauri::State<'_, DiagnosticsState>,
) -> Result<(), String> {
info!("start_backend_update command called");
@@ -285,12 +333,13 @@ pub async fn start_backend_update(
.unwrap_or(false)
{
info!("Stopping backend before update...");
- process::stop_backend(&backend_state, &shutdown)?;
+ process::stop_backend(&backend_state, &shutdown, Some(diagnostics.inner()))?;
}
// Run update in a blocking thread
let state = update_state.inner().clone();
- tokio::task::spawn_blocking(move || update::run_backend_update(app, state))
+ let diagnostics_state = diagnostics.inner().clone();
+ tokio::task::spawn_blocking(move || update::run_backend_update(app, state, diagnostics_state))
.await
.map_err(|e| format!("Update task panicked: {e}"))?
}
@@ -303,6 +352,7 @@ pub async fn start_managed_repair(
shutdown: tauri::State<'_, ShutdownFlag>,
update_state: tauri::State<'_, update::UpdateState>,
install_state: tauri::State<'_, install::InstallState>,
+ diagnostics: tauri::State<'_, DiagnosticsState>,
) -> Result<(), String> {
info!("start_managed_repair command called");
@@ -322,6 +372,10 @@ pub async fn start_managed_repair(
return Err("Repair is already running.".to_string());
}
+ let diagnostics_state = diagnostics.inner().clone();
+ let repair_group_id = install::take_pending_repair_group_for_resume(&install_state)
+ .unwrap_or_else(|| diagnostics::begin_repair_group(&diagnostics_state));
+
shutdown.store(true, std::sync::atomic::Ordering::SeqCst);
if backend_state
@@ -330,14 +384,21 @@ pub async fn start_managed_repair(
.unwrap_or(false)
{
info!("Stopping backend before repair...");
- process::stop_backend(&backend_state, &shutdown)?;
+ process::stop_backend(&backend_state, &shutdown, Some(&diagnostics_state))?;
}
let _ = app.emit("repair-progress", "Updating existing Studio install...");
let update_app = app.clone();
let update_state = update_state.inner().clone();
+ let update_diagnostics = diagnostics_state.clone();
+ let update_repair_group_id = repair_group_id.clone();
let update_result = tokio::task::spawn_blocking(move || {
- update::run_backend_update_for_repair(update_app, update_state)
+ update::run_backend_update_for_repair(
+ update_app,
+ update_state,
+ update_diagnostics,
+ update_repair_group_id,
+ )
})
.await
.map_err(|e| format!("Repair update task panicked: {e}"))?;
@@ -345,6 +406,7 @@ pub async fn start_managed_repair(
match update_result {
Ok(()) if managed_install_ready_after_repair().await => {
info!("Managed repair complete after update");
+ diagnostics::finish_repair_group(&diagnostics_state, &repair_group_id, "success", None);
let _ = app.emit("repair-complete", ());
return Ok(());
}
@@ -358,6 +420,12 @@ pub async fn start_managed_repair(
Err(msg) => {
if msg.to_ascii_lowercase().contains("already running") {
error!("Managed repair update conflict: {}", msg);
+ diagnostics::finish_repair_group(
+ &diagnostics_state,
+ &repair_group_id,
+ "failed",
+ Some(msg.clone()),
+ );
let _ = app.emit("repair-failed", &msg);
return Err(msg);
}
@@ -375,13 +443,30 @@ pub async fn start_managed_repair(
let install_app = app.clone();
let install_state = install_state.inner().clone();
+ let install_diagnostics = diagnostics_state.clone();
+ let install_repair_group_id = repair_group_id.clone();
let install_result = tokio::task::spawn_blocking(move || {
- install::run_install_for_repair(install_app, install_state)
+ install::run_install_for_repair(
+ install_app,
+ install_state,
+ install_diagnostics,
+ install_repair_group_id,
+ )
})
.await
.map_err(|e| format!("Repair install task panicked: {e}"))?;
if let Err(msg) = install_result {
+ diagnostics::finish_repair_group(
+ &diagnostics_state,
+ &repair_group_id,
+ if msg == "NEEDS_ELEVATION" {
+ "needs_elevation"
+ } else {
+ "failed"
+ },
+ Some(msg.clone()),
+ );
if should_emit_repair_failed(&msg) {
error!("Managed repair installer failed: {}", msg);
let _ = app.emit("repair-failed", &msg);
@@ -391,18 +476,27 @@ pub async fn start_managed_repair(
if managed_install_ready_after_repair().await {
info!("Managed repair complete after installer");
+ diagnostics::finish_repair_group(&diagnostics_state, &repair_group_id, "success", None);
let _ = app.emit("repair-complete", ());
return Ok(());
}
let msg = "Repair finished, but Studio install is still not desktop-ready.".to_string();
error!("{}", msg);
+ diagnostics::finish_repair_group(
+ &diagnostics_state,
+ &repair_group_id,
+ "failed",
+ Some(msg.clone()),
+ );
let _ = app.emit("repair-failed", &msg);
Err(msg)
}
#[cfg(test)]
mod tests {
+ use std::time::Duration;
+
#[test]
fn repair_elevation_is_not_a_terminal_repair_failure() {
assert!(!super::should_emit_repair_failed("NEEDS_ELEVATION"));
@@ -410,63 +504,132 @@ mod tests {
"Installer exited with code 1"
));
}
+
+ #[test]
+ fn watchdog_ignores_startup_failures_within_grace_period() {
+ assert!(!super::should_count_watchdog_failure(
+ false,
+ super::BACKEND_STARTUP_GRACE_PERIOD - Duration::from_secs(1)
+ ));
+ }
+
+ #[test]
+ fn watchdog_counts_failures_after_backend_was_healthy() {
+ assert!(super::should_count_watchdog_failure(
+ true,
+ Duration::from_secs(1)
+ ));
+ }
+
+ #[test]
+ fn watchdog_counts_startup_failures_after_grace_period() {
+ assert!(super::should_count_watchdog_failure(
+ false,
+ super::BACKEND_STARTUP_GRACE_PERIOD
+ ));
+ }
}
/// Periodic health check that detects deadlocked or hung backends.
-/// Starts 30s after the backend is launched (to allow initial startup),
-/// then pings /api/health every 15s. After 3 consecutive failures (45s)
-/// with the process still alive, emits `server-crashed` so the frontend
-/// can offer a restart.
-async fn health_watchdog(app: AppHandle, state: BackendState, shutdown: ShutdownFlag) {
+/// During startup, failures are ignored for a generous grace period so a slow
+/// but legitimate backend boot is not killed. After the backend has answered at
+/// least once, or after the startup grace expires, 3 consecutive failed checks
+/// emit `server-crashed` so the frontend can offer a restart.
+async fn health_watchdog(
+ app: AppHandle,
+ state: BackendState,
+ shutdown: ShutdownFlag,
+ diagnostics: DiagnosticsState,
+ generation: u64,
+) {
use std::sync::atomic::Ordering;
- // Give the backend time to start up
- tokio::time::sleep(std::time::Duration::from_secs(30)).await;
-
+ let started_at = Instant::now();
let mut consecutive_failures: u32 = 0;
+ let mut has_seen_healthy = false;
loop {
- tokio::time::sleep(std::time::Duration::from_secs(15)).await;
+ tokio::time::sleep(HEALTH_WATCHDOG_INTERVAL).await;
if shutdown.load(Ordering::SeqCst) {
info!("Health watchdog: shutdown flag set, exiting");
break;
}
- let (port, has_child) = {
+ let (port, has_child, current_generation) = {
let proc = match state.lock() {
Ok(p) => p,
Err(_) => break,
};
- (proc.port, proc.child.is_some())
+ (proc.port, proc.child.is_some(), proc.generation)
};
+ if current_generation != generation {
+ info!("Health watchdog: backend generation changed, exiting");
+ break;
+ }
+
// Stop watching if the backend is gone
if !has_child {
info!("Health watchdog: backend stopped, exiting");
break;
}
+ let should_count_failure =
+ should_count_watchdog_failure(has_seen_healthy, started_at.elapsed());
+
let Some(port) = port else {
- continue; // Port not yet known
+ if should_count_failure {
+ consecutive_failures += 1;
+ warn!(
+ "Health watchdog: backend has not reported a port ({}/{})",
+ consecutive_failures, HEALTH_WATCHDOG_MAX_FAILURES
+ );
+ }
+
+ if consecutive_failures >= HEALTH_WATCHDOG_MAX_FAILURES {
+ error!(
+ "Health watchdog: backend never reported a port, killing and declaring dead"
+ );
+ diagnostics::record_backend_watchdog(
+ &diagnostics,
+ generation,
+ "no_port_after_grace",
+ );
+ let _ = process::stop_backend(&state, &shutdown, Some(&diagnostics));
+ let _ = app.emit("server-crashed", ());
+ break;
+ }
+
+ continue;
};
match check_health_inner(port).await {
Ok(true) => {
+ has_seen_healthy = true;
consecutive_failures = 0;
}
+ _ if !should_count_failure => {
+ info!(
+ "Health watchdog: startup health check failed on port {} before grace period elapsed",
+ port
+ );
+ }
_ => {
consecutive_failures += 1;
warn!(
- "Health watchdog: failure {}/3 on port {}",
- consecutive_failures, port
+ "Health watchdog: failure {}/{} on port {}",
+ consecutive_failures, HEALTH_WATCHDOG_MAX_FAILURES, port
);
- if consecutive_failures >= 3 {
- error!(
- "Health watchdog: backend unresponsive for 45s, killing and declaring dead"
+ if consecutive_failures >= HEALTH_WATCHDOG_MAX_FAILURES {
+ error!("Health watchdog: backend unresponsive, killing and declaring dead");
+ diagnostics::record_backend_watchdog(
+ &diagnostics,
+ generation,
+ "unresponsive_health_check",
);
// Kill the zombie process so retry can start fresh
- let _ = process::stop_backend(&state, &shutdown);
+ let _ = process::stop_backend(&state, &shutdown, Some(&diagnostics));
let _ = app.emit("server-crashed", ());
break;
}
diff --git a/studio/src-tauri/src/desktop_auth.rs b/studio/src-tauri/src/desktop_auth.rs
index df09df7a14d..483e7c04327 100644
--- a/studio/src-tauri/src/desktop_auth.rs
+++ b/studio/src-tauri/src/desktop_auth.rs
@@ -1,6 +1,7 @@
+use crate::diagnostics::{self, DiagnosticsState};
use crate::preflight::{DesktopPreflightDisposition, DesktopPreflightResult};
use crate::process::BackendState;
-use log::info;
+use log::{info, warn};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
@@ -39,13 +40,16 @@ struct BackendPort {
#[derive(Debug)]
enum AuthError {
Connectivity(String),
+ StaleResponder(String),
Failed(String),
}
impl AuthError {
fn message(self) -> String {
match self {
- Self::Connectivity(message) | Self::Failed(message) => message,
+ Self::Connectivity(message) | Self::StaleResponder(message) | Self::Failed(message) => {
+ message
+ }
}
}
}
@@ -73,11 +77,14 @@ fn read_secret_if_exists(path: &Path) -> Result<Option<String>, String> {
match std::fs::read_to_string(path) {
Ok(s) => Ok(Some(s.trim().to_string())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
- Err(e) => Err(format!(
- "Failed to read auth secret at {}: {}",
- path.display(),
- e
- )),
+ Err(e) => {
+ warn!(
+ "Desktop auth: ignoring unreadable auth secret at {}: {}",
+ path.display(),
+ e
+ );
+ Ok(None)
+ }
}
}
@@ -138,7 +145,10 @@ fn classify_auth_send_error(error: reqwest::Error) -> AuthError {
fn should_retry_with_discovered_port(source: PortSource, error: &AuthError) -> bool {
matches!(
(source, error),
- (PortSource::Cached, AuthError::Connectivity(_))
+ (
+ PortSource::Cached,
+ AuthError::Connectivity(_) | AuthError::StaleResponder(_)
+ )
)
}
@@ -157,7 +167,7 @@ async fn exchange_desktop_secret(
.map_err(classify_auth_send_error)?;
if response.status() == reqwest::StatusCode::NOT_FOUND {
- return Err(AuthError::Failed(
+ return Err(AuthError::StaleResponder(
"Running Studio backend is too old for this desktop app. Update that backend and restart."
.to_string(),
));
@@ -166,7 +176,7 @@ async fn exchange_desktop_secret(
return Ok(None);
}
if !response.status().is_success() {
- return Err(AuthError::Failed("Desktop auth failed".to_string()));
+ return Err(AuthError::StaleResponder("Desktop auth failed".to_string()));
}
response
@@ -213,6 +223,33 @@ async fn provision_desktop_auth() -> Result<(), String> {
))
}
+async fn retry_on_discovered_port(
+ client: &Client,
+ state: &tauri::State<'_, BackendState>,
+ previous: BackendPort,
+ secret: &str,
+) -> Result<Option<(Option<DesktopAuthResponse>, BackendPort)>, String> {
+ if previous.source != PortSource::Cached {
+ return Ok(None);
+ }
+ let Some(port) = discover_compatible_backend_port().await else {
+ return Ok(None);
+ };
+ if port == previous.port {
+ return Ok(None);
+ }
+
+ update_backend_port(state, port)?;
+ let backend = BackendPort {
+ port,
+ source: PortSource::Discovered,
+ };
+ exchange_desktop_secret(client, port, secret)
+ .await
+ .map(|tokens| Some((tokens, backend)))
+ .map_err(AuthError::message)
+}
+
async fn authenticate_with_stale_port_retry(
client: &Client,
state: &tauri::State<'_, BackendState>,
@@ -220,20 +257,19 @@ async fn authenticate_with_stale_port_retry(
secret: &str,
) -> Result<(Option<DesktopAuthResponse>, BackendPort), String> {
match exchange_desktop_secret(client, backend.port, secret).await {
- Ok(tokens) => Ok((tokens, backend)),
+ Ok(Some(tokens)) => Ok((Some(tokens), backend)),
+ Ok(None) => {
+ // 401 means the backend is reachable but the cached secret is stale.
+ // Keep using the same backend so the next desktop_auth_inner attempt
+ // provisions a new secret for the server we are retrying instead of
+ // switching to an unrelated discovered/attached backend.
+ Ok((None, backend))
+ }
Err(error) if should_retry_with_discovered_port(backend.source, &error) => {
- let Some(port) = discover_compatible_backend_port().await else {
- return Err(error.message());
- };
- update_backend_port(state, port)?;
- let backend = BackendPort {
- port,
- source: PortSource::Discovered,
- };
- exchange_desktop_secret(client, port, secret)
- .await
- .map(|tokens| (tokens, backend))
- .map_err(AuthError::message)
+ if let Some(retried) = retry_on_discovered_port(client, state, backend, secret).await? {
+ return Ok(retried);
+ }
+ Err(error.message())
}
Err(error) => Err(error.message()),
}
@@ -242,9 +278,25 @@ async fn authenticate_with_stale_port_retry(
#[tauri::command]
pub async fn desktop_auth(
state: tauri::State<'_, BackendState>,
+ diagnostics: tauri::State<'_, DiagnosticsState>,
+) -> Result<DesktopAuthResponse, String> {
+ let result = desktop_auth_inner(&state, diagnostics.inner()).await;
+ if let Err(message) = &result {
+ let port = state.lock().ok().and_then(|proc| proc.port);
+ diagnostics::record_auth_failure(&diagnostics, "desktop_auth", port, message);
+ }
+ result
+}
+
+async fn desktop_auth_inner(
+ state: &tauri::State<'_, BackendState>,
+ diagnostics: &DiagnosticsState,
) -> Result<DesktopAuthResponse, String> {
let _auth_guard = DESKTOP_AUTH_LOCK.lock().await;
- let mut backend = current_backend_port(&state).await?;
+ let mut backend = current_backend_port(state).await?;
+ if backend.source == PortSource::Discovered {
+ diagnostics::record_attached_external_backend(diagnostics, backend.port);
+ }
let client = Client::builder()
.timeout(std::time::Duration::from_secs(5))
.build()
@@ -263,8 +315,11 @@ pub async fn desktop_auth(
info!("Desktop auth: exchanging desktop secret");
let (tokens, resolved_backend) =
- authenticate_with_stale_port_retry(&client, &state, backend, &secret).await?;
+ authenticate_with_stale_port_retry(&client, state, backend, &secret).await?;
backend = resolved_backend;
+ if backend.source == PortSource::Discovered {
+ diagnostics::record_attached_external_backend(diagnostics, backend.port);
+ }
if let Some(tokens) = tokens {
return Ok(tokens);
}
@@ -317,11 +372,15 @@ mod tests {
}
#[test]
- fn retry_discovery_only_for_cached_connectivity_errors() {
+ fn retry_discovery_only_for_cached_recoverable_errors() {
assert!(should_retry_with_discovered_port(
PortSource::Cached,
&AuthError::Connectivity("connection refused".to_string())
));
+ assert!(should_retry_with_discovered_port(
+ PortSource::Cached,
+ &AuthError::StaleResponder("old responder".to_string())
+ ));
assert!(!should_retry_with_discovered_port(
PortSource::Discovered,
&AuthError::Connectivity("connection refused".to_string())
@@ -332,6 +391,64 @@ mod tests {
));
}
+ #[test]
+ fn read_secret_returns_none_for_missing_file() {
+ let path = std::env::temp_dir().join(format!(
+ "unsloth-missing-desktop-secret-{}",
+ std::process::id()
+ ));
+ let _ = std::fs::remove_file(&path);
+
+ assert_eq!(read_secret_if_exists(&path).unwrap(), None);
+ }
+
+ #[test]
+ fn read_secret_trims_existing_file() {
+ let path =
+ std::env::temp_dir().join(format!("unsloth-desktop-secret-{}", std::process::id()));
+ std::fs::write(&path, " desktop-secret\n").unwrap();
+
+ assert_eq!(
+ read_secret_if_exists(&path).unwrap(),
+ Some("desktop-secret".to_string())
+ );
+ std::fs::remove_file(path).unwrap();
+ }
+
+ #[test]
+ fn read_secret_treats_invalid_utf8_as_missing_for_repair() {
+ let path = std::env::temp_dir().join(format!(
+ "unsloth-invalid-desktop-secret-{}",
+ std::process::id()
+ ));
+ std::fs::write(&path, [0xff, 0xfe]).unwrap();
+
+ assert_eq!(read_secret_if_exists(&path).unwrap(), None);
+ std::fs::remove_file(path).unwrap();
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn read_secret_treats_permission_denied_as_missing_for_repair() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let path = std::env::temp_dir().join(format!(
+ "unsloth-unreadable-desktop-secret-{}",
+ std::process::id()
+ ));
+ std::fs::write(&path, "desktop-stale").unwrap();
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap();
+
+ let result = read_secret_if_exists(&path);
+
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
+ std::fs::remove_file(path).unwrap();
+ if matches!(result, Ok(Some(_))) {
+ return;
+ }
+ assert_eq!(result.unwrap(), None);
+ }
+
#[test]
fn attached_ready_port_requires_attached_ready_with_port() {
let compatible = DesktopPreflightResult {
diff --git a/studio/src-tauri/src/diagnostics/mod.rs b/studio/src-tauri/src/diagnostics/mod.rs
new file mode 100644
index 00000000000..5ab940af38a
--- /dev/null
+++ b/studio/src-tauri/src/diagnostics/mod.rs
@@ -0,0 +1,169 @@
+mod phase_log;
+mod redaction;
+mod report;
+mod state;
+
+use crate::process::BackendState;
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+use tauri::AppHandle;
+
+pub use phase_log::append_phase_line;
+#[cfg(target_os = "linux")]
+pub use phase_log::PhaseLogHandle;
+pub use state::{
+ begin_backend_session, begin_install_attempt, begin_repair_child, begin_repair_group,
+ begin_update_attempt, finish_attempt, finish_repair_group, new_diagnostics_state,
+ record_attached_external_backend, record_auth_failure, record_backend_exit,
+ record_backend_intentional_stop, record_backend_port, record_backend_start_failure,
+ record_backend_watchdog, record_diag_marker, record_elevation_packages, record_preflight,
+ record_progress, record_step, AttemptLog, BackendLog, DiagnosticsState,
+ FrontendSupportSnapshot,
+};
+
+pub const SCHEMA_VERSION: u32 = 1;
+pub const PHASE_LOG_SEGMENT_MAX_BYTES: u64 = 5 * 1024 * 1024;
+pub const PHASE_LOG_MAX_SEGMENTS_PER_GROUP: usize = 3;
+#[allow(dead_code)]
+pub const PHASE_LOG_KEEP_GROUPS_PER_KIND: usize = 5;
+pub const TAIL_MAX_LINES: usize = 1000;
+pub const TAIL_MAX_BYTES: usize = 200 * 1024;
+pub const REPORT_MAX_BYTES: usize = 1024 * 1024;
+
+pub(crate) const MAX_STATE_ITEMS: usize = 200;
+pub(crate) const MAX_PHASE_LINE_BYTES: usize = 16 * 1024;
+pub(crate) const FOOTER_BUDGET_BYTES: usize = 8 * 1024;
+
+static ID_COUNTER: AtomicU64 = AtomicU64::new(1);
+
+pub(crate) fn now_ms() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_else(|_| Duration::from_secs(0))
+ .as_millis() as u64
+}
+
+pub(crate) fn new_id(prefix: &str) -> String {
+ let n = ID_COUNTER.fetch_add(1, Ordering::Relaxed);
+ format!("{}-{}-{}", sanitize_component(prefix), now_ms(), n)
+}
+
+pub fn studio_dir() -> PathBuf {
+ dirs::home_dir()
+ .unwrap_or_else(|| PathBuf::from("."))
+ .join(".unsloth")
+ .join("studio")
+}
+
+pub fn logs_dir() -> PathBuf {
+ studio_dir().join("logs")
+}
+
+pub(crate) fn cap_string(value: &str, max: usize) -> String {
+ if value.len() <= max {
+ return value.to_string();
+ }
+ let boundary = valid_utf8_boundary(value, max);
+ format!("{} [truncated]", &value[..boundary])
+}
+
+pub(crate) fn valid_utf8_boundary(s: &str, max: usize) -> usize {
+ if max >= s.len() {
+ return s.len();
+ }
+ let mut index = max;
+ while index > 0 && !s.is_char_boundary(index) {
+ index -= 1;
+ }
+ index
+}
+
+pub(crate) fn sanitize_component(value: &str) -> String {
+ value
+ .chars()
+ .map(|ch| {
+ if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == '.' {
+ ch
+ } else {
+ '_'
+ }
+ })
+ .collect()
+}
+
+#[tauri::command]
+pub async fn collect_support_diagnostics(
+ _app: AppHandle,
+ diagnostics: tauri::State<'_, DiagnosticsState>,
+ backend: tauri::State<'_, BackendState>,
+ snapshot: FrontendSupportSnapshot,
+) -> Result<String, String> {
+ let diagnostics_snapshot = state::clone_snapshot(diagnostics.inner());
+ let backend_port = backend.lock().ok().and_then(|proc| proc.port).or_else(|| {
+ diagnostics_snapshot
+ .backend
+ .as_ref()
+ .and_then(|backend| backend.reported_port.or(backend.requested_port))
+ });
+
+ let health = match backend_port {
+ Some(port) => Some(collect_backend_health(port).await),
+ None => None,
+ };
+
+ match tokio::task::spawn_blocking(move || {
+ report::render_report(diagnostics_snapshot, snapshot, health)
+ })
+ .await
+ {
+ Ok(report) => Ok(report),
+ Err(error) => Ok(format!(
+ "DEGRADED RUST DIAGNOSTICS\ncollection_warning=report task failed: {error}\n"
+ )),
+ }
+}
+
+async fn collect_backend_health(port: u16) -> report::BackendHealthSection {
+ let mut section = report::BackendHealthSection {
+ port,
+ fields: Vec::new(),
+ warning: None,
+ };
+ let client = match reqwest::Client::builder()
+ .timeout(Duration::from_millis(750))
+ .build()
+ {
+ Ok(client) => client,
+ Err(error) => {
+ section.warning = Some(format!("health client unavailable: {error}"));
+ return section;
+ }
+ };
+ let url = format!("http://127.0.0.1:{port}/api/health");
+ match client.get(url).send().await {
+ Ok(response) => match response.json::<serde_json::Value>().await {
+ Ok(json) => {
+ for key in [
+ "status",
+ "service",
+ "version",
+ "device_type",
+ "chat_only",
+ "desktop_protocol_version",
+ "supports_api_only",
+ "supports_desktop_auth",
+ ] {
+ if let Some(value) = json.get(key) {
+ section
+ .fields
+ .push((key.to_string(), report::selected_json_value(value)));
+ }
+ }
+ }
+ Err(error) => section.warning = Some(format!("health json unavailable: {error}")),
+ },
+ Err(error) => section.warning = Some(format!("health request unavailable: {error}")),
+ }
+ section
+}
diff --git a/studio/src-tauri/src/diagnostics/phase_log.rs b/studio/src-tauri/src/diagnostics/phase_log.rs
new file mode 100644
index 00000000000..a1e0c5424c0
--- /dev/null
+++ b/studio/src-tauri/src/diagnostics/phase_log.rs
@@ -0,0 +1,823 @@
+use log::warn;
+use std::collections::{BTreeMap, HashMap};
+use std::fs::{self, File, OpenOptions};
+use std::io::{Read, Write};
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
+use std::time::UNIX_EPOCH;
+
+use super::state::{
+ forget_segment_path, record_segment_path, DiagnosticsSnapshot, DiagnosticsState,
+};
+use super::{
+ logs_dir, now_ms, sanitize_component, valid_utf8_boundary, MAX_PHASE_LINE_BYTES,
+ PHASE_LOG_KEEP_GROUPS_PER_KIND, PHASE_LOG_MAX_SEGMENTS_PER_GROUP, PHASE_LOG_SEGMENT_MAX_BYTES,
+ SCHEMA_VERSION,
+};
+
+pub type PhaseLogHandle = Arc<Mutex<PhaseLogWriter>>;
+
+#[derive(Clone, Debug)]
+pub(crate) enum SegmentOwner {
+ Install {
+ attempt_id: String,
+ },
+ Update {
+ attempt_id: String,
+ },
+ Repair {
+ repair_group_id: String,
+ attempt_id: String,
+ child_type: String,
+ },
+ Backend {
+ session_id: String,
+ },
+}
+
+pub struct PhaseLogWriter {
+ owner: SegmentOwner,
+ flow: String,
+ started_at_ms: u64,
+ backend_kind: Option<String>,
+ log_dir: PathBuf,
+ segment_index: usize,
+ current_bytes: u64,
+ segments: Vec<PathBuf>,
+ file: Option<File>,
+ disabled: bool,
+ disable_reason: Option<String>,
+ diagnostics: DiagnosticsState,
+ max_bytes: u64,
+ max_segments: usize,
+}
+
+impl PhaseLogWriter {
+ pub(crate) fn new(
+ diagnostics: DiagnosticsState,
+ owner: SegmentOwner,
+ flow: impl Into<String>,
+ started_at_ms: u64,
+ backend_kind: Option<String>,
+ ) -> Self {
+ let mut writer = Self {
+ owner,
+ flow: flow.into(),
+ started_at_ms,
+ backend_kind,
+ log_dir: logs_dir(),
+ segment_index: 1,
+ current_bytes: 0,
+ segments: Vec::new(),
+ file: None,
+ disabled: false,
+ disable_reason: None,
+ diagnostics,
+ max_bytes: PHASE_LOG_SEGMENT_MAX_BYTES,
+ max_segments: PHASE_LOG_MAX_SEGMENTS_PER_GROUP,
+ };
+ writer.open_segment();
+ writer
+ }
+
+ #[cfg(test)]
+ fn new_for_test(
+ diagnostics: DiagnosticsState,
+ owner: SegmentOwner,
+ flow: impl Into<String>,
+ started_at_ms: u64,
+ log_dir: PathBuf,
+ max_bytes: u64,
+ max_segments: usize,
+ ) -> Self {
+ let mut writer = Self {
+ owner,
+ flow: flow.into(),
+ started_at_ms,
+ backend_kind: None,
+ log_dir,
+ segment_index: 1,
+ current_bytes: 0,
+ segments: Vec::new(),
+ file: None,
+ disabled: false,
+ disable_reason: None,
+ diagnostics,
+ max_bytes,
+ max_segments,
+ };
+ writer.open_segment();
+ writer
+ }
+
+ fn open_segment(&mut self) {
+ if self.disabled {
+ return;
+ }
+ if let Err(error) = ensure_logs_dir_at(&self.log_dir) {
+ self.disable(format!("failed to create diagnostics log dir: {error}"));
+ return;
+ }
+ if self.segment_index == 1 {
+ cleanup_retention(&self.log_dir, &self.flow, &owner_group_key(&self.owner));
+ }
+
+ let path = self.segment_path(self.segment_index);
+ if path_has_symlink(&path) {
+ self.disable(format!(
+ "refusing to write diagnostics phase log through symlink: {}",
+ path.display()
+ ));
+ return;
+ }
+
+ let mut options = OpenOptions::new();
+ options.create(true).append(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+
+ match options.open(&path) {
+ Ok(mut file) => {
+ let header = self.header();
+ if let Err(error) = file.write_all(header.as_bytes()) {
+ self.disable(format!(
+ "failed to write diagnostics phase log header to {}: {error}",
+ path.display()
+ ));
+ return;
+ }
+ self.current_bytes = header.len() as u64;
+ self.segments.push(path.clone());
+ self.file = Some(file);
+ record_segment_path(&self.diagnostics, &self.owner, path);
+ }
+ Err(error) => self.disable(format!(
+ "failed to open diagnostics phase log {}: {error}",
+ path.display()
+ )),
+ }
+ }
+
+ fn header(&self) -> String {
+ let mut lines = vec![
+ "# Unsloth Studio diagnostics phase log".to_string(),
+ format!("diag_schema={SCHEMA_VERSION}"),
+ format!("flow={}", self.flow),
+ format!("segment_index={}", self.segment_index),
+ format!("started_at_ms={}", self.started_at_ms),
+ ];
+ match &self.owner {
+ SegmentOwner::Install { attempt_id }
+ | SegmentOwner::Update { attempt_id }
+ | SegmentOwner::Repair { attempt_id, .. } => {
+ lines.push(format!("attempt_id={attempt_id}"));
+ }
+ SegmentOwner::Backend { session_id } => {
+ lines.push(format!("attempt_id={session_id}"));
+ lines.push(format!("backend_session_id={session_id}"));
+ }
+ }
+ if let SegmentOwner::Repair {
+ repair_group_id,
+ child_type,
+ ..
+ } = &self.owner
+ {
+ lines.push(format!("repair_group_id={repair_group_id}"));
+ lines.push(format!("child_type={child_type}"));
+ }
+ if let Some(kind) = &self.backend_kind {
+ lines.push(format!("backend_kind={kind}"));
+ }
+ lines.push("--- log ---".to_string());
+ lines.push(String::new());
+ lines.join("\n")
+ }
+
+ fn segment_path(&self, segment_index: usize) -> PathBuf {
+ let name = match &self.owner {
+ SegmentOwner::Install { attempt_id } => {
+ format!(
+ "install-{}-s{segment_index:02}.log",
+ sanitize_component(attempt_id)
+ )
+ }
+ SegmentOwner::Update { attempt_id } => {
+ format!(
+ "update-{}-s{segment_index:02}.log",
+ sanitize_component(attempt_id)
+ )
+ }
+ SegmentOwner::Repair {
+ repair_group_id,
+ attempt_id,
+ child_type,
+ } => format!(
+ "repair-{}-{}-{}-s{segment_index:02}.log",
+ sanitize_component(repair_group_id),
+ sanitize_component(child_type),
+ sanitize_component(attempt_id)
+ ),
+ SegmentOwner::Backend { session_id } => {
+ format!(
+ "backend-{}-s{segment_index:02}.log",
+ sanitize_component(session_id)
+ )
+ }
+ };
+ self.log_dir.join(name)
+ }
+
+ fn append_line(&mut self, stream: &str, text: &str) {
+ if self.disabled {
+ return;
+ }
+ let mut line = text.replace('\r', "");
+ let mut truncated = false;
+ if line.len() > MAX_PHASE_LINE_BYTES {
+ line.truncate(valid_utf8_boundary(&line, MAX_PHASE_LINE_BYTES));
+ truncated = true;
+ }
+ if truncated {
+ line.push_str(" [line truncated]");
+ }
+ let entry = format!("[{}][{}] {}\n", now_ms(), stream, line);
+ if self.current_bytes + entry.len() as u64 > self.max_bytes {
+ self.rotate();
+ }
+ let Some(file) = self.file.as_mut() else {
+ return;
+ };
+ match file.write_all(entry.as_bytes()) {
+ Ok(()) => {
+ self.current_bytes += entry.len() as u64;
+ }
+ Err(error) => self.disable(format!("diagnostics phase log write failed: {error}")),
+ }
+ }
+
+ fn rotate(&mut self) {
+ self.file.take();
+ self.segment_index += 1;
+ self.current_bytes = 0;
+ self.open_segment();
+ self.prune_old_segments();
+ }
+
+ fn prune_old_segments(&mut self) {
+ while self.segments.len() > self.max_segments {
+ let old_path = self.segments.remove(0);
+ forget_segment_path(&self.diagnostics, &self.owner, &old_path);
+ safe_delete_phase_log(&self.log_dir, &old_path);
+ }
+ }
+
+ fn disable(&mut self, reason: String) {
+ if !self.disabled {
+ warn!("{}", reason);
+ }
+ self.disabled = true;
+ self.disable_reason = Some(reason);
+ self.file.take();
+ }
+}
+
+#[allow(dead_code)]
+pub fn ensure_logs_dir() -> std::io::Result<PathBuf> {
+ let dir = logs_dir();
+ ensure_logs_dir_at(&dir)?;
+ Ok(dir)
+}
+
+pub(crate) fn ensure_logs_dir_at(dir: &Path) -> std::io::Result<()> {
+ fs::create_dir_all(dir)?;
+ if fs::symlink_metadata(dir)
+ .map(|metadata| metadata.file_type().is_symlink())
+ .unwrap_or(false)
+ {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::Other,
+ "refusing diagnostics logs dir symlink",
+ ));
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = fs::set_permissions(dir, fs::Permissions::from_mode(0o700));
+ }
+ Ok(())
+}
+
+pub fn append_phase_line(handle: &PhaseLogHandle, stream: &str, text: &str) {
+ if let Ok(mut writer) = handle.lock() {
+ writer.append_line(stream, text);
+ }
+}
+#[derive(Debug)]
+pub(crate) struct PhaseGroup {
+ pub(crate) label: String,
+ pub(crate) source: String,
+ pub(crate) paths: Vec<PathBuf>,
+ pub(crate) note: Option<String>,
+}
+
+pub(crate) fn collect_phase_groups(
+ snapshot: &DiagnosticsSnapshot,
+ warnings: &mut Vec<String>,
+) -> Vec<PhaseGroup> {
+ let mut groups = Vec::new();
+ for install in snapshot.install_history.iter().rev().take(4).rev() {
+ if !install.log_segments.is_empty() {
+ groups.push(PhaseGroup {
+ label: format!("install:{}", install.attempt_id),
+ source: "live-state-history".to_string(),
+ paths: install.log_segments.clone(),
+ note: Some("previous linked install attempt retained in memory".to_string()),
+ });
+ }
+ }
+ if let Some(install) = &snapshot.install {
+ if !install.log_segments.is_empty() {
+ groups.push(PhaseGroup {
+ label: format!("install:{}", install.attempt_id),
+ source: "live-state".to_string(),
+ paths: install.log_segments.clone(),
+ note: None,
+ });
+ }
+ }
+ if let Some(update) = &snapshot.update {
+ if !update.log_segments.is_empty() {
+ groups.push(PhaseGroup {
+ label: format!("update:{}", update.attempt_id),
+ source: "live-state".to_string(),
+ paths: update.log_segments.clone(),
+ note: None,
+ });
+ }
+ }
+ for group in snapshot.repair_groups.iter().rev().take(5).rev() {
+ let mut paths = Vec::new();
+ for child in &group.children {
+ paths.extend(child.log_segments.clone());
+ }
+ if !paths.is_empty() {
+ groups.push(PhaseGroup {
+ label: format!("repair:{}", group.repair_group_id),
+ source: "live-state".to_string(),
+ paths,
+ note: None,
+ });
+ }
+ }
+ if let Some(backend) = &snapshot.backend {
+ if backend.backend_kind == "managed" && !backend.log_segments.is_empty() {
+ groups.push(PhaseGroup {
+ label: backend
+ .session_id
+ .as_ref()
+ .map(|id| format!("backend:{id}"))
+ .unwrap_or_else(|| "backend:unknown".to_string()),
+ source: "live-state".to_string(),
+ paths: backend.log_segments.clone(),
+ note: None,
+ });
+ } else if backend.backend_kind == "attached_external" {
+ groups.push(PhaseGroup {
+ label: "backend:attached_external".to_string(),
+ source: "live-state".to_string(),
+ paths: Vec::new(),
+ note: Some("Tauri does not own attached/external backend process logs".to_string()),
+ });
+ }
+ }
+
+ let has_install = groups.iter().any(|g| g.label.starts_with("install:"));
+ let has_update = groups.iter().any(|g| g.label.starts_with("update:"));
+ let has_repair = groups.iter().any(|g| g.label.starts_with("repair:"));
+ let has_backend = groups.iter().any(|g| g.label.starts_with("backend:"));
+ let fallback = scan_phase_logs(warnings);
+ for flow in ["install", "update", "repair", "backend"] {
+ let already_live = match flow {
+ "install" => has_install,
+ "update" => has_update,
+ "repair" => has_repair,
+ "backend" => has_backend,
+ _ => false,
+ };
+ if already_live {
+ continue;
+ }
+ if let Some(group) = latest_disk_group(&fallback, flow) {
+ groups.push(group);
+ }
+ }
+
+ groups
+}
+
+#[derive(Clone, Debug)]
+struct PhaseLogMeta {
+ path: PathBuf,
+ flow: String,
+ group_key: String,
+ segment_index: usize,
+ started_at_ms: u64,
+ mtime_ms: u64,
+}
+
+fn scan_phase_logs(warnings: &mut Vec<String>) -> Vec<PhaseLogMeta> {
+ scan_phase_logs_in_dir(&logs_dir(), warnings)
+}
+
+fn scan_phase_logs_in_dir(dir: &Path, warnings: &mut Vec<String>) -> Vec<PhaseLogMeta> {
+ let entries = match fs::read_dir(dir) {
+ Ok(entries) => entries,
+ Err(error) => {
+ warnings.push(format!("phase log dir unavailable: {error}"));
+ return Vec::new();
+ }
+ };
+ let mut metas = Vec::new();
+ for entry in entries.flatten() {
+ let path = entry.path();
+ let Some(file_name) = path.file_name().and_then(|n| n.to_str()) else {
+ continue;
+ };
+ if !is_phase_log_name(file_name) {
+ continue;
+ }
+ if path_has_symlink(&path) {
+ warnings.push(format!("ignored phase log symlink: {}", path.display()));
+ continue;
+ }
+ match parse_phase_log_meta(&path, file_name) {
+ Some(meta) => metas.push(meta),
+ None => warnings.push(format!(
+ "could not reconstruct phase log metadata: {}",
+ path.display()
+ )),
+ }
+ }
+ metas
+}
+
+fn safe_delete_phase_log(log_dir: &Path, path: &Path) {
+ if path_has_symlink(path) {
+ return;
+ }
+ let Ok(canonical_dir) = log_dir.canonicalize() else {
+ return;
+ };
+ let Ok(parent) = path.parent().unwrap_or(log_dir).canonicalize() else {
+ return;
+ };
+ if parent != canonical_dir {
+ return;
+ }
+ let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
+ return;
+ };
+ if !is_phase_log_name(name) {
+ return;
+ }
+ let _ = fs::remove_file(path);
+}
+
+fn cleanup_retention(dir: &Path, flow: &str, current_group_key: &str) {
+ let canonical_dir = match dir.canonicalize() {
+ Ok(path) => path,
+ Err(_) => return,
+ };
+ let mut warnings = Vec::new();
+ let metas = scan_phase_logs_in_dir(dir, &mut warnings);
+ let mut groups: BTreeMap<String, Vec<PhaseLogMeta>> = BTreeMap::new();
+ for meta in metas.into_iter().filter(|meta| meta.flow == flow) {
+ groups.entry(meta.group_key.clone()).or_default().push(meta);
+ }
+ let mut ordered: Vec<(String, u64)> = groups
+ .iter()
+ .map(|(key, items)| {
+ let newest = items
+ .iter()
+ .map(|meta| meta.started_at_ms.max(meta.mtime_ms))
+ .max()
+ .unwrap_or(0);
+ (key.clone(), newest)
+ })
+ .collect();
+ ordered.sort_by_key(|(_, newest)| *newest);
+ let removable = ordered.len().saturating_sub(PHASE_LOG_KEEP_GROUPS_PER_KIND);
+ for (group_key, _) in ordered.into_iter().take(removable) {
+ if group_key == current_group_key {
+ continue;
+ }
+ let Some(items) = groups.get(&group_key) else {
+ continue;
+ };
+ for meta in items {
+ let Ok(parent) = meta.path.parent().unwrap_or(dir).canonicalize() else {
+ continue;
+ };
+ if parent != canonical_dir {
+ continue;
+ }
+ safe_delete_phase_log(dir, &meta.path);
+ }
+ }
+}
+
+fn owner_group_key(owner: &SegmentOwner) -> String {
+ match owner {
+ SegmentOwner::Install { attempt_id } => format!("install:{attempt_id}"),
+ SegmentOwner::Update { attempt_id } => format!("update:{attempt_id}"),
+ SegmentOwner::Repair {
+ repair_group_id, ..
+ } => format!("repair:{repair_group_id}"),
+ SegmentOwner::Backend { session_id } => format!("backend:{session_id}"),
+ }
+}
+
+fn parse_phase_log_meta(path: &Path, file_name: &str) -> Option<PhaseLogMeta> {
+ let mut file = File::open(path).ok()?;
+ let mut buf = vec![0u8; 8192];
+ let read = file.read(&mut buf).ok()?;
+ buf.truncate(read);
+ let header = String::from_utf8_lossy(&buf);
+ let mut map = HashMap::new();
+ for line in header.lines().take(32) {
+ if line == "--- log ---" {
+ break;
+ }
+ if let Some((key, value)) = line.split_once('=') {
+ map.insert(key.trim().to_string(), value.trim().to_string());
+ }
+ }
+
+ let flow = map
+ .get("flow")
+ .cloned()
+ .or_else(|| file_name.split('-').next().map(str::to_string))?;
+ let segment_index = map
+ .get("segment_index")
+ .and_then(|v| v.parse::<usize>().ok())
+ .or_else(|| segment_from_filename(file_name))
+ .unwrap_or(1);
+ let started_at_ms = map
+ .get("started_at_ms")
+ .and_then(|v| v.parse::<u64>().ok())
+ .unwrap_or_else(|| file_mtime_ms(path).unwrap_or(0));
+ let mtime_ms = file_mtime_ms(path).unwrap_or(started_at_ms);
+ let group_key = if flow == "repair" {
+ map.get("repair_group_id")
+ .cloned()
+ .or_else(|| repair_group_from_filename(file_name))
+ .map(|id| format!("repair:{id}"))?
+ } else if flow == "backend" {
+ map.get("backend_session_id")
+ .or_else(|| map.get("attempt_id"))
+ .cloned()
+ .or_else(|| attempt_from_filename(file_name, "backend"))
+ .map(|id| format!("backend:{id}"))?
+ } else {
+ map.get("attempt_id")
+ .cloned()
+ .or_else(|| attempt_from_filename(file_name, &flow))
+ .map(|id| format!("{flow}:{id}"))?
+ };
+
+ Some(PhaseLogMeta {
+ path: path.to_path_buf(),
+ flow,
+ group_key,
+ segment_index,
+ started_at_ms,
+ mtime_ms,
+ })
+}
+
+fn latest_disk_group(metas: &[PhaseLogMeta], flow: &str) -> Option<PhaseGroup> {
+ let mut groups: BTreeMap<String, Vec<PhaseLogMeta>> = BTreeMap::new();
+ for meta in metas.iter().filter(|m| m.flow == flow) {
+ groups
+ .entry(meta.group_key.clone())
+ .or_default()
+ .push(meta.clone());
+ }
+ let (_, mut selected) = groups
+ .into_iter()
+ .max_by_key(|(_, items)| items.iter().map(|m| (m.started_at_ms, m.mtime_ms)).max())?;
+ selected.sort_by_key(|m| (m.started_at_ms, m.segment_index, m.path.clone()));
+ let label = selected
+ .first()
+ .map(|m| m.group_key.clone())
+ .unwrap_or_else(|| format!("{flow}:unknown"));
+ Some(PhaseGroup {
+ label,
+ source: "disk-fallback".to_string(),
+ paths: selected.into_iter().map(|m| m.path).collect(),
+ note: Some("reconstructed from phase-log headers/filenames".to_string()),
+ })
+}
+
+pub(crate) fn path_has_symlink(path: &Path) -> bool {
+ fs::symlink_metadata(path)
+ .map(|metadata| metadata.file_type().is_symlink())
+ .unwrap_or(false)
+}
+
+fn file_mtime_ms(path: &Path) -> Option<u64> {
+ fs::metadata(path)
+ .ok()?
+ .modified()
+ .ok()?
+ .duration_since(UNIX_EPOCH)
+ .ok()
+ .map(|d| d.as_millis() as u64)
+}
+
+fn is_phase_log_name(name: &str) -> bool {
+ name.ends_with(".log")
+ && (name.starts_with("install-")
+ || name.starts_with("update-")
+ || name.starts_with("repair-")
+ || name.starts_with("backend-"))
+}
+
+fn segment_from_filename(name: &str) -> Option<usize> {
+ let stem = name.strip_suffix(".log")?;
+ let segment = stem.rsplit_once("-s")?.1;
+ segment.parse::<usize>().ok()
+}
+
+fn attempt_from_filename(name: &str, flow: &str) -> Option<String> {
+ let stem = name.strip_suffix(".log")?;
+ let rest = stem.strip_prefix(&format!("{flow}-"))?;
+ let (attempt, _) = rest.rsplit_once("-s")?;
+ Some(attempt.to_string())
+}
+
+fn repair_group_from_filename(name: &str) -> Option<String> {
+ let stem = name.strip_suffix(".log")?;
+ let rest = stem.strip_prefix("repair-")?;
+ let (before_segment, _) = rest.rsplit_once("-s")?;
+
+ // New repair filenames include both child type and attempt id:
+ // repair-<repair_group_id>-<child_type>-<attempt_id>-sNN.log.
+ // Repair/attempt ids contain hyphens, so split on the deterministic
+ // child/attempt prefix pair emitted by SegmentOwner::Repair.
+ for child_type in [
+ "update",
+ "install",
+ "elevation",
+ "resume",
+ "resume_update",
+ "resume_install",
+ ] {
+ let marker = format!("-{child_type}-{child_type}-");
+ if let Some((group, _)) = before_segment.split_once(&marker) {
+ return Some(group.to_string());
+ }
+ }
+
+ // Backward-compatible fallback for the older repair-<group>-<child>-sNN form.
+ let (group, _) = before_segment.rsplit_once('-')?;
+ Some(group.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::diagnostics::state::{clone_snapshot, with_snapshot, AttemptSummary};
+ use crate::diagnostics::{new_diagnostics_state, now_ms};
+
+ #[test]
+ fn phase_writer_keeps_latest_segments_and_terminal_lines() {
+ let dir = std::env::temp_dir().join(format!(
+ "unsloth-phase-writer-{}-{}",
+ std::process::id(),
+ now_ms()
+ ));
+ let diagnostics = new_diagnostics_state();
+ let attempt_id = "install-test".to_string();
+ with_snapshot(&diagnostics, |snapshot| {
+ snapshot.install = Some(AttemptSummary::new(
+ "install",
+ attempt_id.clone(),
+ None,
+ None,
+ now_ms(),
+ ));
+ });
+ let mut writer = PhaseLogWriter::new_for_test(
+ diagnostics.clone(),
+ SegmentOwner::Install {
+ attempt_id: attempt_id.clone(),
+ },
+ "install",
+ now_ms(),
+ dir.clone(),
+ 128,
+ 2,
+ );
+ for i in 0..100 {
+ writer.append_line("stdout", &format!("chunk {i}"));
+ }
+ writer.append_line("stdout", "terminal failure survives");
+ let snapshot = clone_snapshot(&diagnostics);
+ let segments = snapshot.install.unwrap().log_segments;
+ assert_eq!(segments.len(), 2);
+ let total_size: u64 = segments
+ .iter()
+ .map(|path| fs::metadata(path).unwrap().len())
+ .sum();
+ assert!(total_size < 1024);
+ assert!(segments.iter().any(|path| {
+ fs::read_to_string(path)
+ .map(|text| text.contains("terminal failure survives"))
+ .unwrap_or(false)
+ }));
+ assert!(!dir.join("install-install-test-s01.log").exists());
+ let _ = fs::remove_dir_all(dir);
+ }
+
+ #[test]
+ fn repair_group_filename_fallback_handles_attempt_id_suffix() {
+ let filename = "repair-repair-123-4-install-install-567-8-s01.log";
+ assert_eq!(
+ repair_group_from_filename(filename),
+ Some("repair-123-4".to_string())
+ );
+ }
+
+ #[test]
+ fn repair_children_with_same_type_get_unique_segment_paths() {
+ let dir = std::env::temp_dir().join(format!(
+ "unsloth-repair-paths-{}-{}",
+ std::process::id(),
+ now_ms()
+ ));
+ let diagnostics = new_diagnostics_state();
+ let first = PhaseLogWriter::new_for_test(
+ diagnostics.clone(),
+ SegmentOwner::Repair {
+ repair_group_id: "repair-group".to_string(),
+ attempt_id: "attempt-one".to_string(),
+ child_type: "install".to_string(),
+ },
+ "repair",
+ now_ms(),
+ dir.clone(),
+ 1024,
+ 2,
+ );
+ let second = PhaseLogWriter::new_for_test(
+ diagnostics,
+ SegmentOwner::Repair {
+ repair_group_id: "repair-group".to_string(),
+ attempt_id: "attempt-two".to_string(),
+ child_type: "install".to_string(),
+ },
+ "repair",
+ now_ms(),
+ dir.clone(),
+ 1024,
+ 2,
+ );
+
+ assert_ne!(first.segment_path(1), second.segment_path(1));
+ let _ = fs::remove_dir_all(dir);
+ }
+
+ #[test]
+ fn parses_latest_disk_group_by_metadata_not_mtime_only() {
+ let dir = std::env::temp_dir().join(format!(
+ "unsloth-phase-parse-{}-{}",
+ std::process::id(),
+ now_ms()
+ ));
+ fs::create_dir_all(&dir).unwrap();
+ let old = dir.join("install-old-s01.log");
+ let new = dir.join("install-new-s01.log");
+ fs::write(
+ &old,
+ "diag_schema=1\nflow=install\nattempt_id=old\nsegment_index=1\nstarted_at_ms=1\n--- log ---\nold\n",
+ )
+ .unwrap();
+ fs::write(
+ &new,
+ "diag_schema=1\nflow=install\nattempt_id=new\nsegment_index=1\nstarted_at_ms=2\n--- log ---\nnew\n",
+ )
+ .unwrap();
+ let metas = vec![
+ parse_phase_log_meta(&old, "install-old-s01.log").unwrap(),
+ parse_phase_log_meta(&new, "install-new-s01.log").unwrap(),
+ ];
+ let group = latest_disk_group(&metas, "install").unwrap();
+ assert_eq!(group.label, "install:new");
+ let _ = fs::remove_dir_all(dir);
+ }
+}
diff --git a/studio/src-tauri/src/diagnostics/redaction.rs b/studio/src-tauri/src/diagnostics/redaction.rs
new file mode 100644
index 00000000000..5c5589a4943
--- /dev/null
+++ b/studio/src-tauri/src/diagnostics/redaction.rs
@@ -0,0 +1,198 @@
+use regex::Regex;
+use std::path::Path;
+use std::sync::OnceLock;
+
+use super::studio_dir;
+
+#[derive(Default, Debug)]
+pub(crate) struct RedactionReport {
+ pub(crate) replacements: usize,
+}
+
+pub(crate) fn redact_text(text: &str, report: &mut RedactionReport) -> String {
+ let mut out = ansi_re().replace_all(text, "").to_string();
+ if out.len() != text.len() {
+ report.replacements += 1;
+ }
+ out = replace_regex(private_key_re(), &out, "<redacted private key>", report);
+ out = replace_regex(url_credentials_re(), &out, "$1<redacted>@", report);
+ out = replace_regex(auth_header_re(), &out, "$1: <redacted>", report);
+ out = replace_regex(cookie_re(), &out, "$1: <redacted>", report);
+ out = replace_regex(token_re(), &out, "<redacted token>", report);
+ out = replace_regex(env_secret_re(), &out, "$1=<redacted>", report);
+ out = replace_known_paths(&out, report);
+ out = replace_regex(windows_studio_re(), &out, "<studio_home>", report);
+ out = replace_regex(windows_home_re(), &out, "%USERPROFILE%", report);
+ out = replace_regex(unix_studio_re(), &out, "<studio_home>", report);
+ out = replace_regex(unix_home_re(), &out, "$HOME", report);
+ out = replace_regex(email_re(), &out, "<redacted email>", report);
+ out
+}
+
+fn replace_regex(
+ regex: &'static Regex,
+ input: &str,
+ replacement: &str,
+ report: &mut RedactionReport,
+) -> String {
+ let count = regex.find_iter(input).count();
+ if count > 0 {
+ report.replacements += count;
+ regex.replace_all(input, replacement).to_string()
+ } else {
+ input.to_string()
+ }
+}
+
+fn replace_known_paths(input: &str, report: &mut RedactionReport) -> String {
+ let mut out = input.to_string();
+ let studio = studio_dir();
+ out = replace_path_literal(&out, &studio, "<studio_home>", report);
+ if let Some(home) = dirs::home_dir() {
+ out = replace_path_literal(&out, &home, "$HOME", report);
+ }
+ out
+}
+
+fn replace_path_literal(
+ input: &str,
+ path: &Path,
+ replacement: &str,
+ report: &mut RedactionReport,
+) -> String {
+ let path_str = path.display().to_string();
+ let mut out = input.to_string();
+ for needle in path_variants(&path_str) {
+ if needle.is_empty() {
+ continue;
+ }
+ let count = out.matches(&needle).count();
+ if count > 0 {
+ report.replacements += count;
+ out = out.replace(&needle, replacement);
+ }
+ }
+ out
+}
+
+fn path_variants(path: &str) -> Vec<String> {
+ let mut variants = vec![path.to_string()];
+ variants.push(path.replace('/', "\\"));
+ variants.push(path.replace('\\', "/"));
+ variants.sort();
+ variants.dedup();
+ variants
+}
+
+fn ansi_re() -> &'static Regex {
+ static RE: OnceLock<Regex> = OnceLock::new();
+ RE.get_or_init(|| Regex::new(r"\x1b\[[0-9;?]*[ -/]*[@-~]").unwrap())
+}
+
+fn private_key_re() -> &'static Regex {
+ static RE: OnceLock<Regex> = OnceLock::new();
+ RE.get_or_init(|| {
+ Regex::new(
+ r"(?is)-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----.*?-----END [A-Z0-9 ]*PRIVATE KEY-----",
+ )
+ .unwrap()
+ })
+}
+
+fn url_credentials_re() -> &'static Regex {
+ static RE: OnceLock<Regex> = OnceLock::new();
+ RE.get_or_init(|| Regex::new(r"(?i)\b([a-z][a-z0-9+.-]*://)[^/\s:@]+(:[^/\s@]*)?@").unwrap())
+}
+
+fn auth_header_re() -> &'static Regex {
+ static RE: OnceLock<Regex> = OnceLock::new();
+ RE.get_or_init(|| Regex::new(r"(?i)\b(authorization|proxy-authorization)\s*[:=]\s*(bearer|basic)?\s*[A-Za-z0-9._~+/=-]+").unwrap())
+}
+
+fn cookie_re() -> &'static Regex {
+ static RE: OnceLock<Regex> = OnceLock::new();
+ RE.get_or_init(|| Regex::new(r"(?i)\b(cookie|set-cookie)\s*[:=]\s*[^\r\n]+").unwrap())
+}
+
+fn token_re() -> &'static Regex {
+ static RE: OnceLock<Regex> = OnceLock::new();
+ RE.get_or_init(|| Regex::new(r"(?i)\b(hf_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{20,}|ghp_[A-Za-z0-9]{20,}|sk-[A-Za-z0-9]{20,})\b").unwrap())
+}
+
+fn env_secret_re() -> &'static Regex {
+ static RE: OnceLock<Regex> = OnceLock::new();
+ RE.get_or_init(|| {
+ Regex::new(r"(?i)\b((?:[A-Z0-9]+_)*(?:TOKEN|SECRET|PASSWORD|API_KEY|ACCESS_KEY|KEY)(?:_[A-Z0-9]+)*)\s*=\s*[^\s;&]+").unwrap()
+ })
+}
+
+fn windows_studio_re() -> &'static Regex {
+ static RE: OnceLock<Regex> = OnceLock::new();
+ RE.get_or_init(|| {
+ Regex::new(r"(?i)\b[A-Z]:[\\/]Users[\\/][^\\/\r\n\s]+[\\/]\.unsloth[\\/]studio").unwrap()
+ })
+}
+
+fn windows_home_re() -> &'static Regex {
+ static RE: OnceLock<Regex> = OnceLock::new();
+ RE.get_or_init(|| Regex::new(r"(?i)\b[A-Z]:[\\/]Users[\\/][^\\/\r\n\s]+").unwrap())
+}
+
+fn unix_studio_re() -> &'static Regex {
+ static RE: OnceLock<Regex> = OnceLock::new();
+ RE.get_or_init(|| Regex::new(r"(?i)(?:/Users|/home)/[A-Za-z0-9._-]+/\.unsloth/studio").unwrap())
+}
+
+fn unix_home_re() -> &'static Regex {
+ static RE: OnceLock<Regex> = OnceLock::new();
+ RE.get_or_init(|| Regex::new(r"(?i)(?:/Users|/home)/[A-Za-z0-9._-]+").unwrap())
+}
+
+fn email_re() -> &'static Regex {
+ static RE: OnceLock<Regex> = OnceLock::new();
+ RE.get_or_init(|| Regex::new(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b").unwrap())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn redacts_common_secret_and_path_patterns() {
+ let input = concat!(
+ "\u{1b}[31mred\u{1b}[0m\n",
+ "Authorization: Bearer abcdefghijklmnop\n",
+ "Cookie: session=abcdef\n",
+ "HF_TOKEN=hf_abcdefghijklmnopqrstuvwxyz\n",
+ "API_KEY=secret123\n",
+ "url=https://user:[email protected]/path\n",
+ "path=/Users/alex/.unsloth/studio/logs/install.log\n",
+ "win=C:\\Users\\Alex\\.unsloth\\studio\\logs\\install.log\n",
+ "-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----\n"
+ );
+ let mut report = RedactionReport::default();
+ let redacted = redact_text(input, &mut report);
+ assert!(!redacted.contains("\u{1b}"));
+ assert!(!redacted.contains("abcdefghijklmnop"));
+ assert!(!redacted.contains("session=abcdef"));
+ assert!(!redacted.contains("hf_abcdefghijklmnopqrstuvwxyz"));
+ assert!(!redacted.contains("secret123"));
+ assert!(redacted.contains("https://<redacted>@example.com/path"));
+ assert!(!redacted.contains("[email protected]"));
+ assert!(redacted.contains("<studio_home>"));
+ assert!(!redacted.contains("PRIVATE KEY-----\nabc"));
+ }
+
+ #[test]
+ fn redaction_avoids_keyboard_monkey_false_positives() {
+ let input = "keyboard=present monkey=banana MONKEY=banana KEYBOARD=present API_KEY=secret";
+ let mut report = RedactionReport::default();
+ let redacted = redact_text(input, &mut report);
+ assert!(redacted.contains("keyboard=present"));
+ assert!(redacted.contains("monkey=banana"));
+ assert!(redacted.contains("MONKEY=banana"));
+ assert!(redacted.contains("KEYBOARD=present"));
+ assert!(redacted.contains("API_KEY=<redacted>"));
+ }
+}
diff --git a/studio/src-tauri/src/diagnostics/report.rs b/studio/src-tauri/src/diagnostics/report.rs
new file mode 100644
index 00000000000..6301e7face3
--- /dev/null
+++ b/studio/src-tauri/src/diagnostics/report.rs
@@ -0,0 +1,607 @@
+use std::fs::{self, File};
+use std::io::{Read, Seek, SeekFrom};
+use std::path::Path;
+use std::time::UNIX_EPOCH;
+
+use super::phase_log::{collect_phase_groups, path_has_symlink};
+use super::redaction::{redact_text, RedactionReport};
+use super::state::{AttemptSummary, CappedStrings, DiagnosticsSnapshot, FrontendSupportSnapshot};
+use super::{
+ cap_string, logs_dir, now_ms, studio_dir, valid_utf8_boundary, FOOTER_BUDGET_BYTES,
+ MAX_PHASE_LINE_BYTES, REPORT_MAX_BYTES, SCHEMA_VERSION, TAIL_MAX_BYTES, TAIL_MAX_LINES,
+};
+
+#[derive(Clone, Debug)]
+pub(crate) struct BackendHealthSection {
+ pub(crate) port: u16,
+ pub(crate) fields: Vec<(String, String)>,
+ pub(crate) warning: Option<String>,
+}
+
+pub(crate) fn render_report(
+ snapshot: DiagnosticsSnapshot,
+ frontend: FrontendSupportSnapshot,
+ health: Option<BackendHealthSection>,
+) -> String {
+ let mut warnings = Vec::new();
+ let mut raw = String::new();
+
+ raw.push_str("Unsloth Studio Support Diagnostics\n");
+ raw.push_str(&format!("diag_report_schema={SCHEMA_VERSION}\n"));
+ raw.push_str(&format!("created_at_ms={}\n", now_ms()));
+ raw.push_str(&format!("app_version={}\n", env!("CARGO_PKG_VERSION")));
+ raw.push_str(&format!("os={}\n", std::env::consts::OS));
+ raw.push_str(&format!("arch={}\n", std::env::consts::ARCH));
+ raw.push_str(&format!("debug_build={}\n", cfg!(debug_assertions)));
+ raw.push_str(&format!(
+ "appimage={}\n",
+ std::env::var_os("APPIMAGE").is_some()
+ ));
+ raw.push_str(&format!(
+ "cpu_logical_count={}\n",
+ std::thread::available_parallelism()
+ .map(|n| n.get().to_string())
+ .unwrap_or_else(|_| "unavailable".to_string())
+ ));
+ raw.push_str(&format!("studio_dir={}\n", studio_dir().display()));
+ raw.push_str(&format!("logs_dir={}\n", logs_dir().display()));
+ raw.push_str(&format!("app_session_id={}\n", snapshot.app_session_id));
+ raw.push_str(&format!(
+ "app_started_at_ms={}\n",
+ snapshot.app_started_at_ms
+ ));
+ raw.push_str(
+ "disk_budget=5MiB x 3 segments x 5 groups x 4 kinds ~= 300MiB plus tauri.log/.1\n",
+ );
+
+ append_frontend_section(&mut raw, &frontend);
+ append_preflight_section(&mut raw, &snapshot);
+ append_flow_section(&mut raw, &snapshot);
+ append_backend_section(&mut raw, &snapshot, health.as_ref());
+ append_device_signals_section(&mut raw, &snapshot, health.as_ref());
+ append_log_sections(&mut raw, &snapshot, &mut warnings);
+
+ if let Some(health) = &health {
+ if let Some(warning) = &health.warning {
+ warnings.push(format!("backend /api/health unavailable: {warning}"));
+ }
+ }
+
+ let mut redaction = RedactionReport::default();
+ let redacted_body = redact_text(&raw, &mut redaction);
+
+ // Redact collection warnings/footer too. Some warnings include raw local paths
+ // from failed log reads, so the footer must not be appended after redaction.
+ let footer_for_count = render_footer(&warnings, &redaction);
+ let _ = redact_text(&footer_for_count, &mut redaction);
+ let footer = redact_text(
+ &render_footer(&warnings, &redaction),
+ &mut RedactionReport::default(),
+ );
+
+ enforce_report_limit(redacted_body, footer)
+}
+
+fn append_frontend_section(out: &mut String, frontend: &FrontendSupportSnapshot) {
+ out.push_str("\n== Trigger/UI state ==\n");
+ append_opt(out, "status", frontend.status.as_deref());
+ append_opt(out, "error", frontend.error.as_deref());
+ append_opt(
+ out,
+ "current_step_index",
+ frontend
+ .current_step_index
+ .map(|v| v.to_string())
+ .as_deref(),
+ );
+ append_opt(out, "progress_detail", frontend.progress_detail.as_deref());
+ append_opt(out, "flow", frontend.flow.as_deref());
+ append_opt(out, "update_phase", frontend.update_phase.as_deref());
+ let update_progress = frontend.update_progress.as_ref().map(selected_json_value);
+ append_opt(out, "update_progress", update_progress.as_deref());
+ if let Some(packages) = &frontend.elevation_packages {
+ out.push_str(&format!("elevation_packages={}\n", packages.join(", ")));
+ }
+ out.push_str("last_ui_log_tail:\n");
+ match &frontend.last_ui_log_lines {
+ Some(lines) if !lines.is_empty() => {
+ for line in tail_lines(lines, TAIL_MAX_LINES) {
+ out.push_str(" ");
+ out.push_str(line);
+ out.push('\n');
+ }
+ }
+ _ => out.push_str(" unavailable\n"),
+ }
+}
+
+fn append_preflight_section(out: &mut String, snapshot: &DiagnosticsSnapshot) {
+ out.push_str("\n== Preflight/install state ==\n");
+ match &snapshot.latest_preflight {
+ Some(preflight) => {
+ out.push_str("source=live-state\n");
+ out.push_str(&format!("recorded_at_ms={}\n", preflight.recorded_at_ms));
+ out.push_str(&format!("disposition={}\n", preflight.disposition));
+ append_opt(out, "reason", preflight.reason.as_deref());
+ append_opt(
+ out,
+ "port",
+ preflight.port.map(|p| p.to_string()).as_deref(),
+ );
+ out.push_str(&format!("can_auto_repair={}\n", preflight.can_auto_repair));
+ if let Some(path) = &preflight.managed_bin {
+ out.push_str(&format!("managed_bin={}\n", path.display()));
+ out.push_str(&format!("managed_bin_exists={}\n", path.exists()));
+ } else {
+ out.push_str("managed_bin=unavailable\n");
+ }
+ }
+ None => out.push_str("source=live-state unavailable\n"),
+ }
+}
+
+fn append_flow_section(out: &mut String, snapshot: &DiagnosticsSnapshot) {
+ out.push_str("\n== Flow summaries ==\n");
+ append_attempt_summary(out, "install", snapshot.install.as_ref(), "live-state");
+ if !snapshot.install_history.is_empty() {
+ out.push_str("install_history:\n");
+ for install in snapshot.install_history.iter().rev().take(4).rev() {
+ append_attempt_summary(
+ out,
+ " previous_install",
+ Some(install),
+ "live-state-history",
+ );
+ }
+ }
+ append_attempt_summary(out, "update", snapshot.update.as_ref(), "live-state");
+
+ out.push_str("repair_groups:\n");
+ if snapshot.repair_groups.is_empty() {
+ out.push_str(" unavailable\n");
+ } else {
+ for group in snapshot.repair_groups.iter().rev().take(5).rev() {
+ out.push_str(&format!(
+ " repair_group_id={} started_at_ms={} ended_at_ms={} final_status={} last_error={}\n",
+ group.repair_group_id,
+ group.started_at_ms,
+ opt_u64(group.ended_at_ms),
+ group.final_status.as_deref().unwrap_or("unavailable"),
+ group.last_error.as_deref().unwrap_or("unavailable")
+ ));
+ for child in &group.children {
+ append_attempt_summary(out, " child", Some(child), "live-state");
+ }
+ }
+ }
+}
+
+fn append_attempt_summary(
+ out: &mut String,
+ label: &str,
+ attempt: Option<&AttemptSummary>,
+ source: &str,
+) {
+ match attempt {
+ Some(attempt) => {
+ out.push_str(&format!(
+ "{label}: source={source} flow={} attempt_id={} group_id={} child_type={} started_at_ms={} ended_at_ms={} exit_status={} intentional_stop={} last_error={} log_segments={}\n",
+ attempt.flow,
+ attempt.attempt_id,
+ attempt.repair_group_id.as_deref().unwrap_or("none"),
+ attempt.child_type.as_deref().unwrap_or("none"),
+ attempt.started_at_ms,
+ opt_u64(attempt.ended_at_ms),
+ attempt.exit_status.as_deref().unwrap_or("unavailable"),
+ attempt.intentional_stop,
+ attempt.last_error.as_deref().unwrap_or("unavailable"),
+ attempt
+ .log_segments
+ .iter()
+ .map(|p| p.display().to_string())
+ .collect::<Vec<_>>()
+ .join(",")
+ ));
+ if !attempt.elevation_packages.is_empty() {
+ out.push_str(&format!(
+ "{label}.elevation_packages={}\n",
+ attempt.elevation_packages.join(", ")
+ ));
+ }
+ append_capped(out, &format!("{label}.steps"), &attempt.steps);
+ append_capped(
+ out,
+ &format!("{label}.progress_details"),
+ &attempt.progress_details,
+ );
+ append_capped(out, &format!("{label}.diag_markers"), &attempt.diag_markers);
+ }
+ None => out.push_str(&format!("{label}: unavailable\n")),
+ }
+}
+
+fn append_backend_section(
+ out: &mut String,
+ snapshot: &DiagnosticsSnapshot,
+ health: Option<&BackendHealthSection>,
+) {
+ out.push_str("\n== Backend/auth/watchdog ==\n");
+ match &snapshot.backend {
+ Some(backend) => {
+ out.push_str("source=live-state\n");
+ out.push_str(&format!("backend_kind={}\n", backend.backend_kind));
+ append_opt(out, "session_id", backend.session_id.as_deref());
+ append_opt(
+ out,
+ "requested_port",
+ backend.requested_port.map(|p| p.to_string()).as_deref(),
+ );
+ append_opt(
+ out,
+ "reported_port",
+ backend.reported_port.map(|p| p.to_string()).as_deref(),
+ );
+ append_opt(
+ out,
+ "generation",
+ backend.generation.map(|g| g.to_string()).as_deref(),
+ );
+ append_opt(
+ out,
+ "started_at_ms",
+ backend.started_at_ms.map(|t| t.to_string()).as_deref(),
+ );
+ append_opt(
+ out,
+ "ended_at_ms",
+ backend.ended_at_ms.map(|t| t.to_string()).as_deref(),
+ );
+ append_opt(out, "exit_status", backend.exit_status.as_deref());
+ out.push_str(&format!("intentional_stop={}\n", backend.intentional_stop));
+ append_opt(out, "terminal_reason", backend.terminal_reason.as_deref());
+ append_opt(out, "last_error", backend.last_error.as_deref());
+ if backend.backend_kind == "attached_external" {
+ out.push_str("managed_process_logs=not_owned_by_tauri\n");
+ }
+ }
+ None => out.push_str("backend=unavailable backend_kind=unknown\n"),
+ }
+
+ match &snapshot.auth {
+ Some(auth) => {
+ out.push_str(&format!(
+ "auth_failure: failed_at_ms={} stage={} port={} message={}\n",
+ auth.failed_at_ms,
+ auth.stage,
+ auth.port
+ .map(|p| p.to_string())
+ .unwrap_or_else(|| "unavailable".to_string()),
+ auth.message
+ ));
+ }
+ None => out.push_str("auth_failure=unavailable\n"),
+ }
+
+ out.push_str("runtime_health:\n");
+ match health {
+ Some(health) => {
+ out.push_str(&format!(" port={}\n", health.port));
+ if health.fields.is_empty() {
+ out.push_str(" selected_fields=unavailable\n");
+ } else {
+ for (key, value) in &health.fields {
+ out.push_str(&format!(" {key}={value}\n"));
+ }
+ }
+ if let Some(warning) = &health.warning {
+ out.push_str(&format!(" warning={warning}\n"));
+ }
+ }
+ None => out.push_str(" unavailable: no known backend port\n"),
+ }
+}
+
+fn append_device_signals_section(
+ out: &mut String,
+ snapshot: &DiagnosticsSnapshot,
+ health: Option<&BackendHealthSection>,
+) {
+ out.push_str("\n== Lightweight device signals ==\n");
+ out.push_str("scope=setup/runtime signals, not full hardware inventory\n");
+ out.push_str(&format!(
+ "os={} arch={}\n",
+ std::env::consts::OS,
+ std::env::consts::ARCH
+ ));
+ out.push_str("installer_diag_markers:\n");
+ let mut any = false;
+ if let Some(install) = &snapshot.install {
+ append_marker_tail(out, "install", install);
+ any |= !install.diag_markers.items.is_empty();
+ }
+ if let Some(update) = &snapshot.update {
+ append_marker_tail(out, "update", update);
+ any |= !update.diag_markers.items.is_empty();
+ }
+ for group in &snapshot.repair_groups {
+ for child in &group.children {
+ append_marker_tail(out, "repair_child", child);
+ any |= !child.diag_markers.items.is_empty();
+ }
+ }
+ if !any {
+ out.push_str(" unavailable\n");
+ }
+ if let Some(health) = health {
+ out.push_str("runtime_health_selected_fields:\n");
+ for (key, value) in &health.fields {
+ if matches!(
+ key.as_str(),
+ "version"
+ | "device_type"
+ | "chat_only"
+ | "desktop_protocol_version"
+ | "supports_api_only"
+ | "supports_desktop_auth"
+ ) {
+ out.push_str(&format!(" {key}={value}\n"));
+ }
+ }
+ }
+}
+
+fn append_log_sections(
+ out: &mut String,
+ snapshot: &DiagnosticsSnapshot,
+ warnings: &mut Vec<String>,
+) {
+ out.push_str("\n== Log tails ==\n");
+ for name in ["tauri.log", "tauri.log.1"] {
+ let path = studio_dir().join(name);
+ append_tail_section(out, &path, name, "local-app-log", warnings);
+ }
+
+ let phase_groups = collect_phase_groups(snapshot, warnings);
+ if phase_groups.is_empty() {
+ out.push_str("phase_logs=unavailable\n");
+ }
+ for group in phase_groups {
+ out.push_str(&format!(
+ "\n-- phase_log_group label={} source={} --\n",
+ group.label, group.source
+ ));
+ if let Some(note) = &group.note {
+ out.push_str(&format!("note={}\n", note));
+ }
+ for path in group.paths {
+ append_tail_section(out, &path, &group.label, &group.source, warnings);
+ }
+ }
+}
+
+fn append_tail_section(
+ out: &mut String,
+ path: &Path,
+ label: &str,
+ source: &str,
+ warnings: &mut Vec<String>,
+) {
+ match read_tail(path, TAIL_MAX_LINES, TAIL_MAX_BYTES) {
+ Ok(tail) => {
+ out.push_str(&format!(
+ "file={} label={} source={} size_bytes={} mtime_ms={} included_bytes={} included_lines={} truncated={}\n",
+ path.display(),
+ label,
+ source,
+ tail.size_bytes,
+ opt_u64(tail.mtime_ms),
+ tail.included_bytes,
+ tail.included_lines,
+ tail.truncated
+ ));
+ out.push_str("```text\n");
+ out.push_str(&tail.text);
+ if !tail.text.ends_with('\n') {
+ out.push('\n');
+ }
+ out.push_str("```\n");
+ }
+ Err(error) => {
+ out.push_str(&format!(
+ "file={} label={} source={} unavailable={}\n",
+ path.display(),
+ label,
+ source,
+ error
+ ));
+ warnings.push(format!("{} unavailable: {}", path.display(), error));
+ }
+ }
+}
+
+#[derive(Debug)]
+struct TailRead {
+ text: String,
+ size_bytes: u64,
+ mtime_ms: Option<u64>,
+ included_bytes: usize,
+ included_lines: usize,
+ truncated: bool,
+}
+
+fn read_tail(path: &Path, max_lines: usize, max_bytes: usize) -> Result<TailRead, String> {
+ if path_has_symlink(path) {
+ return Err("refusing to read symlink".to_string());
+ }
+ let metadata = fs::metadata(path).map_err(|e| e.to_string())?;
+ let size = metadata.len();
+ let mut file = File::open(path).map_err(|e| e.to_string())?;
+ let start = size.saturating_sub(max_bytes as u64);
+ file.seek(SeekFrom::Start(start))
+ .map_err(|e| e.to_string())?;
+ let mut bytes = Vec::new();
+ file.take(max_bytes as u64)
+ .read_to_end(&mut bytes)
+ .map_err(|e| e.to_string())?;
+ let mut text = String::from_utf8_lossy(&bytes).into_owned();
+ let mut truncated = start > 0;
+ if truncated {
+ text = format!("[tail truncated to last {max_bytes} bytes]\n{text}");
+ }
+ let mut lines: Vec<String> = text
+ .lines()
+ .map(|line| {
+ if line.len() > MAX_PHASE_LINE_BYTES {
+ let boundary = valid_utf8_boundary(line, MAX_PHASE_LINE_BYTES);
+ format!("{} [line truncated]", &line[..boundary])
+ } else {
+ line.to_string()
+ }
+ })
+ .collect();
+ if lines.len() > max_lines {
+ truncated = true;
+ let omitted = lines.len() - max_lines;
+ lines = lines.split_off(omitted);
+ lines.insert(0, format!("[tail truncated to last {max_lines} lines]"));
+ }
+ let included_lines = lines.len();
+ let mut text = lines.join("\n");
+ if !text.is_empty() {
+ text.push('\n');
+ }
+ Ok(TailRead {
+ text,
+ size_bytes: size,
+ mtime_ms: metadata
+ .modified()
+ .ok()
+ .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
+ .map(|d| d.as_millis() as u64),
+ included_bytes: bytes.len(),
+ included_lines,
+ truncated,
+ })
+}
+
+fn render_footer(warnings: &[String], redaction: &RedactionReport) -> String {
+ let mut footer = String::new();
+ footer.push_str("\n== Collection warnings ==\n");
+ if warnings.is_empty() {
+ footer.push_str("none\n");
+ } else {
+ for warning in warnings.iter().take(100) {
+ footer.push_str("- ");
+ footer.push_str(warning);
+ footer.push('\n');
+ }
+ if warnings.len() > 100 {
+ footer.push_str(&format!(
+ "- omitted {} additional warnings\n",
+ warnings.len() - 100
+ ));
+ }
+ }
+ footer.push_str("\n== Redaction/omission summary ==\n");
+ footer.push_str(&format!(
+ "redaction_replacements={}\n",
+ redaction.replacements
+ ));
+ footer.push_str("redaction_scope=ANSI, private keys, URL credentials, auth headers, cookies, token patterns, assignment-style secrets, studio/home paths, emails\n");
+ footer.push_str(
+ "report_bounds=log sections <=1000 lines/200KiB each; total clipboard text <=1MiB\n",
+ );
+ footer.push_str("known_v1_gap=elevated apt helper may buffer subprocess output before diagnostics caps it\n");
+ footer.push_str("known_v1_gap=normal install elevation resume is linked in same-run state/report history; disk fallback conservatively includes recent install attempts but has no explicit install_group_id in V1\n");
+ footer
+}
+
+fn enforce_report_limit(body: String, footer: String) -> String {
+ if body.len() + footer.len() <= REPORT_MAX_BYTES {
+ return format!("{body}{footer}");
+ }
+ let notice = "\n[report truncated to fit clipboard budget; footer preserved]\n";
+ let footer_budget = footer.len().min(FOOTER_BUDGET_BYTES).max(footer.len());
+ let budget = REPORT_MAX_BYTES
+ .saturating_sub(footer_budget)
+ .saturating_sub(notice.len());
+ let boundary = valid_utf8_boundary(&body, budget);
+ format!("{}{}{}", &body[..boundary], notice, footer)
+}
+fn append_opt(out: &mut String, key: &str, value: Option<&str>) {
+ out.push_str(key);
+ out.push('=');
+ out.push_str(value.unwrap_or("unavailable"));
+ out.push('\n');
+}
+
+fn append_capped(out: &mut String, label: &str, values: &CappedStrings) {
+ out.push_str(&format!("{label}: omitted={}\n", values.omitted));
+ if values.items.is_empty() {
+ out.push_str(" unavailable\n");
+ } else {
+ for value in values.items.iter().rev().take(20).rev() {
+ out.push_str(" ");
+ out.push_str(value);
+ out.push('\n');
+ }
+ }
+}
+
+fn append_marker_tail(out: &mut String, label: &str, attempt: &AttemptSummary) {
+ for marker in attempt.diag_markers.items.iter().rev().take(10).rev() {
+ out.push_str(&format!(" {label}: {marker}\n"));
+ }
+}
+
+fn tail_lines(lines: &[String], max_lines: usize) -> &[String] {
+ if lines.len() > max_lines {
+ &lines[lines.len() - max_lines..]
+ } else {
+ lines
+ }
+}
+
+fn opt_u64(value: Option<u64>) -> String {
+ value
+ .map(|v| v.to_string())
+ .unwrap_or_else(|| "unavailable".to_string())
+}
+
+pub(crate) fn selected_json_value(value: &serde_json::Value) -> String {
+ match value {
+ serde_json::Value::String(s) => cap_string(s, 256),
+ serde_json::Value::Bool(b) => b.to_string(),
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::Null => "null".to_string(),
+ _ => "<non-scalar>".to_string(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn report_redacts_footer_collection_warning_paths() {
+ let snapshot = DiagnosticsSnapshot::default();
+ let report = render_report(snapshot, FrontendSupportSnapshot::default(), None);
+ let studio = studio_dir().display().to_string();
+ assert!(!report.contains(&studio));
+ assert!(report.contains("<studio_home>"));
+ }
+
+ #[test]
+ fn tail_handles_missing_and_non_utf8() {
+ let missing =
+ std::env::temp_dir().join(format!("unsloth-missing-tail-{}", std::process::id()));
+ assert!(read_tail(&missing, 10, 100).is_err());
+
+ let path =
+ std::env::temp_dir().join(format!("unsloth-nonutf8-tail-{}", std::process::id()));
+ fs::write(&path, [0xff, b'a', b'\n', b'b']).unwrap();
+ let tail = read_tail(&path, 10, 100).unwrap();
+ assert!(tail.text.contains('�'));
+ let _ = fs::remove_file(path);
+ }
+}
diff --git a/studio/src-tauri/src/diagnostics/state.rs b/studio/src-tauri/src/diagnostics/state.rs
new file mode 100644
index 00000000000..ccbd5fbb8e6
--- /dev/null
+++ b/studio/src-tauri/src/diagnostics/state.rs
@@ -0,0 +1,774 @@
+use crate::preflight::{DesktopPreflightDisposition, DesktopPreflightResult};
+use serde::{Deserialize, Serialize};
+use std::path::PathBuf;
+use std::sync::{Arc, Mutex};
+
+use super::phase_log::{PhaseLogHandle, PhaseLogWriter, SegmentOwner};
+use super::{cap_string, new_id, now_ms, MAX_STATE_ITEMS};
+
+pub type DiagnosticsState = Arc<Mutex<DiagnosticsSnapshot>>;
+
+#[derive(Clone, Debug)]
+pub struct DiagnosticsSnapshot {
+ pub app_session_id: String,
+ pub app_started_at_ms: u64,
+ pub latest_preflight: Option<PreflightSummary>,
+ pub install: Option<AttemptSummary>,
+ pub install_history: Vec<AttemptSummary>,
+ pub repair_groups: Vec<RepairGroupSummary>,
+ pub update: Option<AttemptSummary>,
+ pub backend: Option<BackendSummary>,
+ pub auth: Option<AuthSummary>,
+}
+
+impl Default for DiagnosticsSnapshot {
+ fn default() -> Self {
+ Self {
+ app_session_id: new_id("app"),
+ app_started_at_ms: now_ms(),
+ latest_preflight: None,
+ install: None,
+ install_history: Vec::new(),
+ repair_groups: Vec::new(),
+ update: None,
+ backend: None,
+ auth: None,
+ }
+ }
+}
+
+#[derive(Clone, Debug, Default)]
+pub struct CappedStrings {
+ pub items: Vec<String>,
+ pub omitted: usize,
+}
+
+impl CappedStrings {
+ fn push(&mut self, value: impl Into<String>) {
+ if self.items.len() >= MAX_STATE_ITEMS {
+ self.items.remove(0);
+ self.omitted += 1;
+ }
+ self.items.push(value.into());
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct PreflightSummary {
+ pub disposition: String,
+ pub reason: Option<String>,
+ pub port: Option<u16>,
+ pub can_auto_repair: bool,
+ pub managed_bin: Option<PathBuf>,
+ pub recorded_at_ms: u64,
+}
+
+#[derive(Clone, Debug)]
+pub struct AttemptSummary {
+ pub flow: String,
+ pub attempt_id: String,
+ pub repair_group_id: Option<String>,
+ pub child_type: Option<String>,
+ pub log_segments: Vec<PathBuf>,
+ pub started_at_ms: u64,
+ pub ended_at_ms: Option<u64>,
+ pub exit_status: Option<String>,
+ pub intentional_stop: bool,
+ pub last_error: Option<String>,
+ pub elevation_packages: Vec<String>,
+ pub steps: CappedStrings,
+ pub progress_details: CappedStrings,
+ pub diag_markers: CappedStrings,
+}
+
+impl AttemptSummary {
+ pub(crate) fn new(
+ flow: impl Into<String>,
+ attempt_id: String,
+ repair_group_id: Option<String>,
+ child_type: Option<String>,
+ started_at_ms: u64,
+ ) -> Self {
+ Self {
+ flow: flow.into(),
+ attempt_id,
+ repair_group_id,
+ child_type,
+ log_segments: Vec::new(),
+ started_at_ms,
+ ended_at_ms: None,
+ exit_status: None,
+ intentional_stop: false,
+ last_error: None,
+ elevation_packages: Vec::new(),
+ steps: CappedStrings::default(),
+ progress_details: CappedStrings::default(),
+ diag_markers: CappedStrings::default(),
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct RepairGroupSummary {
+ pub repair_group_id: String,
+ pub children: Vec<AttemptSummary>,
+ pub started_at_ms: u64,
+ pub ended_at_ms: Option<u64>,
+ pub final_status: Option<String>,
+ pub last_error: Option<String>,
+}
+
+#[derive(Clone, Debug)]
+pub struct BackendSummary {
+ pub session_id: Option<String>,
+ pub backend_kind: String,
+ pub log_segments: Vec<PathBuf>,
+ pub requested_port: Option<u16>,
+ pub reported_port: Option<u16>,
+ pub generation: Option<u64>,
+ pub started_at_ms: Option<u64>,
+ pub ended_at_ms: Option<u64>,
+ pub exit_status: Option<String>,
+ pub intentional_stop: bool,
+ pub terminal_reason: Option<String>,
+ pub last_error: Option<String>,
+}
+
+#[derive(Clone, Debug)]
+pub struct AuthSummary {
+ pub failed_at_ms: u64,
+ pub stage: String,
+ pub port: Option<u16>,
+ pub message: String,
+}
+
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FrontendSupportSnapshot {
+ pub status: Option<String>,
+ pub error: Option<String>,
+ pub current_step_index: Option<i64>,
+ pub progress_detail: Option<String>,
+ pub elevation_packages: Option<Vec<String>>,
+ pub last_ui_log_lines: Option<Vec<String>>,
+ pub flow: Option<String>,
+ pub update_phase: Option<String>,
+ /// Frontend update progress can be numeric today; keep this tolerant of strings/numbers.
+ pub update_progress: Option<serde_json::Value>,
+}
+
+#[derive(Clone)]
+pub struct AttemptLog {
+ pub flow: String,
+ pub attempt_id: String,
+ pub repair_group_id: Option<String>,
+ #[allow(dead_code)]
+ pub child_type: Option<String>,
+ pub handle: PhaseLogHandle,
+}
+
+#[derive(Clone)]
+pub struct BackendLog {
+ pub session_id: String,
+ pub handle: PhaseLogHandle,
+}
+
+pub fn new_diagnostics_state() -> DiagnosticsState {
+ Arc::new(Mutex::new(DiagnosticsSnapshot::default()))
+}
+
+pub fn begin_install_attempt(diagnostics: &DiagnosticsState) -> AttemptLog {
+ begin_attempt(diagnostics, "install", None, None)
+}
+
+pub fn begin_update_attempt(diagnostics: &DiagnosticsState) -> AttemptLog {
+ begin_attempt(diagnostics, "update", None, None)
+}
+
+pub fn begin_repair_group(diagnostics: &DiagnosticsState) -> String {
+ let repair_group_id = new_id("repair");
+ with_snapshot(diagnostics, |snapshot| {
+ if snapshot.repair_groups.len() >= MAX_STATE_ITEMS {
+ snapshot.repair_groups.remove(0);
+ }
+ snapshot.repair_groups.push(RepairGroupSummary {
+ repair_group_id: repair_group_id.clone(),
+ children: Vec::new(),
+ started_at_ms: now_ms(),
+ ended_at_ms: None,
+ final_status: None,
+ last_error: None,
+ });
+ });
+ repair_group_id
+}
+
+pub fn begin_repair_child(
+ diagnostics: &DiagnosticsState,
+ repair_group_id: &str,
+ child_type: &str,
+) -> AttemptLog {
+ begin_attempt(
+ diagnostics,
+ "repair",
+ Some(repair_group_id.to_string()),
+ Some(child_type.to_string()),
+ )
+}
+
+fn begin_attempt(
+ diagnostics: &DiagnosticsState,
+ flow: &str,
+ repair_group_id: Option<String>,
+ child_type: Option<String>,
+) -> AttemptLog {
+ let started_at_ms = now_ms();
+ let attempt_id = new_id(child_type.as_deref().unwrap_or(flow));
+ let owner = match (flow, repair_group_id.as_ref(), child_type.as_ref()) {
+ ("install", None, _) => SegmentOwner::Install {
+ attempt_id: attempt_id.clone(),
+ },
+ ("update", None, _) => SegmentOwner::Update {
+ attempt_id: attempt_id.clone(),
+ },
+ (_, Some(group), Some(child)) => SegmentOwner::Repair {
+ repair_group_id: group.clone(),
+ attempt_id: attempt_id.clone(),
+ child_type: child.clone(),
+ },
+ _ => SegmentOwner::Install {
+ attempt_id: attempt_id.clone(),
+ },
+ };
+
+ let summary = AttemptSummary::new(
+ flow,
+ attempt_id.clone(),
+ repair_group_id.clone(),
+ child_type.clone(),
+ started_at_ms,
+ );
+
+ with_snapshot(diagnostics, |snapshot| {
+ if let Some(group_id) = &repair_group_id {
+ let group = ensure_repair_group(snapshot, group_id);
+ if group.children.len() >= MAX_STATE_ITEMS {
+ group.children.remove(0);
+ }
+ group.children.push(summary);
+ } else if flow == "update" {
+ snapshot.update = Some(summary);
+ } else {
+ if let Some(previous) = snapshot.install.take() {
+ if snapshot.install_history.len() >= MAX_STATE_ITEMS {
+ snapshot.install_history.remove(0);
+ }
+ snapshot.install_history.push(previous);
+ }
+ snapshot.install = Some(summary);
+ }
+ });
+
+ let writer = PhaseLogWriter::new(
+ diagnostics.clone(),
+ owner,
+ if repair_group_id.is_some() {
+ "repair"
+ } else {
+ flow
+ },
+ started_at_ms,
+ None,
+ );
+
+ AttemptLog {
+ flow: flow.to_string(),
+ attempt_id,
+ repair_group_id,
+ child_type,
+ handle: Arc::new(Mutex::new(writer)),
+ }
+}
+
+pub fn finish_attempt(
+ diagnostics: &DiagnosticsState,
+ attempt: &AttemptLog,
+ exit_status: Option<String>,
+ intentional_stop: bool,
+ last_error: Option<String>,
+) {
+ with_snapshot(diagnostics, |snapshot| {
+ update_attempt_mut(snapshot, attempt, |summary| {
+ if summary.ended_at_ms.is_none() {
+ summary.ended_at_ms = Some(now_ms());
+ }
+ if exit_status.is_some() {
+ summary.exit_status = exit_status.clone();
+ }
+ summary.intentional_stop |= intentional_stop;
+ if last_error.is_some() {
+ summary.last_error = last_error.clone();
+ }
+ });
+ });
+}
+
+pub fn finish_repair_group(
+ diagnostics: &DiagnosticsState,
+ repair_group_id: &str,
+ final_status: impl Into<String>,
+ last_error: Option<String>,
+) {
+ let status = final_status.into();
+ with_snapshot(diagnostics, |snapshot| {
+ let group = ensure_repair_group(snapshot, repair_group_id);
+ group.ended_at_ms = Some(now_ms());
+ group.final_status = Some(status.clone());
+ group.last_error = last_error.clone();
+ });
+}
+
+pub fn record_step(diagnostics: &DiagnosticsState, attempt: &AttemptLog, step: &str) {
+ record_attempt_string(diagnostics, attempt, step, |summary, value| {
+ summary.steps.push(value)
+ });
+}
+
+pub fn record_progress(diagnostics: &DiagnosticsState, attempt: &AttemptLog, progress: &str) {
+ record_attempt_string(diagnostics, attempt, progress, |summary, value| {
+ summary.progress_details.push(value)
+ });
+}
+
+pub fn record_diag_marker(diagnostics: &DiagnosticsState, attempt: &AttemptLog, marker: &str) {
+ record_attempt_string(diagnostics, attempt, marker, |summary, value| {
+ summary.diag_markers.push(value)
+ });
+}
+
+pub fn record_elevation_packages(
+ diagnostics: &DiagnosticsState,
+ attempt: &AttemptLog,
+ packages: &[String],
+) {
+ let capped: Vec<String> = packages.iter().take(100).cloned().collect();
+ with_snapshot(diagnostics, |snapshot| {
+ update_attempt_mut(snapshot, attempt, |summary| {
+ summary.elevation_packages = capped.clone();
+ });
+ });
+}
+
+fn record_attempt_string<F>(
+ diagnostics: &DiagnosticsState,
+ attempt: &AttemptLog,
+ value: &str,
+ mut update: F,
+) where
+ F: FnMut(&mut AttemptSummary, String),
+{
+ let capped = cap_string(value, 4096);
+ with_snapshot(diagnostics, |snapshot| {
+ update_attempt_mut(snapshot, attempt, |summary| {
+ update(summary, capped.clone());
+ });
+ });
+}
+
+pub fn record_preflight(diagnostics: &DiagnosticsState, result: &DesktopPreflightResult) {
+ let summary = PreflightSummary {
+ disposition: disposition_label(&result.disposition).to_string(),
+ reason: result.reason.clone(),
+ port: result.port,
+ can_auto_repair: result.can_auto_repair,
+ managed_bin: result.managed_bin.clone(),
+ recorded_at_ms: now_ms(),
+ };
+ with_snapshot(diagnostics, |snapshot| {
+ snapshot.latest_preflight = Some(summary);
+ });
+ if matches!(
+ result.disposition,
+ DesktopPreflightDisposition::AttachedReady
+ ) {
+ if let Some(port) = result.port {
+ record_attached_external_backend(diagnostics, port);
+ }
+ }
+}
+
+pub fn begin_backend_session(
+ diagnostics: &DiagnosticsState,
+ requested_port: u16,
+ generation: u64,
+) -> BackendLog {
+ let session_id = new_id("backend");
+ let started_at_ms = now_ms();
+ with_snapshot(diagnostics, |snapshot| {
+ snapshot.backend = Some(BackendSummary {
+ session_id: Some(session_id.clone()),
+ backend_kind: "managed".to_string(),
+ log_segments: Vec::new(),
+ requested_port: Some(requested_port),
+ reported_port: None,
+ generation: Some(generation),
+ started_at_ms: Some(started_at_ms),
+ ended_at_ms: None,
+ exit_status: None,
+ intentional_stop: false,
+ terminal_reason: None,
+ last_error: None,
+ });
+ });
+ let writer = PhaseLogWriter::new(
+ diagnostics.clone(),
+ SegmentOwner::Backend {
+ session_id: session_id.clone(),
+ },
+ "backend",
+ started_at_ms,
+ Some("managed".to_string()),
+ );
+ BackendLog {
+ session_id,
+ handle: Arc::new(Mutex::new(writer)),
+ }
+}
+
+pub fn record_backend_start_failure(
+ diagnostics: &DiagnosticsState,
+ requested_port: Option<u16>,
+ generation: Option<u64>,
+ stage: &str,
+ error: &str,
+) {
+ let error = cap_string(error, 4096);
+ with_snapshot(diagnostics, |snapshot| {
+ snapshot.backend = Some(BackendSummary {
+ session_id: None,
+ backend_kind: "managed".to_string(),
+ log_segments: Vec::new(),
+ requested_port,
+ reported_port: None,
+ generation,
+ started_at_ms: Some(now_ms()),
+ ended_at_ms: Some(now_ms()),
+ exit_status: None,
+ intentional_stop: false,
+ terminal_reason: Some(stage.to_string()),
+ last_error: Some(error.clone()),
+ });
+ });
+}
+
+pub fn record_backend_port(diagnostics: &DiagnosticsState, session_id: &str, port: u16) {
+ with_snapshot(diagnostics, |snapshot| {
+ if let Some(backend) = snapshot.backend.as_mut() {
+ if backend.session_id.as_deref() == Some(session_id) {
+ backend.reported_port = Some(port);
+ }
+ }
+ });
+}
+
+pub fn record_backend_exit(
+ diagnostics: &DiagnosticsState,
+ session_id: &str,
+ exit_status: Option<String>,
+ intentional_stop: bool,
+ terminal_reason: Option<String>,
+) {
+ with_snapshot(diagnostics, |snapshot| {
+ if let Some(backend) = snapshot.backend.as_mut() {
+ if backend.session_id.as_deref() != Some(session_id) {
+ return;
+ }
+ if backend.ended_at_ms.is_none() {
+ backend.ended_at_ms = Some(now_ms());
+ }
+ if exit_status.is_some() {
+ backend.exit_status = exit_status.clone();
+ }
+ backend.intentional_stop |= intentional_stop;
+ if backend.terminal_reason.is_none() {
+ backend.terminal_reason = terminal_reason.clone().or_else(|| {
+ Some(if intentional_stop {
+ "intentional_stop".to_string()
+ } else {
+ "process_exit".to_string()
+ })
+ });
+ }
+ }
+ });
+}
+
+pub fn record_backend_watchdog(
+ diagnostics: &DiagnosticsState,
+ generation: u64,
+ terminal_reason: &str,
+) {
+ with_snapshot(diagnostics, |snapshot| {
+ if let Some(backend) = snapshot.backend.as_mut() {
+ if backend.generation == Some(generation) && backend.terminal_reason.is_none() {
+ backend.terminal_reason = Some(terminal_reason.to_string());
+ backend.ended_at_ms = Some(now_ms());
+ }
+ }
+ });
+}
+
+pub fn record_backend_intentional_stop(diagnostics: &DiagnosticsState) {
+ with_snapshot(diagnostics, |snapshot| {
+ if let Some(backend) = snapshot.backend.as_mut() {
+ if matches!(
+ backend.terminal_reason.as_deref(),
+ Some("no_port_after_grace" | "unresponsive_health_check")
+ ) {
+ return;
+ }
+ backend.intentional_stop = true;
+ if backend.terminal_reason.is_none() {
+ backend.terminal_reason = Some("intentional_stop".to_string());
+ }
+ }
+ });
+}
+
+pub fn record_attached_external_backend(diagnostics: &DiagnosticsState, port: u16) {
+ with_snapshot(diagnostics, |snapshot| {
+ let should_replace = snapshot
+ .backend
+ .as_ref()
+ .map(|backend| backend.backend_kind != "managed" || backend.session_id.is_none())
+ .unwrap_or(true);
+ if should_replace {
+ snapshot.backend = Some(BackendSummary {
+ session_id: None,
+ backend_kind: "attached_external".to_string(),
+ log_segments: Vec::new(),
+ requested_port: None,
+ reported_port: Some(port),
+ generation: None,
+ started_at_ms: None,
+ ended_at_ms: None,
+ exit_status: None,
+ intentional_stop: false,
+ terminal_reason: None,
+ last_error: None,
+ });
+ }
+ });
+}
+
+pub fn record_auth_failure(
+ diagnostics: &DiagnosticsState,
+ stage: &str,
+ port: Option<u16>,
+ message: &str,
+) {
+ let message = cap_string(message, 4096);
+ with_snapshot(diagnostics, |snapshot| {
+ snapshot.auth = Some(AuthSummary {
+ failed_at_ms: now_ms(),
+ stage: stage.to_string(),
+ port,
+ message,
+ });
+ });
+}
+
+pub(crate) fn with_snapshot<F>(diagnostics: &DiagnosticsState, update: F)
+where
+ F: FnOnce(&mut DiagnosticsSnapshot),
+{
+ match diagnostics.lock() {
+ Ok(mut snapshot) => update(&mut snapshot),
+ Err(poisoned) => {
+ let mut snapshot = poisoned.into_inner();
+ update(&mut snapshot);
+ }
+ }
+}
+
+pub(crate) fn clone_snapshot(diagnostics: &DiagnosticsState) -> DiagnosticsSnapshot {
+ match diagnostics.lock() {
+ Ok(snapshot) => snapshot.clone(),
+ Err(poisoned) => poisoned.into_inner().clone(),
+ }
+}
+
+fn ensure_repair_group<'a>(
+ snapshot: &'a mut DiagnosticsSnapshot,
+ repair_group_id: &str,
+) -> &'a mut RepairGroupSummary {
+ if let Some(index) = snapshot
+ .repair_groups
+ .iter()
+ .position(|group| group.repair_group_id == repair_group_id)
+ {
+ return &mut snapshot.repair_groups[index];
+ }
+ snapshot.repair_groups.push(RepairGroupSummary {
+ repair_group_id: repair_group_id.to_string(),
+ children: Vec::new(),
+ started_at_ms: now_ms(),
+ ended_at_ms: None,
+ final_status: None,
+ last_error: None,
+ });
+ snapshot.repair_groups.last_mut().expect("just pushed")
+}
+
+fn update_attempt_mut<F>(snapshot: &mut DiagnosticsSnapshot, attempt: &AttemptLog, update: F)
+where
+ F: FnOnce(&mut AttemptSummary),
+{
+ if let Some(group_id) = &attempt.repair_group_id {
+ if let Some(group) = snapshot
+ .repair_groups
+ .iter_mut()
+ .find(|group| &group.repair_group_id == group_id)
+ {
+ if let Some(child) = group
+ .children
+ .iter_mut()
+ .rev()
+ .find(|child| child.attempt_id == attempt.attempt_id)
+ {
+ update(child);
+ }
+ }
+ } else if attempt.flow == "update" {
+ if let Some(summary) = snapshot.update.as_mut() {
+ if summary.attempt_id == attempt.attempt_id {
+ update(summary);
+ }
+ }
+ } else if let Some(summary) = snapshot.install.as_mut() {
+ if summary.attempt_id == attempt.attempt_id {
+ update(summary);
+ }
+ }
+}
+
+pub(crate) fn record_segment_path(
+ diagnostics: &DiagnosticsState,
+ owner: &SegmentOwner,
+ path: PathBuf,
+) {
+ with_snapshot(diagnostics, |snapshot| match owner {
+ SegmentOwner::Install { attempt_id } => {
+ if let Some(summary) = snapshot.install.as_mut() {
+ if &summary.attempt_id == attempt_id && !summary.log_segments.contains(&path) {
+ summary.log_segments.push(path.clone());
+ }
+ }
+ for summary in &mut snapshot.install_history {
+ if &summary.attempt_id == attempt_id && !summary.log_segments.contains(&path) {
+ summary.log_segments.push(path.clone());
+ }
+ }
+ }
+ SegmentOwner::Update { attempt_id } => {
+ if let Some(summary) = snapshot.update.as_mut() {
+ if &summary.attempt_id == attempt_id && !summary.log_segments.contains(&path) {
+ summary.log_segments.push(path.clone());
+ }
+ }
+ }
+ SegmentOwner::Repair {
+ repair_group_id,
+ attempt_id,
+ ..
+ } => {
+ if let Some(group) = snapshot
+ .repair_groups
+ .iter_mut()
+ .find(|group| &group.repair_group_id == repair_group_id)
+ {
+ if let Some(child) = group
+ .children
+ .iter_mut()
+ .find(|child| &child.attempt_id == attempt_id)
+ {
+ if !child.log_segments.contains(&path) {
+ child.log_segments.push(path.clone());
+ }
+ }
+ }
+ }
+ SegmentOwner::Backend { session_id } => {
+ if let Some(backend) = snapshot.backend.as_mut() {
+ if backend.session_id.as_deref() == Some(session_id)
+ && !backend.log_segments.contains(&path)
+ {
+ backend.log_segments.push(path.clone());
+ }
+ }
+ }
+ });
+}
+
+pub(crate) fn forget_segment_path(
+ diagnostics: &DiagnosticsState,
+ owner: &SegmentOwner,
+ path: &PathBuf,
+) {
+ with_snapshot(diagnostics, |snapshot| match owner {
+ SegmentOwner::Install { attempt_id } => {
+ if let Some(summary) = snapshot.install.as_mut() {
+ if &summary.attempt_id == attempt_id {
+ summary.log_segments.retain(|segment| segment != path);
+ }
+ }
+ for summary in &mut snapshot.install_history {
+ if &summary.attempt_id == attempt_id {
+ summary.log_segments.retain(|segment| segment != path);
+ }
+ }
+ }
+ SegmentOwner::Update { attempt_id } => {
+ if let Some(summary) = snapshot.update.as_mut() {
+ if &summary.attempt_id == attempt_id {
+ summary.log_segments.retain(|segment| segment != path);
+ }
+ }
+ }
+ SegmentOwner::Repair {
+ repair_group_id,
+ attempt_id,
+ ..
+ } => {
+ if let Some(group) = snapshot
+ .repair_groups
+ .iter_mut()
+ .find(|group| &group.repair_group_id == repair_group_id)
+ {
+ if let Some(child) = group
+ .children
+ .iter_mut()
+ .find(|child| &child.attempt_id == attempt_id)
+ {
+ child.log_segments.retain(|segment| segment != path);
+ }
+ }
+ }
+ SegmentOwner::Backend { session_id } => {
+ if let Some(backend) = snapshot.backend.as_mut() {
+ if backend.session_id.as_deref() == Some(session_id) {
+ backend.log_segments.retain(|segment| segment != path);
+ }
+ }
+ }
+ });
+}
+
+fn disposition_label(disposition: &DesktopPreflightDisposition) -> &'static str {
+ match disposition {
+ DesktopPreflightDisposition::NotInstalled => "not_installed",
+ DesktopPreflightDisposition::ManagedReady => "managed_ready",
+ DesktopPreflightDisposition::ManagedStale => "managed_stale",
+ DesktopPreflightDisposition::AttachedReady => "attached_ready",
+ }
+}
diff --git a/studio/src-tauri/src/install.rs b/studio/src-tauri/src/install.rs
index 57609893533..9d672f5e731 100644
--- a/studio/src-tauri/src/install.rs
+++ b/studio/src-tauri/src/install.rs
@@ -1,3 +1,4 @@
+use crate::diagnostics::{self, AttemptLog, DiagnosticsState};
use log::{error, info, warn};
use process_wrap::std::*;
use std::io::BufRead;
@@ -14,6 +15,8 @@ pub struct InstallProcess {
pub intentional_stop: bool,
/// Packages needing elevated install, parsed from [TAURI:NEED_SUDO] output.
pub needed_packages: Vec<String>,
+ /// Current diagnostics attempt; kept after NEEDS_ELEVATION so apt output can be linked.
+ pub current_attempt: Option<AttemptLog>,
}
impl Default for InstallProcess {
@@ -22,6 +25,7 @@ impl Default for InstallProcess {
child: None,
intentional_stop: false,
needed_packages: Vec::new(),
+ current_attempt: None,
}
}
}
@@ -228,6 +232,8 @@ fn stream_output(
app: &AppHandle,
state: &InstallState,
event_mode: InstallEventMode,
+ diagnostics: DiagnosticsState,
+ attempt: AttemptLog,
stdout: Option<std::process::ChildStdout>,
stderr: Option<std::process::ChildStderr>,
) -> Vec<std::thread::JoinHandle<()>> {
@@ -236,6 +242,8 @@ fn stream_output(
if let Some(out) = stdout {
let app_clone = app.clone();
let state_clone = Arc::clone(state);
+ let diagnostics_clone = diagnostics.clone();
+ let attempt_clone = attempt.clone();
threads.push(std::thread::spawn(move || {
let mut reader = std::io::BufReader::new(out);
let mut buf = Vec::new();
@@ -245,14 +253,21 @@ fn stream_output(
Ok(0) => break,
Ok(_) => {
let text = String::from_utf8_lossy(trim_line_endings(&buf)).into_owned();
+ diagnostics::append_phase_line(&attempt_clone.handle, "stdout", &text);
// Parse structured Tauri protocol lines
if let Some(packages) = text.strip_prefix("[TAURI:NEED_SUDO] ") {
let pkgs: Vec<String> =
packages.split_whitespace().map(String::from).collect();
if let Ok(mut install) = state_clone.lock() {
- install.needed_packages = pkgs;
+ install.needed_packages = pkgs.clone();
}
+ diagnostics::record_elevation_packages(
+ &diagnostics_clone,
+ &attempt_clone,
+ &pkgs,
+ );
} else if let Some(step) = text.strip_prefix("[TAURI:STEP] ") {
+ diagnostics::record_step(&diagnostics_clone, &attempt_clone, step);
if !event_mode.emit_install_structured_events() {
info!("[install][stdout] {}", text);
let _ = app_clone.emit(event_mode.progress_event(), &text);
@@ -260,12 +275,23 @@ fn stream_output(
}
let _ = app_clone.emit("install-step", step);
} else if let Some(detail) = text.strip_prefix("[TAURI:PROGRESS] ") {
+ diagnostics::record_progress(
+ &diagnostics_clone,
+ &attempt_clone,
+ detail,
+ );
if !event_mode.emit_install_structured_events() {
info!("[install][stdout] {}", text);
let _ = app_clone.emit(event_mode.progress_event(), detail);
continue;
}
let _ = app_clone.emit("install-progress-detail", detail);
+ } else if let Some(marker) = text.strip_prefix("[TAURI:DIAG] ") {
+ diagnostics::record_diag_marker(
+ &diagnostics_clone,
+ &attempt_clone,
+ marker,
+ );
}
// Always forward the raw line
info!("[install][stdout] {}", text);
@@ -282,6 +308,7 @@ fn stream_output(
if let Some(err) = stderr {
let app_clone = app.clone();
+ let attempt_clone = attempt.clone();
threads.push(std::thread::spawn(move || {
let mut reader = std::io::BufReader::new(err);
let mut buf = Vec::new();
@@ -291,6 +318,7 @@ fn stream_output(
Ok(0) => break,
Ok(_) => {
let text = String::from_utf8_lossy(trim_line_endings(&buf)).into_owned();
+ diagnostics::append_phase_line(&attempt_clone.handle, "stderr", &text);
warn!("[install][stderr] {}", text);
let _ = app_clone.emit(event_mode.progress_event(), &text);
}
@@ -345,30 +373,94 @@ fn wait_for_exit(state: &InstallState) -> Result<(ExitStatus, bool), String> {
/// Run the install script. Returns Ok(()) on success.
/// Returns Err("NEEDS_ELEVATION") if system packages need elevated install (Linux only).
/// Returns Err(message) on other failures.
-pub fn run_install(app: AppHandle, state: InstallState) -> Result<(), String> {
- run_install_with_event_mode(app, state, InstallEventMode::Full)
+pub fn run_install(
+ app: AppHandle,
+ state: InstallState,
+ diagnostics: DiagnosticsState,
+) -> Result<(), String> {
+ run_install_with_event_mode(app, state, diagnostics, InstallEventMode::Full, None)
}
-pub(crate) fn run_install_for_repair(app: AppHandle, state: InstallState) -> Result<(), String> {
- run_install_with_event_mode(app, state, InstallEventMode::Repair)
+pub(crate) fn run_install_for_repair(
+ app: AppHandle,
+ state: InstallState,
+ diagnostics: DiagnosticsState,
+ repair_group_id: String,
+) -> Result<(), String> {
+ run_install_with_event_mode(
+ app,
+ state,
+ diagnostics,
+ InstallEventMode::Repair,
+ Some(repair_group_id),
+ )
}
fn run_install_with_event_mode(
app: AppHandle,
state: InstallState,
+ diagnostics: DiagnosticsState,
event_mode: InstallEventMode,
+ repair_group_id: Option<String>,
) -> Result<(), String> {
+ let attempt = match repair_group_id.as_deref() {
+ Some(group_id) => diagnostics::begin_repair_child(&diagnostics, group_id, "install"),
+ None => diagnostics::begin_install_attempt(&diagnostics),
+ };
+ if let Ok(mut install) = state.lock() {
+ install.current_attempt = Some(attempt.clone());
+ }
+
emit_mode_progress(&app, event_mode, "Starting installation...");
- let (script, args) = resolve_install_script(&app)?;
+ let (script, args) = match resolve_install_script(&app) {
+ Ok(resolved) => resolved,
+ Err(msg) => {
+ diagnostics::finish_attempt(
+ &diagnostics,
+ &attempt,
+ None,
+ false,
+ Some(format!("resolve_install_script: {msg}")),
+ );
+ clear_current_attempt(&state);
+ return Err(msg);
+ }
+ };
+ diagnostics::append_phase_line(
+ &attempt.handle,
+ "meta",
+ &format!("Using script: {}", script.display()),
+ );
emit_mode_progress(
&app,
event_mode,
&format!("Using script: {}", script.display()),
);
- let (stdout, stderr) = spawn_script(&script, &args, &state)?;
- let threads = stream_output(&app, &state, event_mode, stdout, stderr);
+ let (stdout, stderr) = match spawn_script(&script, &args, &state) {
+ Ok(handles) => handles,
+ Err(msg) => {
+ diagnostics::finish_attempt(
+ &diagnostics,
+ &attempt,
+ None,
+ false,
+ Some(format!("spawn_install_script: {msg}")),
+ );
+ clear_current_attempt(&state);
+ return Err(msg);
+ }
+ };
+ let threads = stream_output(
+ &app,
+ &state,
+ event_mode,
+ diagnostics.clone(),
+ attempt.clone(),
+ stdout,
+ stderr,
+ );
// Wait for exit, join reader threads
let result = wait_for_exit(&state);
@@ -378,12 +470,20 @@ fn run_install_with_event_mode(
match result {
Ok((status, _)) if status.success() => {
+ diagnostics::finish_attempt(
+ &diagnostics,
+ &attempt,
+ Some(status.to_string()),
+ false,
+ None,
+ );
+ clear_current_attempt(&state);
if event_mode.emit_terminal_events() {
emit_complete(&app);
}
Ok(())
}
- Ok((status, _)) => {
+ Ok((status, intentional)) => {
let code = status.code().unwrap_or(-1);
if code == 2 {
// Script needs elevated package install — report to frontend
@@ -391,11 +491,27 @@ fn run_install_with_event_mode(
.lock()
.map(|i| i.needed_packages.clone())
.unwrap_or_default();
+ diagnostics::record_elevation_packages(&diagnostics, &attempt, &packages);
+ diagnostics::finish_attempt(
+ &diagnostics,
+ &attempt,
+ Some(status.to_string()),
+ intentional,
+ Some("needs_elevation".to_string()),
+ );
info!("[install] Needs elevation for packages: {:?}", packages);
let _ = app.emit(event_mode.needs_elevation_event(), &packages);
Err("NEEDS_ELEVATION".to_string())
} else {
let msg = format!("Installer exited with code {}", code);
+ diagnostics::finish_attempt(
+ &diagnostics,
+ &attempt,
+ Some(status.to_string()),
+ intentional,
+ Some(msg.clone()),
+ );
+ clear_current_attempt(&state);
if event_mode.emit_terminal_events() {
emit_failed(&app, &msg);
}
@@ -403,10 +519,14 @@ fn run_install_with_event_mode(
}
}
Err(msg) if msg == "Installation stopped." => {
+ diagnostics::finish_attempt(&diagnostics, &attempt, None, true, Some(msg.clone()));
+ clear_current_attempt(&state);
info!("[install] Installation stopped intentionally");
Err(msg)
}
Err(msg) => {
+ diagnostics::finish_attempt(&diagnostics, &attempt, None, false, Some(msg.clone()));
+ clear_current_attempt(&state);
if event_mode.emit_terminal_events() {
emit_failed(&app, &msg);
}
@@ -415,6 +535,69 @@ fn run_install_with_event_mode(
}
}
+fn clear_current_attempt(state: &InstallState) {
+ if let Ok(mut install) = state.lock() {
+ install.current_attempt = None;
+ }
+}
+
+pub fn take_pending_repair_group_for_resume(state: &InstallState) -> Option<String> {
+ let mut install = state.lock().ok()?;
+ let repair_group_id = install
+ .current_attempt
+ .as_ref()
+ .and_then(|attempt| attempt.repair_group_id.clone());
+ if repair_group_id.is_some() {
+ install.current_attempt = None;
+ }
+ repair_group_id
+}
+
+pub fn record_pending_elevation_canceled(
+ state: &InstallState,
+ diagnostics: &DiagnosticsState,
+) -> bool {
+ let attempt = state
+ .lock()
+ .ok()
+ .and_then(|mut install| install.current_attempt.take());
+ let Some(attempt) = attempt else {
+ return false;
+ };
+ diagnostics::finish_attempt(
+ diagnostics,
+ &attempt,
+ None,
+ true,
+ Some("elevation_canceled".to_string()),
+ );
+ if let Some(repair_group_id) = attempt.repair_group_id.as_deref() {
+ diagnostics::finish_repair_group(
+ diagnostics,
+ repair_group_id,
+ "canceled",
+ Some("elevation_canceled".to_string()),
+ );
+ }
+ true
+}
+
+pub fn record_install_intentional_stop(state: &InstallState, diagnostics: &DiagnosticsState) {
+ let attempt = state
+ .lock()
+ .ok()
+ .and_then(|install| install.current_attempt.clone());
+ if let Some(attempt) = attempt {
+ diagnostics::finish_attempt(
+ diagnostics,
+ &attempt,
+ None,
+ true,
+ Some("intentional_stop".to_string()),
+ );
+ }
+}
+
/// Stop a running install process gracefully.
/// Unix: SIGTERM to process group -> wait up to 5s -> SIGKILL
/// Windows: hidden taskkill /T /F to terminate the installer tree
@@ -481,65 +664,222 @@ pub fn stop_install(state: &InstallState) -> Result<(), String> {
}
}
-/// Install system packages with elevated permissions (Linux only).
+/// Install apt system packages with elevated permissions (Linux only).
/// Uses `elevated-command` crate for native auth dialog.
#[cfg(target_os = "linux")]
-pub fn install_system_packages(packages: &[String]) -> Result<(), String> {
+pub fn install_system_packages(
+ packages: &[String],
+ state: &InstallState,
+ diagnostics: &DiagnosticsState,
+) -> Result<(), String> {
use regex::Regex;
use std::path::Path;
use std::process::Command as StdCommand;
+ let current_attempt = state
+ .lock()
+ .ok()
+ .and_then(|install| install.current_attempt.clone());
+ let elevation_attempt = current_attempt
+ .as_ref()
+ .and_then(|attempt| attempt.repair_group_id.as_deref())
+ .map(|group_id| diagnostics::begin_repair_child(diagnostics, group_id, "elevation"))
+ .or_else(|| current_attempt.clone());
+ if let Some(attempt) = elevation_attempt.as_ref() {
+ diagnostics::append_phase_line(
+ &attempt.handle,
+ "meta",
+ &format!("Starting elevated apt install for: {}", packages.join(", ")),
+ );
+ diagnostics::record_elevation_packages(diagnostics, attempt, packages);
+ }
+
// Validate package names to prevent injection via elevated command.
let valid_pkg = Regex::new(r"^[a-zA-Z0-9][a-zA-Z0-9.+\-]*$").unwrap();
for pkg in packages {
if !valid_pkg.is_match(pkg) {
- return Err(format!("Invalid package name: {}", pkg));
+ let msg = format!("Invalid package name: {}", pkg);
+ finish_elevation_failure(diagnostics, elevation_attempt.as_ref(), None, msg.clone());
+ clear_current_attempt(state);
+ return Err(msg);
}
}
- // AppImage bundles run on non-Debian distros too. Pick the first package
- // manager we find. Names in `packages` are Debian-style; callers that want
- // cross-distro support should translate before invoking.
- let (program, base_args): (&str, &[&str]) = if Path::new("/usr/bin/apt-get").exists() {
- ("apt-get", &["install", "-y"])
- } else if Path::new("/usr/bin/dnf").exists() {
- ("dnf", &["install", "-y"])
- } else if Path::new("/usr/bin/zypper").exists() {
- ("zypper", &["install", "-y"])
- } else if Path::new("/usr/bin/pacman").exists() {
- ("pacman", &["-S", "--noconfirm"])
- } else {
- return Err(
- "No supported system package manager found (apt-get, dnf, zypper, pacman)".to_string(),
- );
- };
+ // install.sh reports Debian package names. Do not pass them to dnf,
+ // zypper, or pacman where names differ; show an explicit support boundary
+ // instead of offering an elevation flow that is likely to fail.
+ if !Path::new("/usr/bin/apt-get").exists() {
+ let msg = "Automatic system package installation is supported on apt-based Linux distributions (Ubuntu/Debian) only. Install the missing dependencies with your package manager and retry."
+ .to_string();
+ finish_elevation_failure(diagnostics, elevation_attempt.as_ref(), None, msg.clone());
+ clear_current_attempt(state);
+ return Err(msg);
+ }
info!(
- "[install] Elevated install of packages via {}: {}",
- program,
+ "[install] Elevated install of apt packages: {}",
packages.join(", ")
);
- let mut cmd = StdCommand::new(program);
- cmd.args(base_args).args(packages);
+ let mut update_cmd = StdCommand::new("apt-get");
+ update_cmd.args(["update", "-y"]);
+ match elevated_command::Command::new(update_cmd).output() {
+ Ok(elevated_update) => {
+ if let Some(attempt) = elevation_attempt.as_ref() {
+ diagnostics::append_phase_line(
+ &attempt.handle,
+ "apt-update-status",
+ &elevated_update.status.to_string(),
+ );
+ append_capped_output(
+ &attempt.handle,
+ "apt-update-stdout",
+ &elevated_update.stdout,
+ );
+ append_capped_output(
+ &attempt.handle,
+ "apt-update-stderr",
+ &elevated_update.stderr,
+ );
+ }
+ if !elevated_update.status.success() {
+ let stderr = capped_output_text(&elevated_update.stderr);
+ warn!(
+ "[install] apt-get update failed before elevated install; continuing with cached package metadata: {}",
+ stderr
+ );
+ if let Some(attempt) = elevation_attempt.as_ref() {
+ diagnostics::append_phase_line(
+ &attempt.handle,
+ "apt-update-warning",
+ "apt-get update failed; continuing with apt-get install",
+ );
+ }
+ }
+ }
+ Err(error) => {
+ warn!(
+ "[install] Elevated apt update could not run before install; continuing with apt-get install: {}",
+ error
+ );
+ if let Some(attempt) = elevation_attempt.as_ref() {
+ diagnostics::append_phase_line(
+ &attempt.handle,
+ "apt-update-error",
+ &format!(
+ "apt-get update could not run; continuing with apt-get install: {error}"
+ ),
+ );
+ }
+ }
+ }
- let elevated = elevated_command::Command::new(cmd)
- .output()
- .map_err(|e| format!("Elevated install failed: {}", e))?;
+ let mut install_cmd = StdCommand::new("apt-get");
+ install_cmd.args(["install", "-y"]).args(packages);
- if !elevated.status.success() {
- let stderr = String::from_utf8_lossy(&elevated.stderr);
+ let elevated_install = match elevated_command::Command::new(install_cmd).output() {
+ Ok(output) => output,
+ Err(error) => {
+ let msg = format!("Elevated install failed: {}", error);
+ finish_elevation_failure(diagnostics, elevation_attempt.as_ref(), None, msg.clone());
+ clear_current_attempt(state);
+ return Err(msg);
+ }
+ };
+ if let Some(attempt) = elevation_attempt.as_ref() {
+ diagnostics::append_phase_line(
+ &attempt.handle,
+ "apt-install-status",
+ &elevated_install.status.to_string(),
+ );
+ append_capped_output(
+ &attempt.handle,
+ "apt-install-stdout",
+ &elevated_install.stdout,
+ );
+ append_capped_output(
+ &attempt.handle,
+ "apt-install-stderr",
+ &elevated_install.stderr,
+ );
+ }
+
+ if !elevated_install.status.success() {
+ let stderr = capped_output_text(&elevated_install.stderr);
+ finish_elevation_failure(
+ diagnostics,
+ elevation_attempt.as_ref(),
+ Some(elevated_install.status.to_string()),
+ format!("Package installation failed: {stderr}"),
+ );
+ clear_current_attempt(state);
return Err(format!("Package installation failed: {}", stderr));
}
- info!("[install] Elevated package install succeeded");
+ if let Some(attempt) = elevation_attempt.as_ref() {
+ diagnostics::finish_attempt(
+ diagnostics,
+ attempt,
+ Some(elevated_install.status.to_string()),
+ false,
+ None,
+ );
+ }
+ info!("[install] Elevated apt package install succeeded");
Ok(())
}
+#[cfg(target_os = "linux")]
+fn finish_elevation_failure(
+ diagnostics: &DiagnosticsState,
+ attempt: Option<&AttemptLog>,
+ exit_status: Option<String>,
+ message: String,
+) {
+ if let Some(attempt) = attempt {
+ diagnostics::finish_attempt(
+ diagnostics,
+ attempt,
+ exit_status,
+ false,
+ Some(message.clone()),
+ );
+ if let Some(repair_group_id) = attempt.repair_group_id.as_deref() {
+ diagnostics::finish_repair_group(diagnostics, repair_group_id, "failed", Some(message));
+ }
+ }
+}
+
+#[cfg(target_os = "linux")]
+fn append_capped_output(handle: &diagnostics::PhaseLogHandle, stream: &str, bytes: &[u8]) {
+ diagnostics::append_phase_line(handle, stream, &capped_output_text(bytes));
+}
+
+#[cfg(any(target_os = "linux", test))]
+fn capped_output_text(bytes: &[u8]) -> String {
+ const MAX_ELEVATED_OUTPUT_BYTES: usize = 64 * 1024;
+ let text = String::from_utf8_lossy(bytes);
+ if text.len() <= MAX_ELEVATED_OUTPUT_BYTES {
+ return text.into_owned();
+ }
+ let boundary = diagnostics::valid_utf8_boundary(&text, MAX_ELEVATED_OUTPUT_BYTES);
+ let mut truncated = text[..boundary].to_string();
+ truncated.push_str("\n[elevated output truncated after 64KiB]");
+ truncated
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn elevated_output_cap_is_utf8_boundary_safe() {
+ let text = "é".repeat(40_000);
+ let capped = capped_output_text(text.as_bytes());
+ assert!(capped.ends_with("[elevated output truncated after 64KiB]"));
+ assert!(capped.is_char_boundary(capped.len()));
+ }
+
#[test]
fn repair_install_mode_uses_repair_elevation_event() {
assert_eq!(
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index f7d49cce60f..b4e718d867c 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -2,6 +2,7 @@
mod commands;
mod desktop_auth;
+mod diagnostics;
mod install;
mod preflight;
mod process;
@@ -58,6 +59,39 @@ fn setup_logging() {
}
}
+#[cfg(any(target_os = "windows", target_os = "linux"))]
+fn setup_custom_titlebar(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
+ let window = app.get_webview_window("main").ok_or_else(|| {
+ std::io::Error::new(std::io::ErrorKind::NotFound, "main window not found")
+ })?;
+ window.set_decorations(false)?;
+ Ok(())
+}
+
+fn cleanup_child_processes(app: &tauri::AppHandle) {
+ let diagnostics_state = app
+ .try_state::<diagnostics::DiagnosticsState>()
+ .map(|state| state.inner().clone());
+ if let Some(install_state) = app.try_state::<install::InstallState>() {
+ if let Some(diagnostics) = diagnostics_state.as_ref() {
+ install::record_install_intentional_stop(&install_state, diagnostics);
+ }
+ let _ = install::stop_install(&install_state);
+ }
+ if let Some(update_state) = app.try_state::<update::UpdateState>() {
+ if let Some(diagnostics) = diagnostics_state.as_ref() {
+ update::record_update_intentional_stop(&update_state, diagnostics);
+ }
+ let _ = update::stop_update(&update_state);
+ }
+ if let Some(backend_state) = app.try_state::<process::BackendState>() {
+ let shutdown = app
+ .try_state::<process::ShutdownFlag>()
+ .expect("ShutdownFlag must be managed");
+ let _ = process::stop_backend(&backend_state, &shutdown, diagnostics_state.as_ref());
+ }
+}
+
fn setup_tray(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
let open = MenuItemBuilder::with_id("open", "Open Studio").build(app)?;
let toggle = MenuItemBuilder::with_id("toggle", "Start/Stop Server").build(app)?;
@@ -81,17 +115,15 @@ fn setup_tray(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
let _ = app.emit("tray-toggle-server", ());
}
"quit" => {
- let install_state = app.state::<crate::install::InstallState>();
- let _ = crate::install::stop_install(&install_state);
- let update_state = app.state::<crate::update::UpdateState>();
- let _ = crate::update::stop_update(&update_state);
- // Detach the 5s graceful-wait so the tray click does not
- // block the Tauri main loop. Exit runs the RunEvent::Exit
- // safety net which also calls stop_backend synchronously.
- let shutdown = app.state::<crate::process::ShutdownFlag>().inner().clone();
- let backend_state = app.state::<crate::process::BackendState>().inner().clone();
- crate::process::stop_backend_detached(backend_state, shutdown);
- app.exit(0);
+ // Run cleanup off the menu callback, but only exit after the
+ // backend tree has been reaped. Exiting first can terminate this
+ // process while a detached cleanup thread is still waiting,
+ // leaving the backend orphaned.
+ let app_handle = app.clone();
+ std::thread::spawn(move || {
+ cleanup_child_processes(&app_handle);
+ app_handle.exit(0);
+ });
}
_ => {}
})
@@ -133,6 +165,8 @@ fn main() {
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_updater::Builder::new().build())
+ .plugin(tauri_plugin_clipboard_manager::init())
+ .manage(diagnostics::new_diagnostics_state())
.manage(install::new_install_state())
.manage(new_backend_state())
.manage(process::new_shutdown_flag())
@@ -149,10 +183,14 @@ fn main() {
commands::open_logs_dir,
commands::start_backend_update,
commands::start_managed_repair,
+ commands::cancel_pending_elevation,
commands::install_system_packages,
desktop_auth::desktop_auth,
+ diagnostics::collect_support_diagnostics,
])
.setup(|app| {
+ #[cfg(any(target_os = "windows", target_os = "linux"))]
+ setup_custom_titlebar(app)?;
setup_tray(app)?;
Ok(())
})
@@ -172,18 +210,7 @@ fn main() {
.run(|app, event| {
if let tauri::RunEvent::Exit = event {
// Cleanup on ALL exit paths — safety net for non-tray exits
- if let Some(install_state) = app.try_state::<install::InstallState>() {
- let _ = install::stop_install(&install_state);
- }
- if let Some(update_state) = app.try_state::<update::UpdateState>() {
- let _ = update::stop_update(&update_state);
- }
- if let Some(backend_state) = app.try_state::<process::BackendState>() {
- let shutdown = app
- .try_state::<process::ShutdownFlag>()
- .expect("ShutdownFlag must be managed");
- let _ = process::stop_backend(&backend_state, &shutdown);
- }
+ cleanup_child_processes(app);
}
});
}
diff --git a/studio/src-tauri/src/process.rs b/studio/src-tauri/src/process.rs
index beba8c1208a..ed2659c0d99 100644
--- a/studio/src-tauri/src/process.rs
+++ b/studio/src-tauri/src/process.rs
@@ -1,3 +1,4 @@
+use crate::diagnostics::{self, BackendLog, DiagnosticsState};
use log::{error, info, warn};
use process_wrap::std::*;
use regex::Regex;
@@ -15,6 +16,8 @@ pub struct BackendProcess {
pub port: Option<u16>,
pub logs: VecDeque<String>,
pub intentional_stop: bool,
+ pub generation: u64,
+ pub diagnostics_session: Option<BackendLog>,
}
impl Default for BackendProcess {
@@ -24,6 +27,8 @@ impl Default for BackendProcess {
port: None,
logs: VecDeque::with_capacity(MAX_LOG_LINES),
intentional_stop: false,
+ generation: 0,
+ diagnostics_session: None,
}
}
}
@@ -245,24 +250,48 @@ pub fn start_backend(
state: &BackendState,
port: u16,
shutdown: &ShutdownFlag,
-) -> Result<(), String> {
- let bin = resolve_backend_binary()?;
+ diagnostics_state: &DiagnosticsState,
+) -> Result<u64, String> {
+ let bin = match resolve_backend_binary() {
+ Ok(bin) => bin,
+ Err(msg) => {
+ diagnostics::record_backend_start_failure(
+ diagnostics_state,
+ Some(port),
+ None,
+ "resolve_backend_binary",
+ &msg,
+ );
+ return Err(msg);
+ }
+ };
shutdown.store(false, Ordering::SeqCst);
- // Reset state
- {
+ // Reset state and invalidate any readers from an older backend generation
+ // before we release the lock and spawn a new child.
+ let generation = {
let mut proc = state.lock().map_err(|e| e.to_string())?;
if proc.child.is_some() {
return Err("Backend is already running.".to_string());
}
+ proc.generation = proc.generation.wrapping_add(1);
proc.port = None;
proc.logs.clear();
proc.intentional_stop = false;
- }
+ proc.diagnostics_session = None;
+ proc.generation
+ };
+
+ let backend_log = diagnostics::begin_backend_session(diagnostics_state, port, generation);
let args = backend_args(port);
info!("Starting backend: {:?} {}", bin, args.join(" "));
+ diagnostics::append_phase_line(
+ &backend_log.handle,
+ "meta",
+ &format!("Starting backend: {:?} {}", bin, args.join(" ")),
+ );
let mut cmd = Command::new(&bin);
cmd.args(&args)
@@ -289,9 +318,17 @@ pub fn start_backend(
const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
cmd.creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW);
- let child = cmd
- .spawn()
- .map_err(|e| format!("Failed to spawn backend: {}", e))?;
+ let child = cmd.spawn().map_err(|e| {
+ let msg = format!("Failed to spawn backend: {}", e);
+ diagnostics::record_backend_start_failure(
+ diagnostics_state,
+ Some(port),
+ Some(generation),
+ "spawn_backend",
+ &msg,
+ );
+ msg
+ })?;
Box::new(child)
};
@@ -300,25 +337,45 @@ pub fn start_backend(
// Keep the backend tree in a process group on Unix for cleanup.
let mut wrap = CommandWrap::from(cmd);
wrap.wrap(ProcessGroup::leader());
- wrap.spawn()
- .map_err(|e| format!("Failed to spawn backend: {}", e))?
+ wrap.spawn().map_err(|e| {
+ let msg = format!("Failed to spawn backend: {}", e);
+ diagnostics::record_backend_start_failure(
+ diagnostics_state,
+ Some(port),
+ Some(generation),
+ "spawn_backend",
+ &msg,
+ );
+ msg
+ })?
};
let stdout = child.stdout().take();
let stderr = child.stderr().take();
- // Store child in state
+ // Store child in state for the already-selected generation.
{
let mut proc = state.lock().map_err(|e| e.to_string())?;
proc.child = Some(child);
+ proc.diagnostics_session = Some(backend_log.clone());
}
// Spawn stdout reader thread
if let Some(stdout) = stdout {
let app_handle = app.clone();
let state_clone = Arc::clone(state);
+ let diagnostics_clone = diagnostics_state.clone();
+ let backend_log_clone = backend_log.clone();
std::thread::spawn(move || {
- read_output_stream(stdout, &app_handle, &state_clone, false);
+ read_output_stream(
+ stdout,
+ &app_handle,
+ &state_clone,
+ &diagnostics_clone,
+ &backend_log_clone,
+ false,
+ generation,
+ );
});
}
@@ -326,12 +383,22 @@ pub fn start_backend(
if let Some(stderr) = stderr {
let app_handle = app.clone();
let state_clone = Arc::clone(state);
+ let diagnostics_clone = diagnostics_state.clone();
+ let backend_log_clone = backend_log.clone();
std::thread::spawn(move || {
- read_output_stream(stderr, &app_handle, &state_clone, true);
+ read_output_stream(
+ stderr,
+ &app_handle,
+ &state_clone,
+ &diagnostics_clone,
+ &backend_log_clone,
+ true,
+ generation,
+ );
});
}
- Ok(())
+ Ok(generation)
}
/// Read lines from a child process stream (stdout or stderr).
@@ -341,7 +408,10 @@ fn read_output_stream<R: std::io::Read>(
stream: R,
app: &AppHandle,
state: &BackendState,
+ diagnostics_state: &DiagnosticsState,
+ backend_log: &BackendLog,
is_stderr: bool,
+ generation: u64,
) {
let mut reader = std::io::BufReader::new(stream);
let port_re = Regex::new(r"TAURI_PORT=(\d+)").unwrap();
@@ -359,27 +429,56 @@ fn read_output_stream<R: std::io::Read>(
text.clone()
};
+ diagnostics::append_phase_line(
+ &backend_log.handle,
+ if is_stderr { "stderr" } else { "stdout" },
+ &text,
+ );
+
// Check for TAURI_PORT on stdout only
- if !is_stderr {
- if let Some(caps) = port_re.captures(&text) {
- if let Some(port_str) = caps.get(1) {
- if let Ok(port) = port_str.as_str().parse::<u16>() {
- info!("Detected backend port: {}", port);
- if let Ok(mut proc) = state.lock() {
- proc.port = Some(port);
- }
- let _ = app.emit("server-port", port);
- }
+ let detected_port = if !is_stderr {
+ port_re
+ .captures(&text)
+ .and_then(|caps| caps.get(1))
+ .and_then(|port_str| port_str.as_str().parse::<u16>().ok())
+ } else {
+ None
+ };
+
+ // Buffer the log line only for the current backend generation.
+ // Old reader threads can briefly outlive a stop/start cycle;
+ // they must not overwrite the new backend's port or logs.
+ let mut should_record_port = None;
+ let current_generation = if let Ok(mut proc) = state.lock() {
+ if proc.generation != generation {
+ false
+ } else {
+ if let Some(port) = detected_port {
+ proc.port = Some(port);
+ should_record_port = Some(port);
+ }
+ if proc.logs.len() >= MAX_LOG_LINES {
+ proc.logs.pop_front();
}
+ proc.logs.push_back(log_line.clone());
+ true
}
+ } else {
+ false
+ };
+
+ if !current_generation {
+ break;
}
- // Buffer the log line
- if let Ok(mut proc) = state.lock() {
- if proc.logs.len() >= MAX_LOG_LINES {
- proc.logs.pop_front();
- }
- proc.logs.push_back(log_line.clone());
+ if let Some(port) = should_record_port {
+ diagnostics::record_backend_port(
+ diagnostics_state,
+ &backend_log.session_id,
+ port,
+ );
+ info!("Detected backend port: {}", port);
+ let _ = app.emit("server-port", port);
}
info!("[backend] {}", log_line);
@@ -400,12 +499,18 @@ fn read_output_stream<R: std::io::Read>(
// Stream closed. Only the stdout reader checks for crashes.
if !is_stderr {
+ let mut exit_record: Option<(String, bool)> = None;
+ let mut emit_crash = false;
if let Ok(mut proc) = state.lock() {
+ if proc.generation != generation {
+ return;
+ }
let intentional = proc.intentional_stop;
let exited = if let Some(ref mut child) = proc.child {
match child.try_wait() {
Ok(Some(status)) => {
info!("Backend stdout stream ended with status: {}", status);
+ exit_record = Some((status.to_string(), intentional));
true
}
Ok(None) => {
@@ -423,20 +528,38 @@ fn read_output_stream<R: std::io::Read>(
if exited {
proc.child = None;
- if !intentional {
- error!("Backend process stdout closed unexpectedly (crash detected)");
- let _ = app.emit("server-crashed", ());
- }
+ proc.diagnostics_session = None;
+ emit_crash = !intentional;
}
}
+ if let Some((status, intentional)) = exit_record {
+ diagnostics::record_backend_exit(
+ diagnostics_state,
+ &backend_log.session_id,
+ Some(status),
+ intentional,
+ None,
+ );
+ }
+ if emit_crash {
+ error!("Backend process stdout closed unexpectedly (crash detected)");
+ let _ = app.emit("server-crashed", ());
+ }
}
}
/// Graceful shutdown of the backend process and its entire subprocess tree.
/// Unix: SIGTERM to process group -> wait up to 5s -> SIGKILL to group
/// Windows: CTRL_BREAK_EVENT -> wait up to 5s -> hidden taskkill /T /F
-pub fn stop_backend(state: &BackendState, shutdown: &ShutdownFlag) -> Result<(), String> {
+pub fn stop_backend(
+ state: &BackendState,
+ shutdown: &ShutdownFlag,
+ diagnostics_state: Option<&DiagnosticsState>,
+) -> Result<(), String> {
shutdown.store(true, Ordering::SeqCst);
+ if let Some(diagnostics_state) = diagnostics_state {
+ diagnostics::record_backend_intentional_stop(diagnostics_state);
+ }
// Extract the child and mark intentional stop.
// We take the child OUT of the mutex so we don't hold the lock during the wait loop.
@@ -526,12 +649,3 @@ pub fn stop_backend(state: &BackendState, shutdown: &ShutdownFlag) -> Result<(),
Ok(())
}
}
-
-/// Spawn `stop_backend` on a background thread and return immediately.
-/// Used by the tray "quit" path so the 5s graceful-wait does not block
-/// the Tauri main event loop before `app.exit(0)` fires.
-pub fn stop_backend_detached(state: BackendState, shutdown: ShutdownFlag) {
- std::thread::spawn(move || {
- let _ = stop_backend(&state, &shutdown);
- });
-}
diff --git a/studio/src-tauri/src/update.rs b/studio/src-tauri/src/update.rs
index 477f18ce28b..e79432312a6 100644
--- a/studio/src-tauri/src/update.rs
+++ b/studio/src-tauri/src/update.rs
@@ -1,3 +1,4 @@
+use crate::diagnostics::{self, AttemptLog, DiagnosticsState};
use log::{error, info, warn};
use process_wrap::std::*;
use std::io::BufRead;
@@ -10,6 +11,7 @@ use tauri::{AppHandle, Emitter};
pub struct UpdateProcess {
pub child: Option<Box<dyn ChildWrapper + Send>>,
pub intentional_stop: bool,
+ pub current_attempt: Option<AttemptLog>,
}
impl Default for UpdateProcess {
@@ -17,6 +19,7 @@ impl Default for UpdateProcess {
Self {
child: None,
intentional_stop: false,
+ current_attempt: None,
}
}
}
@@ -88,6 +91,8 @@ fn spawn_update(
fn stream_output(
app: &AppHandle,
progress_event: &'static str,
+ diagnostics: DiagnosticsState,
+ attempt: AttemptLog,
stdout: Option<std::process::ChildStdout>,
stderr: Option<std::process::ChildStderr>,
) -> Vec<std::thread::JoinHandle<()>> {
@@ -95,11 +100,29 @@ fn stream_output(
if let Some(out) = stdout {
let app_clone = app.clone();
+ let diagnostics_clone = diagnostics.clone();
+ let attempt_clone = attempt.clone();
threads.push(std::thread::spawn(move || {
let reader = std::io::BufReader::new(out);
for line in reader.lines() {
match line {
Ok(text) => {
+ diagnostics::append_phase_line(&attempt_clone.handle, "stdout", &text);
+ if let Some(step) = text.strip_prefix("[TAURI:STEP] ") {
+ diagnostics::record_step(&diagnostics_clone, &attempt_clone, step);
+ } else if let Some(progress) = text.strip_prefix("[TAURI:PROGRESS] ") {
+ diagnostics::record_progress(
+ &diagnostics_clone,
+ &attempt_clone,
+ progress,
+ );
+ } else if let Some(marker) = text.strip_prefix("[TAURI:DIAG] ") {
+ diagnostics::record_diag_marker(
+ &diagnostics_clone,
+ &attempt_clone,
+ marker,
+ );
+ }
info!("[update][stdout] {}", text);
let _ = app_clone.emit(progress_event, &text);
}
@@ -114,11 +137,13 @@ fn stream_output(
if let Some(err) = stderr {
let app_clone = app.clone();
+ let attempt_clone = attempt.clone();
threads.push(std::thread::spawn(move || {
let reader = std::io::BufReader::new(err);
for line in reader.lines() {
match line {
Ok(text) => {
+ diagnostics::append_phase_line(&attempt_clone.handle, "stderr", &text);
warn!("[update][stderr] {}", text);
let _ = app_clone.emit(progress_event, &text);
}
@@ -167,26 +192,54 @@ fn wait_for_exit(state: &UpdateState) -> Result<(ExitStatus, bool), String> {
// ── Public API ──
-pub fn run_backend_update(app: AppHandle, state: UpdateState) -> Result<(), String> {
- run_backend_update_with_terminal_events(app, state, true)
+pub fn run_backend_update(
+ app: AppHandle,
+ state: UpdateState,
+ diagnostics: DiagnosticsState,
+) -> Result<(), String> {
+ run_backend_update_with_terminal_events(app, state, diagnostics, true, None)
}
pub(crate) fn run_backend_update_for_repair(
app: AppHandle,
state: UpdateState,
+ diagnostics: DiagnosticsState,
+ repair_group_id: String,
) -> Result<(), String> {
- run_backend_update_with_terminal_events(app, state, false)
+ run_backend_update_with_terminal_events(app, state, diagnostics, false, Some(repair_group_id))
}
fn run_backend_update_with_terminal_events(
app: AppHandle,
state: UpdateState,
+ diagnostics: DiagnosticsState,
terminal_events: bool,
+ repair_group_id: Option<String>,
) -> Result<(), String> {
- let bin = crate::process::find_unsloth_binary()
- .ok_or("Unsloth binary not found. Cannot run update.")?;
+ let attempt = match repair_group_id.as_deref() {
+ Some(group_id) => diagnostics::begin_repair_child(&diagnostics, group_id, "update"),
+ None => diagnostics::begin_update_attempt(&diagnostics),
+ };
+ if let Ok(mut update) = state.lock() {
+ update.current_attempt = Some(attempt.clone());
+ }
+
+ let bin = match crate::process::find_unsloth_binary() {
+ Some(bin) => bin,
+ None => {
+ let msg = "Unsloth binary not found. Cannot run update.".to_string();
+ diagnostics::finish_attempt(&diagnostics, &attempt, None, false, Some(msg.clone()));
+ clear_current_attempt(&state);
+ return Err(msg);
+ }
+ };
info!("[update] Starting backend update via {:?}", bin);
+ diagnostics::append_phase_line(
+ &attempt.handle,
+ "meta",
+ &format!("Starting backend update via {:?}", bin),
+ );
let progress_event = if terminal_events {
"update-progress"
} else {
@@ -194,8 +247,28 @@ fn run_backend_update_with_terminal_events(
};
let _ = app.emit(progress_event, "Starting backend update...");
- let (stdout, stderr) = spawn_update(&bin, &state)?;
- let threads = stream_output(&app, progress_event, stdout, stderr);
+ let (stdout, stderr) = match spawn_update(&bin, &state) {
+ Ok(handles) => handles,
+ Err(msg) => {
+ diagnostics::finish_attempt(
+ &diagnostics,
+ &attempt,
+ None,
+ false,
+ Some(format!("spawn_update: {msg}")),
+ );
+ clear_current_attempt(&state);
+ return Err(msg);
+ }
+ };
+ let threads = stream_output(
+ &app,
+ progress_event,
+ diagnostics.clone(),
+ attempt.clone(),
+ stdout,
+ stderr,
+ );
let result = wait_for_exit(&state);
for handle in threads {
@@ -204,19 +277,43 @@ fn run_backend_update_with_terminal_events(
match result {
Ok((status, _)) if status.success() => {
+ diagnostics::finish_attempt(
+ &diagnostics,
+ &attempt,
+ Some(status.to_string()),
+ false,
+ None,
+ );
+ clear_current_attempt(&state);
info!("[update] Backend update complete");
if terminal_events {
let _ = app.emit("update-complete", ());
}
Ok(())
}
- Ok((_status, intentional)) if intentional => {
+ Ok((status, intentional)) if intentional => {
+ diagnostics::finish_attempt(
+ &diagnostics,
+ &attempt,
+ Some(status.to_string()),
+ true,
+ Some("Update stopped.".to_string()),
+ );
+ clear_current_attempt(&state);
info!("[update] Update stopped intentionally");
Err("Update stopped.".to_string())
}
- Ok((status, _)) => {
+ Ok((status, intentional)) => {
let code = status.code().unwrap_or(-1);
let msg = format!("Update exited with code {}", code);
+ diagnostics::finish_attempt(
+ &diagnostics,
+ &attempt,
+ Some(status.to_string()),
+ intentional,
+ Some(msg.clone()),
+ );
+ clear_current_attempt(&state);
error!("[update] {}", msg);
if terminal_events {
let _ = app.emit("update-failed", &msg);
@@ -224,6 +321,8 @@ fn run_backend_update_with_terminal_events(
Err(msg)
}
Err(msg) => {
+ diagnostics::finish_attempt(&diagnostics, &attempt, None, false, Some(msg.clone()));
+ clear_current_attempt(&state);
error!("[update] {}", msg);
if terminal_events {
let _ = app.emit("update-failed", &msg);
@@ -233,6 +332,28 @@ fn run_backend_update_with_terminal_events(
}
}
+fn clear_current_attempt(state: &UpdateState) {
+ if let Ok(mut update) = state.lock() {
+ update.current_attempt = None;
+ }
+}
+
+pub fn record_update_intentional_stop(state: &UpdateState, diagnostics: &DiagnosticsState) {
+ let attempt = state
+ .lock()
+ .ok()
+ .and_then(|update| update.current_attempt.clone());
+ if let Some(attempt) = attempt {
+ diagnostics::finish_attempt(
+ diagnostics,
+ &attempt,
+ None,
+ true,
+ Some("intentional_stop".to_string()),
+ );
+ }
+}
+
pub fn stop_update(state: &UpdateState) -> Result<(), String> {
let mut child = {
let mut update = match state.lock() {
diff --git a/studio/src-tauri/tauri.conf.json b/studio/src-tauri/tauri.conf.json
index 49819f8a25f..fce43889b5c 100644
--- a/studio/src-tauri/tauri.conf.json
+++ b/studio/src-tauri/tauri.conf.json
@@ -2,8 +2,14 @@
"productName": "Unsloth Studio (Desktop)",
"identifier": "ai.unsloth.studio",
"build": {
- "beforeDevCommand": "npm --prefix ../frontend run dev -- --port 5173 --strictPort",
- "beforeBuildCommand": "npm --prefix ../frontend run build",
+ "beforeDevCommand": {
+ "cwd": "../frontend",
+ "script": "npm run dev -- --port 5173 --strictPort"
+ },
+ "beforeBuildCommand": {
+ "cwd": "../frontend",
+ "script": "npm run build"
+ },
"frontendDist": "../frontend/dist",
"devUrl": "http://localhost:5173"
},
@@ -21,18 +27,13 @@
"visible": false,
"resizable": false
}
- ],
- "trayIcon": {
- "iconPath": "icons/icon.png",
- "id": "main",
- "tooltip": "Unsloth Studio (Desktop)"
- }
+ ]
},
"plugins": {
"updater": {
- "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDJENjJENDYxMTQ1QTYyOEIKUldTTFlsb1VZZFJpTFY1aHgyRkRqZUdjWGg0Sm1BVEZoMDVWME5PdE42bjZiekFRc1Fsb0JNbmIK",
+ "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEQ2RDhGMDMzNDNEMTlGMkQKUldRdG45RkRNL0RZMXZsaVo2TElUQlVHb1hVNWEyajhUOGFXeTdNVDFZTFdBVUtlZUh5L2wwWVYK",
"endpoints": [
- "https://github.com/danielhanchen/unsloth-staging-2/releases/latest/download/latest.json"
+ "https://github.com/unslothai/unsloth/releases/latest/download/latest.json"
],
"windows": {
"installMode": "passive"
@@ -42,11 +43,14 @@
"bundle": {
"active": true,
"createUpdaterArtifacts": true,
+ "publisher": "Unsloth AI",
+ "homepage": "https://unsloth.ai/",
+ "copyright": "© 2026 Unsloth AI. All rights reserved.",
+ "license": "AGPL-3.0-only",
"targets": ["app", "appimage", "deb", "dmg", "nsis"],
"resources": {
"../../install.sh": "install.sh",
- "../../install.ps1": "install.ps1",
- "../install_python_stack.py": "install_python_stack.py"
+ "../../install.ps1": "install.ps1"
},
"icon": [
"icons/32x32.png",
@@ -54,6 +58,18 @@
"icons/icon.ico",
"icons/icon.icns"
],
+ "windows": {
+ "nsis": {
+ "installerHooks": "./windows/hooks.nsh",
+ "template": "./windows/installer.nsi",
+ "installerIcon": "./icons/icon.ico",
+ "headerImage": "./windows/branding/nsis-header.bmp",
+ "sidebarImage": "./windows/branding/nsis-sidebar.bmp",
+ "installMode": "currentUser",
+ "languages": ["English"],
+ "displayLanguageSelector": false
+ }
+ },
"linux": {
"deb": {
"postRemoveScript": "./linux/postremove.sh"
diff --git a/studio/src-tauri/tauri.windows.conf.json b/studio/src-tauri/tauri.windows.conf.json
index a68cf6351f9..83f685cda49 100644
--- a/studio/src-tauri/tauri.windows.conf.json
+++ b/studio/src-tauri/tauri.windows.conf.json
@@ -4,12 +4,6 @@
"signCommand": {
"cmd": "trusted-signing-cli",
"args": ["-e", "https://eus.codesigning.azure.net", "-d", "Unsloth Studio (Desktop)", "%1"]
- },
- "nsis": {
- "installerHooks": "./windows/hooks.nsh",
- "installerIcon": "./icons/icon.ico",
- "headerImage": "./windows/branding/nsis-header.bmp",
- "sidebarImage": "./windows/branding/nsis-sidebar.bmp"
}
}
}
diff --git a/studio/src-tauri/windows/branding/nsis-header.bmp b/studio/src-tauri/windows/branding/nsis-header.bmp
index 7eacdce7db5..b675c4e1c3e 100644
Binary files a/studio/src-tauri/windows/branding/nsis-header.bmp and b/studio/src-tauri/windows/branding/nsis-header.bmp differ
diff --git a/studio/src-tauri/windows/branding/nsis-sidebar.bmp b/studio/src-tauri/windows/branding/nsis-sidebar.bmp
index c3bd480fc89..0113ee5932f 100644
Binary files a/studio/src-tauri/windows/branding/nsis-sidebar.bmp and b/studio/src-tauri/windows/branding/nsis-sidebar.bmp differ
diff --git a/studio/src-tauri/windows/hooks.nsh b/studio/src-tauri/windows/hooks.nsh
index 64655e8f6ea..8c68a3e54f2 100644
--- a/studio/src-tauri/windows/hooks.nsh
+++ b/studio/src-tauri/windows/hooks.nsh
@@ -1,8 +1,9 @@
; Unsloth Studio NSIS installer hooks
!macro NSIS_HOOK_POSTUNINSTALL
- MessageBox MB_YESNO|MB_ICONQUESTION "Remove all Unsloth data ($PROFILE\.unsloth)?$\n$\nThis deletes installed models, training outputs, and configuration." IDNO skip_cleanup
- RMDir /r "$PROFILE\.unsloth"
- DetailPrint "Removed $PROFILE\.unsloth"
- skip_cleanup:
+ ; Desktop uninstall must not remove $PROFILE\.unsloth. The CLI/web
+ ; installers also use that tree for environments, models, outputs, and
+ ; configuration, and there has been no prior public desktop release whose
+ ; private state needs cleanup here.
+ DetailPrint "Preserved shared Unsloth data at $PROFILE\.unsloth"
!macroend
diff --git a/studio/src-tauri/windows/installer.nsi b/studio/src-tauri/windows/installer.nsi
new file mode 100644
index 00000000000..7cc2f223c73
--- /dev/null
+++ b/studio/src-tauri/windows/installer.nsi
@@ -0,0 +1,994 @@
+; Unsloth Studio custom NSIS template.
+; Source: https://raw.githubusercontent.com/tauri-apps/tauri/tauri-cli-v2.10.1/crates/tauri-bundler/src/bundle/windows/nsis/installer.nsi
+; Source tags tauri-cli-v2.10.1 and tauri-bundler-v2.8.1 resolve to commit 9b17a7aeae9a83222ffe829aa4e2d8a5ba6bed8c.
+; Verified release CLI: @tauri-apps/cli 2.10.1 / tauri-cli 2.10.1
+; Verified bundler/template crate: tauri-bundler 2.8.1
+; Copied: 2026-04-30
+; Local patches:
+; - UNSLOTH_PATCH_START: non-WiX newer/unknown upgrades install in place.
+; - UNSLOTH_PATCH_START: guard non-WiX upgrade leave routing.
+
+Unicode true
+ManifestDPIAware true
+; Add in `dpiAwareness` `PerMonitorV2` to manifest for Windows 10 1607+ (note this should not affect lower versions since they should be able to ignore this and pick up `dpiAware` `true` set by `ManifestDPIAware true`)
+; Currently undocumented on NSIS's website but is in the Docs folder of source tree, see
+; https://github.com/kichik/nsis/blob/5fc0b87b819a9eec006df4967d08e522ddd651c9/Docs/src/attributes.but#L286-L300
+; https://github.com/tauri-apps/tauri/pull/10106
+ManifestDPIAwareness PerMonitorV2
+
+!if "{{compression}}" == "none"
+ SetCompress off
+!else
+ ; Set the compression algorithm. We default to LZMA.
+ SetCompressor /SOLID "{{compression}}"
+!endif
+
+!include MUI2.nsh
+!include FileFunc.nsh
+!include x64.nsh
+!include WordFunc.nsh
+!include "utils.nsh"
+!include "FileAssociation.nsh"
+!include "Win\COM.nsh"
+!include "Win\Propkey.nsh"
+!include "StrFunc.nsh"
+${StrCase}
+${StrLoc}
+
+{{#if installer_hooks}}
+!include "{{installer_hooks}}"
+{{/if}}
+
+!define WEBVIEW2APPGUID "{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"
+
+!define MANUFACTURER "{{manufacturer}}"
+!define PRODUCTNAME "{{product_name}}"
+!define VERSION "{{version}}"
+!define VERSIONWITHBUILD "{{version_with_build}}"
+!define HOMEPAGE "{{homepage}}"
+!define INSTALLMODE "{{install_mode}}"
+!define LICENSE "{{license}}"
+!define INSTALLERICON "{{installer_icon}}"
+!define SIDEBARIMAGE "{{sidebar_image}}"
+!define HEADERIMAGE "{{header_image}}"
+!define MAINBINARYNAME "{{main_binary_name}}"
+!define MAINBINARYSRCPATH "{{main_binary_path}}"
+!define BUNDLEID "{{bundle_id}}"
+!define COPYRIGHT "{{copyright}}"
+!define OUTFILE "{{out_file}}"
+!define ARCH "{{arch}}"
+!define ADDITIONALPLUGINSPATH "{{additional_plugins_path}}"
+!define ALLOWDOWNGRADES "{{allow_downgrades}}"
+!define DISPLAYLANGUAGESELECTOR "{{display_language_selector}}"
+!define INSTALLWEBVIEW2MODE "{{install_webview2_mode}}"
+!define WEBVIEW2INSTALLERARGS "{{webview2_installer_args}}"
+!define WEBVIEW2BOOTSTRAPPERPATH "{{webview2_bootstrapper_path}}"
+!define WEBVIEW2INSTALLERPATH "{{webview2_installer_path}}"
+!define MINIMUMWEBVIEW2VERSION "{{minimum_webview2_version}}"
+!define UNINSTKEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCTNAME}"
+!define MANUKEY "Software\${MANUFACTURER}"
+!define MANUPRODUCTKEY "${MANUKEY}\${PRODUCTNAME}"
+!define UNINSTALLERSIGNCOMMAND "{{uninstaller_sign_cmd}}"
+!define ESTIMATEDSIZE "{{estimated_size}}"
+!define STARTMENUFOLDER "{{start_menu_folder}}"
+
+Var PassiveMode
+Var UpdateMode
+Var NoShortcutMode
+Var WixMode
+Var OldMainBinaryName
+
+Name "${PRODUCTNAME}"
+BrandingText "${COPYRIGHT}"
+OutFile "${OUTFILE}"
+
+; We don't actually use this value as default install path,
+; it's just for nsis to append the product name folder in the directory selector
+; https://nsis.sourceforge.io/Reference/InstallDir
+!define PLACEHOLDER_INSTALL_DIR "placeholder\${PRODUCTNAME}"
+InstallDir "${PLACEHOLDER_INSTALL_DIR}"
+
+VIProductVersion "${VERSIONWITHBUILD}"
+VIAddVersionKey "ProductName" "${PRODUCTNAME}"
+VIAddVersionKey "FileDescription" "${PRODUCTNAME}"
+VIAddVersionKey "LegalCopyright" "${COPYRIGHT}"
+VIAddVersionKey "FileVersion" "${VERSION}"
+VIAddVersionKey "ProductVersion" "${VERSION}"
+
+# additional plugins
+!addplugindir "${ADDITIONALPLUGINSPATH}"
+
+; Uninstaller signing command
+!if "${UNINSTALLERSIGNCOMMAND}" != ""
+ !uninstfinalize '${UNINSTALLERSIGNCOMMAND}'
+!endif
+
+; Handle install mode, `perUser`, `perMachine` or `both`
+!if "${INSTALLMODE}" == "perMachine"
+ RequestExecutionLevel admin
+!endif
+
+!if "${INSTALLMODE}" == "currentUser"
+ RequestExecutionLevel user
+!endif
+
+!if "${INSTALLMODE}" == "both"
+ !define MULTIUSER_MUI
+ !define MULTIUSER_INSTALLMODE_INSTDIR "${PRODUCTNAME}"
+ !define MULTIUSER_INSTALLMODE_COMMANDLINE
+ !if "${ARCH}" == "x64"
+ !define MULTIUSER_USE_PROGRAMFILES64
+ !else if "${ARCH}" == "arm64"
+ !define MULTIUSER_USE_PROGRAMFILES64
+ !endif
+ !define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_KEY "${UNINSTKEY}"
+ !define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_VALUENAME "CurrentUser"
+ !define MULTIUSER_INSTALLMODEPAGE_SHOWUSERNAME
+ !define MULTIUSER_INSTALLMODE_FUNCTION RestorePreviousInstallLocation
+ !define MULTIUSER_EXECUTIONLEVEL Highest
+ !include MultiUser.nsh
+!endif
+
+; Installer icon
+!if "${INSTALLERICON}" != ""
+ !define MUI_ICON "${INSTALLERICON}"
+!endif
+
+; Installer sidebar image
+!if "${SIDEBARIMAGE}" != ""
+ !define MUI_WELCOMEFINISHPAGE_BITMAP "${SIDEBARIMAGE}"
+!endif
+
+; Installer header image
+!if "${HEADERIMAGE}" != ""
+ !define MUI_HEADERIMAGE
+ !define MUI_HEADERIMAGE_BITMAP "${HEADERIMAGE}"
+!endif
+
+; Define registry key to store installer language
+!define MUI_LANGDLL_REGISTRY_ROOT "HKCU"
+!define MUI_LANGDLL_REGISTRY_KEY "${MANUPRODUCTKEY}"
+!define MUI_LANGDLL_REGISTRY_VALUENAME "Installer Language"
+
+; Installer pages, must be ordered as they appear
+; 1. Welcome Page
+!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
+!insertmacro MUI_PAGE_WELCOME
+
+; 2. License Page (if defined)
+!if "${LICENSE}" != ""
+ !define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
+ !insertmacro MUI_PAGE_LICENSE "${LICENSE}"
+!endif
+
+; 3. Install mode (if it is set to `both`)
+!if "${INSTALLMODE}" == "both"
+ !define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
+ !insertmacro MULTIUSER_PAGE_INSTALLMODE
+!endif
+
+; 4. Custom page to ask user if he wants to reinstall/uninstall
+; only if a previous installation was detected
+Var ReinstallPageCheck
+Page custom PageReinstall PageLeaveReinstall
+Function PageReinstall
+ ; Uninstall previous WiX installation if exists.
+ ;
+ ; A WiX installer stores the installation info in registry
+ ; using a UUID and so we have to loop through all keys under
+ ; `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall`
+ ; and check if `DisplayName` and `Publisher` keys match ${PRODUCTNAME} and ${MANUFACTURER}
+ ;
+ ; This has a potential issue that there maybe another installation that matches
+ ; our ${PRODUCTNAME} and ${MANUFACTURER} but wasn't installed by our WiX installer,
+ ; however, this should be fine since the user will have to confirm the uninstallation
+ ; and they can chose to abort it if doesn't make sense.
+ StrCpy $0 0
+ wix_loop:
+ EnumRegKey $1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" $0
+ StrCmp $1 "" wix_loop_done ; Exit loop if there is no more keys to loop on
+ IntOp $0 $0 + 1
+ ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "DisplayName"
+ ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "Publisher"
+ StrCmp "$R0$R1" "${PRODUCTNAME}${MANUFACTURER}" 0 wix_loop
+ ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "UninstallString"
+ ${StrCase} $R1 $R0 "L"
+ ${StrLoc} $R0 $R1 "msiexec" ">"
+ StrCmp $R0 0 0 wix_loop_done
+ StrCpy $WixMode 1
+ StrCpy $R6 "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1"
+ Goto compare_version
+ wix_loop_done:
+
+ ; Check if there is an existing installation, if not, abort the reinstall page
+ ReadRegStr $R0 SHCTX "${UNINSTKEY}" ""
+ ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"
+ ${IfThen} "$R0$R1" == "" ${|} Abort ${|}
+
+ ; Compare this installar version with the existing installation
+ ; and modify the messages presented to the user accordingly
+ compare_version:
+ StrCpy $R4 "$(older)"
+ ${If} $WixMode = 1
+ ReadRegStr $R0 HKLM "$R6" "DisplayVersion"
+ ${Else}
+ ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion"
+ ${EndIf}
+ ${IfThen} $R0 == "" ${|} StrCpy $R4 "$(unknown)" ${|}
+
+ nsis_tauri_utils::SemverCompare "${VERSION}" $R0
+ Pop $R0
+
+ ; UNSLOTH_PATCH_START: non-WiX newer/unknown upgrades install in place.
+ ; Do not invoke stale internal NSIS uninstallers during normal desktop
+ ; upgrades; continue to Section Install so Tauri handles the running app.
+ ${If} $WixMode <> 1
+ ${If} $UpdateMode = 1
+ Abort
+ ${ElseIf} $R0 = 1
+ Abort
+ ${ElseIf} $R0 <> 0
+ ${If} $R0 <> -1
+ StrCpy $R0 1
+ Abort
+ ${EndIf}
+ ${EndIf}
+ ${EndIf}
+ ; UNSLOTH_PATCH_END
+
+ ; Reinstalling the same version
+ ${If} $R0 = 0
+ StrCpy $R1 "$(alreadyInstalledLong)"
+ StrCpy $R2 "$(addOrReinstall)"
+ StrCpy $R3 "$(uninstallApp)"
+ !insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(chooseMaintenanceOption)"
+ ; Upgrading
+ ${ElseIf} $R0 = 1
+ StrCpy $R1 "$(olderOrUnknownVersionInstalled)"
+ StrCpy $R2 "$(uninstallBeforeInstalling)"
+ StrCpy $R3 "$(dontUninstall)"
+ !insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)"
+ ; Downgrading
+ ${ElseIf} $R0 = -1
+ StrCpy $R1 "$(newerVersionInstalled)"
+ StrCpy $R2 "$(uninstallBeforeInstalling)"
+ !if "${ALLOWDOWNGRADES}" == "true"
+ StrCpy $R3 "$(dontUninstall)"
+ !else
+ StrCpy $R3 "$(dontUninstallDowngrade)"
+ !endif
+ !insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)"
+ ${Else}
+ Abort
+ ${EndIf}
+
+ ; Skip showing the page if passive
+ ;
+ ; Note that we don't call this earlier at the begining
+ ; of this function because we need to populate some variables
+ ; related to current installed version if detected and whether
+ ; we are downgrading or not.
+ ${If} $PassiveMode = 1
+ Call PageLeaveReinstall
+ ${Else}
+ nsDialogs::Create 1018
+ Pop $R4
+ ${IfThen} $(^RTL) = 1 ${|} nsDialogs::SetRTL $(^RTL) ${|}
+
+ ${NSD_CreateLabel} 0 0 100% 24u $R1
+ Pop $R1
+
+ ${NSD_CreateRadioButton} 30u 50u -30u 8u $R2
+ Pop $R2
+ ${NSD_OnClick} $R2 PageReinstallUpdateSelection
+
+ ${NSD_CreateRadioButton} 30u 70u -30u 8u $R3
+ Pop $R3
+ ; Disable this radio button if downgrading and downgrades are disabled
+ !if "${ALLOWDOWNGRADES}" == "false"
+ ${IfThen} $R0 = -1 ${|} EnableWindow $R3 0 ${|}
+ !endif
+ ${NSD_OnClick} $R3 PageReinstallUpdateSelection
+
+ ; Check the first radio button if this the first time
+ ; we enter this page or if the second button wasn't
+ ; selected the last time we were on this page
+ ${If} $ReinstallPageCheck <> 2
+ SendMessage $R2 ${BM_SETCHECK} ${BST_CHECKED} 0
+ ${Else}
+ SendMessage $R3 ${BM_SETCHECK} ${BST_CHECKED} 0
+ ${EndIf}
+
+ ${NSD_SetFocus} $R2
+ nsDialogs::Show
+ ${EndIf}
+FunctionEnd
+Function PageReinstallUpdateSelection
+ ${NSD_GetState} $R2 $R1
+ ${If} $R1 == ${BST_CHECKED}
+ StrCpy $ReinstallPageCheck 1
+ ${Else}
+ StrCpy $ReinstallPageCheck 2
+ ${EndIf}
+FunctionEnd
+Function PageLeaveReinstall
+ ${NSD_GetState} $R2 $R1
+
+ ; If migrating from Wix, always uninstall
+ ${If} $WixMode = 1
+ Goto reinst_uninstall
+ ${EndIf}
+
+ ; In update mode, always proceeds without uninstalling
+ ${If} $UpdateMode = 1
+ Goto reinst_done
+ ${EndIf}
+
+ ; UNSLOTH_PATCH_START: guard non-WiX upgrade leave routing.
+ ; Passive/default upgrade choices must not ExecWait the old UninstallString.
+ ${If} $WixMode <> 1
+ ${If} $R0 = 1
+ Goto reinst_done
+ ${ElseIf} $R0 <> 0
+ ${If} $R0 <> -1
+ Goto reinst_done
+ ${EndIf}
+ ${EndIf}
+ ${EndIf}
+ ; UNSLOTH_PATCH_END
+
+ ; $R0 holds whether same(0)/upgrading(1)/downgrading(-1) version
+ ; $R1 holds the radio buttons state:
+ ; 1 => first choice was selected
+ ; 0 => second choice was selected
+ ${If} $R0 = 0 ; Same version, proceed
+ ${If} $R1 = 1 ; User chose to add/reinstall
+ Goto reinst_done
+ ${Else} ; User chose to uninstall
+ Goto reinst_uninstall
+ ${EndIf}
+ ${ElseIf} $R0 = 1 ; Upgrading
+ ${If} $R1 = 1 ; User chose to uninstall
+ Goto reinst_uninstall
+ ${Else}
+ Goto reinst_done ; User chose NOT to uninstall
+ ${EndIf}
+ ${ElseIf} $R0 = -1 ; Downgrading
+ ${If} $R1 = 1 ; User chose to uninstall
+ Goto reinst_uninstall
+ ${Else}
+ Goto reinst_done ; User chose NOT to uninstall
+ ${EndIf}
+ ${EndIf}
+
+ reinst_uninstall:
+ HideWindow
+ ClearErrors
+
+ ${If} $WixMode = 1
+ ReadRegStr $R1 HKLM "$R6" "UninstallString"
+ ExecWait '$R1' $0
+ ${Else}
+ ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""
+ ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"
+ ${IfThen} $UpdateMode = 1 ${|} StrCpy $R1 "$R1 /UPDATE" ${|} ; append /UPDATE
+ ${IfThen} $PassiveMode = 1 ${|} StrCpy $R1 "$R1 /P" ${|} ; append /P
+ StrCpy $R1 "$R1 _?=$4" ; append uninstall directory
+ ExecWait '$R1' $0
+ ${EndIf}
+
+ BringToFront
+
+ ${IfThen} ${Errors} ${|} StrCpy $0 2 ${|} ; ExecWait failed, set fake exit code
+
+ ${If} $0 <> 0
+ ${OrIf} ${FileExists} "$INSTDIR\${MAINBINARYNAME}.exe"
+ ; User cancelled wix uninstaller? return to select un/reinstall page
+ ${If} $WixMode = 1
+ ${AndIf} $0 = 1602
+ Abort
+ ${EndIf}
+
+ ; User cancelled NSIS uninstaller? return to select un/reinstall page
+ ${If} $0 = 1
+ Abort
+ ${EndIf}
+
+ ; Other erros? show generic error message and return to select un/reinstall page
+ MessageBox MB_ICONEXCLAMATION "$(unableToUninstall)"
+ Abort
+ ${EndIf}
+ reinst_done:
+FunctionEnd
+
+; 5. Choose install directory page
+!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
+!insertmacro MUI_PAGE_DIRECTORY
+
+; 6. Start menu shortcut page
+Var AppStartMenuFolder
+!if "${STARTMENUFOLDER}" != ""
+ !define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
+ !define MUI_STARTMENUPAGE_DEFAULTFOLDER "${STARTMENUFOLDER}"
+!else
+ !define MUI_PAGE_CUSTOMFUNCTION_PRE Skip
+!endif
+!insertmacro MUI_PAGE_STARTMENU Application $AppStartMenuFolder
+
+; 7. Installation page
+!insertmacro MUI_PAGE_INSTFILES
+
+; 8. Finish page
+;
+; Don't auto jump to finish page after installation page,
+; because the installation page has useful info that can be used debug any issues with the installer.
+!define MUI_FINISHPAGE_NOAUTOCLOSE
+; Use show readme button in the finish page as a button create a desktop shortcut
+!define MUI_FINISHPAGE_SHOWREADME
+!define MUI_FINISHPAGE_SHOWREADME_TEXT "$(createDesktop)"
+!define MUI_FINISHPAGE_SHOWREADME_FUNCTION CreateOrUpdateDesktopShortcut
+; Show run app after installation.
+!define MUI_FINISHPAGE_RUN
+!define MUI_FINISHPAGE_RUN_FUNCTION RunMainBinary
+!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
+!insertmacro MUI_PAGE_FINISH
+
+Function RunMainBinary
+ nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" ""
+FunctionEnd
+
+; Uninstaller Pages
+; 1. Confirm uninstall page
+Var DeleteAppDataCheckbox
+Var DeleteAppDataCheckboxState
+!define /ifndef WS_EX_LAYOUTRTL 0x00400000
+!define MUI_PAGE_CUSTOMFUNCTION_SHOW un.ConfirmShow
+Function un.ConfirmShow ; Add add a `Delete app data` check box
+ ; $1 inner dialog HWND
+ ; $2 window DPI
+ ; $3 style
+ ; $4 x
+ ; $5 y
+ ; $6 width
+ ; $7 height
+ FindWindow $1 "#32770" "" $HWNDPARENT ; Find inner dialog
+ System::Call "user32::GetDpiForWindow(p r1) i .r2"
+ ${If} $(^RTL) = 1
+ StrCpy $3 "${__NSD_CheckBox_EXSTYLE} | ${WS_EX_LAYOUTRTL}"
+ IntOp $4 50 * $2
+ ${Else}
+ StrCpy $3 "${__NSD_CheckBox_EXSTYLE}"
+ IntOp $4 0 * $2
+ ${EndIf}
+ IntOp $5 100 * $2
+ IntOp $6 400 * $2
+ IntOp $7 25 * $2
+ IntOp $4 $4 / 96
+ IntOp $5 $5 / 96
+ IntOp $6 $6 / 96
+ IntOp $7 $7 / 96
+ System::Call 'user32::CreateWindowEx(i r3, w "${__NSD_CheckBox_CLASS}", w "$(deleteAppData)", i ${__NSD_CheckBox_STYLE}, i r4, i r5, i r6, i r7, p r1, i0, i0, i0) i .s'
+ Pop $DeleteAppDataCheckbox
+ SendMessage $HWNDPARENT ${WM_GETFONT} 0 0 $1
+ SendMessage $DeleteAppDataCheckbox ${WM_SETFONT} $1 1
+FunctionEnd
+!define MUI_PAGE_CUSTOMFUNCTION_LEAVE un.ConfirmLeave
+Function un.ConfirmLeave
+ SendMessage $DeleteAppDataCheckbox ${BM_GETCHECK} 0 0 $DeleteAppDataCheckboxState
+FunctionEnd
+!define MUI_PAGE_CUSTOMFUNCTION_PRE un.SkipIfPassive
+!insertmacro MUI_UNPAGE_CONFIRM
+
+; 2. Uninstalling Page
+!insertmacro MUI_UNPAGE_INSTFILES
+
+;Languages
+{{#each languages}}
+!insertmacro MUI_LANGUAGE "{{this}}"
+{{/each}}
+!insertmacro MUI_RESERVEFILE_LANGDLL
+{{#each language_files}}
+ !include "{{this}}"
+{{/each}}
+
+Function .onInit
+ ${GetOptions} $CMDLINE "/P" $PassiveMode
+ ${IfNot} ${Errors}
+ StrCpy $PassiveMode 1
+ ${EndIf}
+
+ ${GetOptions} $CMDLINE "/NS" $NoShortcutMode
+ ${IfNot} ${Errors}
+ StrCpy $NoShortcutMode 1
+ ${EndIf}
+
+ ${GetOptions} $CMDLINE "/UPDATE" $UpdateMode
+ ${IfNot} ${Errors}
+ StrCpy $UpdateMode 1
+ ${EndIf}
+
+ !if "${DISPLAYLANGUAGESELECTOR}" == "true"
+ !insertmacro MUI_LANGDLL_DISPLAY
+ !endif
+
+ !insertmacro SetContext
+
+ ${If} $INSTDIR == "${PLACEHOLDER_INSTALL_DIR}"
+ ; Set default install location
+ !if "${INSTALLMODE}" == "perMachine"
+ ${If} ${RunningX64}
+ !if "${ARCH}" == "x64"
+ StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}"
+ !else if "${ARCH}" == "arm64"
+ StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}"
+ !else
+ StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}"
+ !endif
+ ${Else}
+ StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}"
+ ${EndIf}
+ !else if "${INSTALLMODE}" == "currentUser"
+ StrCpy $INSTDIR "$LOCALAPPDATA\${PRODUCTNAME}"
+ !endif
+
+ Call RestorePreviousInstallLocation
+ ${EndIf}
+
+
+ !if "${INSTALLMODE}" == "both"
+ !insertmacro MULTIUSER_INIT
+ !endif
+FunctionEnd
+
+
+Section EarlyChecks
+ ; Abort silent installer if downgrades is disabled
+ !if "${ALLOWDOWNGRADES}" == "false"
+ ${If} ${Silent}
+ ; If downgrading
+ ${If} $R0 = -1
+ System::Call 'kernel32::AttachConsole(i -1)i.r0'
+ ${If} $0 <> 0
+ System::Call 'kernel32::GetStdHandle(i -11)i.r0'
+ System::call 'kernel32::SetConsoleTextAttribute(i r0, i 0x0004)' ; set red color
+ FileWrite $0 "$(silentDowngrades)"
+ ${EndIf}
+ Abort
+ ${EndIf}
+ ${EndIf}
+ !endif
+
+SectionEnd
+
+Section WebView2
+ ; Check if Webview2 is already installed and skip this section
+ ${If} ${RunningX64}
+ ReadRegStr $4 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv"
+ ${Else}
+ ReadRegStr $4 HKLM "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv"
+ ${EndIf}
+ ${If} $4 == ""
+ ReadRegStr $4 HKCU "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv"
+ ${EndIf}
+
+ ${If} $4 == ""
+ ; Webview2 installation
+ ;
+ ; Skip if updating
+ ${If} $UpdateMode <> 1
+ !if "${INSTALLWEBVIEW2MODE}" == "downloadBootstrapper"
+ Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe"
+ DetailPrint "$(webview2Downloading)"
+ NSISdl::download "https://go.microsoft.com/fwlink/p/?LinkId=2124703" "$TEMP\MicrosoftEdgeWebview2Setup.exe"
+ Pop $0
+ ${If} $0 == "success"
+ DetailPrint "$(webview2DownloadSuccess)"
+ ${Else}
+ DetailPrint "$(webview2DownloadError)"
+ Abort "$(webview2AbortError)"
+ ${EndIf}
+ StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe"
+ Goto install_webview2
+ !endif
+
+ !if "${INSTALLWEBVIEW2MODE}" == "embedBootstrapper"
+ Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe"
+ File "/oname=$TEMP\MicrosoftEdgeWebview2Setup.exe" "${WEBVIEW2BOOTSTRAPPERPATH}"
+ DetailPrint "$(installingWebview2)"
+ StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe"
+ Goto install_webview2
+ !endif
+
+ !if "${INSTALLWEBVIEW2MODE}" == "offlineInstaller"
+ Delete "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe"
+ File "/oname=$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe" "${WEBVIEW2INSTALLERPATH}"
+ DetailPrint "$(installingWebview2)"
+ StrCpy $6 "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe"
+ Goto install_webview2
+ !endif
+
+ Goto webview2_done
+
+ install_webview2:
+ DetailPrint "$(installingWebview2)"
+ ; $6 holds the path to the webview2 installer
+ ExecWait "$6 ${WEBVIEW2INSTALLERARGS} /install" $1
+ ${If} $1 = 0
+ DetailPrint "$(webview2InstallSuccess)"
+ ${Else}
+ DetailPrint "$(webview2InstallError)"
+ Abort "$(webview2AbortError)"
+ ${EndIf}
+ webview2_done:
+ ${EndIf}
+ ${Else}
+ !if "${MINIMUMWEBVIEW2VERSION}" != ""
+ ${VersionCompare} "${MINIMUMWEBVIEW2VERSION}" "$4" $R0
+ ${If} $R0 = 1
+ update_webview:
+ DetailPrint "$(installingWebview2)"
+ ${If} ${RunningX64}
+ ReadRegStr $R1 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate" "path"
+ ${Else}
+ ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\EdgeUpdate" "path"
+ ${EndIf}
+ ${If} $R1 == ""
+ ReadRegStr $R1 HKCU "SOFTWARE\Microsoft\EdgeUpdate" "path"
+ ${EndIf}
+ ${If} $R1 != ""
+ ; Chromium updater docs: https://source.chromium.org/chromium/chromium/src/+/main:docs/updater/user_manual.md
+ ; Modified from "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft EdgeWebView\ModifyPath"
+ ExecWait `"$R1" /install appguid=${WEBVIEW2APPGUID}&needsadmin=true` $1
+ ${If} $1 = 0
+ DetailPrint "$(webview2InstallSuccess)"
+ ${Else}
+ MessageBox MB_ICONEXCLAMATION|MB_ABORTRETRYIGNORE "$(webview2InstallError)" IDIGNORE ignore IDRETRY update_webview
+ Quit
+ ignore:
+ ${EndIf}
+ ${EndIf}
+ ${EndIf}
+ !endif
+ ${EndIf}
+SectionEnd
+
+Section Install
+ SetOutPath $INSTDIR
+
+ !ifmacrodef NSIS_HOOK_PREINSTALL
+ !insertmacro NSIS_HOOK_PREINSTALL
+ !endif
+
+ !insertmacro CheckIfAppIsRunning "${MAINBINARYNAME}.exe" "${PRODUCTNAME}"
+
+ ; Copy main executable
+ File "${MAINBINARYSRCPATH}"
+
+ ; Copy resources
+ {{#each resources_dirs}}
+ CreateDirectory "$INSTDIR\\{{this}}"
+ {{/each}}
+ {{#each resources}}
+ File /a "/oname={{this.[1]}}" "{{no-escape @key}}"
+ {{/each}}
+
+ ; Copy external binaries
+ {{#each binaries}}
+ File /a "/oname={{this}}" "{{no-escape @key}}"
+ {{/each}}
+
+ ; Create file associations
+ {{#each file_associations as |association| ~}}
+ {{#each association.ext as |ext| ~}}
+ !insertmacro APP_ASSOCIATE "{{ext}}" "{{or association.name ext}}" "{{association-description association.description ext}}" "$INSTDIR\${MAINBINARYNAME}.exe,0" "Open with ${PRODUCTNAME}" "$INSTDIR\${MAINBINARYNAME}.exe $\"%1$\""
+ {{/each}}
+ {{/each}}
+
+ ; Register deep links
+ {{#each deep_link_protocols as |protocol| ~}}
+ WriteRegStr SHCTX "Software\Classes\\{{protocol}}" "URL Protocol" ""
+ WriteRegStr SHCTX "Software\Classes\\{{protocol}}" "" "URL:${BUNDLEID} protocol"
+ WriteRegStr SHCTX "Software\Classes\\{{protocol}}\DefaultIcon" "" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\",0"
+ WriteRegStr SHCTX "Software\Classes\\{{protocol}}\shell\open\command" "" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\" $\"%1$\""
+ {{/each}}
+
+ ; Create uninstaller
+ WriteUninstaller "$INSTDIR\uninstall.exe"
+
+ ; Save $INSTDIR in registry for future installations
+ WriteRegStr SHCTX "${MANUPRODUCTKEY}" "" $INSTDIR
+
+ !if "${INSTALLMODE}" == "both"
+ ; Save install mode to be selected by default for the next installation such as updating
+ ; or when uninstalling
+ WriteRegStr SHCTX "${UNINSTKEY}" $MultiUser.InstallMode 1
+ !endif
+
+ ; Remove old main binary if it doesn't match new main binary name
+ ReadRegStr $OldMainBinaryName SHCTX "${UNINSTKEY}" "MainBinaryName"
+ ${If} $OldMainBinaryName != ""
+ ${AndIf} $OldMainBinaryName != "${MAINBINARYNAME}.exe"
+ Delete "$INSTDIR\$OldMainBinaryName"
+ ${EndIf}
+
+ ; Save current MAINBINARYNAME for future updates
+ WriteRegStr SHCTX "${UNINSTKEY}" "MainBinaryName" "${MAINBINARYNAME}.exe"
+
+ ; Registry information for add/remove programs
+ WriteRegStr SHCTX "${UNINSTKEY}" "DisplayName" "${PRODUCTNAME}"
+ WriteRegStr SHCTX "${UNINSTKEY}" "DisplayIcon" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\""
+ WriteRegStr SHCTX "${UNINSTKEY}" "DisplayVersion" "${VERSION}"
+ WriteRegStr SHCTX "${UNINSTKEY}" "Publisher" "${MANUFACTURER}"
+ WriteRegStr SHCTX "${UNINSTKEY}" "InstallLocation" "$\"$INSTDIR$\""
+ WriteRegStr SHCTX "${UNINSTKEY}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\""
+ WriteRegDWORD SHCTX "${UNINSTKEY}" "NoModify" "1"
+ WriteRegDWORD SHCTX "${UNINSTKEY}" "NoRepair" "1"
+
+ ${GetSize} "$INSTDIR" "/M=uninstall.exe /S=0K /G=0" $0 $1 $2
+ IntOp $0 $0 + ${ESTIMATEDSIZE}
+ IntFmt $0 "0x%08X" $0
+ WriteRegDWORD SHCTX "${UNINSTKEY}" "EstimatedSize" "$0"
+
+ !if "${HOMEPAGE}" != ""
+ WriteRegStr SHCTX "${UNINSTKEY}" "URLInfoAbout" "${HOMEPAGE}"
+ WriteRegStr SHCTX "${UNINSTKEY}" "URLUpdateInfo" "${HOMEPAGE}"
+ WriteRegStr SHCTX "${UNINSTKEY}" "HelpLink" "${HOMEPAGE}"
+ !endif
+
+ ; Create start menu shortcut
+ !insertmacro MUI_STARTMENU_WRITE_BEGIN Application
+ Call CreateOrUpdateStartMenuShortcut
+ !insertmacro MUI_STARTMENU_WRITE_END
+
+ ; Create desktop shortcut for silent and passive installers
+ ; because finish page will be skipped
+ ${If} $PassiveMode = 1
+ ${OrIf} ${Silent}
+ Call CreateOrUpdateDesktopShortcut
+ ${EndIf}
+
+ !ifmacrodef NSIS_HOOK_POSTINSTALL
+ !insertmacro NSIS_HOOK_POSTINSTALL
+ !endif
+
+ ; Auto close this page for passive mode
+ ${If} $PassiveMode = 1
+ SetAutoClose true
+ ${EndIf}
+SectionEnd
+
+Function .onInstSuccess
+ ; Check for `/R` flag only in silent and passive installers because
+ ; GUI installer has a toggle for the user to (re)start the app
+ ${If} $PassiveMode = 1
+ ${OrIf} ${Silent}
+ ${GetOptions} $CMDLINE "/R" $R0
+ ${IfNot} ${Errors}
+ ${GetOptions} $CMDLINE "/ARGS" $R0
+ nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" "$R0"
+ ${EndIf}
+ ${EndIf}
+FunctionEnd
+
+Function un.onInit
+ !insertmacro SetContext
+
+ !if "${INSTALLMODE}" == "both"
+ !insertmacro MULTIUSER_UNINIT
+ !endif
+
+ !insertmacro MUI_UNGETLANGUAGE
+
+ ${GetOptions} $CMDLINE "/P" $PassiveMode
+ ${IfNot} ${Errors}
+ StrCpy $PassiveMode 1
+ ${EndIf}
+
+ ${GetOptions} $CMDLINE "/UPDATE" $UpdateMode
+ ${IfNot} ${Errors}
+ StrCpy $UpdateMode 1
+ ${EndIf}
+FunctionEnd
+
+Section Uninstall
+
+ !ifmacrodef NSIS_HOOK_PREUNINSTALL
+ !insertmacro NSIS_HOOK_PREUNINSTALL
+ !endif
+
+ !insertmacro CheckIfAppIsRunning "${MAINBINARYNAME}.exe" "${PRODUCTNAME}"
+
+ ; Delete the app directory and its content from disk
+ ; Copy main executable
+ Delete "$INSTDIR\${MAINBINARYNAME}.exe"
+
+ ; Delete resources
+ {{#each resources}}
+ Delete "$INSTDIR\\{{this.[1]}}"
+ {{/each}}
+
+ ; Delete external binaries
+ {{#each binaries}}
+ Delete "$INSTDIR\\{{this}}"
+ {{/each}}
+
+ ; Delete app associations
+ {{#each file_associations as |association| ~}}
+ {{#each association.ext as |ext| ~}}
+ !insertmacro APP_UNASSOCIATE "{{ext}}" "{{or association.name ext}}"
+ {{/each}}
+ {{/each}}
+
+ ; Delete deep links
+ {{#each deep_link_protocols as |protocol| ~}}
+ ReadRegStr $R7 SHCTX "Software\Classes\\{{protocol}}\shell\open\command" ""
+ ${If} $R7 == "$\"$INSTDIR\${MAINBINARYNAME}.exe$\" $\"%1$\""
+ DeleteRegKey SHCTX "Software\Classes\\{{protocol}}"
+ ${EndIf}
+ {{/each}}
+
+
+ ; Delete uninstaller
+ Delete "$INSTDIR\uninstall.exe"
+
+ {{#each resources_ancestors}}
+ RMDir /REBOOTOK "$INSTDIR\\{{this}}"
+ {{/each}}
+ RMDir "$INSTDIR"
+
+ ; Remove shortcuts if not updating
+ ${If} $UpdateMode <> 1
+ !insertmacro DeleteAppUserModelId
+
+ ; Remove start menu shortcut
+ !insertmacro MUI_STARTMENU_GETFOLDER Application $AppStartMenuFolder
+ !insertmacro IsShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
+ Pop $0
+ ${If} $0 = 1
+ !insertmacro UnpinShortcut "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk"
+ Delete "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk"
+ RMDir "$SMPROGRAMS\$AppStartMenuFolder"
+ ${EndIf}
+ !insertmacro IsShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
+ Pop $0
+ ${If} $0 = 1
+ !insertmacro UnpinShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk"
+ Delete "$SMPROGRAMS\${PRODUCTNAME}.lnk"
+ ${EndIf}
+
+ ; Remove desktop shortcuts
+ !insertmacro IsShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
+ Pop $0
+ ${If} $0 = 1
+ !insertmacro UnpinShortcut "$DESKTOP\${PRODUCTNAME}.lnk"
+ Delete "$DESKTOP\${PRODUCTNAME}.lnk"
+ ${EndIf}
+ ${EndIf}
+
+ ; Remove registry information for add/remove programs
+ !if "${INSTALLMODE}" == "both"
+ DeleteRegKey SHCTX "${UNINSTKEY}"
+ !else if "${INSTALLMODE}" == "perMachine"
+ DeleteRegKey HKLM "${UNINSTKEY}"
+ !else
+ DeleteRegKey HKCU "${UNINSTKEY}"
+ !endif
+
+ ; Removes the Autostart entry for ${PRODUCTNAME} from the HKCU Run key if it exists.
+ ; This ensures the program does not launch automatically after uninstallation if it exists.
+ ; If it doesn't exist, it does nothing.
+ ; We do this when not updating (to preserve the registry value on updates)
+ ${If} $UpdateMode <> 1
+ DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCTNAME}"
+ ${EndIf}
+
+ ; Delete app data if the checkbox is selected
+ ; and if not updating
+ ${If} $DeleteAppDataCheckboxState = 1
+ ${AndIf} $UpdateMode <> 1
+ ; Clear the install location $INSTDIR from registry
+ DeleteRegKey SHCTX "${MANUPRODUCTKEY}"
+ DeleteRegKey /ifempty SHCTX "${MANUKEY}"
+
+ ; Clear the install language from registry
+ DeleteRegValue HKCU "${MANUPRODUCTKEY}" "Installer Language"
+ DeleteRegKey /ifempty HKCU "${MANUPRODUCTKEY}"
+ DeleteRegKey /ifempty HKCU "${MANUKEY}"
+
+ SetShellVarContext current
+ RmDir /r "$APPDATA\${BUNDLEID}"
+ RmDir /r "$LOCALAPPDATA\${BUNDLEID}"
+ ${EndIf}
+
+ !ifmacrodef NSIS_HOOK_POSTUNINSTALL
+ !insertmacro NSIS_HOOK_POSTUNINSTALL
+ !endif
+
+ ; Auto close if passive mode or updating
+ ${If} $PassiveMode = 1
+ ${OrIf} $UpdateMode = 1
+ SetAutoClose true
+ ${EndIf}
+SectionEnd
+
+Function RestorePreviousInstallLocation
+ ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""
+ StrCmp $4 "" +2 0
+ StrCpy $INSTDIR $4
+FunctionEnd
+
+Function Skip
+ Abort
+FunctionEnd
+
+Function SkipIfPassive
+ ${IfThen} $PassiveMode = 1 ${|} Abort ${|}
+FunctionEnd
+Function un.SkipIfPassive
+ ${IfThen} $PassiveMode = 1 ${|} Abort ${|}
+FunctionEnd
+
+Function CreateOrUpdateStartMenuShortcut
+ ; We used to use product name as MAINBINARYNAME
+ ; migrate old shortcuts to target the new MAINBINARYNAME
+ StrCpy $R0 0
+
+ !insertmacro IsShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName"
+ Pop $0
+ ${If} $0 = 1
+ !insertmacro SetShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
+ StrCpy $R0 1
+ ${EndIf}
+
+ !insertmacro IsShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName"
+ Pop $0
+ ${If} $0 = 1
+ !insertmacro SetShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
+ StrCpy $R0 1
+ ${EndIf}
+
+ ${If} $R0 = 1
+ Return
+ ${EndIf}
+
+ ; Skip creating shortcut if in update mode or no shortcut mode
+ ; but always create if migrating from wix
+ ${If} $WixMode = 0
+ ${If} $UpdateMode = 1
+ ${OrIf} $NoShortcutMode = 1
+ Return
+ ${EndIf}
+ ${EndIf}
+
+ !if "${STARTMENUFOLDER}" != ""
+ CreateDirectory "$SMPROGRAMS\$AppStartMenuFolder"
+ CreateShortcut "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
+ !insertmacro SetLnkAppUserModelId "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk"
+ !else
+ CreateShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
+ !insertmacro SetLnkAppUserModelId "$SMPROGRAMS\${PRODUCTNAME}.lnk"
+ !endif
+FunctionEnd
+
+Function CreateOrUpdateDesktopShortcut
+ ; We used to use product name as MAINBINARYNAME
+ ; migrate old shortcuts to target the new MAINBINARYNAME
+ !insertmacro IsShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName"
+ Pop $0
+ ${If} $0 = 1
+ !insertmacro SetShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
+ Return
+ ${EndIf}
+
+ ; Skip creating shortcut if in update mode or no shortcut mode
+ ; but always create if migrating from wix
+ ${If} $WixMode = 0
+ ${If} $UpdateMode = 1
+ ${OrIf} $NoShortcutMode = 1
+ Return
+ ${EndIf}
+ ${EndIf}
+
+ CreateShortcut "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
+ !insertmacro SetLnkAppUserModelId "$DESKTOP\${PRODUCTNAME}.lnk"
+FunctionEnd