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.

Harden Tauri release flow (#5341)

Wasim Yousef Said0a54d001ec0f
diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml
index ea827399684..13afacc2a83 100644
--- a/.github/workflows/release-desktop.yml
+++ b/.github/workflows/release-desktop.yml
@@ -3,15 +3,295 @@ name: Release Desktop App
on:
workflow_dispatch:
inputs:
+ studio_version:
+ description: 'Studio version tag to release (for example, v0.1.39-beta)'
+ type: string
+ required: true
+ pypi_version:
+ description: 'Exact PyPI unsloth version just published/stamped (for example, 2026.5.3); leave blank to use MIN_DESKTOP_BACKEND_VERSION'
+ type: string
+ required: false
draft:
- description: 'Create as draft release'
+ description: 'Create as draft release; draft runs do not advance desktop-latest updater channel'
type: boolean
default: true
permissions:
contents: write
+concurrency:
+ group: release-desktop-${{ github.repository }}
+ cancel-in-progress: false
+
jobs:
+ prepare-version:
+ name: Prepare release versions
+ runs-on: ubuntu-latest
+ outputs:
+ studio_version: ${{ steps.prepare.outputs.studio_version }}
+ app_version: ${{ steps.prepare.outputs.app_version }}
+ desktop_release_tag: ${{ steps.prepare.outputs.desktop_release_tag }}
+ prerelease: ${{ steps.prepare.outputs.prerelease }}
+ pypi_version: ${{ steps.prepare.outputs.pypi_version }}
+
+ steps:
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
+
+ - name: Validate release versions
+ id: prepare
+ shell: bash
+ env:
+ INPUT_STUDIO_VERSION: ${{ inputs.studio_version }}
+ INPUT_PYPI_VERSION: ${{ inputs.pypi_version }}
+ run: |
+ python3 <<'PY'
+ import os
+ import pathlib
+ import re
+ import sys
+
+ studio_version = os.environ['INPUT_STUDIO_VERSION'].strip()
+ if not studio_version:
+ sys.exit('studio_version is required, for example v0.1.39-beta')
+ if re.fullmatch(r'v?20\d{2}\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?', studio_version):
+ sys.exit(f'studio_version must be a Studio SemVer tag, not a date-style backend version: {studio_version}')
+
+ semver_tag = re.compile(
+ r'^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)'
+ r'(?:-[0-9A-Za-z.][0-9A-Za-z.-]*)?$'
+ )
+ if not semver_tag.fullmatch(studio_version):
+ sys.exit(f'studio_version must be a SemVer tag with leading v, for example v0.1.39-beta: {studio_version}')
+
+ app_version = studio_version.removeprefix('v')
+ desktop_release_tag = f'desktop-v{app_version}'
+ prerelease = 'true' if '-' in app_version.split('+', 1)[0] else 'false'
+
+ def parse_backend_version(version):
+ match = re.fullmatch(
+ r'(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)'
+ r'(?:([a-zA-Z]|\.dev|dev|\.rc|rc|\.post|post)(\d*))?'
+ r'(?:[-+]([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?',
+ version,
+ )
+ if not match:
+ return None
+ major, minor, patch, suffix_name, suffix_number, suffix_text = match.groups()
+ if suffix_name:
+ normalized = suffix_name.lower().lstrip('.')
+ order = {'dev': 0, 'a': 1, 'b': 2, 'rc': 3, 'post': 5}.get(normalized)
+ if order is None:
+ return None
+ number = int(suffix_number or '0')
+ elif suffix_text:
+ order = 3 if version[version.find(suffix_text) - 1] == '-' else 4
+ number = 0
+ else:
+ order = 4
+ number = 0
+ return (int(major), int(minor), int(patch), order, number)
+
+ preflight = pathlib.Path('studio/src-tauri/src/preflight/version.rs').read_text()
+ match = re.search(r'MIN_DESKTOP_BACKEND_VERSION:\s*&str\s*=\s*"([^"]+)"', preflight)
+ if not match:
+ sys.exit('Could not read MIN_DESKTOP_BACKEND_VERSION')
+ min_backend_version = match.group(1)
+
+ input_pypi_version = os.environ.get('INPUT_PYPI_VERSION', '').strip()
+ parsed_min_backend = parse_backend_version(min_backend_version)
+ if parsed_min_backend is None:
+ sys.exit(f'MIN_DESKTOP_BACKEND_VERSION is not a supported backend package version: {min_backend_version}')
+
+ pypi_version = input_pypi_version or min_backend_version
+ parsed_pypi = parse_backend_version(pypi_version)
+ if parsed_pypi is None:
+ sys.exit(f'pypi_version is not a supported backend package version: {pypi_version}')
+ if parsed_pypi < parsed_min_backend:
+ sys.exit(
+ f'pypi_version {pypi_version} is lower than desktop minimum '
+ f'MIN_DESKTOP_BACKEND_VERSION {min_backend_version}'
+ )
+
+ if input_pypi_version:
+ print(
+ 'Using exact PyPI unsloth version from pypi_version input: '
+ f'{pypi_version} (desktop minimum: {min_backend_version})'
+ )
+ else:
+ print(
+ 'Using exact PyPI unsloth version from MIN_DESKTOP_BACKEND_VERSION: '
+ f'{pypi_version}'
+ )
+
+ with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as output:
+ print(f'studio_version={studio_version}', file=output)
+ print(f'app_version={app_version}', file=output)
+ print(f'desktop_release_tag={desktop_release_tag}', file=output)
+ print(f'prerelease={prerelease}', file=output)
+ print(f'pypi_version={pypi_version}', file=output)
+ PY
+
+ - name: Verify PyPI package and Studio stamp
+ shell: bash
+ env:
+ STUDIO_VERSION: ${{ steps.prepare.outputs.studio_version }}
+ PYPI_VERSION: ${{ steps.prepare.outputs.pypi_version }}
+ run: |
+ set -euo pipefail
+ python3 <<'PY'
+ import json
+ import os
+ import pathlib
+ import sys
+ import time
+ import urllib.error
+ import urllib.request
+
+ pypi_version = os.environ['PYPI_VERSION']
+ dist_dir = pathlib.Path(os.environ['RUNNER_TEMP'], 'pypi-unsloth-dist')
+ dist_dir.mkdir(parents=True, exist_ok=True)
+ metadata_url = f'https://pypi.org/pypi/unsloth/{pypi_version}/json'
+
+ last_error = None
+ for attempt in range(1, 6):
+ try:
+ with urllib.request.urlopen(metadata_url, timeout=30) as response:
+ metadata = json.load(response)
+ break
+ except Exception as exc:
+ last_error = exc
+ if attempt < 5:
+ time.sleep(10 * attempt)
+ else:
+ sys.exit(f'Publish unsloth=={pypi_version} to PyPI before the desktop release ({last_error})')
+
+ files = metadata.get('urls') or []
+ if not files:
+ sys.exit(f'PyPI returned no distribution files for unsloth=={pypi_version}')
+
+ for file_info in files:
+ filename = file_info.get('filename')
+ url = file_info.get('url')
+ if not filename or '/' in filename or not url:
+ sys.exit(f'Unexpected PyPI file entry for unsloth=={pypi_version}: {file_info!r}')
+ target = dist_dir / filename
+ for attempt in range(1, 4):
+ try:
+ with urllib.request.urlopen(url, timeout=60) as response:
+ target.write_bytes(response.read())
+ break
+ except Exception as exc:
+ last_error = exc
+ if attempt < 3:
+ time.sleep(5 * attempt)
+ else:
+ sys.exit(f'Could not download {filename} from PyPI ({last_error})')
+ PY
+
+ if [ -f scripts/stamp_studio_release.py ]; then
+ mapfile -t dists < <(find "$RUNNER_TEMP/pypi-unsloth-dist" -type f \( -name '*.whl' -o -name '*.tar.gz' \) | sort)
+ if [ "${#dists[@]}" -eq 0 ]; then
+ echo "No PyPI wheel/sdist artifacts downloaded for unsloth==$PYPI_VERSION" >&2
+ exit 1
+ fi
+ python3 scripts/stamp_studio_release.py --verify-dist "$RUNNER_TEMP/pypi-unsloth-dist" --expected "$STUDIO_VERSION"
+ else
+ echo "scripts/stamp_studio_release.py not found; release-desktop requires #5308 to verify the PyPI Studio stamp." >&2
+ exit 1
+ fi
+
+ - name: Guard public updater channel version
+ if: ${{ !inputs.draft }}
+ shell: bash
+ env:
+ GH_REPO: ${{ github.repository }}
+ GH_TOKEN: ${{ github.token }}
+ APP_VERSION: ${{ steps.prepare.outputs.app_version }}
+ run: |
+ set -euo pipefail
+ mkdir -p "$RUNNER_TEMP/desktop-current"
+ if ! gh release download desktop-latest --pattern latest.json --dir "$RUNNER_TEMP/desktop-current" --clobber 2>/dev/null; then
+ echo "No existing desktop-latest latest.json found; allowing first channel publish."
+ exit 0
+ fi
+ python3 <<'PY'
+ import json
+ import os
+ import pathlib
+ import re
+ import sys
+
+ def parse(value: str):
+ value = value.removeprefix('v')
+ match = re.fullmatch(
+ r'(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)'
+ r'(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?'
+ r'(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?',
+ value,
+ )
+ if not match:
+ sys.exit(f'desktop-latest latest.json has invalid version: {value}')
+ major, minor, patch, prerelease = match.groups()
+ return (int(major), int(minor), int(patch), prerelease)
+
+ def numeric_tail(identifier: str) -> tuple[str, int] | None:
+ match = re.fullmatch(r'([A-Za-z-]+)(\d+)', identifier)
+ if not match:
+ return None
+ return (match.group(1).lower(), int(match.group(2)))
+
+ def compare_identifier(left: str, right: str) -> int:
+ left_num = left.isdigit()
+ right_num = right.isdigit()
+ if left_num and right_num:
+ return (int(left) > int(right)) - (int(left) < int(right))
+ if left_num:
+ return -1
+ if right_num:
+ return 1
+
+ left_tail = numeric_tail(left)
+ right_tail = numeric_tail(right)
+ if left_tail and right_tail and left_tail[0] == right_tail[0]:
+ return (left_tail[1] > right_tail[1]) - (left_tail[1] < right_tail[1])
+
+ return (left > right) - (left < right)
+
+ def compare_prerelease(left: str | None, right: str | None) -> int:
+ if left == right:
+ return 0
+ if left is None:
+ return 1
+ if right is None:
+ return -1
+ left_parts = left.split('.')
+ right_parts = right.split('.')
+ for left_part, right_part in zip(left_parts, right_parts):
+ order = compare_identifier(left_part, right_part)
+ if order:
+ return order
+ return (len(left_parts) > len(right_parts)) - (len(left_parts) < len(right_parts))
+
+ def compare(left: str, right: str) -> int:
+ left_major, left_minor, left_patch, left_pre = parse(left)
+ right_major, right_minor, right_patch, right_pre = parse(right)
+ left_core = (left_major, left_minor, left_patch)
+ right_core = (right_major, right_minor, right_patch)
+ if left_core != right_core:
+ return (left_core > right_core) - (left_core < right_core)
+ return compare_prerelease(left_pre, right_pre)
+
+ current_path = pathlib.Path(os.environ['RUNNER_TEMP'], 'desktop-current', 'latest.json')
+ current = json.loads(current_path.read_text()).get('version')
+ next_version = os.environ['APP_VERSION']
+ if not isinstance(current, str):
+ sys.exit('desktop-latest latest.json has missing version')
+ if compare(next_version, current) < 0:
+ sys.exit(
+ f'Refusing to publish {next_version}; desktop-latest currently points at newer version {current}.'
+ )
+ PY
+
build:
strategy:
fail-fast: false
@@ -32,11 +312,15 @@ jobs:
label: Windows (x64)
name: Build ${{ matrix.label }}
+ needs: prepare-version
runs-on: ${{ matrix.platform }}
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
-
+ APP_VERSION: ${{ needs.prepare-version.outputs.app_version }}
+ STUDIO_VERSION: ${{ needs.prepare-version.outputs.studio_version }}
+ DESKTOP_RELEASE_TAG: ${{ needs.prepare-version.outputs.desktop_release_tag }}
+ DESKTOP_PRERELEASE: ${{ needs.prepare-version.outputs.prerelease }}
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
@@ -67,36 +351,144 @@ jobs:
exit 1
fi
- - name: Install frontend dependencies
- working-directory: studio/frontend
- run: npm install
-
- - name: Verify backend package is published
+ - name: Verify desktop updater and Linux package config
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 expected = 'https://github.com/unslothai/unsloth/releases/download/desktop-latest/latest.json';
+ const config = JSON.parse(readFileSync('studio/src-tauri/tauri.conf.json', 'utf8'));
+ const endpoints = config.plugins?.updater?.endpoints;
+ if (!Array.isArray(endpoints) || endpoints.length !== 1) {
+ throw new Error('Expected exactly one desktop updater endpoint');
+ }
+ if (endpoints[0] !== expected) {
+ throw new Error('Desktop updater endpoint must be ' + expected + ', got ' + endpoints[0]);
+ }
+ if (endpoints.some((endpoint) => endpoint.includes('/releases/latest/'))) {
+ throw new Error('Desktop updater endpoint must not use repo-wide /releases/latest/');
+ }
- 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})`);
+ const targets = config.bundle?.targets;
+ if (Array.isArray(targets) && targets.some((target) => String(target).toLowerCase() === 'rpm')) {
+ throw new Error('Desktop release must not target RPM packages');
+ }
+ if (config.bundle?.linux?.rpm) {
+ throw new Error('bundle.linux.rpm must not be configured');
+ }
+
+ const workflow = readFileSync('.github/workflows/release-desktop.yml', 'utf8');
+ const lines = workflow.split(/\r?\n/);
+ const releaseBodies = [];
+ for (let i = 0; i < lines.length; i += 1) {
+ const match = lines[i].match(/^(\s*)releaseBody:\s*\|\s*$/);
+ if (!match) continue;
+ const baseIndent = match[1].length;
+ const bodyLines = [];
+ i += 1;
+ for (; i < lines.length; i += 1) {
+ const line = lines[i];
+ if (line.trim() === '') {
+ bodyLines.push('');
+ continue;
+ }
+ const indent = line.match(/^\s*/)[0].length;
+ if (indent <= baseIndent) {
+ i -= 1;
+ break;
+ }
+ bodyLines.push(line.slice(baseIndent + 2));
+ }
+ releaseBodies.push(bodyLines.join('\n'));
+ }
+ if (releaseBodies.length === 0) {
+ throw new Error('Expected at least one desktop release body');
+ }
+ for (const body of releaseBodies) {
+ if (/\brpm\b|\.rpm/i.test(body)) {
+ throw new Error('Desktop release body must not advertise RPM packages');
}
- })();
+ }
JS
+ - name: Install frontend dependencies
+ working-directory: studio/frontend
+ run: npm install
+
# ── Rust ──
- name: Install Rust stable
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.platform == 'macos-latest' && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }}
+ - name: Patch desktop app version
+ shell: bash
+ working-directory: studio/src-tauri
+ run: |
+ set -euo pipefail
+ if command -v python3 >/dev/null 2>&1; then
+ PYTHON=python3
+ else
+ PYTHON=python
+ fi
+ "$PYTHON" <<'PY'
+ import os
+ import pathlib
+ import re
+ import sys
+
+ app_version = os.environ['APP_VERSION']
+ if not app_version:
+ sys.exit('APP_VERSION is required')
+
+ cargo_toml = pathlib.Path('Cargo.toml')
+ lines = cargo_toml.read_text().splitlines(keepends=True)
+ in_package = False
+ patched = False
+ for index, line in enumerate(lines):
+ stripped = line.strip()
+ if stripped == '[package]':
+ in_package = True
+ continue
+ if stripped.startswith('[') and stripped.endswith(']'):
+ in_package = False
+ if in_package and re.fullmatch(r'version\s*=\s*"[^"]+"\s*', stripped):
+ lines[index] = f'version = "{app_version}"\n'
+ patched = True
+ break
+ if not patched:
+ sys.exit('Could not patch [package] version in Cargo.toml')
+ cargo_toml.write_text(''.join(lines))
+
+ cargo_lock = pathlib.Path('Cargo.lock')
+ lock_text = cargo_lock.read_text()
+ lock_text, count = re.subn(
+ r'(?m)(^\[\[package\]\]\nname = "unsloth-studio"\nversion = ")[^"]+(")',
+ lambda match: f'{match.group(1)}{app_version}{match.group(2)}',
+ lock_text,
+ )
+ if count != 1:
+ sys.exit(f'Could not patch unsloth-studio version in Cargo.lock (matches={count})')
+ cargo_lock.write_text(lock_text)
+ PY
+
+ cargo metadata --locked --no-deps --format-version 1 > "$RUNNER_TEMP/cargo-metadata.json"
+ "$PYTHON" <<'PY'
+ import json
+ import os
+ import pathlib
+ import sys
+
+ app_version = os.environ['APP_VERSION']
+ metadata = json.loads(pathlib.Path(os.environ['RUNNER_TEMP'], 'cargo-metadata.json').read_text())
+ versions = [package['version'] for package in metadata.get('packages', []) if package.get('name') == 'unsloth-studio']
+ if versions != [app_version]:
+ sys.exit(f'cargo metadata unsloth-studio version mismatch: expected {app_version}, got {versions}')
+ PY
+
+ git diff -- Cargo.toml Cargo.lock
+
- name: Rust cache
uses: swatinem/rust-cache@42dc69e1aa15d09112580998cf2ef0119e2e91ae
with:
@@ -146,8 +538,8 @@ jobs:
with:
projectPath: studio
tauriScript: npx --prefix . tauri
- tagName: desktop-v__VERSION__
- releaseName: 'Unsloth Studio (Desktop) v__VERSION__'
+ tagName: ${{ needs.prepare-version.outputs.desktop_release_tag }}
+ releaseName: 'Unsloth Studio (Desktop) ${{ needs.prepare-version.outputs.studio_version }}'
releaseBody: |
Desktop app for Unsloth Studio.
@@ -159,7 +551,7 @@ jobs:
> 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
+ prerelease: ${{ needs.prepare-version.outputs.prerelease }}
args: -v ${{ matrix.args }}
# ── macOS: build + sign + notarize + upload ──
@@ -177,8 +569,8 @@ jobs:
with:
projectPath: studio
tauriScript: npx --prefix . tauri
- tagName: desktop-v__VERSION__
- releaseName: 'Unsloth Studio (Desktop) v__VERSION__'
+ tagName: ${{ needs.prepare-version.outputs.desktop_release_tag }}
+ releaseName: 'Unsloth Studio (Desktop) ${{ needs.prepare-version.outputs.studio_version }}'
releaseBody: |
Desktop app for Unsloth Studio.
@@ -190,7 +582,7 @@ jobs:
> 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
+ prerelease: ${{ needs.prepare-version.outputs.prerelease }}
args: -v ${{ matrix.args }}
# ── Windows: build + sign + upload ──
@@ -209,8 +601,8 @@ jobs:
with:
projectPath: studio
tauriScript: npx --prefix . tauri
- tagName: desktop-v__VERSION__
- releaseName: 'Unsloth Studio (Desktop) v__VERSION__'
+ tagName: ${{ needs.prepare-version.outputs.desktop_release_tag }}
+ releaseName: 'Unsloth Studio (Desktop) ${{ needs.prepare-version.outputs.studio_version }}'
releaseBody: |
Desktop app for Unsloth Studio.
@@ -222,5 +614,254 @@ jobs:
> 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
+ prerelease: ${{ needs.prepare-version.outputs.prerelease }}
args: -v ${{ matrix.args }}
+
+ # Release process note: only non-draft workflow runs advance the public
+ # desktop-latest updater channel. Draft builds are for private review; if a
+ # draft is manually published later, this channel intentionally remains
+ # unchanged until a narrow manual channel-publish flow is added or a public
+ # desktop release is created by running this workflow with draft=false.
+ publish-updater-channel:
+ name: Publish desktop updater channel
+ needs: [prepare-version, build]
+ if: ${{ !inputs.draft }}
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ env:
+ GH_REPO: ${{ github.repository }}
+ APP_VERSION: ${{ needs.prepare-version.outputs.app_version }}
+ STUDIO_VERSION: ${{ needs.prepare-version.outputs.studio_version }}
+ DESKTOP_RELEASE_TAG: ${{ needs.prepare-version.outputs.desktop_release_tag }}
+ DESKTOP_PRERELEASE: ${{ needs.prepare-version.outputs.prerelease }}
+
+ steps:
+ - name: Download versioned updater metadata
+ shell: bash
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ set -euo pipefail
+ mkdir -p "$RUNNER_TEMP/desktop-updater"
+ gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${DESKTOP_RELEASE_TAG}" > "$RUNNER_TEMP/source-release.json"
+ python3 <<'PY'
+ import json
+ import os
+ import pathlib
+ import sys
+
+ source = json.loads(pathlib.Path(os.environ['RUNNER_TEMP'], 'source-release.json').read_text())
+ expected_tag = os.environ['DESKTOP_RELEASE_TAG']
+ if source.get('tag_name') != expected_tag:
+ sys.exit(f'Expected source release {expected_tag}, got {source.get("tag_name")}')
+ if source.get('draft'):
+ sys.exit(f'Source desktop release {expected_tag} is draft; refusing to publish public updater channel')
+ PY
+ gh release download "$DESKTOP_RELEASE_TAG" --pattern latest.json --dir "$RUNNER_TEMP/desktop-updater" --clobber
+ test -s "$RUNNER_TEMP/desktop-updater/latest.json"
+
+ - name: Validate versioned updater metadata
+ shell: bash
+ run: |
+ python3 <<'PY'
+ import json
+ import os
+ import pathlib
+ import re
+ import sys
+
+ app_version = os.environ['APP_VERSION']
+ release_tag = os.environ['DESKTOP_RELEASE_TAG']
+ latest_path = pathlib.Path(os.environ['RUNNER_TEMP'], 'desktop-updater', 'latest.json')
+ data = json.loads(latest_path.read_text())
+ if not isinstance(data, dict):
+ sys.exit('latest.json must be a JSON object')
+
+ version = data.get('version')
+ if not isinstance(version, str) or not version:
+ sys.exit('latest.json missing version')
+ if not re.fullmatch(r'v?\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?', version):
+ sys.exit(f'latest.json version is not SemVer-like: {version}')
+ if version.removeprefix('v') != app_version:
+ sys.exit(f'latest.json version {version} does not match desktop app version {app_version}')
+
+ platforms = data.get('platforms')
+ if not isinstance(platforms, dict) or not platforms:
+ sys.exit('latest.json missing platforms')
+
+ required_families = {
+ 'darwin-aarch64': False,
+ 'linux-x86_64': False,
+ 'windows-x86_64': False,
+ }
+ expected_prefix = f'https://github.com/unslothai/unsloth/releases/download/{release_tag}/'
+ forbidden_fragments = ('/releases/latest/', '/releases/download/desktop-latest/')
+
+ for platform, entry in platforms.items():
+ if not isinstance(entry, dict):
+ sys.exit(f'Platform {platform} must be an object')
+ url = entry.get('url')
+ signature = entry.get('signature')
+ if not isinstance(url, str) or not url.strip():
+ sys.exit(f'Platform {platform} missing url')
+ if not isinstance(signature, str) or not signature.strip():
+ sys.exit(f'Platform {platform} missing signature')
+ if any(fragment in url for fragment in forbidden_fragments):
+ sys.exit(f'Platform {platform} points at a moving updater channel: {url}')
+ if not url.startswith(expected_prefix):
+ sys.exit(f'Platform {platform} URL must point at {release_tag}: {url}')
+ for family in required_families:
+ if platform == family or platform.startswith(family + '-'):
+ required_families[family] = True
+
+ missing = [family for family, found in required_families.items() if not found]
+ if missing:
+ sys.exit('latest.json missing required platform families: ' + ', '.join(missing))
+ PY
+
+ - name: Ensure desktop updater channel release
+ shell: bash
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ set -euo pipefail
+ channel_json="$RUNNER_TEMP/desktop-latest-release.json"
+ if ! gh api "repos/${GITHUB_REPOSITORY}/releases/tags/desktop-latest" > "$channel_json" 2>/dev/null; then
+ gh release create desktop-latest \
+ --title "Unsloth Studio Desktop updater channel" \
+ --notes "Machine-managed desktop updater channel; latest.json is replaced by release-desktop.yml." \
+ --prerelease \
+ --latest=false \
+ --target "$GITHUB_SHA"
+ gh api "repos/${GITHUB_REPOSITORY}/releases/tags/desktop-latest" > "$channel_json"
+ fi
+
+ python3 <<'PY'
+ import json
+ import os
+ import pathlib
+ import sys
+
+ channel = json.loads(pathlib.Path(os.environ['RUNNER_TEMP'], 'desktop-latest-release.json').read_text())
+ if channel.get('draft'):
+ sys.exit('desktop-latest release is draft; refusing to publish updater channel')
+ if channel.get('immutable'):
+ sys.exit('desktop-latest release is immutable; cannot replace latest.json')
+ if not channel.get('prerelease'):
+ sys.exit('desktop-latest release must be a prerelease so it cannot compete with repo-wide latest')
+ PY
+
+ - name: Prevent updater channel downgrade
+ shell: bash
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ set -euo pipefail
+ mkdir -p "$RUNNER_TEMP/desktop-current"
+ if ! gh release download desktop-latest --pattern latest.json --dir "$RUNNER_TEMP/desktop-current" --clobber 2>/dev/null; then
+ echo "No existing desktop-latest latest.json found; allowing first channel publish."
+ exit 0
+ fi
+ python3 <<'PY'
+ import json
+ import os
+ import pathlib
+ import re
+ import sys
+
+ def parse(value: str):
+ value = value.removeprefix('v')
+ match = re.fullmatch(
+ r'(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)'
+ r'(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?'
+ r'(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?',
+ value,
+ )
+ if not match:
+ sys.exit(f'desktop-latest latest.json has invalid version: {value}')
+ major, minor, patch, prerelease = match.groups()
+ return (int(major), int(minor), int(patch), prerelease)
+
+ def numeric_tail(identifier: str) -> tuple[str, int] | None:
+ match = re.fullmatch(r'([A-Za-z-]+)(\d+)', identifier)
+ if not match:
+ return None
+ return (match.group(1).lower(), int(match.group(2)))
+
+ def compare_identifier(left: str, right: str) -> int:
+ left_num = left.isdigit()
+ right_num = right.isdigit()
+ if left_num and right_num:
+ return (int(left) > int(right)) - (int(left) < int(right))
+ if left_num:
+ return -1
+ if right_num:
+ return 1
+
+ left_tail = numeric_tail(left)
+ right_tail = numeric_tail(right)
+ if left_tail and right_tail and left_tail[0] == right_tail[0]:
+ return (left_tail[1] > right_tail[1]) - (left_tail[1] < right_tail[1])
+
+ return (left > right) - (left < right)
+
+ def compare_prerelease(left: str | None, right: str | None) -> int:
+ if left == right:
+ return 0
+ if left is None:
+ return 1
+ if right is None:
+ return -1
+ left_parts = left.split('.')
+ right_parts = right.split('.')
+ for left_part, right_part in zip(left_parts, right_parts):
+ order = compare_identifier(left_part, right_part)
+ if order:
+ return order
+ return (len(left_parts) > len(right_parts)) - (len(left_parts) < len(right_parts))
+
+ def compare(left: str, right: str) -> int:
+ left_major, left_minor, left_patch, left_pre = parse(left)
+ right_major, right_minor, right_patch, right_pre = parse(right)
+ left_core = (left_major, left_minor, left_patch)
+ right_core = (right_major, right_minor, right_patch)
+ if left_core != right_core:
+ return (left_core > right_core) - (left_core < right_core)
+ return compare_prerelease(left_pre, right_pre)
+
+ current_path = pathlib.Path(os.environ['RUNNER_TEMP'], 'desktop-current', 'latest.json')
+ next_path = pathlib.Path(os.environ['RUNNER_TEMP'], 'desktop-updater', 'latest.json')
+ current = json.loads(current_path.read_text()).get('version')
+ next_version = json.loads(next_path.read_text()).get('version')
+ if not isinstance(current, str) or not isinstance(next_version, str):
+ sys.exit('Could not compare desktop-latest channel versions')
+ if compare(next_version, current) < 0:
+ sys.exit(
+ f'Refusing to move desktop-latest from {current} to older version {next_version}.'
+ )
+ PY
+
+ - name: Publish desktop updater channel metadata
+ shell: bash
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ set -euo pipefail
+ gh release upload desktop-latest "$RUNNER_TEMP/desktop-updater/latest.json" --clobber
+ gh api "repos/${GITHUB_REPOSITORY}/releases/tags/desktop-latest" > "$RUNNER_TEMP/desktop-latest-release.json"
+ python3 <<'PY'
+ import json
+ import os
+ import pathlib
+ import sys
+
+ channel = json.loads(pathlib.Path(os.environ['RUNNER_TEMP'], 'desktop-latest-release.json').read_text())
+ assets = [asset for asset in channel.get('assets', []) if asset.get('name') == 'latest.json']
+ if len(assets) != 1:
+ sys.exit(f'Expected exactly one desktop-latest latest.json asset, found {len(assets)}')
+ expected_url = f'https://github.com/{os.environ["GITHUB_REPOSITORY"]}/releases/download/desktop-latest/latest.json'
+ actual_url = assets[0].get('browser_download_url')
+ if actual_url != expected_url:
+ sys.exit(f'desktop-latest latest.json URL mismatch: expected {expected_url}, got {actual_url}')
+ PY
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 650a4882122..2fba2756e7e 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -42,6 +42,7 @@ if _STUDIO_ROOT_RESOLVED != _LEGACY_STUDIO_ROOT:
if not os.environ.get("UNSLOTH_LLAMA_CPP_PATH"):
os.environ["UNSLOTH_LLAMA_CPP_PATH"] = str(_STUDIO_ROOT_RESOLVED / "llama.cpp")
+import hashlib
import mimetypes
import re as _re
import shutil
@@ -163,6 +164,24 @@ UNSLOTH_VERSION = get_unsloth_version()
STUDIO_VERSION = get_studio_version()
+def _load_desktop_owner() -> dict[str, str] | None:
+ token = os.environ.pop("UNSLOTH_STUDIO_DESKTOP_OWNER_TOKEN", "")
+ kind = os.environ.pop("UNSLOTH_STUDIO_DESKTOP_OWNER_KIND", "")
+ if kind != "tauri" or not token:
+ return None
+ return {
+ "kind": "tauri",
+ "token_sha256": hashlib.sha256(token.encode("utf-8")).hexdigest(),
+ }
+
+
+_DESKTOP_OWNER = _load_desktop_owner()
+
+
+def _desktop_owner() -> dict[str, str] | None:
+ return _DESKTOP_OWNER
+
+
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Startup: detect hardware, seed default admin if needed. Shutdown: clean up compiled cache."""
@@ -306,12 +325,15 @@ async def health_check():
"device_type": device_type,
"chat_only": _hw_module.CHAT_ONLY,
"desktop_protocol_version": 1,
+ "desktop_manageability_version": 1,
"supports_desktop_auth": True,
+ "supports_desktop_backend_ownership": True,
# why: launchers compare against an install-time hash so a sibling
# Studio on the same port is rejected; hex digest avoids leaking the
# raw install path on -H 0.0.0.0.
"studio_root_id": _studio_root_id(),
"native_path_leases_supported": native_path_leases_supported(),
+ **({"desktop_owner": owner} if (owner := _desktop_owner()) else {}),
}
diff --git a/studio/backend/run.py b/studio/backend/run.py
index 1dd1230a17d..dfd4b7453eb 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -307,7 +307,6 @@ def run_server(
import asyncio
from threading import Thread, Event
- import time
import uvicorn
from main import app, setup_frontend
@@ -336,10 +335,6 @@ def run_server(
print("=" * 50)
print("")
- # Output port for Tauri to parse when in api-only mode
- if api_only:
- print(f"TAURI_PORT={port}", flush = True)
-
# Setup frontend if path provided (skip in api-only mode)
if frontend_path and not api_only:
if setup_frontend(app, frontend_path):
@@ -349,11 +344,21 @@ def run_server(
if not silent:
print(f"[WARNING] Frontend not found at {frontend_path}")
+ ready_event = Event()
+ startup_failed = Event()
+ startup_errors = []
+
+ class _ReadyServer(uvicorn.Server):
+ async def startup(self, *args, **kwargs):
+ await super().startup(*args, **kwargs)
+ if getattr(self, "started", False) and not self.should_exit:
+ ready_event.set()
+
# Create the uvicorn server and expose it for signal handlers
config = uvicorn.Config(
app, host = host, port = port, log_level = "info", access_log = False
)
- _server = uvicorn.Server(config)
+ _server = _ReadyServer(config)
_shutdown_event = Event()
# Expose the actual bound port so request-handling code can build
@@ -365,27 +370,55 @@ def run_server(
app.state.server_port = port if port and port > 0 else None
app.state.llama_parallel_slots = llama_parallel_slots
+ # Expose a shutdown callable via app.state before the server can accept
+ # requests so /api/shutdown is available as soon as readiness is published.
+ def _trigger_shutdown():
+ _graceful_shutdown(_server)
+ if _shutdown_event is not None:
+ _shutdown_event.set()
+
+ app.state.trigger_shutdown = _trigger_shutdown
+
# Run server in a daemon thread
def _run():
- asyncio.run(_server.serve())
+ try:
+ asyncio.run(_server.serve())
+ except BaseException as exc:
+ startup_errors.append(exc)
+ startup_failed.set()
+ finally:
+ if not ready_event.is_set():
+ startup_failed.set()
thread = Thread(target = _run, daemon = True)
thread.start()
- time.sleep(3)
+
+ # Wait until uvicorn has completed lifespan startup and bound sockets, or
+ # until the server exits/fails before startup. This intentionally has no
+ # correctness deadline: a slow but live startup should remain in progress.
+ try:
+ while not ready_event.is_set():
+ if startup_failed.is_set() or not thread.is_alive():
+ if startup_errors:
+ raise RuntimeError(
+ "Uvicorn server failed before startup completed"
+ ) from startup_errors[0]
+ raise RuntimeError("Uvicorn server exited before startup completed")
+ ready_event.wait(timeout = 0.1)
+ except KeyboardInterrupt:
+ _graceful_shutdown(_server)
+ _shutdown_event.set()
+ raise
_write_pid_file()
import atexit
atexit.register(_remove_pid_file)
- # Expose a shutdown callable via app.state so the /api/shutdown endpoint
- # can trigger graceful shutdown without circular imports.
- def _trigger_shutdown():
- _graceful_shutdown(_server)
- if _shutdown_event is not None:
- _shutdown_event.set()
-
- app.state.trigger_shutdown = _trigger_shutdown
+ # Output port for Tauri to parse when in api-only mode. Emit only after
+ # uvicorn sockets are bound and FastAPI lifespan/startup has completed.
+ if api_only:
+ print(f"TAURI_PORT={port}", flush = True)
if not silent:
display_host = _resolve_external_ip() if host == "0.0.0.0" else host
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsx
index fe3173aa41d..8360186d1e5 100644
--- a/studio/frontend/src/app/provider.tsx
+++ b/studio/frontend/src/app/provider.tsx
@@ -23,10 +23,6 @@ interface AppProviderProps {
children: ReactNode;
}
-// ---------------------------------------------------------------------------
-// Tauri window helpers (only imported in Tauri mode)
-// ---------------------------------------------------------------------------
-
type TauriWindowMode = "setup" | "app";
type WindowLayoutGuard = () => boolean;
@@ -53,19 +49,15 @@ async function applyAppWindowLayout(isCurrent: WindowLayoutGuard): Promise<void>
let finalH = 600;
if (monitor) {
- // Convert physical pixels to logical using scale factor
const scale = monitor.scaleFactor;
const screenW = monitor.size.width / scale;
const screenH = monitor.size.height / scale;
- // Target: 75% of screen width, golden ratio height, capped at min 900x600
finalW = Math.max(900, Math.round(screenW * 0.75));
const targetH = Math.max(600, Math.round(finalW / 1.618));
- // Don't exceed screen height
finalH = Math.min(targetH, Math.round(screenH * 0.85));
}
- // Apply constraints and finalize without animating through intermediate sizes
if (!isCurrent()) return;
await win.setSize(new LogicalSize(finalW, finalH));
if (!isCurrent()) return;
@@ -108,10 +100,6 @@ function getTauriWindowMode(
}
}
-// ---------------------------------------------------------------------------
-// TauriWrapper
-// ---------------------------------------------------------------------------
-
function TauriUpdateLayer({ isExternalServer }: { isExternalServer: boolean }) {
const update = useTauriUpdate(isExternalServer);
const isUpdating =
@@ -141,6 +129,8 @@ function TauriUpdateLayer({ isExternalServer }: { isExternalServer: boolean }) {
dismissed={update.dismissed}
lastFailure={update.lastFailure}
isExternalServer={isExternalServer}
+ updatePolicyMode={update.updatePolicyMode}
+ manualReleaseUrl={update.manualReleaseUrl}
onInstall={update.installUpdate}
onDismiss={update.dismiss}
onCopyDiagnostics={update.copyDiagnostics}
@@ -184,8 +174,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {
};
}, []);
- // Keep the Tauri window hidden during preflight, then show it centered in setup
- // mode or apply the final app layout in one instant step.
+ // Keep the Tauri window hidden until setup or app layout is ready.
useEffect(() => {
if (!isTauri) return;
diff --git a/studio/frontend/src/components/tauri/update-banner.tsx b/studio/frontend/src/components/tauri/update-banner.tsx
index 79fbae6bb7d..62038f92a92 100644
--- a/studio/frontend/src/components/tauri/update-banner.tsx
+++ b/studio/frontend/src/components/tauri/update-banner.tsx
@@ -2,7 +2,12 @@
// 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 { RetainedUpdateFailure, UpdateInfo, UpdateStatus } from "@/hooks/use-tauri-update";
+import type {
+ DesktopUpdatePolicyMode,
+ 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";
@@ -13,6 +18,8 @@ interface UpdateBannerProps {
dismissed: boolean;
lastFailure: RetainedUpdateFailure | null;
isExternalServer?: boolean;
+ updatePolicyMode: DesktopUpdatePolicyMode;
+ manualReleaseUrl: string | null;
onInstall: () => void;
onDismiss: () => void;
onCopyDiagnostics: () => Promise<CopySupportDiagnosticsResult>;
@@ -26,6 +33,8 @@ export function UpdateBanner({
dismissed,
lastFailure,
isExternalServer = false,
+ updatePolicyMode,
+ manualReleaseUrl,
onInstall,
onDismiss,
onCopyDiagnostics,
@@ -36,6 +45,10 @@ export function UpdateBanner({
const showFailure = Boolean(lastFailure) && !dismissed;
const showAvailable = status === "available" && !dismissed && !showFailure;
const show = showFailure || (showAvailable && Boolean(info));
+ const isManualLinuxPackage = updatePolicyMode === "manual_linux_package";
+ const installDisabled = isManualLinuxPackage
+ ? manualReleaseUrl === null
+ : isExternalServer;
async function handleCopyDiagnostics() {
setCopying(true);
@@ -67,18 +80,16 @@ export function UpdateBanner({
className="fixed top-4 right-4 z-[9999] w-[380px]"
>
<div className="corner-squircle relative overflow-hidden border border-border/60 bg-background/95 px-5 py-4 shadow-lg backdrop-blur-md">
- {/* Close button */}
<button
type="button"
onClick={onDismiss}
className="absolute top-3 right-3 flex size-6 items-center justify-center rounded-md text-muted-foreground/60 transition-colors hover:bg-muted hover:text-foreground"
>
- <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <svg aria-hidden="true" width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M11 3L3 11M3 3l8 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
</button>
- {/* Header */}
<div className="flex items-center gap-2">
<span className="text-lg">🦥</span>
<div>
@@ -88,37 +99,39 @@ export function UpdateBanner({
<p className="text-xs text-muted-foreground">
{showFailure
? "Backend recovered. Diagnostics are still available."
- : isExternalServer
- ? "Run `unsloth studio update` from your terminal"
- : "A new app update is available"}
+ : isManualLinuxPackage
+ ? "Open the GitHub release page to install the Linux package"
+ : 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">
{showFailure ? (
<>
- <Button size="sm" variant="outline" className="corner-squircle" onClick={() => void handleCopyDiagnostics()}>
+ <Button size="sm" variant="outline" className="corner-squircle" onClick={() => {
+ handleCopyDiagnostics().catch(console.error);
+ }}>
{copying ? "Copying..." : "Copy Diagnostics"}
</Button>
- <Button size="sm" className="corner-squircle" onClick={onInstall} disabled={isExternalServer}>
- Retry Update
+ <Button size="sm" className="corner-squircle" onClick={onInstall} disabled={installDisabled}>
+ {isManualLinuxPackage ? "Open Release Page" : "Retry Update"}
</Button>
</>
) : (
<>
- <Button size="sm" className="corner-squircle" onClick={onInstall} disabled={isExternalServer}>
- Update Now
+ <Button size="sm" className="corner-squircle" onClick={onInstall} disabled={installDisabled}>
+ {isManualLinuxPackage ? "Open Release Page" : "Update Now"}
</Button>
- <Button size="sm" variant="outline" className="corner-squircle" disabled>
+ <Button size="sm" variant="outline" className="corner-squircle" disabled={true}>
Release Notes
</Button>
</>
@@ -132,7 +145,7 @@ export function UpdateBanner({
)}
{manualReport && (
<textarea
- readOnly
+ readOnly={true}
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"
diff --git a/studio/frontend/src/hooks/use-tauri-backend.ts b/studio/frontend/src/hooks/use-tauri-backend.ts
index 6bbbdb91f94..c7628c0fd02 100644
--- a/studio/frontend/src/hooks/use-tauri-backend.ts
+++ b/studio/frontend/src/hooks/use-tauri-backend.ts
@@ -29,7 +29,10 @@ type DesktopPreflightDisposition =
| "not_installed"
| "managed_ready"
| "managed_stale"
- | "attached_ready";
+ | "owned_ready"
+ | "owned_stale"
+ | "attached_ready"
+ | "external_conflict";
interface DesktopPreflightResult {
disposition: DesktopPreflightDisposition;
@@ -39,28 +42,45 @@ 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" };
+ | { status: "aborted" };
function wait(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+function externalConflictMessage(preflight: DesktopPreflightResult) {
+ if (preflight.reason === "desktop_owned_backend_active") {
+ return preflight.port
+ ? `A desktop-owned Studio server for this install is already running on port ${preflight.port}. Quit the other desktop app instance, then try again.`
+ : "A desktop-owned Studio server for this install is already running. Quit the other desktop app instance, then try again.";
+ }
+
+ if (preflight.reason === "desktop_owned_backend_starting") {
+ return "The desktop-owned Studio backend is still starting. Wait a moment, then try again.";
+ }
+
+ if (preflight.reason?.startsWith("desktop_owned_backend_unmanageable:")) {
+ return preflight.port
+ ? `A desktop-owned Studio backend on port ${preflight.port} cannot be safely controlled by this desktop app. Stop that backend, then reopen Studio.`
+ : "A desktop-owned Studio backend cannot be safely controlled by this desktop app. Stop that backend, then reopen Studio.";
+ }
+
+ return preflight.port
+ ? `A Studio server for this install is already running from a terminal on port ${preflight.port}. Stop that server, or run \`unsloth studio update\` from that terminal before using the desktop app.`
+ : "A Studio server for this install is already running from a terminal. Stop that server, or run `unsloth studio update` from that terminal before using the desktop app.";
+}
+
async function waitForManagedServerReady(
invoke: TauriInvoke,
getPort: () => number | null,
shouldContinue: () => boolean,
): Promise<ManagedStartupResult> {
- const deadline = Date.now() + MANAGED_STARTUP_TIMEOUT_MS;
-
- while (Date.now() < deadline) {
+ while (true) {
if (!shouldContinue()) {
return { status: "aborted" };
}
@@ -81,10 +101,6 @@ async function waitForManagedServerReady(
await wait(MANAGED_STARTUP_POLL_MS);
}
-
- return getPort() === null
- ? { status: "missing-port" }
- : { status: "unhealthy" };
}
export function useTauriBackend() {
@@ -109,6 +125,7 @@ export function useTauriBackend() {
const externalPollAbortedRef = useRef(false);
const authFailureRef = useRef<string | null>(getTauriAuthFailure());
const elevationResumeRef = useRef<"install" | "repair" | null>(null);
+ const [tauriEventsReady, setTauriEventsReady] = useState(!isTauri);
function setBackendStatus(nextStatus: BackendStatus) {
if (authFailureRef.current) return;
@@ -205,12 +222,24 @@ export function useTauriBackend() {
startExternalServerPoll(preflight.port);
return;
}
+ case "owned_ready":
+ if (!preflight.port) {
+ setBackendError("Desktop preflight found an owned backend without a port.");
+ return;
+ }
+ setApiBase(preflight.port);
+ portRef.current = preflight.port;
+ setIsExternalServer(false);
+ stopExternalServerPoll();
+ setRunningStatus();
+ return;
case "managed_ready":
setIsExternalServer(false);
stopExternalServerPoll();
setBackendStatus("starting");
await startManagedServer();
return;
+ case "owned_stale":
case "managed_stale":
setIsExternalServer(false);
stopExternalServerPoll();
@@ -218,10 +247,17 @@ export function useTauriBackend() {
await startRepair();
} else {
setBackendError(
- "Managed Studio install is too old. Run `unsloth studio update`.",
+ preflight.disposition === "owned_stale"
+ ? "Desktop-owned Studio backend is too old for this desktop app. Run `unsloth studio update`, then restart Studio."
+ : "Managed Studio install is too old. Run `unsloth studio update`.",
);
}
return;
+ case "external_conflict":
+ setIsExternalServer(false);
+ stopExternalServerPoll();
+ setBackendError(externalConflictMessage(preflight));
+ return;
case "not_installed":
setBackendStatus("not-installed");
return;
@@ -264,11 +300,6 @@ export function useTauriBackend() {
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);
if (msg.includes("already running")) {
@@ -441,9 +472,9 @@ export function useTauriBackend() {
});
}, [currentStepIndex, elevationPackages, error, logs, progressDetail]);
- // Initial check on mount (guarded against Strict Mode double-mount)
+ // Initial check on mount after Tauri event listeners are registered.
useEffect(() => {
- if (mountedRef.current) return;
+ if (!tauriEventsReady || mountedRef.current) return;
mountedRef.current = true;
if (!isTauri) {
@@ -451,7 +482,7 @@ export function useTauriBackend() {
return;
}
checkInstallAndStart();
- }, []);
+ }, [tauriEventsReady]);
// Listen for Tauri events
useEffect(() => {
@@ -460,17 +491,20 @@ export function useTauriBackend() {
let disposed = false;
import("@tauri-apps/api/event").then(({ listen }) => {
+ const registrations: Promise<void>[] = [];
function register<T>(
event: string,
handler: Parameters<typeof listen<T>>[1],
) {
- listen<T>(event, handler).then((unlisten) => {
- if (disposed) {
- unlisten();
- } else {
- cleanup.push(unlisten);
- }
- });
+ registrations.push(
+ listen<T>(event, handler).then((unlisten) => {
+ if (disposed) {
+ unlisten();
+ } else {
+ cleanup.push(unlisten);
+ }
+ }),
+ );
}
register<string>("install-progress", (e) => {
@@ -549,6 +583,16 @@ export function useTauriBackend() {
retry();
}
});
+
+ Promise.all(registrations)
+ .then(() => {
+ if (!disposed) setTauriEventsReady(true);
+ })
+ .catch((error) => {
+ if (!disposed) setBackendError(String(error));
+ });
+ }).catch((error) => {
+ if (!disposed) setBackendError(String(error));
});
const onAuthFailed = (event: Event) => {
diff --git a/studio/frontend/src/hooks/use-tauri-update.ts b/studio/frontend/src/hooks/use-tauri-update.ts
index 67f9bf4c77a..adfe64e8db8 100644
--- a/studio/frontend/src/hooks/use-tauri-update.ts
+++ b/studio/frontend/src/hooks/use-tauri-update.ts
@@ -31,6 +31,21 @@ export type UpdatePhase =
| "shell_install"
| "recovered_after_shell_failure";
+export type DesktopUpdatePolicyMode = "in_app" | "manual_linux_package";
+
+interface DesktopUpdatePolicy {
+ mode: DesktopUpdatePolicyMode;
+ releasePageBaseUrl: string;
+ releaseTagPrefix: string;
+}
+
+interface ManualUpdateInfo {
+ version: string;
+ currentVersion: string;
+ body?: string;
+ date?: string;
+}
+
export interface RetainedUpdateFailure {
error: string;
phase: UpdatePhase;
@@ -38,6 +53,29 @@ export interface RetainedUpdateFailure {
logs: string[];
}
+const DEFAULT_UPDATE_POLICY: DesktopUpdatePolicy = {
+ mode: "in_app",
+ releasePageBaseUrl: "https://github.com/unslothai/unsloth/releases/tag/",
+ releaseTagPrefix: "desktop-v",
+};
+
+const UPDATE_VERSION_RE = /^v?\d+\.\d+\.\d+(?:(?:[-+][0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)|(?:\.(?:post|dev|rc)\d*)|(?:(?:post|dev|rc|a|b)\d*))?$/;
+
+function normalizeUpdateVersion(version: string): string | null {
+ const trimmed = version.trim();
+ if (!UPDATE_VERSION_RE.test(trimmed)) return null;
+ return trimmed.startsWith("v") ? trimmed.slice(1) : trimmed;
+}
+
+function manualReleasePageUrl(
+ policy: DesktopUpdatePolicy,
+ version: string,
+): string | null {
+ const normalized = normalizeUpdateVersion(version);
+ if (!normalized) return null;
+ return `${policy.releasePageBaseUrl}${policy.releaseTagPrefix}${normalized}`;
+}
+
export function useTauriUpdate(isExternalServer = false) {
const [status, setStatus] = useState<UpdateStatus>("idle");
const [info, setInfo] = useState<UpdateInfo | null>(null);
@@ -50,6 +88,7 @@ export function useTauriUpdate(isExternalServer = false) {
const [dismissed, setDismissed] = useState(false);
const [error, setError] = useState<string | null>(null);
const [lastFailure, setLastFailure] = useState<RetainedUpdateFailure | null>(null);
+ const [updatePolicy, setUpdatePolicy] = useState<DesktopUpdatePolicy>(DEFAULT_UPDATE_POLICY);
const updateRef = useRef<Awaited<
ReturnType<typeof import("@tauri-apps/plugin-updater").check>
> | null>(null);
@@ -93,12 +132,63 @@ export function useTauriUpdate(isExternalServer = false) {
return failure;
}
+ async function resolveUpdatePolicy(): Promise<DesktopUpdatePolicy> {
+ if (!isTauri) return DEFAULT_UPDATE_POLICY;
+ try {
+ const { invoke } = await import("@tauri-apps/api/core");
+ const policy = await invoke<DesktopUpdatePolicy>("desktop_update_policy");
+ setUpdatePolicy(policy);
+ return policy;
+ } catch (e) {
+ console.warn("Desktop update policy check failed:", e);
+ const failSafePolicy: DesktopUpdatePolicy = {
+ ...DEFAULT_UPDATE_POLICY,
+ mode: "manual_linux_package",
+ };
+ setUpdatePolicy(failSafePolicy);
+ return failSafePolicy;
+ }
+ }
+
+ async function checkManualUpdateFallback(policy: DesktopUpdatePolicy) {
+ if (policy.mode !== "manual_linux_package") return false;
+ try {
+ const { invoke } = await import("@tauri-apps/api/core");
+ const manualUpdate = await invoke<ManualUpdateInfo | null>(
+ "check_desktop_manual_update",
+ );
+ if (!manualUpdate) return false;
+ updateRef.current = null;
+ setInfo({
+ version: manualUpdate.version,
+ currentVersion: manualUpdate.currentVersion,
+ body: manualUpdate.body,
+ date: manualUpdate.date,
+ });
+ setStatus("available");
+ return true;
+ } catch (e) {
+ console.error("Manual update metadata check failed:", e);
+ return false;
+ }
+ }
+
+ async function openManualUpdatePage(policy: DesktopUpdatePolicy, version: string) {
+ const url = manualReleasePageUrl(policy, version);
+ if (!url) {
+ throw new Error(`Invalid desktop update version: ${version}`);
+ }
+ const { openUrl } = await import("@tauri-apps/plugin-opener");
+ await openUrl(url);
+ }
+
useEffect(() => {
if (!isTauri || checkedRef.current) return;
checkedRef.current = true;
async function checkForUpdate() {
setStatus("checking");
+ const policy = await resolveUpdatePolicy();
try {
const { check } = await import("@tauri-apps/plugin-updater");
const update = await check();
@@ -111,12 +201,14 @@ export function useTauriUpdate(isExternalServer = false) {
date: update.date,
});
setStatus("available");
- } else {
+ } else if (!(await checkManualUpdateFallback(policy))) {
setStatus("idle");
}
} catch (e) {
console.error("Update check failed:", e);
- setStatus("idle");
+ if (!(await checkManualUpdateFallback(policy))) {
+ setStatus("idle");
+ }
}
}
@@ -125,14 +217,31 @@ export function useTauriUpdate(isExternalServer = false) {
}, []);
async function installUpdate() {
- const update = updateRef.current;
- if (!update || updatingRef.current) return;
+ if (updatingRef.current) return;
updatingRef.current = true;
const cleanups: (() => void)[] = [];
try {
- // ── Step 1: Backend update ──
+ const policy = await resolveUpdatePolicy();
+ if (policy.mode === "manual_linux_package") {
+ const version = info?.version ?? updateRef.current?.version;
+ if (!version) return;
+ try {
+ await openManualUpdatePage(policy, version);
+ setDismissed(true);
+ setError(null);
+ } catch (manualError) {
+ const msg = String(manualError);
+ setError(msg);
+ toast.error("Could not open release page", { description: msg });
+ }
+ return;
+ }
+
+ const update = updateRef.current;
+ if (!update) return;
+
setUpdatePhase("backend");
setStatus("updating-backend");
replaceLogs([]);
@@ -144,7 +253,6 @@ export function useTauriUpdate(isExternalServer = false) {
const { listen } = await import("@tauri-apps/api/event");
const { invoke } = await import("@tauri-apps/api/core");
- // Listen for backend update progress
const unlistenProgress = await listen<string>(
"update-progress",
(e) => {
@@ -153,7 +261,6 @@ export function useTauriUpdate(isExternalServer = false) {
);
cleanups.push(unlistenProgress);
- // Wait for complete or failed
const backendResult = await new Promise<"complete" | string>(
(resolve) => {
listen<void>("update-complete", () => resolve("complete")).then(
@@ -171,12 +278,9 @@ export function useTauriUpdate(isExternalServer = false) {
retainFailure(backendResult, "backend");
setError(backendResult);
setStatus("error");
- updatingRef.current = false;
- cleanup(cleanups);
return;
}
- // ── Step 2: Shell update ──
setUpdatePhase("shell_download");
setStatus("downloading");
setUpdateProgress(0);
@@ -201,7 +305,6 @@ export function useTauriUpdate(isExternalServer = false) {
}
});
- // ── Step 3: Relaunch ──
const { relaunch } = await import("@tauri-apps/plugin-process");
await relaunch();
} catch (e) {
@@ -281,6 +384,11 @@ export function useTauriUpdate(isExternalServer = false) {
});
}
+ const manualReleaseUrl =
+ updatePolicy.mode === "manual_linux_package" && info
+ ? manualReleasePageUrl(updatePolicy, info.version)
+ : null;
+
return {
status,
info,
@@ -291,6 +399,8 @@ export function useTauriUpdate(isExternalServer = false) {
phase,
lastFailure,
isExternalServer,
+ updatePolicyMode: updatePolicy.mode,
+ manualReleaseUrl,
installUpdate,
retryUpdate,
skipAndRestart,
diff --git a/studio/frontend/src/lib/api-base.ts b/studio/frontend/src/lib/api-base.ts
index c8be4426533..06bb4917599 100644
--- a/studio/frontend/src/lib/api-base.ts
+++ b/studio/frontend/src/lib/api-base.ts
@@ -1,7 +1,17 @@
-// Central API base URL for Tauri vs browser mode
let apiBase = ''
-const isTauri = typeof window !== 'undefined' && '__TAURI__' in window
+function detectTauri(): boolean {
+ if (typeof window === 'undefined') {
+ return false
+ }
+ return (
+ '__TAURI__' in window ||
+ '__TAURI_INTERNALS__' in window ||
+ window.location.protocol === 'tauri:'
+ )
+}
+
+const isTauri = detectTauri()
const isViteDev = import.meta.env.DEV
if (isTauri && !isViteDev) {
diff --git a/studio/src-tauri/linux/postremove.sh b/studio/src-tauri/linux/postremove.sh
index 6314c0f3dd6..e721c39830e 100755
--- a/studio/src-tauri/linux/postremove.sh
+++ b/studio/src-tauri/linux/postremove.sh
@@ -1,5 +1,5 @@
#!/bin/sh
-# Post-removal script for Unsloth Studio (deb/rpm)
+# Post-removal script for the Unsloth Studio Debian package
# Runs non-interactively; never deletes user data or touches other users' homes.
case "${1:-}" in
diff --git a/studio/src-tauri/src/commands.rs b/studio/src-tauri/src/commands.rs
index e9a27644dfc..06f2dca941c 100644
--- a/studio/src-tauri/src/commands.rs
+++ b/studio/src-tauri/src/commands.rs
@@ -22,12 +22,78 @@ fn should_emit_repair_failed(msg: &str) -> bool {
!msg.contains("NEEDS_ELEVATION")
}
+fn external_conflict_message(conflict: &crate::preflight::ExternalBackendConflict) -> String {
+ if conflict.reason == "desktop_owned_backend_active" {
+ return format!(
+ "A desktop-owned Studio server for this install is already running on port {}. Quit the other desktop app instance, then try again.",
+ conflict.port
+ );
+ }
+ format!(
+ "A Studio server for this install is already running from a terminal on port {}. Stop that server, or run `unsloth studio update` from that terminal before using desktop repair/update.",
+ conflict.port
+ )
+}
+
+fn owned_backend_port(state: &tauri::State<'_, BackendState>) -> Result<Option<u16>, String> {
+ state
+ .lock()
+ .map(|proc| proc.owned_backend_port())
+ .map_err(|e| e.to_string())
+}
+
+fn has_owned_backend(state: &tauri::State<'_, BackendState>) -> Result<bool, String> {
+ state
+ .lock()
+ .map(|proc| proc.has_owned_backend())
+ .map_err(|e| e.to_string())
+}
+
+async fn block_external_conflict(ignored_ports: &[u16]) -> Result<(), String> {
+ if let Some(conflict) =
+ crate::preflight::mutation_blocking_backend_ignoring(ignored_ports).await
+ {
+ return Err(external_conflict_message(&conflict));
+ }
+ Ok(())
+}
+
#[tauri::command]
pub async fn desktop_preflight(
+ app: AppHandle,
+ state: tauri::State<'_, BackendState>,
+ shutdown: tauri::State<'_, ShutdownFlag>,
diagnostics: tauri::State<'_, DiagnosticsState>,
) -> Result<crate::preflight::DesktopPreflightResult, String> {
- let result = crate::preflight::desktop_preflight_result().await;
+ let (result, adopted_watchdog_generation) =
+ crate::preflight::desktop_preflight_result_with_state(state.inner()).await?;
diagnostics::record_preflight(&diagnostics, &result);
+
+ if let Some((generation, newly_adopted)) = adopted_watchdog_generation {
+ if newly_adopted {
+ if let Some(port) = result.port {
+ diagnostics::begin_adopted_backend_session(&diagnostics, port, generation);
+ }
+ }
+ if process::claim_adopted_watchdog_if_current(state.inner(), generation) {
+ shutdown.store(false, std::sync::atomic::Ordering::SeqCst);
+ let watchdog_state = state.inner().clone();
+ let watchdog_shutdown = shutdown.inner().clone();
+ let watchdog_diagnostics = diagnostics.inner().clone();
+ tokio::spawn(async move {
+ health_watchdog(
+ app,
+ watchdog_state,
+ watchdog_shutdown,
+ watchdog_diagnostics,
+ generation,
+ true,
+ )
+ .await;
+ });
+ }
+ }
+
Ok(result)
}
@@ -121,6 +187,7 @@ pub async fn start_server(
watchdog_shutdown,
diagnostics_state,
generation,
+ false,
)
.await;
});
@@ -151,6 +218,7 @@ pub async fn start_managed_server(
watchdog_shutdown,
diagnostics_state,
generation,
+ false,
)
.await;
});
@@ -158,17 +226,22 @@ pub async fn start_managed_server(
Ok(())
}
-/// Stop the backend server.
-/// Sends SIGTERM to the process group, which triggers uvicorn's graceful
-/// shutdown (same codepath as /api/shutdown). Falls back to SIGKILL after 5s.
+/// Stop the current desktop-owned backend if this app can safely control it.
#[tauri::command]
-pub fn stop_server(
+pub async 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, Some(diagnostics.inner()))
+ let state = state.inner().clone();
+ let shutdown = shutdown.inner().clone();
+ let diagnostics = diagnostics.inner().clone();
+ tauri::async_runtime::spawn_blocking(move || {
+ process::stop_backend(&state, &shutdown, Some(&diagnostics))
+ })
+ .await
+ .map_err(|e| format!("stop backend task failed: {e}"))?
}
/// Check if a healthy Unsloth backend is running on the given port.
@@ -207,6 +280,35 @@ async fn check_health_inner(port: u16) -> Result<bool, reqwest::Error> {
Ok(healthy && correct_service)
}
+async fn check_watchdog_health(
+ state: &BackendState,
+ generation: u64,
+ port: u16,
+ has_adopted: bool,
+) -> bool {
+ if !has_adopted {
+ return check_health_inner(port).await.unwrap_or(false);
+ }
+
+ let snapshot = match process::owned_backend_snapshot(state) {
+ Ok(Some(snapshot))
+ if snapshot.is_adopted
+ && snapshot.generation == generation
+ && snapshot.port == Some(port) =>
+ {
+ snapshot
+ }
+ _ => return false,
+ };
+ let Some(owner) = snapshot.owner else {
+ return false;
+ };
+ matches!(
+ crate::desktop_backend_owner::probe_owned_backend_state(owner, Some(port), false).await,
+ crate::desktop_backend_owner::OwnedBackendProbe::Verified(_)
+ )
+}
+
/// Return buffered server logs.
#[tauri::command]
pub fn get_server_logs(state: tauri::State<'_, BackendState>) -> Vec<String> {
@@ -308,12 +410,6 @@ pub async fn start_backend_update(
) -> Result<(), String> {
info!("start_backend_update command called");
- // Signal the health watchdog to exit immediately, before any guards.
- // This closes the race window where the watchdog could emit server-crashed
- // between our command being called and stop_backend completing.
- shutdown.store(true, std::sync::atomic::Ordering::SeqCst);
-
- // Guard: reject if install is running
if install_state
.lock()
.map(|s| s.child.is_some())
@@ -322,7 +418,6 @@ pub async fn start_backend_update(
return Err("Cannot update while installation is in progress.".to_string());
}
- // Guard: reject if update is already running
if update_state
.lock()
.map(|s| s.child.is_some())
@@ -331,17 +426,20 @@ pub async fn start_backend_update(
return Err("Update is already running.".to_string());
}
- // Stop backend if running
- if backend_state
- .lock()
- .map(|s| s.child.is_some())
- .unwrap_or(false)
- {
+ let owned_port = owned_backend_port(&backend_state)?;
+ let has_owned = has_owned_backend(&backend_state)?;
+ if has_owned {
+ if let Some(port) = owned_port {
+ block_external_conflict(&[port]).await?;
+ }
+
info!("Stopping backend before update...");
- process::stop_backend(&backend_state, &shutdown, Some(diagnostics.inner()))?;
+ process::stop_backend_for_mutation(&backend_state, &shutdown, Some(diagnostics.inner()))?;
+ block_external_conflict(&[]).await?;
+ } else {
+ block_external_conflict(&[]).await?;
}
- // Run update in a blocking thread
let state = update_state.inner().clone();
let diagnostics_state = diagnostics.inner().clone();
tokio::task::spawn_blocking(move || update::run_backend_update(app, state, diagnostics_state))
@@ -378,20 +476,24 @@ pub async fn start_managed_repair(
}
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);
+ let owned_port = owned_backend_port(&backend_state)?;
+ let has_owned = has_owned_backend(&backend_state)?;
+ if has_owned {
+ if let Some(port) = owned_port {
+ block_external_conflict(&[port]).await?;
+ }
- if backend_state
- .lock()
- .map(|s| s.child.is_some())
- .unwrap_or(false)
- {
info!("Stopping backend before repair...");
- process::stop_backend(&backend_state, &shutdown, Some(&diagnostics_state))?;
+ process::stop_backend_for_mutation(&backend_state, &shutdown, Some(&diagnostics_state))?;
+ block_external_conflict(&[]).await?;
+ } else {
+ block_external_conflict(&[]).await?;
}
+ let repair_group_id = install::take_pending_repair_group_for_resume(&install_state)
+ .unwrap_or_else(|| diagnostics::begin_repair_group(&diagnostics_state));
+
let _ = app.emit("repair-progress", "Updating existing Studio install...");
let update_app = app.clone();
let update_state = update_state.inner().clone();
@@ -446,6 +548,17 @@ pub async fn start_managed_repair(
}
}
+ if let Err(msg) = block_external_conflict(&[]).await {
+ diagnostics::finish_repair_group(
+ &diagnostics_state,
+ &repair_group_id,
+ "failed",
+ Some(msg.clone()),
+ );
+ let _ = app.emit("repair-failed", &msg);
+ return Err(msg);
+ }
+
let install_app = app.clone();
let install_state = install_state.inner().clone();
let install_diagnostics = diagnostics_state.clone();
@@ -501,6 +614,62 @@ pub async fn start_managed_repair(
#[cfg(test)]
mod tests {
use std::time::Duration;
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ use tokio::net::TcpListener;
+
+ const ROOT_ID: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
+ const OWNER_TOKEN: &str = "desktop-owner-token";
+
+ fn ready_health(include_owner: bool) -> String {
+ let owner = if include_owner {
+ format!(
+ r#", "desktop_owner":{{"kind":"tauri","token_sha256":"{}"}}"#,
+ crate::desktop_backend_owner::token_sha256(OWNER_TOKEN)
+ )
+ } else {
+ String::new()
+ };
+ format!(
+ r#"{{"status":"healthy","service":"Unsloth UI Backend","version":"2026.5.3","desktop_protocol_version":1,"desktop_manageability_version":1,"supports_desktop_auth":true,"supports_desktop_backend_ownership":true,"studio_root_id":"{ROOT_ID}"{owner}}}"#
+ )
+ }
+
+ async fn command_test_backend(health_body: String) -> u16 {
+ let mut listener = None;
+ for port in 8888u16..=8908 {
+ if let Ok(bound) = TcpListener::bind(("127.0.0.1", port)).await {
+ listener = Some(bound);
+ break;
+ }
+ }
+ let listener = listener.expect("test needs a free desktop preflight port");
+ let port = listener.local_addr().unwrap().port();
+ tokio::spawn(async move {
+ for _ in 0..2 {
+ let Ok((mut stream, _)) = listener.accept().await else {
+ return;
+ };
+ let mut buffer = [0; 2048];
+ let Ok(n) = stream.read(&mut buffer).await else {
+ return;
+ };
+ let request = String::from_utf8_lossy(&buffer[..n]);
+ let (status, body) = if request.starts_with("GET /api/health ") {
+ ("200 OK", health_body.as_str())
+ } else if request.starts_with("POST /api/auth/desktop-login ") {
+ ("401 Unauthorized", "")
+ } else {
+ ("404 Not Found", "")
+ };
+ let response = format!(
+ "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = stream.write_all(response.as_bytes()).await;
+ }
+ });
+ port
+ }
#[test]
fn repair_elevation_is_not_a_terminal_repair_failure() {
@@ -510,28 +679,36 @@ mod tests {
));
}
- #[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)
- ));
- }
+ #[tokio::test]
+ async fn mutation_guard_blocks_second_external_backend_when_owned_child_is_ignored() {
+ crate::desktop_backend_owner::install_test_owner(ROOT_ID, OWNER_TOKEN);
+ let owned_port = command_test_backend(ready_health(true)).await;
+ let external_port = command_test_backend(ready_health(false)).await;
- #[test]
- fn watchdog_counts_failures_after_backend_was_healthy() {
- assert!(super::should_count_watchdog_failure(
- true,
- Duration::from_secs(1)
- ));
+ let err = super::block_external_conflict(&[owned_port])
+ .await
+ .expect_err("external non-owned backend should block mutation");
+
+ assert!(err.contains(&format!("port {external_port}")));
+ assert!(err.contains("Stop that server"));
}
#[test]
- fn watchdog_counts_startup_failures_after_grace_period() {
- assert!(super::should_count_watchdog_failure(
- false,
- super::BACKEND_STARTUP_GRACE_PERIOD
- ));
+ fn watchdog_failure_policy_counts_only_after_health_or_grace_period() {
+ for (has_seen_healthy, elapsed, expected) in [
+ (
+ false,
+ super::BACKEND_STARTUP_GRACE_PERIOD - Duration::from_secs(1),
+ false,
+ ),
+ (true, Duration::from_secs(1), true),
+ (false, super::BACKEND_STARTUP_GRACE_PERIOD, true),
+ ] {
+ assert_eq!(
+ super::should_count_watchdog_failure(has_seen_healthy, elapsed),
+ expected
+ );
+ }
}
}
@@ -546,12 +723,13 @@ async fn health_watchdog(
shutdown: ShutdownFlag,
diagnostics: DiagnosticsState,
generation: u64,
+ count_failures_immediately: bool,
) {
use std::sync::atomic::Ordering;
let started_at = Instant::now();
let mut consecutive_failures: u32 = 0;
- let mut has_seen_healthy = false;
+ let mut has_seen_healthy = count_failures_immediately;
loop {
tokio::time::sleep(HEALTH_WATCHDOG_INTERVAL).await;
@@ -561,12 +739,17 @@ async fn health_watchdog(
break;
}
- let (port, has_child, current_generation) = {
+ let (port, has_owned, has_adopted, current_generation) = {
let proc = match state.lock() {
Ok(p) => p,
Err(_) => break,
};
- (proc.port, proc.child.is_some(), proc.generation)
+ (
+ proc.port,
+ proc.has_owned_backend(),
+ proc.has_adopted_backend(),
+ proc.generation,
+ )
};
if current_generation != generation {
@@ -575,70 +758,94 @@ async fn health_watchdog(
}
// Stop watching if the backend is gone
- if !has_child {
+ if !has_owned {
info!("Health watchdog: backend stopped, exiting");
break;
}
let should_count_failure =
- should_count_watchdog_failure(has_seen_healthy, started_at.elapsed());
+ port.is_some() || should_count_watchdog_failure(has_seen_healthy, started_at.elapsed());
let Some(port) = port else {
- if should_count_failure {
- consecutive_failures += 1;
- warn!(
- "Health watchdog: backend has not reported a port ({}/{})",
- consecutive_failures, HEALTH_WATCHDOG_MAX_FAILURES
+ if has_adopted {
+ diagnostics::record_backend_watchdog(
+ &diagnostics,
+ generation,
+ "adopted_port_missing",
+ );
+ error!("Health watchdog: adopted backend lost its port, declaring dead");
+ process::clear_adopted_backend_if_current(
+ &state,
+ generation,
+ None,
+ "watchdog adopted port missing",
);
+ let _ = app.emit("server-crashed", ());
+ break;
}
-
+ if !should_count_failure {
+ info!("Health watchdog: backend has not reported a validated port yet");
+ continue;
+ }
+ consecutive_failures += 1;
+ warn!(
+ "Health watchdog: missing validated port failure {}/{}",
+ 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",
+ "missing_validated_port",
);
+ error!("Health watchdog: backend never reported a validated port, killing and declaring dead");
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 {}/{} on port {}",
- consecutive_failures, HEALTH_WATCHDOG_MAX_FAILURES, port
+ if check_watchdog_health(&state, generation, port, has_adopted).await {
+ has_seen_healthy = true;
+ consecutive_failures = 0;
+ } else if !should_count_failure {
+ info!(
+ "Health watchdog: startup health check failed on port {} before grace period elapsed",
+ port
+ );
+ } else {
+ consecutive_failures += 1;
+ warn!(
+ "Health watchdog: failure {}/{} on port {}",
+ consecutive_failures, HEALTH_WATCHDOG_MAX_FAILURES, port
+ );
+ if consecutive_failures >= HEALTH_WATCHDOG_MAX_FAILURES {
+ diagnostics::record_backend_watchdog(
+ &diagnostics,
+ generation,
+ "unresponsive_health_check",
);
- if consecutive_failures >= HEALTH_WATCHDOG_MAX_FAILURES {
- error!("Health watchdog: backend unresponsive, killing and declaring dead");
- diagnostics::record_backend_watchdog(
- &diagnostics,
+ if has_adopted {
+ error!(
+ "Health watchdog: adopted backend unresponsive, clearing state and declaring dead"
+ );
+ process::clear_adopted_backend_if_current(
+ &state,
generation,
- "unresponsive_health_check",
+ Some(port),
+ "watchdog health check failures",
);
+ } else {
+ error!("Health watchdog: backend unresponsive, killing and declaring dead");
// Kill the zombie process so retry can start fresh
let _ = process::stop_backend(&state, &shutdown, Some(&diagnostics));
- let _ = app.emit("server-crashed", ());
- break;
}
+ let _ = app.emit("server-crashed", ());
+ break;
}
}
}
+
+ process::clear_adopted_watchdog_if_current(&state, generation);
}
diff --git a/studio/src-tauri/src/desktop_auth.rs b/studio/src-tauri/src/desktop_auth.rs
index 49b19008fbf..33605f6c659 100644
--- a/studio/src-tauri/src/desktop_auth.rs
+++ b/studio/src-tauri/src/desktop_auth.rs
@@ -91,13 +91,36 @@ fn read_secret_if_exists(path: &Path) -> Result<Option<String>, String> {
async fn current_backend_port(
state: &tauri::State<'_, BackendState>,
) -> Result<BackendPort, String> {
- if let Some(port) = state.lock().map_err(|e| e.to_string())?.port {
+ let cached_port = {
+ let proc = state.lock().map_err(|e| e.to_string())?;
+ if let Some(port) = proc.owned_backend_port() {
+ return Ok(BackendPort {
+ port,
+ source: PortSource::Cached,
+ });
+ }
+ if proc.has_owned_backend() {
+ None
+ } else {
+ proc.port
+ }
+ };
+
+ if let Some(port) = cached_port {
return Ok(BackendPort {
port,
source: PortSource::Cached,
});
}
+ if state
+ .lock()
+ .map(|proc| proc.has_owned_backend())
+ .map_err(|e| e.to_string())?
+ {
+ return Err("Backend is not ready".to_string());
+ }
+
let port = discover_compatible_backend_port()
.await
.ok_or_else(|| "Backend is not ready".to_string())?;
@@ -152,6 +175,16 @@ fn should_retry_with_discovered_port(source: PortSource, error: &AuthError) -> b
)
}
+fn can_retry_on_discovered_port(state: &BackendState, source: PortSource) -> Result<bool, String> {
+ if source != PortSource::Cached {
+ return Ok(false);
+ }
+ state
+ .lock()
+ .map(|proc| !proc.has_owned_backend())
+ .map_err(|e| e.to_string())
+}
+
async fn exchange_desktop_secret(
client: &Client,
port: u16,
@@ -234,7 +267,7 @@ async fn retry_on_discovered_port(
previous: BackendPort,
secret: &str,
) -> Result<Option<(Option<DesktopAuthResponse>, BackendPort)>, String> {
- if previous.source != PortSource::Cached {
+ if !can_retry_on_discovered_port(state.inner(), previous.source)? {
return Ok(None);
}
let Some(port) = discover_compatible_backend_port().await else {
@@ -359,23 +392,6 @@ mod tests {
port
}
- #[test]
- fn auth_secret_path_joins_expected_location() {
- let home = PathBuf::from("/home/alex");
- assert_eq!(
- auth_secret_path(&home, ".desktop_secret"),
- PathBuf::from("/home/alex/.unsloth/studio/auth/.desktop_secret")
- );
- }
-
- #[test]
- fn auth_url_builds_local_endpoint() {
- assert_eq!(
- auth_url(8890, "desktop-login"),
- "http://127.0.0.1:8890/api/auth/desktop-login"
- );
- }
-
#[test]
fn retry_discovery_only_for_cached_recoverable_errors() {
assert!(should_retry_with_discovered_port(
@@ -397,111 +413,56 @@ 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()
+ fn owned_handle_disables_discovered_auth_retry() {
+ const ROOT_ID: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
+ const TOKEN: &str = "desktop-owner-token";
+
+ let state = crate::process::new_backend_state();
+ assert!(can_retry_on_discovered_port(&state, PortSource::Cached).unwrap());
+ assert!(!can_retry_on_discovered_port(&state, PortSource::Discovered).unwrap());
+
+ let owner = crate::desktop_backend_owner::test_owner_state(ROOT_ID, TOKEN, 8890);
+ state.lock().unwrap().owned = Some(crate::process::OwnedBackendHandle::adopted(
+ owner, 8890, 2, 3,
));
- let _ = std::fs::remove_file(&path);
- assert_eq!(read_secret_if_exists(&path).unwrap(), None);
+ assert!(!can_retry_on_discovered_port(&state, PortSource::Cached).unwrap());
}
#[test]
- fn read_secret_trims_existing_file() {
- let path =
+ fn read_secret_handles_missing_trimmed_and_invalid_files() {
+ let base =
std::env::temp_dir().join(format!("unsloth-desktop-secret-{}", std::process::id()));
- std::fs::write(&path, " desktop-secret\n").unwrap();
-
+ let missing = base.with_extension("missing");
+ let trimmed = base.with_extension("trimmed");
+ let invalid = base.with_extension("invalid");
+ let _ = std::fs::remove_file(&missing);
+ std::fs::write(&trimmed, " desktop-secret\n").unwrap();
+ std::fs::write(&invalid, [0xff, 0xfe]).unwrap();
+
+ assert_eq!(read_secret_if_exists(&missing).unwrap(), None);
assert_eq!(
- read_secret_if_exists(&path).unwrap(),
+ read_secret_if_exists(&trimmed).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 {
- disposition: DesktopPreflightDisposition::AttachedReady,
- reason: None,
- port: Some(8890),
- can_auto_repair: false,
- managed_bin: None,
- };
- assert_eq!(attached_ready_port(compatible), Some(8890));
-
- let missing_port = DesktopPreflightResult {
- disposition: DesktopPreflightDisposition::AttachedReady,
- reason: None,
- port: None,
- can_auto_repair: false,
- managed_bin: None,
- };
- assert_eq!(attached_ready_port(missing_port), None);
-
- let managed_ready = DesktopPreflightResult {
- disposition: DesktopPreflightDisposition::ManagedReady,
- reason: None,
- port: Some(8890),
- can_auto_repair: false,
- managed_bin: None,
- };
- assert_eq!(attached_ready_port(managed_ready), None);
+ assert_eq!(read_secret_if_exists(&invalid).unwrap(), None);
+ let _ = std::fs::remove_file(trimmed);
+ let _ = std::fs::remove_file(invalid);
}
#[tokio::test]
- async fn exchange_desktop_secret_returns_none_for_unauthorized() {
+ async fn exchange_desktop_secret_handles_unauthorized_and_not_found() {
let port = login_server("401 Unauthorized").await;
let tokens = exchange_desktop_secret(&Client::new(), port, "desktop-stale")
.await
.unwrap();
-
assert!(tokens.is_none());
- }
- #[tokio::test]
- async fn exchange_desktop_secret_reports_unsupported_backend_on_not_found() {
let port = login_server("404 Not Found").await;
let error = exchange_desktop_secret(&Client::new(), port, "desktop-secret")
.await
.unwrap_err()
.message();
-
assert_eq!(
error,
"Running Studio backend is too old for this desktop app. Update that backend and restart."
diff --git a/studio/src-tauri/src/desktop_backend_owner.rs b/studio/src-tauri/src/desktop_backend_owner.rs
new file mode 100644
index 00000000000..1d087087418
--- /dev/null
+++ b/studio/src-tauri/src/desktop_backend_owner.rs
@@ -0,0 +1,1018 @@
+use log::warn;
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use std::io::{Read, Write};
+use std::net::{SocketAddr, TcpStream};
+use std::path::{Path, PathBuf};
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+#[cfg(test)]
+static TEST_EXPECTED_STUDIO_ROOT_ID: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
+#[cfg(test)]
+static TEST_METADATA: std::sync::Mutex<Option<DesktopBackendMetadata>> =
+ std::sync::Mutex::new(None);
+
+pub(crate) const OWNER_TOKEN_ENV: &str = "UNSLOTH_STUDIO_DESKTOP_OWNER_TOKEN";
+pub(crate) const OWNER_KIND_ENV: &str = "UNSLOTH_STUDIO_DESKTOP_OWNER_KIND";
+pub(crate) const OWNER_KIND_TAURI: &str = "tauri";
+
+const METADATA_SCHEMA_VERSION: u8 = 1;
+const STUDIO_INSTALL_ID_HEX_LEN: usize = 64;
+const OWNER_TOKEN_BYTES: usize = 32;
+const DESKTOP_PORT_START: u16 = 8888;
+const DESKTOP_PORT_END: u16 = 8908;
+const LOCAL_HTTP_TIMEOUT: Duration = Duration::from_secs(2);
+
+#[derive(Clone, Debug)]
+pub(crate) struct PendingBackendOwner {
+ pub token: String,
+ pub studio_root_id: String,
+}
+
+#[derive(Clone, Debug)]
+pub(crate) struct BackendOwnerState {
+ path: PathBuf,
+ metadata: DesktopBackendMetadata,
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+struct DesktopBackendMetadata {
+ schema_version: u8,
+ kind: String,
+ token: String,
+ token_sha256: String,
+ app_pid: u32,
+ backend_pid: u32,
+ generation: u64,
+ requested_port: u16,
+ port: Option<u16>,
+ studio_root_id: String,
+ started_at_ms: u64,
+ updated_at_ms: u64,
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(crate) enum HealthOwnerMatch {
+ None,
+ CurrentApp,
+ PreviousApp,
+ OtherDesktopOwner,
+}
+
+#[allow(dead_code)]
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub(crate) enum OwnedBackendReadiness {
+ Ready,
+ Stale { reason: String },
+}
+
+#[allow(dead_code)]
+#[derive(Clone, Debug)]
+pub(crate) struct VerifiedOwnedBackend {
+ pub owner: BackendOwnerState,
+ pub port: u16,
+ pub backend_pid: u32,
+ pub generation: u64,
+ pub readiness: OwnedBackendReadiness,
+}
+
+#[allow(dead_code)]
+#[derive(Clone, Debug)]
+pub(crate) enum OwnedBackendProbe {
+ NoMetadata,
+ RemovedMalformed,
+ NotVerified { reason: String },
+ Unmanageable { port: u16, reason: String },
+ Verified(VerifiedOwnedBackend),
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+enum PreviousAppPidStatus {
+ Dead,
+ AliveOrCurrent,
+ Uncertain,
+}
+
+#[derive(Debug, Deserialize)]
+struct HealthDesktopOwner {
+ kind: Option<String>,
+ token_sha256: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+struct HealthResponse {
+ status: Option<String>,
+ service: Option<String>,
+ version: Option<String>,
+ desktop_protocol_version: Option<u16>,
+ desktop_manageability_version: Option<u16>,
+ supports_desktop_auth: Option<bool>,
+ supports_desktop_backend_ownership: Option<bool>,
+ studio_root_id: Option<String>,
+ desktop_owner: Option<HealthDesktopOwner>,
+}
+
+#[derive(Debug)]
+struct SimpleHttpResponse {
+ status: u16,
+ body: Vec<u8>,
+}
+
+#[derive(Serialize)]
+struct DesktopLoginPayload<'a> {
+ secret: &'a str,
+}
+
+#[derive(Deserialize)]
+struct TokenResponse {
+ access_token: String,
+}
+
+pub(crate) fn desktop_candidate_ports() -> std::ops::RangeInclusive<u16> {
+ DESKTOP_PORT_START..=DESKTOP_PORT_END
+}
+
+pub(crate) fn is_valid_studio_root_id(value: &str) -> bool {
+ value.len() == STUDIO_INSTALL_ID_HEX_LEN
+ && value
+ .bytes()
+ .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
+}
+
+pub(crate) fn parse_studio_root_id(value: &str) -> Option<String> {
+ let value = value.trim();
+ is_valid_studio_root_id(value).then(|| value.to_string())
+}
+
+pub(crate) fn managed_studio_root_id_path(home: &Path) -> PathBuf {
+ home.join(".unsloth")
+ .join("studio")
+ .join("share")
+ .join("studio_install_id")
+}
+
+fn managed_run_dir(home: &Path) -> PathBuf {
+ home.join(".unsloth").join("studio").join("run")
+}
+
+fn metadata_path_for_home(home: &Path) -> PathBuf {
+ managed_run_dir(home).join("desktop_backend.json")
+}
+
+fn auth_secret_path_for_home(home: &Path) -> PathBuf {
+ home.join(".unsloth")
+ .join("studio")
+ .join("auth")
+ .join(".desktop_secret")
+}
+
+pub(crate) fn read_expected_studio_root_id() -> Option<String> {
+ #[cfg(test)]
+ if let Ok(guard) = TEST_EXPECTED_STUDIO_ROOT_ID.lock() {
+ if let Some(value) = guard.clone() {
+ return Some(value);
+ }
+ }
+
+ let home = dirs::home_dir()?;
+ let raw = std::fs::read_to_string(managed_studio_root_id_path(&home)).ok()?;
+ parse_studio_root_id(&raw)
+}
+
+fn metadata_path() -> Option<PathBuf> {
+ dirs::home_dir().map(|home| metadata_path_for_home(&home))
+}
+
+pub(crate) fn token_sha256(token: &str) -> String {
+ hex_bytes(&Sha256::digest(token.as_bytes()))
+}
+
+fn random_owner_token() -> String {
+ hex_bytes(&rand::random::<[u8; OWNER_TOKEN_BYTES]>())
+}
+
+fn now_ms() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_else(|_| Duration::from_secs(0))
+ .as_millis() as u64
+}
+
+fn hex_bytes(bytes: &[u8]) -> String {
+ const HEX: &[u8; 16] = b"0123456789abcdef";
+ let mut out = String::with_capacity(bytes.len() * 2);
+ for &byte in bytes {
+ out.push(HEX[(byte >> 4) as usize] as char);
+ out.push(HEX[(byte & 0x0f) as usize] as char);
+ }
+ out
+}
+
+pub(crate) fn new_pending_owner() -> Option<PendingBackendOwner> {
+ Some(PendingBackendOwner {
+ token: random_owner_token(),
+ studio_root_id: read_expected_studio_root_id()?,
+ })
+}
+
+pub(crate) fn activate_owner(
+ pending: PendingBackendOwner,
+ requested_port: u16,
+ generation: u64,
+ backend_pid: u32,
+) -> Option<BackendOwnerState> {
+ let path = metadata_path()?;
+ let now = now_ms();
+ let metadata = DesktopBackendMetadata {
+ schema_version: METADATA_SCHEMA_VERSION,
+ kind: OWNER_KIND_TAURI.to_string(),
+ token_sha256: token_sha256(&pending.token),
+ token: pending.token,
+ app_pid: std::process::id(),
+ backend_pid,
+ generation,
+ requested_port,
+ port: None,
+ studio_root_id: pending.studio_root_id,
+ started_at_ms: now,
+ updated_at_ms: now,
+ };
+ let state = BackendOwnerState { path, metadata };
+ if let Err(error) = state.write() {
+ warn!("Desktop backend owner metadata unavailable: {}", error);
+ return None;
+ }
+ Some(state)
+}
+
+#[allow(dead_code)]
+impl BackendOwnerState {
+ fn from_metadata(path: PathBuf, metadata: DesktopBackendMetadata) -> Self {
+ Self { path, metadata }
+ }
+
+ fn write(&self) -> Result<(), String> {
+ write_metadata(&self.path, &self.metadata)
+ }
+
+ pub(crate) fn update_port(&mut self, port: u16) -> Result<(), String> {
+ self.metadata.port = Some(port);
+ self.metadata.updated_at_ms = now_ms();
+ self.write()
+ }
+
+ pub(crate) fn remove(self) {
+ remove_metadata_file(&self.path);
+ }
+
+ pub(crate) fn port(&self) -> Option<u16> {
+ self.metadata.port
+ }
+
+ pub(crate) fn backend_pid(&self) -> u32 {
+ self.metadata.backend_pid
+ }
+
+ pub(crate) fn generation(&self) -> u64 {
+ self.metadata.generation
+ }
+
+ pub(crate) fn requested_port(&self) -> u16 {
+ self.metadata.requested_port
+ }
+
+ pub(crate) fn token_sha256(&self) -> &str {
+ &self.metadata.token_sha256
+ }
+
+ pub(crate) fn studio_root_id(&self) -> &str {
+ &self.metadata.studio_root_id
+ }
+
+ pub(crate) fn verifies_exact_port_blocking(&self, port: u16) -> bool {
+ match fetch_health_blocking(port) {
+ Ok(Some(health)) => {
+ health_verifies_metadata(&health, &self.metadata)
+ && lifecycle_control_block_reason(&health).is_none()
+ }
+ _ => false,
+ }
+ }
+}
+
+fn write_metadata(path: &Path, metadata: &DesktopBackendMetadata) -> Result<(), String> {
+ let parent = path
+ .parent()
+ .ok_or_else(|| "desktop owner metadata path has no parent".to_string())?;
+ std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
+ set_private_dir_permissions(parent);
+
+ let tmp = parent.join(format!(".desktop_backend.{}.tmp", std::process::id()));
+ let body = serde_json::to_vec_pretty(metadata).map_err(|e| e.to_string())?;
+ write_private_file(&tmp, &body)?;
+ std::fs::rename(&tmp, path).map_err(|e| e.to_string())?;
+ set_private_file_permissions(path);
+ Ok(())
+}
+
+fn write_private_file(path: &Path, body: &[u8]) -> Result<(), String> {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ let mut file = std::fs::OpenOptions::new()
+ .create(true)
+ .truncate(true)
+ .write(true)
+ .mode(0o600)
+ .open(path)
+ .map_err(|e| e.to_string())?;
+ file.write_all(body).map_err(|e| e.to_string())?;
+ file.sync_all().map_err(|e| e.to_string())?;
+ return Ok(());
+ }
+
+ #[cfg(not(unix))]
+ {
+ std::fs::write(path, body).map_err(|e| e.to_string())
+ }
+}
+
+fn set_private_dir_permissions(path: &Path) {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700));
+ }
+}
+
+fn set_private_file_permissions(path: &Path) {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
+ }
+}
+
+fn remove_metadata_file(path: &Path) {
+ if let Err(error) = std::fs::remove_file(path) {
+ if error.kind() != std::io::ErrorKind::NotFound {
+ warn!(
+ "Could not remove desktop backend owner metadata at {}: {}",
+ path.display(),
+ error
+ );
+ }
+ }
+}
+
+fn read_metadata(path: &Path) -> Result<Option<DesktopBackendMetadata>, String> {
+ let raw = match std::fs::read(path) {
+ Ok(raw) => raw,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(error) => return Err(error.to_string()),
+ };
+ serde_json::from_slice::<DesktopBackendMetadata>(&raw)
+ .map(Some)
+ .map_err(|e| e.to_string())
+}
+
+fn metadata_is_well_formed(metadata: &DesktopBackendMetadata) -> bool {
+ metadata.schema_version == METADATA_SCHEMA_VERSION
+ && metadata.kind == OWNER_KIND_TAURI
+ && is_valid_studio_root_id(&metadata.studio_root_id)
+ && metadata.token_sha256 == token_sha256(&metadata.token)
+ && metadata.backend_pid > 0
+}
+
+fn owner_matches_metadata(
+ metadata: &DesktopBackendMetadata,
+ studio_root_id: Option<&str>,
+ owner_kind: Option<&str>,
+ token_sha256_value: Option<&str>,
+) -> bool {
+ studio_root_id == Some(metadata.studio_root_id.as_str())
+ && owner_kind == Some(OWNER_KIND_TAURI)
+ && token_sha256_value == Some(metadata.token_sha256.as_str())
+}
+
+fn classify_health_desktop_owner_for_metadata(
+ metadata: Option<&DesktopBackendMetadata>,
+ expected_studio_root_id: Option<&str>,
+ studio_root_id: Option<&str>,
+ owner_kind: Option<&str>,
+ token_sha256_value: Option<&str>,
+) -> HealthOwnerMatch {
+ if owner_kind.is_none() && token_sha256_value.is_none() {
+ return HealthOwnerMatch::None;
+ }
+
+ let Some(metadata) = metadata else {
+ return HealthOwnerMatch::OtherDesktopOwner;
+ };
+
+ if metadata_is_well_formed(metadata)
+ && expected_studio_root_id == Some(metadata.studio_root_id.as_str())
+ && owner_matches_metadata(metadata, studio_root_id, owner_kind, token_sha256_value)
+ {
+ if metadata.app_pid == std::process::id() {
+ HealthOwnerMatch::CurrentApp
+ } else {
+ HealthOwnerMatch::PreviousApp
+ }
+ } else {
+ HealthOwnerMatch::OtherDesktopOwner
+ }
+}
+
+pub(crate) fn classify_health_desktop_owner(
+ studio_root_id: Option<&str>,
+ owner_kind: Option<&str>,
+ token_sha256_value: Option<&str>,
+) -> HealthOwnerMatch {
+ let metadata = current_owner_metadata();
+ let expected = read_expected_studio_root_id();
+ classify_health_desktop_owner_for_metadata(
+ metadata.as_ref(),
+ expected.as_deref(),
+ studio_root_id,
+ owner_kind,
+ token_sha256_value,
+ )
+}
+
+fn current_owner_metadata() -> Option<DesktopBackendMetadata> {
+ #[cfg(test)]
+ if let Ok(guard) = TEST_METADATA.lock() {
+ if let Some(metadata) = guard.clone() {
+ return Some(metadata);
+ }
+ }
+
+ let path = metadata_path()?;
+ read_metadata(&path).ok().flatten()
+}
+
+#[cfg(test)]
+pub(crate) fn install_test_owner(root_id: &str, token: &str) {
+ let metadata = DesktopBackendMetadata {
+ schema_version: METADATA_SCHEMA_VERSION,
+ kind: OWNER_KIND_TAURI.to_string(),
+ token: token.to_string(),
+ token_sha256: token_sha256(token),
+ app_pid: std::process::id(),
+ backend_pid: 2,
+ generation: 3,
+ requested_port: 8888,
+ port: Some(8888),
+ studio_root_id: root_id.to_string(),
+ started_at_ms: 1,
+ updated_at_ms: 1,
+ };
+ *TEST_EXPECTED_STUDIO_ROOT_ID.lock().unwrap() = Some(root_id.to_string());
+ *TEST_METADATA.lock().unwrap() = Some(metadata);
+}
+
+#[cfg(test)]
+pub(crate) fn test_owner_state(root_id: &str, token: &str, port: u16) -> BackendOwnerState {
+ let metadata = DesktopBackendMetadata {
+ schema_version: METADATA_SCHEMA_VERSION,
+ kind: OWNER_KIND_TAURI.to_string(),
+ token: token.to_string(),
+ token_sha256: token_sha256(token),
+ app_pid: std::process::id(),
+ backend_pid: 2,
+ generation: 3,
+ requested_port: port,
+ port: Some(port),
+ studio_root_id: root_id.to_string(),
+ started_at_ms: 1,
+ updated_at_ms: 1,
+ };
+ BackendOwnerState {
+ path: std::env::temp_dir().join(format!(
+ "unsloth-test-owner-state-{}-{}.json",
+ std::process::id(),
+ now_ms()
+ )),
+ metadata,
+ }
+}
+
+fn health_verifies_metadata(health: &HealthResponse, metadata: &DesktopBackendMetadata) -> bool {
+ let healthy = health.status.as_deref() == Some("healthy")
+ && health.service.as_deref() == Some("Unsloth UI Backend");
+ let Some(owner) = health.desktop_owner.as_ref() else {
+ return false;
+ };
+ healthy
+ && owner_matches_metadata(
+ metadata,
+ health.studio_root_id.as_deref(),
+ owner.kind.as_deref(),
+ owner.token_sha256.as_deref(),
+ )
+}
+
+fn lifecycle_control_block_reason(health: &HealthResponse) -> Option<String> {
+ if health.desktop_protocol_version != Some(crate::preflight::DESKTOP_PROTOCOL_VERSION) {
+ return Some("desktop_protocol_incompatible".to_string());
+ }
+ if health.supports_desktop_auth != Some(true) {
+ return Some("desktop_auth_unsupported".to_string());
+ }
+ if health.desktop_manageability_version.unwrap_or(0)
+ < crate::preflight::DESKTOP_MANAGEABILITY_VERSION
+ {
+ return Some("desktop_manageability_unsupported".to_string());
+ }
+ if health.supports_desktop_backend_ownership != Some(true) {
+ return Some("desktop_backend_ownership_unsupported".to_string());
+ }
+ None
+}
+
+fn ready_for_use_status(health: &HealthResponse) -> OwnedBackendReadiness {
+ match crate::preflight::backend_version_stale_reason(health.version.as_deref()) {
+ Some(reason) => OwnedBackendReadiness::Stale { reason },
+ None => OwnedBackendReadiness::Ready,
+ }
+}
+
+async fn fetch_health(port: u16) -> Result<Option<HealthResponse>, reqwest::Error> {
+ let client = reqwest::Client::builder()
+ .timeout(LOCAL_HTTP_TIMEOUT)
+ .build()?;
+ let response = client
+ .get(format!("http://127.0.0.1:{port}/api/health"))
+ .send()
+ .await?;
+ if !response.status().is_success() {
+ return Ok(None);
+ }
+ response.json::<HealthResponse>().await.map(Some)
+}
+
+fn fetch_health_blocking(port: u16) -> Result<Option<HealthResponse>, String> {
+ let response = http_request_blocking(port, "GET", "/api/health", &[], &[])?;
+ if !(200..300).contains(&response.status) {
+ return Ok(None);
+ }
+ serde_json::from_slice::<HealthResponse>(&response.body)
+ .map(Some)
+ .map_err(|e| e.to_string())
+}
+
+async fn desktop_login_route_compatible(port: u16) -> bool {
+ let client = match reqwest::Client::builder()
+ .timeout(LOCAL_HTTP_TIMEOUT)
+ .build()
+ {
+ Ok(client) => client,
+ Err(_) => return false,
+ };
+ match client
+ .post(format!("http://127.0.0.1:{port}/api/auth/desktop-login"))
+ .json(&DesktopLoginPayload {
+ secret: "desktop-owner-adoption-invalid-secret",
+ })
+ .send()
+ .await
+ {
+ Ok(response) => response.status() == reqwest::StatusCode::UNAUTHORIZED,
+ Err(_) => false,
+ }
+}
+
+async fn desktop_secret_login_compatible(port: u16) -> Result<(), String> {
+ let secret = read_desktop_secret()?.ok_or_else(|| "desktop_auth_secret_missing".to_string())?;
+ let client = reqwest::Client::builder()
+ .timeout(LOCAL_HTTP_TIMEOUT)
+ .build()
+ .map_err(|e| e.to_string())?;
+ let response = client
+ .post(format!("http://127.0.0.1:{port}/api/auth/desktop-login"))
+ .json(&DesktopLoginPayload { secret: &secret })
+ .send()
+ .await
+ .map_err(|_| "desktop_auth_secret_probe_failed".to_string())?;
+ if response.status().is_success() {
+ Ok(())
+ } else if response.status() == reqwest::StatusCode::UNAUTHORIZED {
+ Err("desktop_auth_secret_rejected".to_string())
+ } else {
+ Err(format!(
+ "desktop_auth_secret_probe_http_{}",
+ response.status()
+ ))
+ }
+}
+
+pub(crate) async fn probe_owned_backend_state(
+ owner: BackendOwnerState,
+ port: Option<u16>,
+ require_desktop_secret: bool,
+) -> OwnedBackendProbe {
+ let ports: Vec<u16> = match port {
+ Some(port) => vec![port],
+ None => desktop_candidate_ports().collect(),
+ };
+ let mut verified = Vec::new();
+ for port in ports {
+ let health = match fetch_health(port).await {
+ Ok(Some(health)) => health,
+ Ok(None) => continue,
+ Err(error) => {
+ warn!(
+ "Desktop-owned backend probe skipped port {} after health error: {}",
+ port, error
+ );
+ continue;
+ }
+ };
+ if !health_verifies_metadata(&health, &owner.metadata) {
+ continue;
+ }
+ if let Some(reason) = lifecycle_control_block_reason(&health) {
+ return OwnedBackendProbe::Unmanageable { port, reason };
+ }
+ if !desktop_login_route_compatible(port).await {
+ return OwnedBackendProbe::Unmanageable {
+ port,
+ reason: "desktop_login_probe_failed".to_string(),
+ };
+ }
+ if require_desktop_secret {
+ if let Err(reason) = desktop_secret_login_compatible(port).await {
+ return OwnedBackendProbe::Unmanageable { port, reason };
+ }
+ }
+ verified.push((port, ready_for_use_status(&health)));
+ }
+
+ if verified.len() != 1 {
+ return OwnedBackendProbe::NotVerified {
+ reason: if verified.is_empty() {
+ "owned_backend_not_found".to_string()
+ } else {
+ "owned_backend_ambiguous".to_string()
+ },
+ };
+ }
+
+ let (port, readiness) = verified.remove(0);
+ OwnedBackendProbe::Verified(VerifiedOwnedBackend {
+ backend_pid: owner.backend_pid(),
+ generation: owner.generation(),
+ owner,
+ port,
+ readiness,
+ })
+}
+
+#[allow(dead_code)]
+pub(crate) async fn probe_verified_owned_backend() -> Result<OwnedBackendProbe, String> {
+ let Some(path) = metadata_path() else {
+ return Ok(OwnedBackendProbe::NoMetadata);
+ };
+ probe_verified_owned_backend_at_path(&path).await
+}
+
+async fn probe_verified_owned_backend_at_path(path: &Path) -> Result<OwnedBackendProbe, String> {
+ let expected = read_expected_studio_root_id();
+ probe_verified_owned_backend_at_path_with_expected(path, expected.as_deref()).await
+}
+
+async fn probe_verified_owned_backend_at_path_with_expected(
+ path: &Path,
+ expected_studio_root_id: Option<&str>,
+) -> Result<OwnedBackendProbe, String> {
+ let Some(metadata) = read_metadata(path).map_err(|e| format!("read owner metadata: {e}"))?
+ else {
+ return Ok(OwnedBackendProbe::NoMetadata);
+ };
+
+ if !metadata_is_well_formed(&metadata) {
+ remove_metadata_file(path);
+ return Ok(OwnedBackendProbe::RemovedMalformed);
+ }
+
+ match previous_app_pid_status(metadata.app_pid) {
+ PreviousAppPidStatus::AliveOrCurrent => {
+ return Ok(OwnedBackendProbe::NotVerified {
+ reason: "previous_desktop_app_still_running".to_string(),
+ });
+ }
+ PreviousAppPidStatus::Uncertain => {
+ return Ok(OwnedBackendProbe::NotVerified {
+ reason: "previous_desktop_app_liveness_uncertain".to_string(),
+ });
+ }
+ PreviousAppPidStatus::Dead => {}
+ }
+
+ if expected_studio_root_id != Some(metadata.studio_root_id.as_str()) {
+ return Ok(OwnedBackendProbe::NotVerified {
+ reason: "studio_root_id_mismatch".to_string(),
+ });
+ }
+
+ let owner = BackendOwnerState::from_metadata(path.to_path_buf(), metadata);
+ let port = owner.port();
+ Ok(probe_owned_backend_state(owner, port, true).await)
+}
+
+fn previous_app_pid_status(pid: u32) -> PreviousAppPidStatus {
+ if pid == 0 || pid == std::process::id() {
+ return PreviousAppPidStatus::AliveOrCurrent;
+ }
+ process_liveness(pid)
+}
+
+#[cfg(unix)]
+fn process_liveness(pid: u32) -> PreviousAppPidStatus {
+ if pid > i32::MAX as u32 {
+ return PreviousAppPidStatus::Uncertain;
+ }
+ let rc = unsafe { libc::kill(pid as i32, 0) };
+ if rc == 0 {
+ return PreviousAppPidStatus::AliveOrCurrent;
+ }
+ match std::io::Error::last_os_error().raw_os_error() {
+ Some(libc::ESRCH) => PreviousAppPidStatus::Dead,
+ Some(libc::EPERM) => PreviousAppPidStatus::AliveOrCurrent,
+ _ => PreviousAppPidStatus::Uncertain,
+ }
+}
+
+#[cfg(windows)]
+fn process_liveness(pid: u32) -> PreviousAppPidStatus {
+ use windows_sys::Win32::Foundation::{CloseHandle, GetLastError, ERROR_INVALID_PARAMETER};
+ use windows_sys::Win32::System::Threading::{
+ OpenProcess, WaitForSingleObject, SYNCHRONIZE, WAIT_OBJECT_0, WAIT_TIMEOUT,
+ };
+
+ unsafe {
+ let handle = OpenProcess(SYNCHRONIZE, 0, pid);
+ if handle == 0 {
+ return if GetLastError() == ERROR_INVALID_PARAMETER {
+ PreviousAppPidStatus::Dead
+ } else {
+ PreviousAppPidStatus::Uncertain
+ };
+ }
+ let wait = WaitForSingleObject(handle, 0);
+ let _ = CloseHandle(handle);
+ match wait {
+ WAIT_TIMEOUT => PreviousAppPidStatus::AliveOrCurrent,
+ WAIT_OBJECT_0 => PreviousAppPidStatus::Dead,
+ _ => PreviousAppPidStatus::Uncertain,
+ }
+ }
+}
+
+#[cfg(not(any(unix, windows)))]
+fn process_liveness(_pid: u32) -> PreviousAppPidStatus {
+ PreviousAppPidStatus::Uncertain
+}
+
+pub(crate) fn exact_port_http_shutdown_blocking(port: u16) -> Result<(), String> {
+ let secret =
+ read_desktop_secret()?.ok_or_else(|| "desktop auth secret not found".to_string())?;
+ let login_body =
+ serde_json::to_vec(&DesktopLoginPayload { secret: &secret }).map_err(|e| e.to_string())?;
+ let login = http_request_blocking(
+ port,
+ "POST",
+ "/api/auth/desktop-login",
+ &["Content-Type: application/json".to_string()],
+ &login_body,
+ )?;
+ if login.status == 401 {
+ return Err("desktop auth secret rejected".to_string());
+ }
+ if !(200..300).contains(&login.status) {
+ return Err(format!("desktop login returned HTTP {}", login.status));
+ }
+ let tokens = serde_json::from_slice::<TokenResponse>(&login.body)
+ .map_err(|e| format!("desktop login response invalid: {e}"))?;
+ let shutdown = http_request_blocking(
+ port,
+ "POST",
+ "/api/shutdown",
+ &[format!("Authorization: Bearer {}", tokens.access_token)],
+ &[],
+ )?;
+ if (200..300).contains(&shutdown.status) {
+ Ok(())
+ } else {
+ Err(format!("shutdown returned HTTP {}", shutdown.status))
+ }
+}
+
+pub(crate) fn port_is_listening_blocking(port: u16, timeout: Duration) -> bool {
+ let addr = SocketAddr::from(([127, 0, 0, 1], port));
+ TcpStream::connect_timeout(&addr, timeout).is_ok()
+}
+
+fn read_desktop_secret() -> Result<Option<String>, String> {
+ let Some(home) = dirs::home_dir() else {
+ return Ok(None);
+ };
+ match std::fs::read_to_string(auth_secret_path_for_home(&home)) {
+ Ok(secret) => Ok(Some(secret.trim().to_string())),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
+ Err(error) => Err(error.to_string()),
+ }
+}
+
+fn http_request_blocking(
+ port: u16,
+ method: &str,
+ path: &str,
+ extra_headers: &[String],
+ body: &[u8],
+) -> Result<SimpleHttpResponse, String> {
+ let addr = SocketAddr::from(([127, 0, 0, 1], port));
+ let mut stream = TcpStream::connect_timeout(&addr, LOCAL_HTTP_TIMEOUT)
+ .map_err(|e| format!("connect to 127.0.0.1:{port}: {e}"))?;
+ stream
+ .set_read_timeout(Some(LOCAL_HTTP_TIMEOUT))
+ .map_err(|e| e.to_string())?;
+ stream
+ .set_write_timeout(Some(LOCAL_HTTP_TIMEOUT))
+ .map_err(|e| e.to_string())?;
+
+ let mut request = format!(
+ "{method} {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Length: {}\r\nConnection: close\r\n",
+ body.len()
+ )
+ .into_bytes();
+ for header in extra_headers {
+ request.extend_from_slice(header.as_bytes());
+ request.extend_from_slice(b"\r\n");
+ }
+ request.extend_from_slice(b"\r\n");
+ request.extend_from_slice(body);
+ stream.write_all(&request).map_err(|e| e.to_string())?;
+ stream.flush().map_err(|e| e.to_string())?;
+
+ let mut raw = Vec::new();
+ stream.read_to_end(&mut raw).map_err(|e| e.to_string())?;
+ parse_http_response(&raw)
+}
+
+fn parse_http_response(raw: &[u8]) -> Result<SimpleHttpResponse, String> {
+ let Some(header_end) = raw.windows(4).position(|window| window == b"\r\n\r\n") else {
+ return Err("HTTP response missing header terminator".to_string());
+ };
+ let headers = std::str::from_utf8(&raw[..header_end]).map_err(|e| e.to_string())?;
+ let status = headers
+ .lines()
+ .next()
+ .and_then(|line| line.split_whitespace().nth(1))
+ .and_then(|value| value.parse::<u16>().ok())
+ .ok_or_else(|| "HTTP response missing status".to_string())?;
+ Ok(SimpleHttpResponse {
+ status,
+ body: raw[header_end + 4..].to_vec(),
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const ROOT_ID: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
+ const TOKEN: &str = "desktop-owner-token";
+
+ fn metadata(app_pid: u32, port: Option<u16>) -> DesktopBackendMetadata {
+ DesktopBackendMetadata {
+ schema_version: METADATA_SCHEMA_VERSION,
+ kind: OWNER_KIND_TAURI.to_string(),
+ token: TOKEN.to_string(),
+ token_sha256: token_sha256(TOKEN),
+ app_pid,
+ backend_pid: 2,
+ generation: 3,
+ requested_port: 8888,
+ port,
+ studio_root_id: ROOT_ID.to_string(),
+ started_at_ms: 1,
+ updated_at_ms: 1,
+ }
+ }
+
+ fn dead_child_pid() -> u32 {
+ #[cfg(windows)]
+ let mut child = std::process::Command::new("cmd")
+ .args(["/C", "exit", "0"])
+ .spawn()
+ .unwrap();
+ #[cfg(not(windows))]
+ let mut child = std::process::Command::new("sh")
+ .args(["-c", "exit 0"])
+ .spawn()
+ .unwrap();
+ let pid = child.id();
+ let _ = child.wait();
+ pid
+ }
+
+ fn temp_metadata_path(test_name: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "unsloth-owner-{test_name}-{}-{}",
+ std::process::id(),
+ now_ms()
+ ));
+ std::fs::create_dir_all(&dir).unwrap();
+ dir.join("desktop_backend.json")
+ }
+
+ fn closed_port() -> u16 {
+ let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
+ let port = listener.local_addr().unwrap().port();
+ drop(listener);
+ port
+ }
+
+ #[test]
+ fn parse_studio_root_id_requires_lowercase_64_hex_chars() {
+ assert_eq!(parse_studio_root_id(ROOT_ID), Some(ROOT_ID.to_string()));
+ assert_eq!(
+ parse_studio_root_id(&format!("\n{ROOT_ID}\n")),
+ Some(ROOT_ID.to_string())
+ );
+ assert_eq!(parse_studio_root_id(""), None);
+ assert_eq!(
+ parse_studio_root_id(
+ "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ ),
+ None
+ );
+ assert_eq!(parse_studio_root_id("not-a-root-id"), None);
+ }
+
+ #[test]
+ fn metadata_well_formed_requires_matching_token_hash() {
+ assert_eq!(
+ token_sha256(TOKEN),
+ "943501cb7d1feb2aa8cde1bf09b80092c25b95dbafaca9ccc12d6785b229a6fd"
+ );
+ let mut metadata = metadata(1, Some(8888));
+ assert!(metadata_is_well_formed(&metadata));
+ metadata.token_sha256 = token_sha256("different");
+ assert!(!metadata_is_well_formed(&metadata));
+ }
+
+ #[test]
+ fn health_verification_requires_root_kind_and_token_sha() {
+ let metadata = metadata(1, Some(8888));
+ let health = HealthResponse {
+ status: Some("healthy".to_string()),
+ service: Some("Unsloth UI Backend".to_string()),
+ version: Some("2026.5.2".to_string()),
+ desktop_protocol_version: Some(1),
+ desktop_manageability_version: Some(1),
+ supports_desktop_auth: Some(true),
+ supports_desktop_backend_ownership: Some(true),
+ studio_root_id: Some(ROOT_ID.to_string()),
+ desktop_owner: Some(HealthDesktopOwner {
+ kind: Some(OWNER_KIND_TAURI.to_string()),
+ token_sha256: Some(token_sha256(TOKEN)),
+ }),
+ };
+ assert!(health_verifies_metadata(&health, &metadata));
+
+ let mut wrong_root = health;
+ wrong_root.studio_root_id =
+ Some("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb".to_string());
+ assert!(!health_verifies_metadata(&wrong_root, &metadata));
+ }
+
+ #[tokio::test]
+ async fn unreachable_recorded_port_is_not_verified_not_error() {
+ let port = closed_port();
+ let path = temp_metadata_path("closed-recorded-port");
+ let metadata = metadata(dead_child_pid(), Some(port));
+ write_metadata(&path, &metadata).unwrap();
+
+ let probe = probe_verified_owned_backend_at_path_with_expected(&path, Some(ROOT_ID))
+ .await
+ .unwrap();
+
+ assert!(matches!(
+ probe,
+ OwnedBackendProbe::NotVerified { reason } if reason == "owned_backend_not_found"
+ ));
+ assert!(path.exists());
+ let _ = std::fs::remove_dir_all(path.parent().unwrap());
+ }
+
+ #[test]
+ fn current_app_pid_is_not_adoptable() {
+ assert_eq!(
+ previous_app_pid_status(std::process::id()),
+ PreviousAppPidStatus::AliveOrCurrent
+ );
+ }
+}
diff --git a/studio/src-tauri/src/desktop_update_policy.rs b/studio/src-tauri/src/desktop_update_policy.rs
new file mode 100644
index 00000000000..c83f847eda0
--- /dev/null
+++ b/studio/src-tauri/src/desktop_update_policy.rs
@@ -0,0 +1,420 @@
+use serde::Serialize;
+use std::collections::HashMap;
+
+const DESKTOP_RELEASE_PAGE_BASE_URL: &str = "https://github.com/unslothai/unsloth/releases/tag/";
+const DESKTOP_RELEASE_TAG_PREFIX: &str = "desktop-v";
+const DESKTOP_UPDATER_CHANNEL_URL: &str =
+ "https://github.com/unslothai/unsloth/releases/download/desktop-latest/latest.json";
+
+#[allow(dead_code)]
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub(crate) enum DesktopUpdateMode {
+ InApp,
+ ManualLinuxPackage,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct DesktopUpdatePolicy {
+ mode: DesktopUpdateMode,
+ release_page_base_url: &'static str,
+ release_tag_prefix: &'static str,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct ManualUpdateInfo {
+ version: String,
+ current_version: String,
+ body: Option<String>,
+ date: Option<String>,
+}
+
+#[derive(Debug, serde::Deserialize)]
+struct ChannelMetadata {
+ version: String,
+ body: Option<String>,
+ date: Option<String>,
+ platforms: HashMap<String, ChannelPlatform>,
+}
+
+#[derive(Debug, serde::Deserialize)]
+struct ChannelPlatform {
+ url: String,
+ signature: String,
+}
+
+#[tauri::command]
+pub(crate) fn desktop_update_policy() -> DesktopUpdatePolicy {
+ DesktopUpdatePolicy {
+ mode: desktop_update_mode(),
+ release_page_base_url: DESKTOP_RELEASE_PAGE_BASE_URL,
+ release_tag_prefix: DESKTOP_RELEASE_TAG_PREFIX,
+ }
+}
+
+#[tauri::command]
+pub(crate) async fn check_desktop_manual_update() -> Result<Option<ManualUpdateInfo>, String> {
+ if !matches!(desktop_update_mode(), DesktopUpdateMode::ManualLinuxPackage) {
+ return Ok(None);
+ }
+
+ let client = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(10))
+ .build()
+ .map_err(|e| e.to_string())?;
+ let response = match client.get(DESKTOP_UPDATER_CHANNEL_URL).send().await {
+ Ok(response) => response,
+ Err(error) => {
+ log::warn!("Manual update metadata check failed: {}", error);
+ return Ok(None);
+ }
+ };
+ if !response.status().is_success() {
+ log::warn!(
+ "Manual update metadata check returned HTTP {}",
+ response.status()
+ );
+ return Ok(None);
+ }
+
+ let metadata = response
+ .json::<ChannelMetadata>()
+ .await
+ .map_err(|e| format!("Invalid desktop updater metadata: {e}"))?;
+ let current_version = env!("CARGO_PKG_VERSION");
+ let Some(latest_version) = normalize_version(&metadata.version) else {
+ return Err(format!(
+ "Desktop updater metadata has invalid version: {}",
+ metadata.version
+ ));
+ };
+ validate_channel_metadata(&metadata, &latest_version)?;
+
+ if compare_versions(&latest_version, current_version) <= 0 {
+ return Ok(None);
+ }
+
+ Ok(Some(ManualUpdateInfo {
+ version: latest_version,
+ current_version: current_version.to_string(),
+ body: metadata.body,
+ date: metadata.date,
+ }))
+}
+
+fn validate_channel_metadata(
+ metadata: &ChannelMetadata,
+ normalized_version: &str,
+) -> Result<(), String> {
+ if metadata.platforms.is_empty() {
+ return Err("Desktop updater metadata has no platforms".to_string());
+ }
+
+ let expected_prefix = format!(
+ "https://github.com/unslothai/unsloth/releases/download/desktop-v{normalized_version}/"
+ );
+ for (platform, entry) in &metadata.platforms {
+ if entry.url.trim().is_empty() {
+ return Err(format!(
+ "Desktop updater metadata missing URL for {platform}"
+ ));
+ }
+ if entry.signature.trim().is_empty() {
+ return Err(format!(
+ "Desktop updater metadata missing signature for {platform}"
+ ));
+ }
+ if entry.url.contains("/releases/latest/")
+ || entry.url.contains("/releases/download/desktop-latest/")
+ || !entry.url.starts_with(&expected_prefix)
+ {
+ return Err(format!(
+ "Desktop updater metadata has untrusted URL for {platform}: {}",
+ entry.url
+ ));
+ }
+ }
+ Ok(())
+}
+
+fn desktop_update_mode() -> DesktopUpdateMode {
+ #[cfg(target_os = "linux")]
+ {
+ if std::env::var_os("APPIMAGE").is_some() {
+ DesktopUpdateMode::InApp
+ } else {
+ DesktopUpdateMode::ManualLinuxPackage
+ }
+ }
+
+ #[cfg(not(target_os = "linux"))]
+ {
+ DesktopUpdateMode::InApp
+ }
+}
+
+fn normalize_version(version: &str) -> Option<String> {
+ let trimmed = version.trim();
+ let without_v = trimmed.strip_prefix('v').unwrap_or(trimmed);
+ if parse_version(without_v).is_some() {
+ Some(without_v.to_string())
+ } else {
+ None
+ }
+}
+
+fn compare_versions(left: &str, right: &str) -> i8 {
+ let Some(left) = parse_version(left) else {
+ return 0;
+ };
+ let Some(right) = parse_version(right) else {
+ return 0;
+ };
+ match compare_parsed_versions(&left, &right) {
+ std::cmp::Ordering::Greater => 1,
+ std::cmp::Ordering::Equal => 0,
+ std::cmp::Ordering::Less => -1,
+ }
+}
+
+#[derive(Debug, Eq, PartialEq)]
+struct ParsedVersion {
+ release: [u64; 3],
+ suffix: VersionSuffix,
+}
+
+#[derive(Debug, Eq, PartialEq)]
+enum VersionSuffix {
+ Dev(u64),
+ Alpha(u64),
+ Beta(u64),
+ Rc(u64),
+ PreRelease(String),
+ Stable,
+ Build,
+ Post(u64),
+}
+
+fn parse_version(version: &str) -> Option<ParsedVersion> {
+ let mut parts = version.splitn(3, '.');
+ let major = parts.next()?.parse().ok()?;
+ let minor = parts.next()?.parse().ok()?;
+ let patch_and_suffix = parts.next()?;
+ let patch_len = patch_and_suffix
+ .find(|c: char| !c.is_ascii_digit())
+ .unwrap_or(patch_and_suffix.len());
+ if patch_len == 0 {
+ return None;
+ }
+ let suffix = parse_version_suffix(&patch_and_suffix[patch_len..])?;
+ Some(ParsedVersion {
+ release: [major, minor, patch_and_suffix[..patch_len].parse().ok()?],
+ suffix,
+ })
+}
+
+fn parse_version_suffix(suffix: &str) -> Option<VersionSuffix> {
+ if suffix.is_empty() {
+ return Some(VersionSuffix::Stable);
+ }
+
+ if let Some(value) = suffix.strip_prefix('+') {
+ if suffix_part_valid(value) {
+ return Some(VersionSuffix::Build);
+ }
+ return None;
+ }
+
+ if let Some(value) = suffix.strip_prefix('-') {
+ if suffix_part_valid(value) {
+ return Some(VersionSuffix::PreRelease(value.to_ascii_lowercase()));
+ }
+ return None;
+ }
+
+ if let Some(number) = parse_numbered_suffix(suffix, &[".post", "post"]) {
+ return number.map(VersionSuffix::Post);
+ }
+ if let Some(number) = parse_numbered_suffix(suffix, &[".dev", "dev"]) {
+ return number.map(VersionSuffix::Dev);
+ }
+ if let Some(number) = parse_numbered_suffix(suffix, &[".rc", "rc"]) {
+ return number.map(VersionSuffix::Rc);
+ }
+ if let Some(number) = parse_numbered_suffix(suffix, &["a"]) {
+ return number.map(VersionSuffix::Alpha);
+ }
+ if let Some(number) = parse_numbered_suffix(suffix, &["b"]) {
+ return number.map(VersionSuffix::Beta);
+ }
+
+ None
+}
+
+fn parse_numbered_suffix(suffix: &str, prefixes: &[&str]) -> Option<Option<u64>> {
+ for prefix in prefixes {
+ let Some(number) = suffix.strip_prefix(prefix) else {
+ continue;
+ };
+ if number.is_empty() {
+ return Some(Some(0));
+ }
+ return Some(number.parse().ok());
+ }
+ None
+}
+
+fn suffix_part_valid(value: &str) -> bool {
+ !value.is_empty()
+ && value.split('.').all(|part| {
+ !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
+ })
+}
+
+fn compare_parsed_versions(left: &ParsedVersion, right: &ParsedVersion) -> std::cmp::Ordering {
+ match left.release.cmp(&right.release) {
+ std::cmp::Ordering::Equal => compare_suffixes(&left.suffix, &right.suffix),
+ ordering => ordering,
+ }
+}
+
+fn compare_suffixes(left: &VersionSuffix, right: &VersionSuffix) -> std::cmp::Ordering {
+ let left_precedence = suffix_precedence(left);
+ let right_precedence = suffix_precedence(right);
+ if left_precedence != right_precedence {
+ return left_precedence.cmp(&right_precedence);
+ }
+
+ match (left, right) {
+ (VersionSuffix::Dev(left), VersionSuffix::Dev(right))
+ | (VersionSuffix::Alpha(left), VersionSuffix::Alpha(right))
+ | (VersionSuffix::Beta(left), VersionSuffix::Beta(right))
+ | (VersionSuffix::Rc(left), VersionSuffix::Rc(right))
+ | (VersionSuffix::Post(left), VersionSuffix::Post(right)) => left.cmp(right),
+ (VersionSuffix::Rc(left), VersionSuffix::PreRelease(right)) => {
+ compare_numbered_prefix_to_prerelease("rc", *left, right)
+ .unwrap_or(std::cmp::Ordering::Equal)
+ }
+ (VersionSuffix::PreRelease(left), VersionSuffix::Rc(right)) => {
+ compare_numbered_prefix_to_prerelease("rc", *right, left)
+ .map(std::cmp::Ordering::reverse)
+ .unwrap_or(std::cmp::Ordering::Equal)
+ }
+ (VersionSuffix::PreRelease(left), VersionSuffix::PreRelease(right)) => {
+ compare_prerelease(left, right)
+ }
+ _ => std::cmp::Ordering::Equal,
+ }
+}
+
+fn suffix_precedence(suffix: &VersionSuffix) -> u8 {
+ match suffix {
+ VersionSuffix::Dev(_) => 0,
+ VersionSuffix::Alpha(_) => 1,
+ VersionSuffix::Beta(_) => 2,
+ VersionSuffix::Rc(_) | VersionSuffix::PreRelease(_) => 3,
+ VersionSuffix::Stable | VersionSuffix::Build => 4,
+ VersionSuffix::Post(_) => 5,
+ }
+}
+
+fn compare_prerelease(left: &str, right: &str) -> std::cmp::Ordering {
+ for (left_part, right_part) in left.split('.').zip(right.split('.')) {
+ let ordering = compare_prerelease_part(left_part, right_part);
+ if !ordering.is_eq() {
+ return ordering;
+ }
+ }
+ left.split('.').count().cmp(&right.split('.').count())
+}
+
+fn compare_prerelease_part(left: &str, right: &str) -> std::cmp::Ordering {
+ let left_number = left.parse::<u64>();
+ let right_number = right.parse::<u64>();
+ match (left_number, right_number) {
+ (Ok(left), Ok(right)) => return left.cmp(&right),
+ (Ok(_), Err(_)) => return std::cmp::Ordering::Less,
+ (Err(_), Ok(_)) => return std::cmp::Ordering::Greater,
+ (Err(_), Err(_)) => {}
+ }
+
+ match (split_alpha_numeric(left), split_alpha_numeric(right)) {
+ (Some((left_prefix, left_number)), Some((right_prefix, right_number)))
+ if left_prefix == right_prefix =>
+ {
+ return left_number.cmp(&right_number);
+ }
+ _ => {}
+ }
+
+ left.cmp(right)
+}
+
+fn compare_numbered_prefix_to_prerelease(
+ prefix: &str,
+ number: u64,
+ prerelease: &str,
+) -> Option<std::cmp::Ordering> {
+ let (other_prefix, other_number) = split_alpha_numeric(prerelease)?;
+ (other_prefix == prefix).then(|| number.cmp(&other_number))
+}
+
+fn split_alpha_numeric(value: &str) -> Option<(&str, u64)> {
+ let digit_start = value.find(|c: char| c.is_ascii_digit())?;
+ if digit_start == 0 || value[digit_start..].bytes().any(|b| !b.is_ascii_digit()) {
+ return None;
+ }
+ Some((&value[..digit_start], value[digit_start..].parse().ok()?))
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn compare_versions_orders_supported_suffixes() {
+ assert!(super::compare_versions("2026.5.3", "2026.5.3-rc1") > 0);
+ assert!(super::compare_versions("2026.5.3", "2026.5.3rc1") > 0);
+ assert!(super::compare_versions("2026.5.3", "2026.5.3.dev1") > 0);
+ assert!(super::compare_versions("2026.5.3.post1", "2026.5.3") > 0);
+ assert!(super::compare_versions("2026.5.3.post1", "2026.5.3+build1") > 0);
+ assert!(super::compare_versions("2026.5.3+build1", "2026.5.3-beta.1") > 0);
+ assert!(super::compare_versions("2026.5.3-rc10", "2026.5.3-rc2") > 0);
+ assert!(super::compare_versions("2026.5.3-rc10", "2026.5.3rc2") > 0);
+ assert!(super::compare_versions("2026.5.3rc2", "2026.5.3-rc10") < 0);
+ assert!(super::compare_versions("2026.5.3-beta10", "2026.5.3-beta2") > 0);
+ assert!(super::compare_versions("2026.5.3rc2", "2026.5.3rc1") > 0);
+ assert!(super::compare_versions("2026.5.3b1", "2026.5.3a1") > 0);
+ }
+
+ #[test]
+ fn normalize_version_accepts_backend_suffix_formats() {
+ for version in [
+ "v2026.5.4.post1",
+ "2026.5.4post1",
+ "2026.5.4.dev1",
+ "2026.5.4dev1",
+ "2026.5.4.rc1",
+ "2026.5.4rc1",
+ "2026.5.4a1",
+ "2026.5.4b1",
+ "2026.5.4-rc1",
+ "2026.5.4+build1",
+ ] {
+ assert!(super::normalize_version(version).is_some(), "{version}");
+ }
+ }
+
+ #[test]
+ fn normalize_version_rejects_invalid_suffixes() {
+ for version in [
+ "2026.5.4garbage",
+ "2026.5.4-",
+ "2026.5.4+",
+ "2026.5.4-rc..1",
+ "2026.5.4.devx",
+ ] {
+ assert!(super::normalize_version(version).is_none(), "{version}");
+ }
+ }
+}
diff --git a/studio/src-tauri/src/diagnostics/mod.rs b/studio/src-tauri/src/diagnostics/mod.rs
index 5ab940af38a..998efc893ea 100644
--- a/studio/src-tauri/src/diagnostics/mod.rs
+++ b/studio/src-tauri/src/diagnostics/mod.rs
@@ -13,13 +13,13 @@ 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,
+ begin_adopted_backend_session, 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;
@@ -151,8 +151,10 @@ async fn collect_backend_health(port: u16) -> report::BackendHealthSection {
"device_type",
"chat_only",
"desktop_protocol_version",
+ "desktop_manageability_version",
"supports_api_only",
"supports_desktop_auth",
+ "supports_desktop_backend_ownership",
] {
if let Some(value) = json.get(key) {
section
diff --git a/studio/src-tauri/src/diagnostics/report.rs b/studio/src-tauri/src/diagnostics/report.rs
index 6301e7face3..bd20fe294e3 100644
--- a/studio/src-tauri/src/diagnostics/report.rs
+++ b/studio/src-tauri/src/diagnostics/report.rs
@@ -341,8 +341,10 @@ fn append_device_signals_section(
| "device_type"
| "chat_only"
| "desktop_protocol_version"
+ | "desktop_manageability_version"
| "supports_api_only"
| "supports_desktop_auth"
+ | "supports_desktop_backend_ownership"
) {
out.push_str(&format!(" {key}={value}\n"));
}
diff --git a/studio/src-tauri/src/diagnostics/state.rs b/studio/src-tauri/src/diagnostics/state.rs
index ccbd5fbb8e6..3ed8b66cafd 100644
--- a/studio/src-tauri/src/diagnostics/state.rs
+++ b/studio/src-tauri/src/diagnostics/state.rs
@@ -435,6 +435,27 @@ pub fn begin_backend_session(
}
}
+pub fn begin_adopted_backend_session(diagnostics: &DiagnosticsState, port: u16, generation: u64) {
+ let session_id = new_id("adopted-backend");
+ let started_at_ms = now_ms();
+ with_snapshot(diagnostics, |snapshot| {
+ snapshot.backend = Some(BackendSummary {
+ session_id: Some(session_id.clone()),
+ backend_kind: "adopted".to_string(),
+ log_segments: Vec::new(),
+ requested_port: Some(port),
+ reported_port: Some(port),
+ 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,
+ });
+ });
+}
+
pub fn record_backend_start_failure(
diagnostics: &DiagnosticsState,
requested_port: Option<u16>,
@@ -769,6 +790,9 @@ fn disposition_label(disposition: &DesktopPreflightDisposition) -> &'static str
DesktopPreflightDisposition::NotInstalled => "not_installed",
DesktopPreflightDisposition::ManagedReady => "managed_ready",
DesktopPreflightDisposition::ManagedStale => "managed_stale",
+ DesktopPreflightDisposition::OwnedReady => "owned_ready",
+ DesktopPreflightDisposition::OwnedStale => "owned_stale",
DesktopPreflightDisposition::AttachedReady => "attached_ready",
+ DesktopPreflightDisposition::ExternalConflict => "external_conflict",
}
}
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index 7ad40b8be24..d07ff5e9d6f 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -2,6 +2,8 @@
mod commands;
mod desktop_auth;
+mod desktop_backend_owner;
+mod desktop_update_policy;
mod diagnostics;
mod install;
mod native_backend_lease;
@@ -192,6 +194,8 @@ fn main() {
commands::cancel_pending_elevation,
commands::install_system_packages,
desktop_auth::desktop_auth,
+ desktop_update_policy::check_desktop_manual_update,
+ desktop_update_policy::desktop_update_policy,
diagnostics::collect_support_diagnostics,
native_intents::drain_native_intents,
native_intents::register_native_model_path,
diff --git a/studio/src-tauri/src/preflight.rs b/studio/src-tauri/src/preflight.rs
index c0bbb07b360..9138f30a585 100644
--- a/studio/src-tauri/src/preflight.rs
+++ b/studio/src-tauri/src/preflight.rs
@@ -1,69 +1,55 @@
-use serde::{Deserialize, Serialize};
+mod backend;
+mod managed;
+mod types;
+mod version;
+
+use crate::desktop_backend_owner::{
+ OwnedBackendProbe, OwnedBackendReadiness, VerifiedOwnedBackend,
+};
+use backend::probe_existing_backends;
+use log::warn;
+pub use managed::managed_install_ready;
+use managed::probe_managed_install;
use std::path::PathBuf;
-use std::process::Stdio;
-use std::time::Duration;
-use tokio::io::AsyncReadExt;
-use tokio::process::Command;
-
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum DesktopPreflightDisposition {
- NotInstalled,
- ManagedReady,
- ManagedStale,
- AttachedReady,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-pub struct DesktopPreflightResult {
- pub disposition: DesktopPreflightDisposition,
- pub reason: Option<String>,
- pub port: Option<u16>,
- pub can_auto_repair: bool,
- pub managed_bin: Option<PathBuf>,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq)]
-enum ManagedProbe {
- Missing,
- Ready { bin: PathBuf },
- Stale { bin: PathBuf, reason: String },
-}
+use types::{BackendProbe, ManagedProbe};
+pub use types::{DesktopPreflightDisposition, DesktopPreflightResult, ExternalBackendConflict};
+pub(crate) use version::{
+ backend_version_stale_reason, DESKTOP_MANAGEABILITY_VERSION, DESKTOP_PROTOCOL_VERSION,
+};
-#[derive(Debug, Clone, PartialEq, Eq)]
-enum BackendProbe {
- Missing,
- Ready { port: u16 },
- Old { port: u16, reason: String },
-}
-
-#[derive(Debug, Deserialize)]
-struct DesktopCapability {
- desktop_protocol_version: Option<u16>,
- supports_api_only: Option<bool>,
- supports_provision_desktop_auth: Option<bool>,
- desktop_auth_stale_reason: Option<String>,
-}
-
-#[derive(Debug)]
-struct BackendHealth {
- desktop_protocol_version: Option<u16>,
- supports_desktop_auth: Option<bool>,
- stale_reason: Option<String>,
-}
+#[cfg(test)]
+use backend::{backend_desktop_auth_status, backend_health};
+#[cfg(test)]
+use managed::probe_managed_bin;
+#[cfg(test)]
+use version::{backend_version_compatible, MIN_DESKTOP_BACKEND_VERSION};
fn release_auto_repair() -> bool {
!cfg!(debug_assertions)
}
+fn managed_bin_for_result(managed: &ManagedProbe) -> Option<PathBuf> {
+ match managed {
+ ManagedProbe::Ready { bin } | ManagedProbe::Stale { bin, .. } => Some(bin.clone()),
+ ManagedProbe::Missing => None,
+ }
+}
+
fn choose_preflight(managed: ManagedProbe, backend: BackendProbe) -> DesktopPreflightResult {
match (backend, managed) {
- (BackendProbe::Ready { port }, ManagedProbe::Ready { bin }) => DesktopPreflightResult {
+ (BackendProbe::ExternalConflict { port, reason }, managed) => DesktopPreflightResult {
+ disposition: DesktopPreflightDisposition::ExternalConflict,
+ reason: Some(reason),
+ port: Some(port),
+ can_auto_repair: false,
+ managed_bin: managed_bin_for_result(&managed),
+ },
+ (BackendProbe::Ready { port }, managed) => DesktopPreflightResult {
disposition: DesktopPreflightDisposition::AttachedReady,
reason: None,
port: Some(port),
can_auto_repair: false,
- managed_bin: Some(bin),
+ managed_bin: managed_bin_for_result(&managed),
},
(_, managed) => match managed {
ManagedProbe::Ready { bin } => DesktopPreflightResult {
@@ -91,288 +77,213 @@ fn choose_preflight(managed: ManagedProbe, backend: BackendProbe) -> DesktopPref
}
}
-async fn run_cli_probe(bin: &std::path::Path, args: &[&str]) -> bool {
- let mut cmd = Command::new(bin);
- cmd.args(args).stdout(Stdio::null()).stderr(Stdio::null());
-
- #[cfg(target_os = "linux")]
- if std::env::var_os("APPIMAGE").is_some() {
- cmd.env_remove("LD_LIBRARY_PATH");
- cmd.env_remove("PYTHONHOME");
- cmd.env_remove("PYTHONPATH");
- }
-
- // Tauri uses the legacy root regardless of UNSLOTH_STUDIO_HOME / STUDIO_HOME;
- // probe subprocesses must follow the same isolation as process.rs.
- cmd.env_remove("UNSLOTH_STUDIO_HOME");
- cmd.env_remove("STUDIO_HOME");
-
- #[cfg(windows)]
- {
- use std::os::windows::process::CommandExt;
- cmd.creation_flags(crate::process::CREATE_NO_WINDOW);
- }
-
- let Ok(mut child) = cmd.spawn() else {
- return false;
- };
-
- match tokio::time::timeout(Duration::from_secs(10), child.wait()).await {
- Ok(Ok(status)) => status.success(),
- _ => {
- let _ = child.kill().await;
- let _ = child.wait().await;
- false
- }
- }
+fn owned_unmanageable_reason(reason: &str) -> String {
+ format!("desktop_owned_backend_unmanageable:{reason}")
}
-async fn probe_cli_capability(bin: &std::path::Path) -> Option<DesktopCapability> {
- let mut cmd = Command::new(bin);
- cmd.args(["studio", "desktop-capabilities", "--json"])
- .stdout(Stdio::piped())
- .stderr(Stdio::null());
-
- #[cfg(target_os = "linux")]
- if std::env::var_os("APPIMAGE").is_some() {
- cmd.env_remove("LD_LIBRARY_PATH");
- cmd.env_remove("PYTHONHOME");
- cmd.env_remove("PYTHONPATH");
- }
-
- // Tauri uses the legacy root regardless of UNSLOTH_STUDIO_HOME / STUDIO_HOME;
- // probe subprocesses must follow the same isolation as process.rs.
- cmd.env_remove("UNSLOTH_STUDIO_HOME");
- cmd.env_remove("STUDIO_HOME");
-
- #[cfg(windows)]
- {
- use std::os::windows::process::CommandExt;
- cmd.creation_flags(crate::process::CREATE_NO_WINDOW);
- }
-
- let Ok(mut child) = cmd.spawn() else {
- return None;
- };
- let Some(mut stdout) = child.stdout.take() else {
- return None;
- };
-
- match tokio::time::timeout(Duration::from_secs(10), child.wait()).await {
- Ok(Ok(status)) if status.success() => {}
- Err(_) => {
- let _ = child.kill().await;
- let _ = child.wait().await;
- return None;
- }
- _ => return None,
- }
-
- let mut output = Vec::new();
- if stdout.read_to_end(&mut output).await.is_err() {
- return None;
+fn choose_owned_preflight(
+ managed: &ManagedProbe,
+ owned: &VerifiedOwnedBackend,
+) -> DesktopPreflightResult {
+ match &owned.readiness {
+ OwnedBackendReadiness::Ready => DesktopPreflightResult {
+ disposition: DesktopPreflightDisposition::OwnedReady,
+ reason: None,
+ port: Some(owned.port),
+ can_auto_repair: false,
+ managed_bin: managed_bin_for_result(managed),
+ },
+ OwnedBackendReadiness::Stale { reason } => DesktopPreflightResult {
+ disposition: DesktopPreflightDisposition::OwnedStale,
+ reason: Some(reason.clone()),
+ port: Some(owned.port),
+ can_auto_repair: release_auto_repair(),
+ managed_bin: managed_bin_for_result(managed),
+ },
}
-
- serde_json::from_slice::<DesktopCapability>(&output).ok()
-}
-
-fn desktop_capability_ready(capability: &DesktopCapability) -> bool {
- capability.desktop_protocol_version == Some(1)
- && capability.supports_api_only == Some(true)
- && capability.supports_provision_desktop_auth == Some(true)
-}
-
-fn desktop_capability_stale_reason(capability: &DesktopCapability) -> String {
- capability
- .desktop_auth_stale_reason
- .clone()
- .unwrap_or_else(|| "desktop_capability_incompatible".to_string())
}
-async fn probe_managed_bin(bin: PathBuf) -> ManagedProbe {
- if !run_cli_probe(&bin, &["-h"]).await {
- return ManagedProbe::Stale {
- bin,
- reason: "cli_unusable".to_string(),
- };
- }
-
- let capability = probe_cli_capability(&bin).await;
- if let Some(capability) = capability {
- if desktop_capability_ready(&capability) {
- return ManagedProbe::Ready { bin };
- }
- return ManagedProbe::Stale {
- bin,
- reason: desktop_capability_stale_reason(&capability),
- };
- }
-
- ManagedProbe::Stale {
- bin,
- reason: "desktop_capability_probe_failed".to_string(),
+fn choose_unmanageable_owned_preflight(
+ managed: &ManagedProbe,
+ port: u16,
+ reason: String,
+) -> DesktopPreflightResult {
+ DesktopPreflightResult {
+ disposition: DesktopPreflightDisposition::ExternalConflict,
+ reason: Some(owned_unmanageable_reason(&reason)),
+ port: Some(port),
+ can_auto_repair: false,
+ managed_bin: managed_bin_for_result(managed),
}
}
-async fn probe_managed_install() -> ManagedProbe {
- match crate::process::find_unsloth_binary() {
- Some(bin) => probe_managed_bin(bin).await,
- None => ManagedProbe::Missing,
+fn choose_owned_transitional_preflight(
+ managed: &ManagedProbe,
+ port: Option<u16>,
+) -> DesktopPreflightResult {
+ DesktopPreflightResult {
+ disposition: DesktopPreflightDisposition::ExternalConflict,
+ reason: Some("desktop_owned_backend_starting".to_string()),
+ port,
+ can_auto_repair: false,
+ managed_bin: managed_bin_for_result(managed),
}
}
-pub async fn managed_install_ready() -> bool {
- matches!(probe_managed_install().await, ManagedProbe::Ready { .. })
+fn choose_ownerless_spawned_preflight(
+ managed: &ManagedProbe,
+ backend: &BackendProbe,
+ port: Option<u16>,
+) -> DesktopPreflightResult {
+ match (port, backend) {
+ (Some(owned_port), BackendProbe::Ready { port }) if owned_port == *port => {
+ DesktopPreflightResult {
+ disposition: DesktopPreflightDisposition::OwnedReady,
+ reason: None,
+ port: Some(*port),
+ can_auto_repair: false,
+ managed_bin: managed_bin_for_result(managed),
+ }
+ }
+ (Some(owned_port), BackendProbe::Old { port, reason }) if owned_port == *port => {
+ DesktopPreflightResult {
+ disposition: DesktopPreflightDisposition::OwnedStale,
+ reason: Some(reason.clone()),
+ port: Some(*port),
+ can_auto_repair: release_auto_repair(),
+ managed_bin: managed_bin_for_result(managed),
+ }
+ }
+ _ => choose_owned_transitional_preflight(managed, port),
+ }
}
-async fn backend_health(client: &reqwest::Client, port: u16) -> Option<BackendHealth> {
- let url = format!("http://127.0.0.1:{port}/api/health");
- let response = client.get(url).send().await.ok()?;
- if !response.status().is_success() {
- return None;
- }
- let json = response.json::<serde_json::Value>().await.ok()?;
- let healthy = json
- .get("status")
- .and_then(|v| v.as_str())
- .map(|s| s == "healthy")
- .unwrap_or(false);
- let service = json
- .get("service")
- .and_then(|v| v.as_str())
- .map(|s| s == "Unsloth UI Backend")
- .unwrap_or(false);
- if !healthy || !service {
- return None;
- }
-
- let desktop_protocol_version = json
- .get("desktop_protocol_version")
- .and_then(|v| v.as_u64())
- .and_then(|v| u16::try_from(v).ok());
- let supports_desktop_auth = json.get("supports_desktop_auth").and_then(|v| v.as_bool());
- if desktop_protocol_version.is_none() && supports_desktop_auth.is_none() {
- return None;
- }
- let stale_reason = match supports_desktop_auth {
- Some(false) => json
- .get("desktop_auth_stale_reason")
- .and_then(|v| v.as_str())
- .map(ToOwned::to_owned),
+fn mutation_blocker_from_probe(probe: BackendProbe) -> Option<ExternalBackendConflict> {
+ match probe {
+ BackendProbe::ExternalConflict { port, reason } => {
+ Some(ExternalBackendConflict { port, reason })
+ }
+ BackendProbe::Ready { port } => Some(ExternalBackendConflict {
+ port,
+ reason: "same_root_external_backend_active".to_string(),
+ }),
_ => None,
- };
- Some(BackendHealth {
- desktop_protocol_version,
- supports_desktop_auth,
- stale_reason,
- })
-}
-
-fn backend_capability_stale_reason(health: &BackendHealth) -> Option<String> {
- if health.desktop_protocol_version != Some(1) {
- return health
- .stale_reason
- .clone()
- .or_else(|| Some("desktop_protocol_incompatible".to_string()));
- }
- if health.supports_desktop_auth != Some(true) {
- return health
- .stale_reason
- .clone()
- .or_else(|| Some("desktop_auth_unsupported".to_string()));
}
- None
}
-#[derive(Serialize)]
-struct DesktopLoginProbe<'a> {
- secret: &'a str,
+pub async fn mutation_blocking_backend_ignoring(
+ ignored_ports: &[u16],
+) -> Option<ExternalBackendConflict> {
+ mutation_blocker_from_probe(probe_existing_backends(ignored_ports).await)
}
-async fn backend_desktop_auth_status(
- client: &reqwest::Client,
- port: u16,
- health: &BackendHealth,
-) -> BackendProbe {
- if let Some(reason) = backend_capability_stale_reason(health) {
- return BackendProbe::Old { port, reason };
- }
-
- let url = format!("http://127.0.0.1:{port}/api/auth/desktop-login");
- let response = client
- .post(url)
- .json(&DesktopLoginProbe {
- secret: "desktop-preflight-invalid-secret",
- })
- .send()
- .await;
+pub async fn desktop_preflight_result() -> DesktopPreflightResult {
+ let (managed, backend) = tokio::join!(probe_managed_install(), probe_existing_backends(&[]));
+ choose_preflight(managed, backend)
+}
- let Ok(response) = response else {
- return BackendProbe::Old {
- port,
- reason: backend_capability_stale_reason(health)
- .unwrap_or_else(|| "desktop_login_probe_failed".to_string()),
+pub async fn desktop_preflight_result_with_state(
+ state: &crate::process::BackendState,
+) -> Result<(DesktopPreflightResult, Option<(u64, bool)>), String> {
+ let (managed, backend, owned) = tokio::join!(
+ probe_managed_install(),
+ probe_existing_backends(&[]),
+ crate::desktop_backend_owner::probe_verified_owned_backend()
+ );
+
+ if let Some(snapshot) = crate::process::owned_backend_snapshot(state)? {
+ let Some(owner) = snapshot.owner.clone() else {
+ let probe = match snapshot.port {
+ Some(port) => backend::probe_ownerless_spawned_backend(port).await,
+ None => backend,
+ };
+ return Ok((
+ choose_ownerless_spawned_preflight(&managed, &probe, snapshot.port),
+ None,
+ ));
};
- };
-
- match response.status() {
- reqwest::StatusCode::UNAUTHORIZED => BackendProbe::Ready { port },
- reqwest::StatusCode::NOT_FOUND => BackendProbe::Old {
- port,
- reason: "desktop_login_not_found".to_string(),
- },
- _ => BackendProbe::Old {
- port,
- reason: backend_capability_stale_reason(health)
- .unwrap_or_else(|| "desktop_login_probe_failed".to_string()),
- },
+ match crate::desktop_backend_owner::probe_owned_backend_state(
+ owner,
+ snapshot.port,
+ snapshot.is_adopted,
+ )
+ .await
+ {
+ OwnedBackendProbe::Verified(verified) => {
+ if snapshot.port.is_none() {
+ crate::process::record_owned_backend_port_if_current(
+ state,
+ snapshot.generation,
+ verified.port,
+ );
+ }
+ let result = choose_owned_preflight(&managed, &verified);
+ let watchdog_generation = if snapshot.is_adopted
+ && result.disposition == DesktopPreflightDisposition::OwnedReady
+ {
+ Some((snapshot.generation, false))
+ } else {
+ None
+ };
+ return Ok((result, watchdog_generation));
+ }
+ OwnedBackendProbe::Unmanageable { port, reason } => {
+ return Ok((
+ choose_unmanageable_owned_preflight(&managed, port, reason),
+ None,
+ ));
+ }
+ OwnedBackendProbe::NoMetadata
+ | OwnedBackendProbe::RemovedMalformed
+ | OwnedBackendProbe::NotVerified { .. } => {
+ if snapshot.is_adopted {
+ crate::process::clear_adopted_backend_if_current(
+ state,
+ snapshot.generation,
+ snapshot.port,
+ "state owner probe no longer verifies",
+ );
+ return Ok((choose_preflight(managed, backend), None));
+ }
+ return Ok((
+ choose_owned_transitional_preflight(&managed, snapshot.port),
+ None,
+ ));
+ }
+ }
}
-}
-
-async fn probe_existing_backends() -> BackendProbe {
- let client = match reqwest::Client::builder()
- .timeout(Duration::from_secs(2))
- .build()
- {
- Ok(client) => client,
- Err(_) => return BackendProbe::Missing,
- };
- // Fan out health probes concurrently. The desktop-auth probe is still
- // sequential per candidate because it has auth-log side effects.
- let ports: Vec<u16> = (8888u16..=8908).collect();
- let mut health_futs = Vec::with_capacity(ports.len());
- for port in ports {
- // why: reqwest::Client is internally Arc-wrapped; clone is a refcount bump
- // (documented cheap). tokio::spawn needs 'static, so each task owns its own clone.
- let c = client.clone();
- health_futs.push(tokio::spawn(async move {
- backend_health(&c, port).await.map(|h| (port, h))
- }));
- }
-
- let mut candidates: Vec<(u16, BackendHealth)> = Vec::new();
- for fut in health_futs {
- if let Ok(Some(pair)) = fut.await {
- candidates.push(pair);
+ let owned = match owned {
+ Ok(owned) => owned,
+ Err(error) => {
+ warn!(
+ "Desktop-owned backend probe failed; continuing without adoption: {}",
+ error
+ );
+ return Ok((choose_preflight(managed, backend), None));
}
- }
+ };
- let mut first_old = None;
- for (port, health) in candidates {
- match backend_desktop_auth_status(&client, port, &health).await {
- ready @ BackendProbe::Ready { .. } => return ready,
- old @ BackendProbe::Old { .. } if first_old.is_none() => first_old = Some(old),
- _ => {}
+ match owned {
+ OwnedBackendProbe::Verified(verified) => {
+ let result = choose_owned_preflight(&managed, &verified);
+ let adopted = crate::process::adopt_verified_backend(state, verified)?;
+ let watchdog_generation =
+ if result.disposition == DesktopPreflightDisposition::OwnedReady {
+ Some((adopted.generation, adopted.newly_adopted))
+ } else {
+ None
+ };
+ Ok((result, watchdog_generation))
}
+ OwnedBackendProbe::Unmanageable { port, reason } => Ok((
+ choose_unmanageable_owned_preflight(&managed, port, reason),
+ None,
+ )),
+ OwnedBackendProbe::NoMetadata
+ | OwnedBackendProbe::RemovedMalformed
+ | OwnedBackendProbe::NotVerified { .. } => Ok((choose_preflight(managed, backend), None)),
}
-
- first_old.unwrap_or(BackendProbe::Missing)
-}
-
-pub async fn desktop_preflight_result() -> DesktopPreflightResult {
- let (managed, backend) = tokio::join!(probe_managed_install(), probe_existing_backends());
- choose_preflight(managed, backend)
}
#[cfg(test)]
@@ -382,165 +293,169 @@ mod tests {
use tokio::net::TcpListener;
#[test]
- fn compatible_backend_does_not_win_over_stale_managed_install() {
- let result = choose_preflight(
- ManagedProbe::Stale {
- bin: PathBuf::from("/managed/unsloth"),
- reason: "old cli".to_string(),
- },
- BackendProbe::Ready { port: 8000 },
- );
-
- assert_eq!(
- result.disposition,
- DesktopPreflightDisposition::ManagedStale
- );
- assert_eq!(result.port, None);
- assert_eq!(result.reason, Some("old cli".to_string()));
- assert_eq!(result.can_auto_repair, release_auto_repair());
- assert_eq!(result.managed_bin, Some(PathBuf::from("/managed/unsloth")));
- }
-
- #[test]
- fn compatible_backend_wins_over_ready_managed_install() {
- let result = choose_preflight(
- ManagedProbe::Ready {
- bin: PathBuf::from("/managed/unsloth"),
- },
- BackendProbe::Ready { port: 8000 },
- );
-
- assert_eq!(
- result.disposition,
- DesktopPreflightDisposition::AttachedReady
- );
- assert_eq!(result.port, Some(8000));
- assert_eq!(result.managed_bin, Some(PathBuf::from("/managed/unsloth")));
- assert!(!result.can_auto_repair);
- }
-
- #[test]
- fn compatible_backend_does_not_win_over_missing_managed_install() {
- let result = choose_preflight(ManagedProbe::Missing, BackendProbe::Ready { port: 8000 });
-
- assert_eq!(
- result.disposition,
- DesktopPreflightDisposition::NotInstalled
- );
- assert_eq!(result.port, None);
- assert_eq!(result.managed_bin, None);
- assert!(!result.can_auto_repair);
+ fn choose_preflight_classifies_core_cases() {
+ let bin = || PathBuf::from("/managed/unsloth");
+ let ready = || ManagedProbe::Ready { bin: bin() };
+ let stale = || ManagedProbe::Stale {
+ bin: bin(),
+ reason: "old cli".to_string(),
+ };
+ let old_backend = || BackendProbe::Old {
+ port: 8001,
+ reason: "missing endpoint".to_string(),
+ };
+ let cases = [
+ (
+ stale(),
+ BackendProbe::Ready { port: 8000 },
+ DesktopPreflightDisposition::AttachedReady,
+ Some(8000),
+ None,
+ false,
+ Some(bin()),
+ ),
+ (
+ ready(),
+ BackendProbe::Ready { port: 8000 },
+ DesktopPreflightDisposition::AttachedReady,
+ Some(8000),
+ None,
+ false,
+ Some(bin()),
+ ),
+ (
+ ManagedProbe::Missing,
+ BackendProbe::Ready { port: 8000 },
+ DesktopPreflightDisposition::AttachedReady,
+ Some(8000),
+ None,
+ false,
+ None,
+ ),
+ (
+ ready(),
+ old_backend(),
+ DesktopPreflightDisposition::ManagedReady,
+ None,
+ None,
+ false,
+ Some(bin()),
+ ),
+ (
+ stale(),
+ old_backend(),
+ DesktopPreflightDisposition::ManagedStale,
+ None,
+ Some("old cli"),
+ release_auto_repair(),
+ Some(bin()),
+ ),
+ (
+ ready(),
+ BackendProbe::Missing,
+ DesktopPreflightDisposition::ManagedReady,
+ None,
+ None,
+ false,
+ Some(bin()),
+ ),
+ (
+ stale(),
+ BackendProbe::Missing,
+ DesktopPreflightDisposition::ManagedStale,
+ None,
+ Some("old cli"),
+ release_auto_repair(),
+ Some(bin()),
+ ),
+ (
+ ManagedProbe::Missing,
+ BackendProbe::Missing,
+ DesktopPreflightDisposition::NotInstalled,
+ None,
+ None,
+ false,
+ None,
+ ),
+ ];
+
+ for (managed, backend, disposition, port, reason, can_auto_repair, managed_bin) in cases {
+ let result = choose_preflight(managed, backend);
+ assert_eq!(result.disposition, disposition);
+ assert_eq!(result.port, port);
+ assert_eq!(result.reason.as_deref(), reason);
+ assert_eq!(result.can_auto_repair, can_auto_repair);
+ assert_eq!(result.managed_bin, managed_bin);
+ }
}
#[test]
- fn old_backend_falls_back_to_ready_managed_install() {
+ fn external_conflict_blocks_managed_flow() {
let result = choose_preflight(
ManagedProbe::Ready {
bin: PathBuf::from("/managed/unsloth"),
},
- BackendProbe::Old {
- port: 8001,
- reason: "missing endpoint".to_string(),
+ BackendProbe::ExternalConflict {
+ port: 8888,
+ reason: "same_root_external_backend_active".to_string(),
},
);
assert_eq!(
result.disposition,
- DesktopPreflightDisposition::ManagedReady
- );
- assert_eq!(result.reason, None);
- assert_eq!(result.port, None);
- assert_eq!(result.managed_bin, Some(PathBuf::from("/managed/unsloth")));
- assert!(!result.can_auto_repair);
- }
-
- #[test]
- fn old_backend_falls_back_to_stale_managed_install() {
- let result = choose_preflight(
- ManagedProbe::Stale {
- bin: PathBuf::from("/managed/unsloth"),
- reason: "old cli".to_string(),
- },
- BackendProbe::Old {
- port: 8001,
- reason: "missing endpoint".to_string(),
- },
- );
-
- assert_eq!(
- result.disposition,
- DesktopPreflightDisposition::ManagedStale
- );
- assert_eq!(result.reason, Some("old cli".to_string()));
- assert_eq!(result.port, None);
- assert_eq!(result.can_auto_repair, release_auto_repair());
- assert_eq!(result.managed_bin, Some(PathBuf::from("/managed/unsloth")));
- }
-
- #[test]
- fn managed_ready_when_no_backend() {
- let result = choose_preflight(
- ManagedProbe::Ready {
- bin: PathBuf::from("/managed/unsloth"),
- },
- BackendProbe::Missing,
+ DesktopPreflightDisposition::ExternalConflict
);
-
+ assert_eq!(result.port, Some(8888));
assert_eq!(
- result.disposition,
- DesktopPreflightDisposition::ManagedReady
+ result.reason,
+ Some("same_root_external_backend_active".to_string())
);
- assert_eq!(result.managed_bin, Some(PathBuf::from("/managed/unsloth")));
assert!(!result.can_auto_repair);
+ assert_eq!(result.managed_bin, Some(PathBuf::from("/managed/unsloth")));
}
#[test]
- fn managed_stale_when_no_backend() {
- let result = choose_preflight(
- ManagedProbe::Stale {
- bin: PathBuf::from("/managed/unsloth"),
- reason: "old cli".to_string(),
- },
- BackendProbe::Missing,
- );
-
- assert_eq!(
- result.disposition,
- DesktopPreflightDisposition::ManagedStale
- );
- assert_eq!(result.reason, Some("old cli".to_string()));
- assert_eq!(result.can_auto_repair, release_auto_repair());
- }
-
- #[test]
- fn not_installed_when_no_backend_no_managed_binary() {
- let result = choose_preflight(ManagedProbe::Missing, BackendProbe::Missing);
-
+ fn mutation_blocker_blocks_ready_external_backends() {
assert_eq!(
- result.disposition,
- DesktopPreflightDisposition::NotInstalled
+ mutation_blocker_from_probe(BackendProbe::Ready { port: 8890 }),
+ Some(ExternalBackendConflict {
+ port: 8890,
+ reason: "same_root_external_backend_active".to_string(),
+ })
);
- assert_eq!(result.managed_bin, None);
- assert!(!result.can_auto_repair);
}
#[test]
- fn old_backend_with_no_managed_install_uses_install_flow() {
- let result = choose_preflight(
- ManagedProbe::Missing,
- BackendProbe::Old {
- port: 8002,
- reason: "old version".to_string(),
- },
- );
-
+ fn backend_version_gate_classifies_core_cases() {
+ for version in [
+ MIN_DESKTOP_BACKEND_VERSION,
+ "2026.5.4",
+ "2027.1.0",
+ "2026.5.3.post1",
+ "2026.5.3+local",
+ "2026.5.3.post1",
+ ] {
+ assert!(backend_version_compatible(Some(version)), "{version}");
+ }
+ for (version, reason) in [
+ (None, "desktop_backend_version_missing"),
+ (Some("not-a-version"), "desktop_backend_version_invalid"),
+ (Some("2026.5.3.1"), "desktop_backend_version_invalid"),
+ (Some("2026.5.3foo"), "desktop_backend_version_invalid"),
+ (Some("2026.5.3.devx"), "desktop_backend_version_invalid"),
+ (Some("2026.5.2"), "desktop_backend_version_too_old"),
+ (Some("2026.5.3rc1"), "desktop_backend_version_too_old"),
+ (Some("2026.5.3.dev1"), "desktop_backend_version_too_old"),
+ ] {
+ assert_eq!(
+ backend_version_stale_reason(version).as_deref(),
+ Some(reason)
+ );
+ }
assert_eq!(
- result.disposition,
- DesktopPreflightDisposition::NotInstalled
+ backend_version_compatible(Some("dev")),
+ cfg!(debug_assertions)
);
- assert_eq!(result.reason, None);
- assert_eq!(result.port, None);
- assert!(!result.can_auto_repair);
}
#[cfg(unix)]
@@ -581,137 +496,96 @@ mod tests {
#[cfg(unix)]
#[tokio::test]
- async fn managed_cli_stale_when_desktop_capabilities_missing() {
- let fake = fake_cli(
- "cap-missing",
- r#"#!/bin/sh
+ async fn managed_cli_capability_probe_classifies_core_cases() {
+ for (name, script, stale_reason) in [
+ (
+ "cap-missing",
+ r#"#!/bin/sh
if [ "$1" = "-h" ]; then exit 0; fi
if [ "$1" = "studio" ] && [ "$2" = "provision-desktop-auth" ] && [ "$3" = "--help" ]; then exit 0; fi
exit 1
"#,
- );
- let bin = fake.bin.clone();
-
- assert!(matches!(
- probe_managed_bin(bin.clone()).await,
- ManagedProbe::Stale { bin: actual_bin, .. } if actual_bin == bin
- ));
- }
-
- #[cfg(unix)]
- #[tokio::test]
- async fn managed_cli_stale_when_desktop_capabilities_command_missing() {
- let fake = fake_cli(
- "missing-helper",
- r#"#!/bin/sh
-if [ "$1" = "-h" ]; then exit 0; fi
-exit 1
-"#,
- );
- let bin = fake.bin.clone();
-
- assert!(matches!(
- probe_managed_bin(bin.clone()).await,
- ManagedProbe::Stale { bin: actual_bin, .. } if actual_bin == bin
- ));
- }
-
- #[cfg(unix)]
- #[tokio::test]
- async fn managed_cli_stale_when_help_broken() {
- let fake = fake_cli(
- "broken-help",
- r#"#!/bin/sh
-exit 1
-"#,
- );
- let bin = fake.bin.clone();
-
- assert_eq!(
- probe_managed_bin(bin.clone()).await,
- ManagedProbe::Stale {
- bin,
- reason: "cli_unusable".to_string()
- }
- );
- }
-
- #[cfg(unix)]
- #[tokio::test]
- async fn managed_cli_ready_when_desktop_capabilities_compatible() {
- let fake = fake_cli(
- "cap-true-helper-missing",
- r#"#!/bin/sh
+ Some("desktop_capability_probe_failed"),
+ ),
+ (
+ "cap-true-helper-missing",
+ r#"#!/bin/sh
if [ "$1" = "-h" ]; then exit 0; fi
if [ "$1" = "studio" ] && [ "$2" = "desktop-capabilities" ] && [ "$3" = "--json" ]; then
- printf '{"desktop_protocol_version":1,"supports_api_only":true,"supports_provision_desktop_auth":true}'
+ printf '{"desktop_protocol_version":1,"desktop_manageability_version":1,"supports_api_only":true,"supports_provision_desktop_auth":true,"supports_desktop_backend_ownership":true,"version":"2026.5.3"}'
exit 0
fi
exit 1
"#,
- );
- let bin = fake.bin.clone();
-
- assert_eq!(
- probe_managed_bin(bin.clone()).await,
- ManagedProbe::Ready { bin }
- );
- }
-
- #[cfg(unix)]
- #[tokio::test]
- async fn capability_false_reason_used_when_legacy_helper_missing() {
- let fake = fake_cli(
- "cap-false-helper-missing",
- r#"#!/bin/sh
+ None,
+ ),
+ (
+ "cap-false-helper-ready",
+ r#"#!/bin/sh
if [ "$1" = "-h" ]; then exit 0; fi
if [ "$1" = "studio" ] && [ "$2" = "desktop-capabilities" ] && [ "$3" = "--json" ]; then
- printf '{"desktop_protocol_version":1,"supports_api_only":true,"supports_provision_desktop_auth":false,"desktop_auth_stale_reason":"cap_false"}'
+ printf '{"desktop_protocol_version":1,"desktop_manageability_version":1,"supports_api_only":true,"supports_provision_desktop_auth":false,"supports_desktop_backend_ownership":true,"desktop_auth_stale_reason":"cap_false","version":"2026.5.3"}'
exit 0
fi
+if [ "$1" = "studio" ] && [ "$2" = "provision-desktop-auth" ] && [ "$3" = "--help" ]; then exit 0; fi
exit 1
"#,
- );
- let bin = fake.bin.clone();
-
- assert_eq!(
- probe_managed_bin(bin.clone()).await,
- ManagedProbe::Stale {
- bin,
- reason: "cap_false".to_string()
+ Some("cap_false"),
+ ),
+ ] {
+ let fake = fake_cli(name, script);
+ let bin = fake.bin.clone();
+ match (probe_managed_bin(bin.clone()).await, stale_reason) {
+ (ManagedProbe::Ready { bin: actual }, None) => assert_eq!(actual, bin),
+ (
+ ManagedProbe::Stale {
+ bin: actual,
+ reason,
+ },
+ Some(expected),
+ ) => {
+ assert_eq!((actual, reason.as_str()), (bin, expected));
+ }
+ (probe, expected) => panic!("unexpected probe {probe:?}, expected {expected:?}"),
}
- );
+ }
}
- #[cfg(unix)]
- #[tokio::test]
- async fn capability_false_overrides_working_legacy_helper() {
- let fake = fake_cli(
- "cap-false-helper-ready",
- r#"#!/bin/sh
-if [ "$1" = "-h" ]; then exit 0; fi
-if [ "$1" = "studio" ] && [ "$2" = "desktop-capabilities" ] && [ "$3" = "--json" ]; then
- printf '{"desktop_protocol_version":1,"supports_api_only":true,"supports_provision_desktop_auth":false,"desktop_auth_stale_reason":"cap_false"}'
- exit 0
-fi
-if [ "$1" = "studio" ] && [ "$2" = "provision-desktop-auth" ] && [ "$3" = "--help" ]; then exit 0; fi
-exit 1
-"#,
- );
- let bin = fake.bin.clone();
+ const EXPECTED_ROOT_ID: &str =
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
+ const OTHER_ROOT_ID: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
+ const OWNER_TOKEN: &str = "desktop-owner-token";
- assert_eq!(
- probe_managed_bin(bin.clone()).await,
- ManagedProbe::Stale {
- bin,
- reason: "cap_false".to_string()
- }
- );
+ fn install_test_owner() {
+ crate::desktop_backend_owner::install_test_owner(EXPECTED_ROOT_ID, OWNER_TOKEN);
+ }
+
+ fn desktop_ready_health(root_id: &str) -> String {
+ desktop_ready_health_with_owner(root_id, true)
}
- async fn backend_server(health_body: &'static str, route_status: &'static str) -> u16 {
+ fn desktop_owner_json(include_owner: bool) -> String {
+ if include_owner {
+ format!(
+ r#", "desktop_owner":{{"kind":"tauri","token_sha256":"{}"}}"#,
+ crate::desktop_backend_owner::token_sha256(OWNER_TOKEN)
+ )
+ } else {
+ String::new()
+ }
+ }
+
+ fn desktop_ready_health_with_owner(root_id: &str, include_owner: bool) -> String {
+ let owner = desktop_owner_json(include_owner);
+ format!(
+ r#"{{"status":"healthy","service":"Unsloth UI Backend","version":"2026.5.3","desktop_protocol_version":1,"desktop_manageability_version":1,"supports_desktop_auth":true,"supports_desktop_backend_ownership":true,"studio_root_id":"{root_id}"{owner}}}"#
+ )
+ }
+
+ async fn backend_server(health_body: impl Into<String>, route_status: &'static str) -> u16 {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
+ let health_body = health_body.into();
tokio::spawn(async move {
for _ in 0..2 {
@@ -720,7 +594,7 @@ exit 1
let n = stream.read(&mut buffer).await.unwrap();
let request = String::from_utf8_lossy(&buffer[..n]);
let (status, body) = if request.starts_with("GET /api/health ") {
- ("200 OK", health_body)
+ ("200 OK", health_body.as_str())
} else if request.starts_with("POST /api/auth/desktop-login ") {
(route_status, "")
} else {
@@ -738,17 +612,18 @@ exit 1
}
async fn probe_test_backend(
- health_body: &'static str,
+ health_body: impl Into<String>,
route_status: &'static str,
) -> BackendProbe {
+ install_test_owner();
let port = backend_server(health_body, route_status).await;
let client = reqwest::Client::new();
let health = backend_health(&client, port).await.unwrap();
- backend_desktop_auth_status(&client, port, &health).await
+ backend_desktop_auth_status(&client, port, &health, Some(EXPECTED_ROOT_ID)).await
}
#[tokio::test]
- async fn backend_health_without_desktop_capability_fields_is_not_compatible() {
+ async fn backend_health_without_desktop_capability_fields_is_still_candidate() {
let port = backend_server(
r#"{"status":"healthy","service":"Unsloth UI Backend"}"#,
"401 Unauthorized",
@@ -756,13 +631,16 @@ exit 1
.await;
let client = reqwest::Client::new();
- assert!(backend_health(&client, port).await.is_none());
+ assert!(backend_health(&client, port).await.is_some());
}
#[tokio::test]
async fn backend_with_auth_support_but_missing_protocol_is_old() {
let probe = probe_test_backend(
- r#"{"status":"healthy","service":"Unsloth UI Backend","supports_desktop_auth":true}"#,
+ format!(
+ r#"{{"status":"healthy","service":"Unsloth UI Backend","version":"2026.5.3","desktop_manageability_version":1,"supports_desktop_auth":true,"supports_desktop_backend_ownership":true,"studio_root_id":"{EXPECTED_ROOT_ID}"{}}}"#,
+ desktop_owner_json(true)
+ ),
"401 Unauthorized",
)
.await;
@@ -771,20 +649,17 @@ exit 1
}
#[tokio::test]
- async fn backend_with_auth_support_but_unsupported_protocol_is_old() {
- let probe = probe_test_backend(
- r#"{"status":"healthy","service":"Unsloth UI Backend","desktop_protocol_version":2,"supports_desktop_auth":true}"#,
- "401 Unauthorized",
- )
- .await;
+ async fn backend_health_with_desktop_capability_fields_and_401_is_ready() {
+ let probe =
+ probe_test_backend(desktop_ready_health(EXPECTED_ROOT_ID), "401 Unauthorized").await;
- assert!(matches!(probe, BackendProbe::Old { .. }));
+ assert!(matches!(probe, BackendProbe::Ready { .. }));
}
#[tokio::test]
- async fn backend_health_with_desktop_capability_fields_and_401_is_ready() {
+ async fn compatible_same_root_without_desktop_owner_is_ready() {
let probe = probe_test_backend(
- r#"{"status":"healthy","service":"Unsloth UI Backend","desktop_protocol_version":1,"supports_desktop_auth":true}"#,
+ desktop_ready_health_with_owner(EXPECTED_ROOT_ID, false),
"401 Unauthorized",
)
.await;
@@ -793,45 +668,98 @@ exit 1
}
#[tokio::test]
- async fn backend_route_404_is_old() {
+ async fn stale_same_root_without_desktop_owner_is_external_conflict() {
let probe = probe_test_backend(
- r#"{"status":"healthy","service":"Unsloth UI Backend","desktop_protocol_version":1,"supports_desktop_auth":true}"#,
- "404 Not Found",
+ format!(
+ r#"{{"status":"healthy","service":"Unsloth UI Backend","version":"2026.5.1","desktop_protocol_version":1,"desktop_manageability_version":1,"supports_desktop_auth":true,"supports_desktop_backend_ownership":true,"studio_root_id":"{EXPECTED_ROOT_ID}"}}"#,
+ ),
+ "401 Unauthorized",
)
.await;
+ assert!(matches!(
+ probe,
+ BackendProbe::ExternalConflict {
+ reason,
+ ..
+ } if reason == "desktop_backend_version_too_old"
+ ));
+ }
+
+ #[tokio::test]
+ async fn backend_root_id_mismatch_is_old_before_auth_probe() {
+ let probe =
+ probe_test_backend(desktop_ready_health(OTHER_ROOT_ID), "401 Unauthorized").await;
+
assert!(matches!(
probe,
BackendProbe::Old {
reason,
..
- } if reason == "desktop_login_not_found"
+ } if reason == "studio_root_id_mismatch"
));
}
#[tokio::test]
- async fn backend_route_500_is_old() {
+ async fn backend_missing_root_id_is_external_conflict_before_auth_probe() {
let probe = probe_test_backend(
r#"{"status":"healthy","service":"Unsloth UI Backend","desktop_protocol_version":1,"supports_desktop_auth":true}"#,
- "500 Internal Server Error",
+ "401 Unauthorized",
)
.await;
- assert!(matches!(probe, BackendProbe::Old { .. }));
+ assert!(matches!(
+ probe,
+ BackendProbe::ExternalConflict {
+ reason,
+ ..
+ } if reason == "ambiguous_root_external_backend_active"
+ ));
+ }
+
+ #[tokio::test]
+ async fn backend_expected_root_id_missing_is_external_conflict_before_auth_probe() {
+ install_test_owner();
+ let port = backend_server(desktop_ready_health(EXPECTED_ROOT_ID), "401 Unauthorized").await;
+ let client = reqwest::Client::new();
+ let health = backend_health(&client, port).await.unwrap();
+
+ assert!(matches!(
+ backend_desktop_auth_status(&client, port, &health, None).await,
+ BackendProbe::ExternalConflict {
+ reason,
+ ..
+ } if reason == "ambiguous_root_external_backend_active"
+ ));
+ }
+
+ #[tokio::test]
+ async fn backend_route_404_is_old() {
+ let probe =
+ probe_test_backend(desktop_ready_health(EXPECTED_ROOT_ID), "404 Not Found").await;
+
+ assert!(matches!(
+ probe,
+ BackendProbe::Old {
+ reason,
+ ..
+ } if reason == "desktop_login_not_found"
+ ));
}
#[tokio::test]
async fn backend_capability_false_is_old_even_when_route_401() {
- let port = backend_server(
- r#"{"status":"healthy","service":"Unsloth UI Backend","desktop_protocol_version":1,"supports_desktop_auth":false,"desktop_auth_stale_reason":"cap_false"}"#,
+ let probe = probe_test_backend(
+ format!(
+ r#"{{"status":"healthy","service":"Unsloth UI Backend","version":"2026.5.3","desktop_protocol_version":1,"desktop_manageability_version":1,"supports_desktop_auth":false,"supports_desktop_backend_ownership":true,"desktop_auth_stale_reason":"cap_false","studio_root_id":"{EXPECTED_ROOT_ID}"{}}}"#,
+ desktop_owner_json(true)
+ ),
"401 Unauthorized",
)
.await;
- let client = reqwest::Client::new();
- let health = backend_health(&client, port).await.unwrap();
assert!(matches!(
- backend_desktop_auth_status(&client, port, &health).await,
+ probe,
BackendProbe::Old {
reason,
..
diff --git a/studio/src-tauri/src/preflight/backend.rs b/studio/src-tauri/src/preflight/backend.rs
new file mode 100644
index 00000000000..987adc3892e
--- /dev/null
+++ b/studio/src-tauri/src/preflight/backend.rs
@@ -0,0 +1,336 @@
+use super::types::BackendProbe;
+use super::version::{
+ backend_version_stale_reason, DESKTOP_MANAGEABILITY_VERSION, DESKTOP_PROTOCOL_VERSION,
+};
+use serde::{Deserialize, Serialize};
+use std::time::Duration;
+
+#[derive(Debug, Deserialize)]
+struct DesktopOwnerHealth {
+ kind: Option<String>,
+ token_sha256: Option<String>,
+}
+
+#[derive(Debug)]
+pub(super) struct BackendHealth {
+ desktop_protocol_version: Option<u16>,
+ desktop_manageability_version: Option<u16>,
+ supports_desktop_auth: Option<bool>,
+ supports_desktop_backend_ownership: Option<bool>,
+ studio_root_id: Option<String>,
+ desktop_owner: Option<DesktopOwnerHealth>,
+ version: Option<String>,
+ stale_reason: Option<String>,
+}
+
+pub(super) async fn backend_health(client: &reqwest::Client, port: u16) -> Option<BackendHealth> {
+ let url = format!("http://127.0.0.1:{port}/api/health");
+ let response = client.get(url).send().await.ok()?;
+ if !response.status().is_success() {
+ return None;
+ }
+ let json = response.json::<serde_json::Value>().await.ok()?;
+ let healthy = json
+ .get("status")
+ .and_then(|v| v.as_str())
+ .map(|s| s == "healthy")
+ .unwrap_or(false);
+ let service = json
+ .get("service")
+ .and_then(|v| v.as_str())
+ .map(|s| s == "Unsloth UI Backend")
+ .unwrap_or(false);
+ if !healthy || !service {
+ return None;
+ }
+
+ let desktop_protocol_version = json
+ .get("desktop_protocol_version")
+ .and_then(|v| v.as_u64())
+ .and_then(|v| u16::try_from(v).ok());
+ let desktop_manageability_version = json
+ .get("desktop_manageability_version")
+ .and_then(|v| v.as_u64())
+ .and_then(|v| u16::try_from(v).ok());
+ let supports_desktop_auth = json.get("supports_desktop_auth").and_then(|v| v.as_bool());
+ let supports_desktop_backend_ownership = json
+ .get("supports_desktop_backend_ownership")
+ .and_then(|v| v.as_bool());
+ let studio_root_id = json
+ .get("studio_root_id")
+ .and_then(|v| v.as_str())
+ .map(ToOwned::to_owned);
+ let desktop_owner = json
+ .get("desktop_owner")
+ .and_then(|v| serde_json::from_value::<DesktopOwnerHealth>(v.clone()).ok());
+ let version = json
+ .get("version")
+ .and_then(|v| v.as_str())
+ .map(ToOwned::to_owned);
+ let stale_reason = match supports_desktop_auth {
+ Some(false) => json
+ .get("desktop_auth_stale_reason")
+ .and_then(|v| v.as_str())
+ .map(ToOwned::to_owned),
+ _ => None,
+ };
+ Some(BackendHealth {
+ desktop_protocol_version,
+ desktop_manageability_version,
+ supports_desktop_auth,
+ supports_desktop_backend_ownership,
+ studio_root_id,
+ desktop_owner,
+ version,
+ stale_reason,
+ })
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+enum BackendRootStatus {
+ SameRoot,
+ ForeignRoot,
+ AmbiguousRoot,
+ ExpectedUnavailable,
+}
+
+fn backend_root_status(
+ health: &BackendHealth,
+ expected_studio_root_id: Option<&str>,
+) -> BackendRootStatus {
+ let Some(expected) = expected_studio_root_id else {
+ return BackendRootStatus::ExpectedUnavailable;
+ };
+
+ match health.studio_root_id.as_deref() {
+ Some(actual) if actual == expected => BackendRootStatus::SameRoot,
+ Some(actual) if crate::desktop_backend_owner::is_valid_studio_root_id(actual) => {
+ BackendRootStatus::ForeignRoot
+ }
+ _ => BackendRootStatus::AmbiguousRoot,
+ }
+}
+
+fn backend_desktop_owner_match(
+ health: &BackendHealth,
+) -> crate::desktop_backend_owner::HealthOwnerMatch {
+ let Some(owner) = health.desktop_owner.as_ref() else {
+ return crate::desktop_backend_owner::HealthOwnerMatch::None;
+ };
+ crate::desktop_backend_owner::classify_health_desktop_owner(
+ health.studio_root_id.as_deref(),
+ owner.kind.as_deref(),
+ owner.token_sha256.as_deref(),
+ )
+}
+
+fn backend_capability_stale_reason(health: &BackendHealth) -> Option<String> {
+ if health.desktop_protocol_version != Some(DESKTOP_PROTOCOL_VERSION) {
+ return health
+ .stale_reason
+ .clone()
+ .or_else(|| Some("desktop_protocol_incompatible".to_string()));
+ }
+ if health.supports_desktop_auth != Some(true) {
+ return health
+ .stale_reason
+ .clone()
+ .or_else(|| Some("desktop_auth_unsupported".to_string()));
+ }
+ if health.desktop_manageability_version.unwrap_or(0) < DESKTOP_MANAGEABILITY_VERSION {
+ return Some("desktop_manageability_unsupported".to_string());
+ }
+ if health.supports_desktop_backend_ownership != Some(true) {
+ return Some("desktop_backend_ownership_unsupported".to_string());
+ }
+ backend_version_stale_reason(health.version.as_deref())
+}
+
+#[derive(Serialize)]
+struct DesktopLoginProbe<'a> {
+ secret: &'a str,
+}
+
+pub(super) async fn probe_ownerless_spawned_backend(port: u16) -> BackendProbe {
+ let client = match reqwest::Client::builder()
+ .timeout(Duration::from_secs(2))
+ .build()
+ {
+ Ok(client) => client,
+ Err(_) => return BackendProbe::Missing,
+ };
+ let Some(health) = backend_health(&client, port).await else {
+ return BackendProbe::Missing;
+ };
+ if let Some(reason) = backend_capability_stale_reason(&health) {
+ return BackendProbe::Old { port, reason };
+ }
+
+ let response = client
+ .post(format!("http://127.0.0.1:{port}/api/auth/desktop-login"))
+ .json(&DesktopLoginProbe {
+ secret: "desktop-preflight-invalid-secret",
+ })
+ .send()
+ .await;
+ match response.map(|response| response.status()) {
+ Ok(reqwest::StatusCode::UNAUTHORIZED) => BackendProbe::Ready { port },
+ Ok(reqwest::StatusCode::NOT_FOUND) => BackendProbe::Old {
+ port,
+ reason: "desktop_login_not_found".to_string(),
+ },
+ _ => BackendProbe::Old {
+ port,
+ reason: "desktop_login_probe_failed".to_string(),
+ },
+ }
+}
+
+pub(super) async fn backend_desktop_auth_status(
+ client: &reqwest::Client,
+ port: u16,
+ health: &BackendHealth,
+ expected_studio_root_id: Option<&str>,
+) -> BackendProbe {
+ let root_status = backend_root_status(health, expected_studio_root_id);
+ let owner_match = backend_desktop_owner_match(health);
+ let verified_owner = owner_match == crate::desktop_backend_owner::HealthOwnerMatch::CurrentApp;
+ let same_root_external = root_status == BackendRootStatus::SameRoot && !verified_owner;
+
+ match root_status {
+ BackendRootStatus::AmbiguousRoot | BackendRootStatus::ExpectedUnavailable => {
+ return BackendProbe::ExternalConflict {
+ port,
+ reason: "ambiguous_root_external_backend_active".to_string(),
+ };
+ }
+ BackendRootStatus::ForeignRoot => {
+ return BackendProbe::Old {
+ port,
+ reason: "studio_root_id_mismatch".to_string(),
+ };
+ }
+ BackendRootStatus::SameRoot => {}
+ }
+
+ if same_root_external
+ && matches!(
+ owner_match,
+ crate::desktop_backend_owner::HealthOwnerMatch::PreviousApp
+ | crate::desktop_backend_owner::HealthOwnerMatch::OtherDesktopOwner
+ )
+ {
+ return BackendProbe::ExternalConflict {
+ port,
+ reason: "desktop_owned_backend_active".to_string(),
+ };
+ }
+
+ if let Some(reason) = backend_capability_stale_reason(health) {
+ return if same_root_external {
+ BackendProbe::ExternalConflict { port, reason }
+ } else {
+ BackendProbe::Old { port, reason }
+ };
+ }
+
+ let url = format!("http://127.0.0.1:{port}/api/auth/desktop-login");
+ let response = client
+ .post(url)
+ .json(&DesktopLoginProbe {
+ secret: "desktop-preflight-invalid-secret",
+ })
+ .send()
+ .await;
+
+ let Ok(response) = response else {
+ let reason = backend_capability_stale_reason(health)
+ .unwrap_or_else(|| "desktop_login_probe_failed".to_string());
+ return if same_root_external {
+ BackendProbe::ExternalConflict { port, reason }
+ } else {
+ BackendProbe::Old { port, reason }
+ };
+ };
+
+ match response.status() {
+ reqwest::StatusCode::UNAUTHORIZED => BackendProbe::Ready { port },
+ reqwest::StatusCode::NOT_FOUND => {
+ let reason = "desktop_login_not_found".to_string();
+ if same_root_external {
+ BackendProbe::ExternalConflict { port, reason }
+ } else {
+ BackendProbe::Old { port, reason }
+ }
+ }
+ _ => {
+ let reason = backend_capability_stale_reason(health)
+ .unwrap_or_else(|| "desktop_login_probe_failed".to_string());
+ if same_root_external {
+ BackendProbe::ExternalConflict { port, reason }
+ } else {
+ BackendProbe::Old { port, reason }
+ }
+ }
+ }
+}
+
+pub(super) async fn probe_existing_backends(ignored_ports: &[u16]) -> BackendProbe {
+ let client = match reqwest::Client::builder()
+ .timeout(Duration::from_secs(2))
+ .build()
+ {
+ Ok(client) => client,
+ Err(_) => return BackendProbe::Missing,
+ };
+
+ // Fan out health probes concurrently. The desktop-auth probe is still
+ // sequential per candidate because it has auth-log side effects.
+ let ports: Vec<u16> = crate::desktop_backend_owner::desktop_candidate_ports().collect();
+ let mut health_futs = Vec::with_capacity(ports.len());
+ for port in ports {
+ let c = client.clone();
+ health_futs.push(tokio::spawn(async move {
+ backend_health(&c, port).await.map(|h| (port, h))
+ }));
+ }
+
+ let mut candidates: Vec<(u16, BackendHealth)> = Vec::new();
+ for fut in health_futs {
+ if let Ok(Some(pair)) = fut.await {
+ candidates.push(pair);
+ }
+ }
+
+ let expected_studio_root_id = crate::desktop_backend_owner::read_expected_studio_root_id();
+ let mut first_conflict = None;
+ let mut first_ready = None;
+ let mut first_old = None;
+ for (port, health) in candidates {
+ if ignored_ports.contains(&port) {
+ continue;
+ }
+ match backend_desktop_auth_status(
+ &client,
+ port,
+ &health,
+ expected_studio_root_id.as_deref(),
+ )
+ .await
+ {
+ conflict @ BackendProbe::ExternalConflict { .. } if first_conflict.is_none() => {
+ first_conflict = Some(conflict)
+ }
+ ready @ BackendProbe::Ready { .. } if first_ready.is_none() => {
+ first_ready = Some(ready)
+ }
+ old @ BackendProbe::Old { .. } if first_old.is_none() => first_old = Some(old),
+ _ => {}
+ }
+ }
+
+ first_conflict
+ .or(first_ready)
+ .or(first_old)
+ .unwrap_or(BackendProbe::Missing)
+}
diff --git a/studio/src-tauri/src/preflight/managed.rs b/studio/src-tauri/src/preflight/managed.rs
new file mode 100644
index 00000000000..51fde51896c
--- /dev/null
+++ b/studio/src-tauri/src/preflight/managed.rs
@@ -0,0 +1,169 @@
+use super::types::ManagedProbe;
+use super::version::{
+ backend_version_stale_reason, DESKTOP_MANAGEABILITY_VERSION, DESKTOP_PROTOCOL_VERSION,
+};
+use serde::Deserialize;
+use std::path::{Path, PathBuf};
+use std::process::Stdio;
+use std::time::Duration;
+use tokio::io::AsyncReadExt;
+use tokio::process::Command;
+
+#[derive(Debug, Deserialize)]
+struct DesktopCapability {
+ desktop_protocol_version: Option<u16>,
+ desktop_manageability_version: Option<u16>,
+ supports_api_only: Option<bool>,
+ supports_provision_desktop_auth: Option<bool>,
+ supports_desktop_backend_ownership: Option<bool>,
+ desktop_auth_stale_reason: Option<String>,
+ version: Option<String>,
+}
+
+async fn run_cli_probe(bin: &Path, args: &[&str]) -> bool {
+ let mut cmd = Command::new(bin);
+ cmd.args(args).stdout(Stdio::null()).stderr(Stdio::null());
+
+ #[cfg(target_os = "linux")]
+ if std::env::var_os("APPIMAGE").is_some() {
+ cmd.env_remove("LD_LIBRARY_PATH");
+ cmd.env_remove("PYTHONHOME");
+ cmd.env_remove("PYTHONPATH");
+ }
+
+ // Tauri uses the legacy root regardless of UNSLOTH_STUDIO_HOME / STUDIO_HOME;
+ // probe subprocesses must follow the same isolation as process.rs.
+ cmd.env_remove("UNSLOTH_STUDIO_HOME");
+ cmd.env_remove("STUDIO_HOME");
+
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ cmd.creation_flags(crate::process::CREATE_NO_WINDOW);
+ }
+
+ let Ok(mut child) = cmd.spawn() else {
+ return false;
+ };
+
+ match tokio::time::timeout(Duration::from_secs(10), child.wait()).await {
+ Ok(Ok(status)) => status.success(),
+ _ => {
+ let _ = child.kill().await;
+ let _ = child.wait().await;
+ false
+ }
+ }
+}
+
+async fn probe_cli_capability(bin: &Path) -> Option<DesktopCapability> {
+ let mut cmd = Command::new(bin);
+ cmd.args(["studio", "desktop-capabilities", "--json"])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null());
+
+ #[cfg(target_os = "linux")]
+ if std::env::var_os("APPIMAGE").is_some() {
+ cmd.env_remove("LD_LIBRARY_PATH");
+ cmd.env_remove("PYTHONHOME");
+ cmd.env_remove("PYTHONPATH");
+ }
+
+ // Tauri uses the legacy root regardless of UNSLOTH_STUDIO_HOME / STUDIO_HOME;
+ // probe subprocesses must follow the same isolation as process.rs.
+ cmd.env_remove("UNSLOTH_STUDIO_HOME");
+ cmd.env_remove("STUDIO_HOME");
+
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ cmd.creation_flags(crate::process::CREATE_NO_WINDOW);
+ }
+
+ let Ok(mut child) = cmd.spawn() else {
+ return None;
+ };
+ let Some(mut stdout) = child.stdout.take() else {
+ return None;
+ };
+
+ match tokio::time::timeout(Duration::from_secs(10), child.wait()).await {
+ Ok(Ok(status)) if status.success() => {}
+ Err(_) => {
+ let _ = child.kill().await;
+ let _ = child.wait().await;
+ return None;
+ }
+ _ => return None,
+ }
+
+ let mut output = Vec::new();
+ if stdout.read_to_end(&mut output).await.is_err() {
+ return None;
+ }
+
+ serde_json::from_slice::<DesktopCapability>(&output).ok()
+}
+
+fn desktop_capability_stale_reason(capability: &DesktopCapability) -> Option<String> {
+ if capability.desktop_protocol_version != Some(DESKTOP_PROTOCOL_VERSION) {
+ return Some("desktop_protocol_incompatible".to_string());
+ }
+ if capability.supports_api_only != Some(true) {
+ return Some("desktop_api_only_unsupported".to_string());
+ }
+ if capability.supports_provision_desktop_auth != Some(true) {
+ return capability
+ .desktop_auth_stale_reason
+ .clone()
+ .or_else(|| Some("desktop_auth_unsupported".to_string()));
+ }
+ if capability.desktop_manageability_version.unwrap_or(0) < DESKTOP_MANAGEABILITY_VERSION {
+ return Some("desktop_manageability_unsupported".to_string());
+ }
+ if capability.supports_desktop_backend_ownership != Some(true) {
+ return Some("desktop_backend_ownership_unsupported".to_string());
+ }
+ backend_version_stale_reason(capability.version.as_deref())
+}
+
+fn desktop_capability_ready(capability: &DesktopCapability) -> bool {
+ desktop_capability_stale_reason(capability).is_none()
+}
+
+pub(super) async fn probe_managed_bin(bin: PathBuf) -> ManagedProbe {
+ if !run_cli_probe(&bin, &["-h"]).await {
+ return ManagedProbe::Stale {
+ bin,
+ reason: "cli_unusable".to_string(),
+ };
+ }
+
+ let capability = probe_cli_capability(&bin).await;
+ if let Some(capability) = capability {
+ if desktop_capability_ready(&capability) {
+ return ManagedProbe::Ready { bin };
+ }
+ return ManagedProbe::Stale {
+ bin,
+ reason: desktop_capability_stale_reason(&capability)
+ .unwrap_or_else(|| "desktop_capability_incompatible".to_string()),
+ };
+ }
+
+ ManagedProbe::Stale {
+ bin,
+ reason: "desktop_capability_probe_failed".to_string(),
+ }
+}
+
+pub(super) async fn probe_managed_install() -> ManagedProbe {
+ match crate::process::find_unsloth_binary() {
+ Some(bin) => probe_managed_bin(bin).await,
+ None => ManagedProbe::Missing,
+ }
+}
+
+pub async fn managed_install_ready() -> bool {
+ matches!(probe_managed_install().await, ManagedProbe::Ready { .. })
+}
diff --git a/studio/src-tauri/src/preflight/types.rs b/studio/src-tauri/src/preflight/types.rs
new file mode 100644
index 00000000000..2d306d9a64c
--- /dev/null
+++ b/studio/src-tauri/src/preflight/types.rs
@@ -0,0 +1,44 @@
+use serde::{Deserialize, Serialize};
+use std::path::PathBuf;
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum DesktopPreflightDisposition {
+ NotInstalled,
+ ManagedReady,
+ ManagedStale,
+ OwnedReady,
+ OwnedStale,
+ AttachedReady,
+ ExternalConflict,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct DesktopPreflightResult {
+ pub disposition: DesktopPreflightDisposition,
+ pub reason: Option<String>,
+ pub port: Option<u16>,
+ pub can_auto_repair: bool,
+ pub managed_bin: Option<PathBuf>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ExternalBackendConflict {
+ pub port: u16,
+ pub reason: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(super) enum ManagedProbe {
+ Missing,
+ Ready { bin: PathBuf },
+ Stale { bin: PathBuf, reason: String },
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(super) enum BackendProbe {
+ Missing,
+ Ready { port: u16 },
+ Old { port: u16, reason: String },
+ ExternalConflict { port: u16, reason: String },
+}
diff --git a/studio/src-tauri/src/preflight/version.rs b/studio/src-tauri/src/preflight/version.rs
new file mode 100644
index 00000000000..b920c8744b6
--- /dev/null
+++ b/studio/src-tauri/src/preflight/version.rs
@@ -0,0 +1,163 @@
+use std::cmp::Ordering;
+
+pub(crate) const DESKTOP_PROTOCOL_VERSION: u16 = 1;
+pub(crate) const DESKTOP_MANAGEABILITY_VERSION: u16 = 1;
+// Explicit backend package minimum, not the desktop app Cargo version: backend
+// and app releases can diverge. When bumping, verify this package exists on PyPI.
+pub(super) const MIN_DESKTOP_BACKEND_VERSION: &str = "2026.5.3";
+
+#[derive(Debug, Eq, PartialEq)]
+pub(super) struct ParsedVersion {
+ release: [u64; 3],
+ suffix: VersionSuffix,
+}
+
+#[derive(Debug, Eq, PartialEq)]
+enum VersionSuffix {
+ Dev(u64),
+ Alpha(u64),
+ Beta(u64),
+ Rc(u64),
+ PreRelease(String),
+ Stable,
+ Build,
+ Post(u64),
+}
+
+pub(super) fn parse_version(value: &str) -> Option<ParsedVersion> {
+ let value = value.trim();
+ let mut parts = value.splitn(3, '.');
+ let major = parts.next()?.parse().ok()?;
+ let minor = parts.next()?.parse().ok()?;
+ let patch_and_suffix = parts.next()?;
+ let patch_len = patch_and_suffix
+ .find(|c: char| !c.is_ascii_digit())
+ .unwrap_or(patch_and_suffix.len());
+ if patch_len == 0 {
+ return None;
+ }
+ let suffix = parse_version_suffix(&patch_and_suffix[patch_len..])?;
+ Some(ParsedVersion {
+ release: [major, minor, patch_and_suffix[..patch_len].parse().ok()?],
+ suffix,
+ })
+}
+
+fn parse_version_suffix(suffix: &str) -> Option<VersionSuffix> {
+ if suffix.is_empty() {
+ return Some(VersionSuffix::Stable);
+ }
+
+ if let Some(value) = suffix.strip_prefix('+') {
+ return suffix_part_valid(value).then_some(VersionSuffix::Build);
+ }
+ if let Some(value) = suffix.strip_prefix('-') {
+ return suffix_part_valid(value)
+ .then(|| VersionSuffix::PreRelease(value.to_ascii_lowercase()));
+ }
+ if let Some(number) = parse_numbered_suffix(suffix, &[".post", "post"]) {
+ return number.map(VersionSuffix::Post);
+ }
+ if let Some(number) = parse_numbered_suffix(suffix, &[".dev", "dev"]) {
+ return number.map(VersionSuffix::Dev);
+ }
+ if let Some(number) = parse_numbered_suffix(suffix, &[".rc", "rc"]) {
+ return number.map(VersionSuffix::Rc);
+ }
+ if let Some(number) = parse_numbered_suffix(suffix, &["a"]) {
+ return number.map(VersionSuffix::Alpha);
+ }
+ if let Some(number) = parse_numbered_suffix(suffix, &["b"]) {
+ return number.map(VersionSuffix::Beta);
+ }
+
+ None
+}
+
+fn parse_numbered_suffix(suffix: &str, prefixes: &[&str]) -> Option<Option<u64>> {
+ for prefix in prefixes {
+ let Some(number) = suffix.strip_prefix(prefix) else {
+ continue;
+ };
+ if number.is_empty() {
+ return Some(Some(0));
+ }
+ return Some(number.parse().ok());
+ }
+ None
+}
+
+fn suffix_part_valid(value: &str) -> bool {
+ !value.is_empty()
+ && value.split('.').all(|part| {
+ !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
+ })
+}
+
+fn compare_versions(left: &ParsedVersion, right: &ParsedVersion) -> Ordering {
+ match left.release.cmp(&right.release) {
+ Ordering::Equal => compare_suffixes(&left.suffix, &right.suffix),
+ ordering => ordering,
+ }
+}
+
+fn compare_suffixes(left: &VersionSuffix, right: &VersionSuffix) -> Ordering {
+ let left_precedence = suffix_precedence(left);
+ let right_precedence = suffix_precedence(right);
+ if left_precedence != right_precedence {
+ return left_precedence.cmp(&right_precedence);
+ }
+
+ match (left, right) {
+ (VersionSuffix::Dev(left), VersionSuffix::Dev(right))
+ | (VersionSuffix::Alpha(left), VersionSuffix::Alpha(right))
+ | (VersionSuffix::Beta(left), VersionSuffix::Beta(right))
+ | (VersionSuffix::Rc(left), VersionSuffix::Rc(right))
+ | (VersionSuffix::Post(left), VersionSuffix::Post(right)) => left.cmp(right),
+ (VersionSuffix::PreRelease(left), VersionSuffix::PreRelease(right)) => left.cmp(right),
+ _ => Ordering::Equal,
+ }
+}
+
+fn suffix_precedence(suffix: &VersionSuffix) -> u8 {
+ match suffix {
+ VersionSuffix::Dev(_) => 0,
+ VersionSuffix::Alpha(_) => 1,
+ VersionSuffix::Beta(_) => 2,
+ VersionSuffix::Rc(_) | VersionSuffix::PreRelease(_) => 3,
+ VersionSuffix::Stable | VersionSuffix::Build => 4,
+ VersionSuffix::Post(_) => 5,
+ }
+}
+
+pub(super) fn backend_version_compatible(version: Option<&str>) -> bool {
+ let Some(version) = version else {
+ return false;
+ };
+ if cfg!(debug_assertions) && version == "dev" {
+ return true;
+ }
+ let Some(actual) = parse_version(version) else {
+ return false;
+ };
+ let Some(minimum) = parse_version(MIN_DESKTOP_BACKEND_VERSION) else {
+ return false;
+ };
+ compare_versions(&actual, &minimum) != Ordering::Less
+}
+
+pub(crate) fn backend_version_stale_reason(version: Option<&str>) -> Option<String> {
+ if backend_version_compatible(version) {
+ return None;
+ }
+ match version {
+ None | Some("") => Some("desktop_backend_version_missing".to_string()),
+ Some("dev") if !cfg!(debug_assertions) => {
+ Some("desktop_backend_version_invalid".to_string())
+ }
+ Some(value) if parse_version(value).is_none() => {
+ Some("desktop_backend_version_invalid".to_string())
+ }
+ Some(_) => Some("desktop_backend_version_too_old".to_string()),
+ }
+}
diff --git a/studio/src-tauri/src/process.rs b/studio/src-tauri/src/process.rs
index b64962aa2aa..01ef77f0987 100644
--- a/studio/src-tauri/src/process.rs
+++ b/studio/src-tauri/src/process.rs
@@ -7,28 +7,292 @@ use std::io::BufRead;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
+use std::time::Duration;
use tauri::{AppHandle, Emitter, Manager};
const MAX_LOG_LINES: usize = 1000;
+#[allow(dead_code)]
+pub(crate) enum OwnedBackendHandle {
+ Spawned {
+ child: Box<dyn ChildWrapper + Send>,
+ owner: Option<crate::desktop_backend_owner::BackendOwnerState>,
+ reported_port: Option<u16>,
+ pid: u32,
+ generation: u64,
+ },
+ Adopted {
+ owner: crate::desktop_backend_owner::BackendOwnerState,
+ port: u16,
+ pid: u32,
+ generation: u64,
+ },
+}
+
+#[allow(dead_code)]
+impl OwnedBackendHandle {
+ pub(crate) fn spawned(
+ child: Box<dyn ChildWrapper + Send>,
+ owner: Option<crate::desktop_backend_owner::BackendOwnerState>,
+ pid: u32,
+ generation: u64,
+ ) -> Self {
+ Self::Spawned {
+ child,
+ owner,
+ reported_port: None,
+ pid,
+ generation,
+ }
+ }
+
+ pub(crate) fn adopted(
+ owner: crate::desktop_backend_owner::BackendOwnerState,
+ port: u16,
+ pid: u32,
+ generation: u64,
+ ) -> Self {
+ Self::Adopted {
+ owner,
+ port,
+ pid,
+ generation,
+ }
+ }
+
+ pub(crate) fn port(&self) -> Option<u16> {
+ match self {
+ Self::Spawned { reported_port, .. } => *reported_port,
+ Self::Adopted { port, .. } => Some(*port),
+ }
+ }
+
+ fn set_reported_port(&mut self, port: u16) {
+ if let Self::Spawned {
+ reported_port,
+ owner,
+ ..
+ } = self
+ {
+ *reported_port = Some(port);
+ if let Some(owner) = owner.as_mut() {
+ if let Err(error) = owner.update_port(port) {
+ warn!("Could not update desktop backend owner metadata: {}", error);
+ }
+ }
+ }
+ }
+
+ fn spawned_child_mut(&mut self) -> Option<&mut Box<dyn ChildWrapper + Send>> {
+ match self {
+ Self::Spawned { child, .. } => Some(child),
+ Self::Adopted { .. } => None,
+ }
+ }
+
+ fn remove_owner_metadata(self) {
+ match self {
+ Self::Spawned {
+ owner: Some(owner), ..
+ }
+ | Self::Adopted { owner, .. } => owner.remove(),
+ Self::Spawned { owner: None, .. } => {}
+ }
+ }
+}
+
pub struct BackendProcess {
- pub child: Option<Box<dyn ChildWrapper + Send>>,
+ pub owned: Option<OwnedBackendHandle>,
pub port: Option<u16>,
pub logs: VecDeque<String>,
pub intentional_stop: bool,
pub generation: u64,
pub diagnostics_session: Option<BackendLog>,
+ pub adopted_watchdog_generation: Option<u64>,
+}
+
+impl BackendProcess {
+ pub(crate) fn has_owned_backend(&self) -> bool {
+ self.owned.is_some()
+ }
+
+ pub(crate) fn has_adopted_backend(&self) -> bool {
+ matches!(self.owned, Some(OwnedBackendHandle::Adopted { .. }))
+ }
+
+ pub(crate) fn owned_backend_port(&self) -> Option<u16> {
+ self.owned.as_ref().and_then(OwnedBackendHandle::port)
+ }
+}
+
+#[derive(Clone)]
+pub(crate) struct OwnedBackendSnapshot {
+ pub(crate) owner: Option<crate::desktop_backend_owner::BackendOwnerState>,
+ pub(crate) port: Option<u16>,
+ pub(crate) generation: u64,
+ pub(crate) is_adopted: bool,
+}
+
+pub(crate) struct AdoptedBackendState {
+ pub(crate) generation: u64,
+ pub(crate) newly_adopted: bool,
+}
+
+pub(crate) fn adopt_verified_backend(
+ state: &BackendState,
+ verified: crate::desktop_backend_owner::VerifiedOwnedBackend,
+) -> Result<AdoptedBackendState, String> {
+ let mut proc = state.lock().map_err(|e| e.to_string())?;
+ if proc.has_owned_backend() {
+ if proc.owned_backend_port() == Some(verified.port) {
+ proc.port = Some(verified.port);
+ return Ok(AdoptedBackendState {
+ generation: proc.generation,
+ newly_adopted: false,
+ });
+ }
+ return Err("Backend is already running.".to_string());
+ }
+
+ proc.generation = proc.generation.wrapping_add(1);
+ proc.port = Some(verified.port);
+ proc.logs.clear();
+ proc.intentional_stop = false;
+ proc.diagnostics_session = None;
+ proc.adopted_watchdog_generation = None;
+ proc.owned = Some(OwnedBackendHandle::adopted(
+ verified.owner,
+ verified.port,
+ verified.backend_pid,
+ verified.generation,
+ ));
+ Ok(AdoptedBackendState {
+ generation: proc.generation,
+ newly_adopted: true,
+ })
+}
+
+pub(crate) fn owned_backend_snapshot(
+ state: &BackendState,
+) -> Result<Option<OwnedBackendSnapshot>, String> {
+ let proc = state.lock().map_err(|e| e.to_string())?;
+ let snapshot = match proc.owned.as_ref() {
+ Some(OwnedBackendHandle::Spawned {
+ owner,
+ reported_port,
+ ..
+ }) => Some(OwnedBackendSnapshot {
+ owner: owner.clone(),
+ port: *reported_port,
+ generation: proc.generation,
+ is_adopted: false,
+ }),
+ Some(OwnedBackendHandle::Adopted { owner, port, .. }) => Some(OwnedBackendSnapshot {
+ owner: Some(owner.clone()),
+ port: Some(*port),
+ generation: proc.generation,
+ is_adopted: true,
+ }),
+ None => None,
+ };
+ Ok(snapshot)
+}
+
+pub(crate) fn record_owned_backend_port_if_current(
+ state: &BackendState,
+ generation: u64,
+ port: u16,
+) -> bool {
+ let mut proc = match state.lock() {
+ Ok(guard) => guard,
+ Err(poisoned) => poisoned.into_inner(),
+ };
+ if proc.generation != generation {
+ return false;
+ }
+ match proc.owned.as_mut() {
+ Some(OwnedBackendHandle::Spawned { .. }) => {
+ proc.port = Some(port);
+ if let Some(owned) = proc.owned.as_mut() {
+ owned.set_reported_port(port);
+ }
+ true
+ }
+ Some(OwnedBackendHandle::Adopted {
+ port: current_port, ..
+ }) if *current_port == port => {
+ proc.port = Some(port);
+ true
+ }
+ _ => false,
+ }
+}
+
+pub(crate) fn clear_adopted_backend_if_current(
+ state: &BackendState,
+ generation: u64,
+ port: Option<u16>,
+ reason: &str,
+) -> bool {
+ let mut proc = match state.lock() {
+ Ok(guard) => guard,
+ Err(poisoned) => poisoned.into_inner(),
+ };
+ if proc.generation != generation {
+ return false;
+ }
+ let matches_adopted = matches!(
+ proc.owned.as_ref(),
+ Some(OwnedBackendHandle::Adopted { port: current_port, .. })
+ if port.map_or(true, |port| port == *current_port)
+ );
+ if !matches_adopted {
+ return false;
+ }
+
+ warn!("Clearing adopted backend state after {reason}");
+ proc.owned = None;
+ proc.port = None;
+ proc.diagnostics_session = None;
+ proc.adopted_watchdog_generation = None;
+ true
+}
+
+pub(crate) fn claim_adopted_watchdog_if_current(state: &BackendState, generation: u64) -> bool {
+ let mut proc = match state.lock() {
+ Ok(guard) => guard,
+ Err(poisoned) => poisoned.into_inner(),
+ };
+ if proc.generation != generation || !proc.has_adopted_backend() {
+ return false;
+ }
+ if proc.adopted_watchdog_generation == Some(generation) {
+ return false;
+ }
+ proc.adopted_watchdog_generation = Some(generation);
+ true
+}
+
+pub(crate) fn clear_adopted_watchdog_if_current(state: &BackendState, generation: u64) {
+ let mut proc = match state.lock() {
+ Ok(guard) => guard,
+ Err(poisoned) => poisoned.into_inner(),
+ };
+ if proc.generation == generation && proc.adopted_watchdog_generation == Some(generation) {
+ proc.adopted_watchdog_generation = None;
+ }
}
impl Default for BackendProcess {
fn default() -> Self {
Self {
- child: None,
+ owned: None,
port: None,
logs: VecDeque::with_capacity(MAX_LOG_LINES),
intentional_stop: false,
generation: 0,
diagnostics_session: None,
+ adopted_watchdog_generation: None,
}
}
}
@@ -126,7 +390,10 @@ pub fn find_unsloth_binary() -> Option<std::path::PathBuf> {
mod tests {
use super::*;
use std::fs;
+ use std::io::{Read, Write};
+ use std::net::TcpListener;
use std::path::PathBuf;
+ use std::sync::mpsc;
use std::time::{SystemTime, UNIX_EPOCH};
fn temp_studio_dir(test_name: &str) -> PathBuf {
@@ -143,8 +410,8 @@ mod tests {
}
#[test]
- fn finds_new_layout_before_legacy_layout() {
- let temp = temp_studio_dir("new-before-legacy");
+ fn finds_new_layout_before_legacy_layout_and_falls_back() {
+ let temp = temp_studio_dir("layout-preference");
#[cfg(unix)]
let new_bin = temp.join("unsloth_studio/bin/unsloth");
@@ -160,34 +427,15 @@ mod tests {
fs::write(&new_bin, "").unwrap();
fs::write(&old_bin, "").unwrap();
- assert_eq!(find_unsloth_binary_in_studio_dir(&temp), Some(new_bin));
- fs::remove_dir_all(temp).unwrap();
- }
-
- #[test]
- fn finds_legacy_layout_when_new_missing() {
- let temp = temp_studio_dir("legacy");
-
- #[cfg(unix)]
- let old_bin = temp.join(".venv/bin/unsloth");
- #[cfg(windows)]
- let old_bin = temp.join(".venv/Scripts/unsloth.exe");
-
- fs::create_dir_all(old_bin.parent().unwrap()).unwrap();
- fs::write(&old_bin, "").unwrap();
-
+ assert_eq!(
+ find_unsloth_binary_in_studio_dir(&temp),
+ Some(new_bin.clone())
+ );
+ fs::remove_file(&new_bin).unwrap();
assert_eq!(find_unsloth_binary_in_studio_dir(&temp), Some(old_bin));
fs::remove_dir_all(temp).unwrap();
}
- #[test]
- fn returns_none_when_no_managed_layout_exists() {
- let temp = temp_studio_dir("none");
-
- assert_eq!(find_unsloth_binary_in_studio_dir(&temp), None);
- fs::remove_dir_all(temp).unwrap();
- }
-
#[test]
fn backend_args_always_enable_api_only() {
assert_eq!(
@@ -195,6 +443,62 @@ mod tests {
vec!["studio", "--api-only", "-H", "127.0.0.1", "-p", "8888"]
);
}
+
+ fn listening_non_studio_port() -> (u16, mpsc::Sender<()>, std::thread::JoinHandle<()>) {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ listener.set_nonblocking(true).unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let (tx, rx) = mpsc::channel::<()>();
+ let handle = std::thread::spawn(move || loop {
+ if rx.try_recv().is_ok() {
+ break;
+ }
+ match listener.accept() {
+ Ok((mut stream, _)) => {
+ let mut buf = [0_u8; 512];
+ let _ = stream.read(&mut buf);
+ let _ = stream.write_all(
+ b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
+ );
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ Err(_) => break,
+ }
+ });
+ (port, tx, handle)
+ }
+
+ #[test]
+ fn stop_backend_rolls_back_shutdown_flag_when_adopted_stop_fails() {
+ let (port, stop_listener, listener_thread) = listening_non_studio_port();
+ let state = new_backend_state();
+ let shutdown = new_shutdown_flag();
+ let owner = crate::desktop_backend_owner::test_owner_state(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "desktop-owner-token",
+ port,
+ );
+
+ {
+ let mut proc = state.lock().unwrap();
+ proc.generation = 7;
+ proc.port = Some(port);
+ proc.owned = Some(OwnedBackendHandle::adopted(owner, port, 1234, 3));
+ }
+
+ let error = stop_backend(&state, &shutdown, None)
+ .expect_err("adopted backend should refuse unsafe stop fallback");
+
+ assert!(error.contains("Refusing to stop adopted backend"));
+ assert!(!shutdown.load(Ordering::SeqCst));
+ assert!(state.lock().unwrap().has_adopted_backend());
+
+ let _ = stop_listener.send(());
+ let _ = std::net::TcpStream::connect(("127.0.0.1", port));
+ listener_thread.join().unwrap();
+ }
}
/// Find the unsloth binary, preferring the dev repo if available.
@@ -266,33 +570,9 @@ pub fn start_backend(
}
};
- shutdown.store(false, Ordering::SeqCst);
-
- // 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 start_line = format!("Starting backend: {:?} {}", bin, args.join(" "));
+ let pending_owner = crate::desktop_backend_owner::new_pending_owner();
let mut cmd = Command::new(&bin);
cmd.args(&args)
.stdout(Stdio::piped())
@@ -305,9 +585,20 @@ pub fn start_backend(
);
}
+ if let Some(owner) = pending_owner.as_ref() {
+ cmd.env(
+ crate::desktop_backend_owner::OWNER_TOKEN_ENV,
+ owner.token.as_str(),
+ );
+ cmd.env(
+ crate::desktop_backend_owner::OWNER_KIND_ENV,
+ crate::desktop_backend_owner::OWNER_KIND_TAURI,
+ );
+ }
+
// AppImage sets LD_LIBRARY_PATH to its bundled libs, which breaks the spawned
// Python process (wrong libpython/libz → "No module named encodings").
- // Only clear when running inside an AppImage — native .deb/.rpm installs may
+ // Only clear when running inside an AppImage — native package installs may
// need these env vars for custom CUDA or conda paths.
#[cfg(target_os = "linux")]
if std::env::var_os("APPIMAGE").is_some() {
@@ -322,58 +613,88 @@ pub fn start_backend(
cmd.env_remove("UNSLOTH_STUDIO_HOME");
cmd.env_remove("STUDIO_HOME");
- // On Windows, launch the backend directly with hidden-window flags.
- // The app process is assigned to a KILL_ON_JOB_CLOSE job in main.rs, so
- // children inherit crash-safe cleanup without the buggy per-child JobObject wrapper.
- #[cfg(windows)]
- let mut child: Box<dyn ChildWrapper + Send> = {
- use std::os::windows::process::CommandExt;
+ // Reset state, spawn, and store the child while holding the backend mutex.
+ // This keeps the no-child check atomic: a concurrent start/stop cannot slip
+ // into the old window between generation reset and child storage.
+ let (generation, backend_log, stdout, stderr) = {
+ let mut proc = state.lock().map_err(|e| e.to_string())?;
+ if proc.has_owned_backend() {
+ return Err("Backend is already running.".to_string());
+ }
- const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
- cmd.creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW);
- 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)
- };
+ shutdown.store(false, Ordering::SeqCst);
+ proc.generation = proc.generation.wrapping_add(1);
+ proc.port = None;
+ proc.logs.clear();
+ proc.intentional_stop = false;
+ proc.diagnostics_session = None;
+ proc.adopted_watchdog_generation = None;
+ proc.owned = None;
+ let generation = proc.generation;
- #[cfg(unix)]
- let mut child: Box<dyn ChildWrapper + Send> = {
- // 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| {
- let msg = format!("Failed to spawn backend: {}", e);
- diagnostics::record_backend_start_failure(
- diagnostics_state,
- Some(port),
- Some(generation),
- "spawn_backend",
- &msg,
- );
- msg
- })?
- };
+ let backend_log = diagnostics::begin_backend_session(diagnostics_state, port, generation);
- let stdout = child.stdout().take();
- let stderr = child.stderr().take();
+ // On Windows, launch the backend directly with hidden-window flags.
+ // The app process is assigned to a KILL_ON_JOB_CLOSE job in main.rs, so
+ // children inherit crash-safe cleanup without the buggy per-child JobObject wrapper.
+ #[cfg(windows)]
+ let mut child: Box<dyn ChildWrapper + Send> = {
+ use std::os::windows::process::CommandExt;
+
+ const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
+ cmd.creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW);
+ 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)
+ };
- // Store child in state for the already-selected generation.
- {
- let mut proc = state.lock().map_err(|e| e.to_string())?;
- proc.child = Some(child);
+ #[cfg(unix)]
+ let mut child: Box<dyn ChildWrapper + Send> = {
+ // 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| {
+ let msg = format!("Failed to spawn backend: {}", e);
+ diagnostics::record_backend_start_failure(
+ diagnostics_state,
+ Some(port),
+ Some(generation),
+ "spawn_backend",
+ &msg,
+ );
+ msg
+ })?
+ };
+
+ let backend_pid = child.id();
+ let stdout = child.stdout().take();
+ let stderr = child.stderr().take();
+ let owner = pending_owner.clone().and_then(|pending| {
+ crate::desktop_backend_owner::activate_owner(pending, port, generation, backend_pid)
+ });
+
+ proc.owned = Some(OwnedBackendHandle::spawned(
+ child,
+ owner,
+ backend_pid,
+ generation,
+ ));
proc.diagnostics_session = Some(backend_log.clone());
- }
+ (generation, backend_log, stdout, stderr)
+ };
+
+ info!("{}", start_line);
+ diagnostics::append_phase_line(&backend_log.handle, "meta", &start_line);
- // Spawn stdout reader thread
if let Some(stdout) = stdout {
let app_handle = app.clone();
let state_clone = Arc::clone(state);
@@ -392,7 +713,6 @@ pub fn start_backend(
});
}
- // Spawn stderr reader thread
if let Some(stderr) = stderr {
let app_handle = app.clone();
let state_clone = Arc::clone(state);
@@ -414,8 +734,133 @@ pub fn start_backend(
Ok(generation)
}
+async fn generic_backend_health_ok(port: u16) -> bool {
+ let client = match reqwest::Client::builder()
+ .timeout(Duration::from_secs(2))
+ .build()
+ {
+ Ok(client) => client,
+ Err(error) => {
+ warn!("Could not build backend validation client: {}", error);
+ return false;
+ }
+ };
+ let response = match client
+ .get(format!("http://127.0.0.1:{port}/api/health"))
+ .send()
+ .await
+ {
+ Ok(response) => response,
+ Err(error) => {
+ warn!(
+ "Backend port candidate {} failed health request: {}",
+ port, error
+ );
+ return false;
+ }
+ };
+ if !response.status().is_success() {
+ warn!(
+ "Backend port candidate {} returned HTTP {} from health",
+ port,
+ response.status()
+ );
+ return false;
+ }
+ let json = match response.json::<serde_json::Value>().await {
+ Ok(json) => json,
+ Err(error) => {
+ warn!(
+ "Backend port candidate {} returned invalid health JSON: {}",
+ port, error
+ );
+ return false;
+ }
+ };
+ let healthy = json
+ .get("status")
+ .and_then(|v| v.as_str())
+ .map(|s| s == "healthy")
+ .unwrap_or(false);
+ let service = json
+ .get("service")
+ .and_then(|v| v.as_str())
+ .map(|s| s == "Unsloth UI Backend")
+ .unwrap_or(false);
+ healthy && service
+}
+
+async fn validate_candidate_port(
+ app: AppHandle,
+ state: BackendState,
+ diagnostics_state: DiagnosticsState,
+ session_id: String,
+ generation: u64,
+ port: u16,
+) {
+ let owner = {
+ let proc = match state.lock() {
+ Ok(proc) => proc,
+ Err(error) => {
+ warn!("Backend state unavailable for port validation: {}", error);
+ return;
+ }
+ };
+ if proc.generation != generation || proc.port.is_some() {
+ return;
+ }
+ match proc.owned.as_ref() {
+ Some(OwnedBackendHandle::Spawned { owner, .. }) => owner.clone(),
+ _ => return,
+ }
+ };
+
+ let valid = if let Some(owner) = owner {
+ matches!(
+ crate::desktop_backend_owner::probe_owned_backend_state(owner, Some(port), false).await,
+ crate::desktop_backend_owner::OwnedBackendProbe::Verified(
+ crate::desktop_backend_owner::VerifiedOwnedBackend { port: verified_port, .. }
+ ) if verified_port == port
+ )
+ } else {
+ generic_backend_health_ok(port).await
+ };
+
+ if !valid {
+ warn!("Ignoring unverified TAURI_PORT candidate {}", port);
+ return;
+ }
+
+ let should_emit = {
+ let mut proc = match state.lock() {
+ Ok(proc) => proc,
+ Err(error) => {
+ warn!("Backend state unavailable after port validation: {}", error);
+ return;
+ }
+ };
+ if proc.generation != generation || proc.port.is_some() {
+ false
+ } else if matches!(proc.owned, Some(OwnedBackendHandle::Spawned { .. })) {
+ proc.port = Some(port);
+ if let Some(owned) = proc.owned.as_mut() {
+ owned.set_reported_port(port);
+ }
+ true
+ } else {
+ false
+ }
+ };
+
+ if should_emit {
+ diagnostics::record_backend_port(&diagnostics_state, &session_id, port);
+ info!("Validated backend port: {}", port);
+ let _ = app.emit("server-port", port);
+ }
+}
+
/// Read lines from a child process stream (stdout or stderr).
-/// For stdout, parse TAURI_PORT=(\d+) to detect the actual port.
+/// For stdout, parse TAURI_PORT=(\d+) candidates for async validation.
/// When stdout closes and the stop was not intentional, emit server-crashed.
fn read_output_stream<R: std::io::Read>(
stream: R,
@@ -448,7 +893,6 @@ fn read_output_stream<R: std::io::Read>(
&text,
);
- // Check for TAURI_PORT on stdout only
let detected_port = if !is_stderr {
port_re
.captures(&text)
@@ -461,15 +905,12 @@ fn read_output_stream<R: std::io::Read>(
// 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 mut candidate_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);
- }
+ candidate_port = detected_port;
if proc.logs.len() >= MAX_LOG_LINES {
proc.logs.pop_front();
}
@@ -484,19 +925,26 @@ fn read_output_stream<R: std::io::Read>(
break;
}
- 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);
+ if let Some(port) = candidate_port {
+ let app_handle = app.clone();
+ let state_clone = Arc::clone(state);
+ let diagnostics_clone = diagnostics_state.clone();
+ let session_id = backend_log.session_id.clone();
+ tauri::async_runtime::spawn(async move {
+ validate_candidate_port(
+ app_handle,
+ state_clone,
+ diagnostics_clone,
+ session_id,
+ generation,
+ port,
+ )
+ .await;
+ });
}
info!("[backend] {}", log_line);
- // Emit to frontend
let _ = app.emit("server-log", &log_line);
}
Err(e) => {
@@ -519,7 +967,11 @@ fn read_output_stream<R: std::io::Read>(
return;
}
let intentional = proc.intentional_stop;
- let exited = if let Some(ref mut child) = proc.child {
+ let exited = if let Some(child) = proc
+ .owned
+ .as_mut()
+ .and_then(OwnedBackendHandle::spawned_child_mut)
+ {
match child.try_wait() {
Ok(Some(status)) => {
info!("Backend stdout stream ended with status: {}", status);
@@ -540,7 +992,10 @@ fn read_output_stream<R: std::io::Read>(
};
if exited {
- proc.child = None;
+ if let Some(owned) = proc.owned.take() {
+ owned.remove_owner_metadata();
+ }
+ proc.port = None;
proc.diagnostics_session = None;
emit_crash = !intentional;
}
@@ -561,55 +1016,101 @@ fn read_output_stream<R: std::io::Read>(
}
}
-/// 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,
- 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);
+fn wait_for_child_exit(child: &mut Box<dyn ChildWrapper + Send>, label: &str) -> bool {
+ for _ in 0..50 {
+ match child.try_wait() {
+ Ok(Some(status)) => {
+ info!("{} exited with status: {}", label, status);
+ return true;
+ }
+ Ok(None) => std::thread::sleep(Duration::from_millis(100)),
+ Err(e) => {
+ warn!("Error polling {} process: {}", label, e);
+ return false;
+ }
+ }
}
+ false
+}
- // 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.
- let mut child = {
- let mut proc = match state.lock() {
- Ok(guard) => guard,
- Err(poisoned) => {
- warn!("Backend state mutex poisoned, recovering for cleanup");
- poisoned.into_inner()
- }
- };
- proc.intentional_stop = true;
- proc.child.take()
- };
+fn wait_for_port_disconnect(port: u16, timeout: Duration) -> bool {
+ let started = std::time::Instant::now();
+ while started.elapsed() < timeout {
+ if !crate::desktop_backend_owner::port_is_listening_blocking(
+ port,
+ Duration::from_millis(150),
+ ) {
+ return true;
+ }
+ std::thread::sleep(Duration::from_millis(100));
+ }
+ false
+}
- let Some(ref mut child) = child else {
- return Ok(()); // Nothing running
- };
+fn try_exact_port_http_shutdown(port: u16, label: &str) -> bool {
+ match crate::desktop_backend_owner::exact_port_http_shutdown_blocking(port) {
+ Ok(()) => {
+ info!(
+ "{} exact-port HTTP shutdown requested on port {}",
+ label, port
+ );
+ true
+ }
+ Err(error) => {
+ warn!(
+ "{} exact-port HTTP shutdown failed on port {}: {}",
+ label, port, error
+ );
+ false
+ }
+ }
+}
+
+fn remove_optional_owner(owner: Option<crate::desktop_backend_owner::BackendOwnerState>) {
+ if let Some(owner) = owner {
+ owner.remove();
+ }
+}
- let pid = child.id();
- info!("Stopping backend process group (pid {})", pid);
+fn stop_spawned_backend(
+ mut child: Box<dyn ChildWrapper + Send>,
+ owner: Option<crate::desktop_backend_owner::BackendOwnerState>,
+ reported_port: Option<u16>,
+ pid: u32,
+) -> Result<(), String> {
+ #[cfg(not(windows))]
+ let _ = reported_port;
+ info!("Stopping spawned backend process group (pid {})", pid);
+
+ #[cfg(windows)]
+ if let Some(port) = reported_port {
+ let verified = owner
+ .as_ref()
+ .map(|owner| owner.verifies_exact_port_blocking(port))
+ .unwrap_or(false);
+ if verified
+ && try_exact_port_http_shutdown(port, "Spawned backend")
+ && wait_for_child_exit(&mut child, "Backend")
+ {
+ remove_optional_owner(owner);
+ return Ok(());
+ }
+ }
- // Send SIGTERM to the entire process group (negative PID = group signal).
- // This gives Python and any workers a chance to shut down gracefully.
#[cfg(unix)]
{
if pid > i32::MAX as u32 {
- // PID too large for i32 negation, fall back to direct kill
warn!("PID {} exceeds i32 range, using direct kill", pid);
let _ = child.kill();
let _ = child.wait();
+ remove_optional_owner(owner);
return Ok(());
}
unsafe {
libc::kill(-(pid as i32), libc::SIGTERM);
}
}
+
#[cfg(windows)]
{
unsafe {
@@ -620,21 +1121,9 @@ pub fn stop_backend(
}
}
- // Poll for up to 5 seconds (50 iterations * 100ms)
- for _ in 0..50 {
- match child.try_wait() {
- Ok(Some(status)) => {
- info!("Backend exited with status: {}", status);
- return Ok(());
- }
- Ok(None) => {
- std::thread::sleep(std::time::Duration::from_millis(100));
- }
- Err(e) => {
- warn!("Error polling backend process: {}", e);
- break;
- }
- }
+ if wait_for_child_exit(&mut child, "Backend") {
+ remove_optional_owner(owner);
+ return Ok(());
}
#[cfg(windows)]
@@ -643,22 +1132,197 @@ pub fn stop_backend(
"Backend did not exit gracefully, force killing process tree (pid {})",
pid
);
- force_kill_process_tree(pid, child, "Backend");
+ force_kill_process_tree(pid, &mut child, "Backend");
+ remove_optional_owner(owner);
return Ok(());
}
#[cfg(unix)]
{
- // Force kill the process group on Unix
warn!(
"Backend did not exit gracefully, force killing group (pid {})",
pid
);
let _ = child.kill();
-
- // Reap the process
let _ = child.wait();
+ remove_optional_owner(owner);
info!("Backend process group forcefully stopped");
Ok(())
}
}
+
+fn stop_adopted_backend(
+ owner: crate::desktop_backend_owner::BackendOwnerState,
+ port: u16,
+ pid: u32,
+) -> Result<(), String> {
+ info!(
+ "Stopping adopted desktop-owned backend on exact port {} (pid {})",
+ port, pid
+ );
+
+ if !owner.verifies_exact_port_blocking(port) {
+ return Err(
+ "Refusing to stop adopted backend because ownership could not be verified".to_string(),
+ );
+ }
+
+ if try_exact_port_http_shutdown(port, "Adopted backend")
+ && wait_for_port_disconnect(port, Duration::from_secs(5))
+ {
+ owner.remove();
+ return Ok(());
+ }
+
+ Err(
+ "Adopted backend did not stop via exact-port HTTP shutdown; refusing PID fallback without verified port-to-PID binding"
+ .to_string(),
+ )
+}
+
+/// Graceful shutdown of owned backend handles.
+/// Unix spawned: SIGTERM to process group -> wait -> SIGKILL.
+/// Windows spawned: exact-port HTTP shutdown -> CTRL_BREAK_EVENT -> taskkill.
+/// Adopted handles: exact-port HTTP shutdown only; PID fallback is refused
+/// until the backend process identity can be bound to the verified port.
+pub fn stop_backend(
+ state: &BackendState,
+ shutdown: &ShutdownFlag,
+ diagnostics_state: Option<&DiagnosticsState>,
+) -> Result<(), String> {
+ stop_backend_inner(state, shutdown, diagnostics_state, true)
+}
+
+/// Stop before update/repair mutations without letting the watchdog exit unless the stop succeeds.
+pub fn stop_backend_for_mutation(
+ state: &BackendState,
+ shutdown: &ShutdownFlag,
+ diagnostics_state: Option<&DiagnosticsState>,
+) -> Result<(), String> {
+ stop_backend_inner(state, shutdown, diagnostics_state, false)
+}
+
+fn stop_backend_inner(
+ state: &BackendState,
+ shutdown: &ShutdownFlag,
+ diagnostics_state: Option<&DiagnosticsState>,
+ signal_shutdown_before_stop: bool,
+) -> Result<(), String> {
+ let previous_shutdown = shutdown.load(Ordering::SeqCst);
+ if signal_shutdown_before_stop {
+ shutdown.store(true, Ordering::SeqCst);
+ }
+ if let Some(diagnostics_state) = diagnostics_state {
+ diagnostics::record_backend_intentional_stop(diagnostics_state);
+ }
+
+ enum StopTarget {
+ Spawned(OwnedBackendHandle),
+ Adopted {
+ owner: crate::desktop_backend_owner::BackendOwnerState,
+ port: u16,
+ pid: u32,
+ generation: u64,
+ local_generation: u64,
+ },
+ }
+
+ let target = {
+ let mut proc = match state.lock() {
+ Ok(guard) => guard,
+ Err(poisoned) => {
+ warn!("Backend state mutex poisoned, recovering for cleanup");
+ poisoned.into_inner()
+ }
+ };
+ proc.intentional_stop = true;
+ match proc.owned.as_ref() {
+ Some(OwnedBackendHandle::Spawned { .. }) => {
+ proc.port = None;
+ proc.diagnostics_session = None;
+ proc.adopted_watchdog_generation = None;
+ proc.owned.take().map(StopTarget::Spawned)
+ }
+ Some(OwnedBackendHandle::Adopted {
+ owner,
+ port,
+ pid,
+ generation,
+ }) => Some(StopTarget::Adopted {
+ owner: owner.clone(),
+ port: *port,
+ pid: *pid,
+ generation: *generation,
+ local_generation: proc.generation,
+ }),
+ None => None,
+ }
+ };
+
+ let result = match target {
+ Some(StopTarget::Spawned(OwnedBackendHandle::Spawned {
+ child,
+ owner,
+ reported_port,
+ pid,
+ ..
+ })) => stop_spawned_backend(child, owner, reported_port, pid),
+ Some(StopTarget::Adopted {
+ owner,
+ port,
+ pid,
+ generation,
+ local_generation,
+ }) => {
+ if let Err(error) = stop_adopted_backend(owner, port, pid) {
+ if !crate::desktop_backend_owner::port_is_listening_blocking(
+ port,
+ Duration::from_millis(150),
+ ) {
+ clear_adopted_backend_if_current(
+ state,
+ local_generation,
+ Some(port),
+ "adopted port disappeared during stop",
+ );
+ Ok(())
+ } else {
+ Err(error)
+ }
+ } else {
+ let mut proc = match state.lock() {
+ Ok(guard) => guard,
+ Err(poisoned) => {
+ warn!("Backend state mutex poisoned, recovering after adopted stop");
+ poisoned.into_inner()
+ }
+ };
+ if matches!(
+ proc.owned.as_ref(),
+ Some(OwnedBackendHandle::Adopted {
+ port: current_port,
+ pid: current_pid,
+ generation: current_generation,
+ ..
+ }) if *current_port == port && *current_pid == pid && *current_generation == generation
+ ) {
+ proc.owned = None;
+ proc.port = None;
+ proc.diagnostics_session = None;
+ proc.adopted_watchdog_generation = None;
+ }
+ Ok(())
+ }
+ }
+ Some(StopTarget::Spawned(OwnedBackendHandle::Adopted { .. })) => unreachable!(),
+ None => Ok(()),
+ };
+
+ if result.is_ok() && !signal_shutdown_before_stop {
+ shutdown.store(true, Ordering::SeqCst);
+ } else if result.is_err() && signal_shutdown_before_stop {
+ shutdown.store(previous_shutdown, Ordering::SeqCst);
+ }
+
+ result
+}
diff --git a/studio/src-tauri/tauri.conf.json b/studio/src-tauri/tauri.conf.json
index eed7c1f3524..d4d706cc145 100644
--- a/studio/src-tauri/tauri.conf.json
+++ b/studio/src-tauri/tauri.conf.json
@@ -34,7 +34,7 @@
"updater": {
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEQ2RDhGMDMzNDNEMTlGMkQKUldRdG45RkRNL0RZMXZsaVo2TElUQlVHb1hVNWEyajhUOGFXeTdNVDFZTFdBVUtlZUh5L2wwWVYK",
"endpoints": [
- "https://github.com/unslothai/unsloth/releases/latest/download/latest.json"
+ "https://github.com/unslothai/unsloth/releases/download/desktop-latest/latest.json"
],
"windows": {
"installMode": "passive"
@@ -74,9 +74,6 @@
"linux": {
"deb": {
"postRemoveScript": "./linux/postremove.sh"
- },
- "rpm": {
- "postRemoveScript": "./linux/postremove.sh"
}
}
}
diff --git a/tests/test_studio_install_workspace_guard.py b/tests/test_studio_install_workspace_guard.py
index d077cdb8248..c9aa3b27448 100644
--- a/tests/test_studio_install_workspace_guard.py
+++ b/tests/test_studio_install_workspace_guard.py
@@ -639,18 +639,26 @@ def test_tauri_preflight_scrubs_studio_home_env():
"""All three Tauri CLI-spawn sites that lacked the scrub must now
env_remove UNSLOTH_STUDIO_HOME and STUDIO_HOME, mirroring
process.rs / install.rs / desktop_auth.rs / update.rs."""
- preflight = (
- REPO_ROOT / "studio" / "src-tauri" / "src" / "preflight.rs"
- ).read_text()
+ # preflight was originally a single .rs file; PR #5341 split it into
+ # a directory of submodules (backend / managed / types / version).
+ # Read whichever shape is on disk so the guard stays valid through
+ # future reorgs as long as the scrub calls live somewhere under
+ # studio/src-tauri/src/preflight*.
+ preflight_root = REPO_ROOT / "studio" / "src-tauri" / "src"
+ preflight_paths = [
+ preflight_root / "preflight.rs",
+ *(preflight_root / "preflight").glob("*.rs"),
+ ]
+ preflight = "\n".join(p.read_text() for p in preflight_paths if p.exists())
commands = (REPO_ROOT / "studio" / "src-tauri" / "src" / "commands.rs").read_text()
- # Both functions in preflight.rs (run_cli_probe + probe_cli_capability)
- # must scrub. Count occurrences -- expect 2 in preflight, 1 in commands.
+ # Both functions (run_cli_probe + probe_cli_capability) must scrub.
+ # Count occurrences -- expect 2 in preflight (one per fn), 1 in commands.
assert (
preflight.count('cmd.env_remove("UNSLOTH_STUDIO_HOME")') >= 2
- ), "preflight.rs must scrub UNSLOTH_STUDIO_HOME in both run_cli_probe and probe_cli_capability"
+ ), "preflight must scrub UNSLOTH_STUDIO_HOME in both run_cli_probe and probe_cli_capability"
assert (
preflight.count('cmd.env_remove("STUDIO_HOME")') >= 2
- ), "preflight.rs must scrub STUDIO_HOME in both run_cli_probe and probe_cli_capability"
+ ), "preflight must scrub STUDIO_HOME in both run_cli_probe and probe_cli_capability"
assert (
'cmd.env_remove("UNSLOTH_STUDIO_HOME")' in commands
), "commands.rs check_install_status must scrub UNSLOTH_STUDIO_HOME"
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 74f52feeccc..714ace45339 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -1121,8 +1121,10 @@ def desktop_capabilities(
):
payload = {
"desktop_protocol_version": 1,
+ "desktop_manageability_version": 1,
"supports_provision_desktop_auth": True,
"supports_api_only": True,
+ "supports_desktop_backend_ownership": True,
"version": "unknown",
}
try: