Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Desktop: Add GPU rendering setting with a Linux launch-crash fallback (#15482)
Etherl7af6ba3dde89
diff --git a/.github/workflows/studio-tauri-smoke.yml b/.github/workflows/studio-tauri-smoke.ymlindex d323f45268c..0ecbe31a119 100644--- a/.github/workflows/studio-tauri-smoke.yml+++ b/.github/workflows/studio-tauri-smoke.yml@@ -219,6 +219,64 @@ jobs:fiecho "10 of 10 launches reached the backend spawn and stayed up"+ # GPU rendering setting: Off must keep a working transport on X11, and a GPU launch that+ # dies with Wayland Error 71 before the window is ready must relaunch on the CPU path.+ # UNSLOTH_TEST_GPU_ERROR71 (debug builds only) sends the real GTK message through the hook.+ - name: GPU rendering Off and the Error 71 fallback under Xvfb+ run: |+ set -u+ BIN="$PWD/studio/src-tauri/target/debug/unsloth-studio"+ probe() {+ name="$1"; shift+ H="$RUNNER_TEMP/gpu-$name"+ rm -rf "$H"+ mkdir -p "$H/.unsloth/studio/unsloth_studio/bin" "$H/.config/ai.unsloth.studio" "$H/xdg"+ cp "$RUNNER_TEMP/stub/unsloth" "$H/.unsloth/studio/unsloth_studio/bin/unsloth"+ if [ -n "${SETTING:-}" ]; then+ printf '%s\n' "$SETTING" > "$H/.config/ai.unsloth.studio/gpu-rendering-v1"+ fi+ D=$((90 + ${#name}))+ Xvfb ":$D" -screen 0 1440x900x24 -nolisten tcp > "launch-logs/xvfb-gpu-$name.log" 2>&1 &+ XV=$!+ for _ in $(seq 1 40); do [ -e "/tmp/.X11-unix/X$D" ] && break; sleep 0.25; done+ (+ export DISPLAY=":$D" HOME="$H" XDG_RUNTIME_DIR="$H/xdg" XDG_CONFIG_HOME="$H/.config"+ export G_MESSAGES_DEBUG=all RUST_BACKTRACE=full "$@"+ unset UNSLOTH_STUDIO_HOME STUDIO_HOME+ exec "$BIN"+ ) > "launch-logs/app-gpu-$name.log" 2>&1 &+ APP=$!+ for _ in $(seq 1 25); do kill -0 "$APP" 2>/dev/null || break; sleep 1; done+ up=0+ kill -0 "$APP" 2>/dev/null && up=1+ kill -TERM "$APP" 2>/dev/null || true+ wait "$APP" 2>/dev/null || true+ kill "$XV" 2>/dev/null || true+ wait "$XV" 2>/dev/null || true+ LOG="launch-logs/app-gpu-$name.log"+ if [ "$up" != 1 ] || ! grep -q "start_managed_server spawned" "$LOG"; then+ echo "::error::GPU rendering $name launch did not stay up"+ tail -40 "$LOG"+ return 1+ fi+ }++ mkdir -p launch-logs+ SETTING=off probe off+ grep -q "GPU rendering: setting=off" launch-logs/app-gpu-off.log+ grep -q "GPU rendering off (setting); set WEBKIT_DMABUF_RENDERER_FORCE_SHM=1 WEBKIT_DISABLE_COMPOSITING_MODE=1" \+ launch-logs/app-gpu-off.log || { echo "::error::Off did not take the X11 CPU path"; exit 1; }+ echo "Off: X11 CPU path, stayed up"++ SETTING= probe crash UNSLOTH_TEST_GPU_ERROR71=1+ LOG=launch-logs/app-gpu-crash.log+ grep -q "Error 71 (Protocol error) dispatching to Wayland display" "$LOG"+ grep -q "fell back to the CPU path after a launch crash" "$LOG" \+ || { echo "::error::no CPU fallback after the simulated Error 71"; tail -40 "$LOG"; exit 1; }+ FLAG="$RUNNER_TEMP/gpu-crash/.config/ai.unsloth.studio/gpu-rendering-unsafe-v1"+ grep -q "reason=error71" "$FLAG" || { echo "::error::fallback flag not written"; exit 1; }+ echo "Error 71: fell back to the CPU path, flag written, stayed up"+- name: Upload launch logsif: failure()uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2@@ -286,6 +344,52 @@ jobs:working-directory: studio/src-taurirun: cargo check --all-targets --release+ - name: Install pinned Tauri CLI (matches release-desktop.yml)+ run: npm ci --prefix studio --no-fund --no-audit++ - name: Tauri debug build (Windows, no bundle)+ env:+ TAURI_SIGNING_PRIVATE_KEY: ''+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ''+ run: npx --prefix studio tauri build --debug --no-bundle++ # GPU rendering Off must reach WebView2 as --disable-gpu without dropping wry's default+ # flags; Auto must leave the arguments alone. The second launch follows the first at once,+ # so a WebView2 that cannot switch arguments on a fast relaunch fails here.+ - name: GPU rendering Off reaches WebView2+ shell: pwsh+ run: |+ $bin = Resolve-Path "studio/src-tauri/target/debug/unsloth-studio.exe"+ $cfg = Join-Path $env:APPDATA "ai.unsloth.studio"+ New-Item -ItemType Directory -Force $cfg | Out-Null+ function Get-Browser {+ Get-CimInstance Win32_Process -Filter "Name='msedgewebview2.exe'" |+ Where-Object { $_.CommandLine -notmatch '--type=' -and $_.CommandLine -match 'ai\.unsloth\.studio\\EBWebView' }+ }+ function Stop-App($app) {+ Stop-Process -Id $app.Id -Force -ErrorAction SilentlyContinue+ Get-Browser | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }+ }+ function Probe($setting) {+ Set-Content -Path (Join-Path $cfg "gpu-rendering-v1") -Value $setting+ $app = Start-Process -FilePath $bin -PassThru+ $browser = $null+ for ($i = 0; $i -lt 90 -and -not $browser; $i++) { Start-Sleep 1; $browser = Get-Browser }+ if (-not $browser) { Stop-App $app; throw "no WebView2 browser process for setting=$setting" }+ $line = ($browser | Select-Object -First 1).CommandLine+ Write-Host "setting=$setting -> $line"+ Start-Sleep 20+ if ($app.HasExited) { throw "app exited (code $($app.ExitCode)) with setting=$setting" }+ Stop-App $app+ return $line+ }+ $off = Probe "off"+ if ($off -notmatch '--disable-gpu') { throw "Off: --disable-gpu missing" }+ if ($off -notmatch 'msSmartScreenProtection') { throw "Off: wry's default --disable-features was dropped" }+ $auto = Probe "auto"+ if ($auto -match '--disable-gpu') { throw "Auto: --disable-gpu present" }+ Write-Host "Off passes --disable-gpu with wry's defaults; Auto leaves the arguments alone"+macos-unit-tests:if: github.event_name != 'pull_request' || !github.event.pull_request.draftname: Rust unit tests (macos)diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.tsindex 516d6877338..bbc20a350d0 100644--- a/studio/frontend/scripts/check-bundle-budget.ts+++ b/studio/frontend/scripts/check-bundle-budget.ts@@ -439,8 +439,12 @@ export const BUDGET = {// (5,942,150 -> 5,972,134 B raw, 1,836,750 -> 1,847,702 B transfer, ed9857c0c3 -> 39b8a6ce13, Node 24,// 85 chunks): its color themes are read by the theme store at startup, and loading its dialog on first// open saves 3 KB transfer but adds five startup chunks. Raised by that growth.- transferBytes: 1_849_773,- rawBytes: 5_989_442,+ // The GPU rendering setting (#15482) adds 1,948 B raw / 637 B transfer (5,977,895 -> 5,979,843 B raw,+ // 1,849,311 -> 1,849,948 B transfer against b80df648bf, one machine and build, Node 22, 85 chunks both): the app+ // provider reports a ready renderer through the setting's API module at startup, plus the setting's strings in+ // the eager English catalog and its search rows. Raised by that.+ transferBytes: 1_850_410,+ rawBytes: 5_991_390,};// Chunk count is not budgeted: splitting a page out raises it while lowering bytes.diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsxindex 55126d69abd..0098ede50aa 100644--- a/studio/frontend/src/app/provider.tsx+++ b/studio/frontend/src/app/provider.tsx@@ -39,6 +39,7 @@ import {applyCustomizationToDocument,applyInterfaceScale,getAppliedInterfaceZoom,+ notifyRendererReady,subscribeAppliedInterfaceZoom,useAppearanceCustomStore,useInterfaceScaleStore,@@ -346,6 +347,7 @@ async function showSetupWindow(isCurrent: WindowLayoutGuard): Promise<void> {if (await wasLaunchedHidden()) return;if (!isCurrent()) return;await win.show();+ void notifyRendererReady();}async function enforceWindowSizeBounds(@@ -439,6 +441,7 @@ async function applyAppWindowLayout(if (hiddenAtLaunch) return false;if (!isCurrent()) return false;await win.show();+ void notifyRendererReady();return true;},waitForSettled: hiddenAtLaunch@@ -470,6 +473,7 @@ async function showWindowFallback(): Promise<void> {await win.setResizable(true);if (await wasLaunchedHidden()) return;await win.show();+ void notifyRendererReady();}function getTauriWindowMode(diff --git a/studio/frontend/src/features/settings/api/gpu-rendering.ts b/studio/frontend/src/features/settings/api/gpu-rendering.tsnew file mode 100644index 00000000000..5500c2323a0--- /dev/null+++ b/studio/frontend/src/features/settings/api/gpu-rendering.ts@@ -0,0 +1,61 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { isTauri } from "@/lib/api-base";++export type GpuRenderingSetting = "auto" | "on" | "off";++export interface GpuRenderingStatus {+ setting: GpuRenderingSetting;+ /** False on macOS, where WebKit always renders with the GPU. */+ configurable: boolean;+ restartRequired: boolean;+ /** GPU rendering crashed at launch, so this launch fell back to CPU rendering. */+ fallbackActive: boolean;+ /** Name of the environment variable that overrides the setting. */+ envOverride: string | null;+ /** Runtime WebKitGTK version; set on Linux Wayland below 2.54.2 only. */+ oldWebkitWarning: string | null;+ /** NVIDIA driver branch; set on Linux X11 below 610, where On keeps compositing off. */+ oldDriverWarning: string | null;+}++export async function loadGpuRendering(): Promise<GpuRenderingStatus> {+ const { invoke } = await import("@tauri-apps/api/core");+ return invoke<GpuRenderingStatus>("get_gpu_rendering");+}++export async function updateGpuRendering(+ value: GpuRenderingSetting,+): Promise<GpuRenderingStatus> {+ const { invoke } = await import("@tauri-apps/api/core");+ return invoke<GpuRenderingStatus>("set_gpu_rendering", { value });+}++/** False when a quit is already pending; otherwise the app quits through its usual confirmations. */+export async function relaunchToApplyGpuRendering(): Promise<boolean> {+ const { invoke } = await import("@tauri-apps/api/core");+ return invoke<boolean>("relaunch_to_apply_gpu_rendering");+}++function nextFrame(): Promise<void> {+ return new Promise((resolve) => {+ window.requestAnimationFrame(() => resolve());+ });+}++/**+ * Tells the desktop shell the window has painted, which ends the GPU startup+ * watch. Waits two frames so the first frame after show() has been drawn.+ */+export async function notifyRendererReady(): Promise<void> {+ if (!isTauri) return;+ try {+ await nextFrame();+ await nextFrame();+ const { invoke } = await import("@tauri-apps/api/core");+ await invoke("renderer_ready");+ } catch {+ // Older shells lack the command, and the shell has its own ready path.+ }+}diff --git a/studio/frontend/src/features/settings/components/gpu-rendering-segmented.tsx b/studio/frontend/src/features/settings/components/gpu-rendering-segmented.tsxnew file mode 100644index 00000000000..0da5a019879--- /dev/null+++ b/studio/frontend/src/features/settings/components/gpu-rendering-segmented.tsx@@ -0,0 +1,64 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { type TranslationKey, useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { motion, useReducedMotionConfig } from "motion/react";+import type { GpuRenderingSetting } from "../api/gpu-rendering";++const OPTIONS: { value: GpuRenderingSetting; labelKey: TranslationKey }[] = [+ { value: "auto", labelKey: "settings.appearance.gpuRendering.auto" },+ { value: "on", labelKey: "settings.appearance.gpuRendering.on" },+ { value: "off", labelKey: "settings.appearance.gpuRendering.off" },+];++export function GpuRenderingSegmented({+ value,+ onChange,+ disabled = false,+}: {+ value: GpuRenderingSetting | null;+ onChange: (value: GpuRenderingSetting) => void;+ disabled?: boolean;+}) {+ const t = useT();+ const reduced = useReducedMotionConfig();+ return (+ <div className="hub-tab-toggle inline-flex h-8 items-center rounded-full">+ {OPTIONS.map((opt) => {+ const active = value === opt.value;+ return (+ <button+ key={opt.value}+ type="button"+ onClick={() => onChange(opt.value)}+ aria-pressed={active}+ disabled={disabled}+ className={cn(+ "relative flex h-8 items-center rounded-full px-3 text-xs font-medium transition-colors",+ disabled && "cursor-not-allowed",+ active+ ? "text-foreground"+ : disabled+ ? "text-muted-foreground/45"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {active && (+ <motion.span+ layoutId="gpu-rendering-pill"+ className="hub-tab-toggle-pill absolute inset-0 rounded-full"+ transition={+ reduced+ ? { duration: 0 }+ : { type: "spring", stiffness: 500, damping: 35, mass: 0.5 }+ }+ />+ )}+ <span className="relative z-10">{t(opt.labelKey)}</span>+ </button>+ );+ })}+ </div>+ );+}diff --git a/studio/frontend/src/features/settings/gpu-rendering-notes.ts b/studio/frontend/src/features/settings/gpu-rendering-notes.tsnew file mode 100644index 00000000000..1c3c5e9876e--- /dev/null+++ b/studio/frontend/src/features/settings/gpu-rendering-notes.ts@@ -0,0 +1,36 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type {+ GpuRenderingSetting,+ GpuRenderingStatus,+} from "./api/gpu-rendering";++export type GpuRenderingNote =+ | { kind: "macNote" }+ | { kind: "envOverride"; name: string }+ | { kind: "fallbackNote" }+ | { kind: "oldWebkitWarning"; version: string }+ | { kind: "oldDriverWarning"; version: string }+ | { kind: "restartPending" };++/** Notes shown under the GPU rendering row, in display order. */+export function gpuRenderingNotes(+ status: GpuRenderingStatus,+ selected: GpuRenderingSetting,+): GpuRenderingNote[] {+ if (!status.configurable) return [{ kind: "macNote" }];+ const notes: GpuRenderingNote[] = [];+ if (status.envOverride) {+ notes.push({ kind: "envOverride", name: status.envOverride });+ }+ if (status.fallbackActive) notes.push({ kind: "fallbackNote" });+ if (selected === "on" && status.oldWebkitWarning) {+ notes.push({ kind: "oldWebkitWarning", version: status.oldWebkitWarning });+ }+ if (selected === "on" && status.oldDriverWarning) {+ notes.push({ kind: "oldDriverWarning", version: status.oldDriverWarning });+ }+ if (status.restartRequired) notes.push({ kind: "restartPending" });+ return notes;+}diff --git a/studio/frontend/src/features/settings/hooks/use-gpu-rendering-setting.ts b/studio/frontend/src/features/settings/hooks/use-gpu-rendering-setting.tsnew file mode 100644index 00000000000..643d727bda3--- /dev/null+++ b/studio/frontend/src/features/settings/hooks/use-gpu-rendering-setting.ts@@ -0,0 +1,79 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { useCallback, useEffect, useState } from "react";+import {+ type GpuRenderingSetting,+ type GpuRenderingStatus,+ loadGpuRendering,+ relaunchToApplyGpuRendering,+ updateGpuRendering,+} from "../api/gpu-rendering";++interface GpuRenderingSettingOptions {+ enabled: boolean;+ loadError: string;+ saveError: string;+ restartError: string;+}++export function useGpuRenderingSetting({+ enabled,+ loadError,+ saveError,+ restartError,+}: GpuRenderingSettingOptions) {+ const [status, setStatus] = useState<GpuRenderingStatus | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [saving, setSaving] = useState(false);+ const [restarting, setRestarting] = useState(false);++ useEffect(() => {+ if (!enabled) return;+ let cancelled = false;+ void loadGpuRendering()+ .then((loaded) => {+ if (cancelled) return;+ setStatus(loaded);+ setError(null);+ })+ .catch((cause) => {+ if (cancelled) return;+ setError(cause instanceof Error ? cause.message : loadError);+ });+ return () => {+ cancelled = true;+ };+ }, [enabled, loadError]);++ // Re-selecting the current value is how "Try GPU again" clears the fallback.+ const update = useCallback(+ async (next: GpuRenderingSetting) => {+ setSaving(true);+ setError(null);+ try {+ setStatus(await updateGpuRendering(next));+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : saveError);+ } finally {+ setSaving(false);+ }+ },+ [saveError],+ );++ const relaunch = useCallback(async () => {+ setRestarting(true);+ setError(null);+ try {+ // False means a quit is already pending and its dialog is showing.+ await relaunchToApplyGpuRendering();+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : restartError);+ } finally {+ setRestarting(false);+ }+ }, [restartError]);++ return { status, error, saving, restarting, update, relaunch };+}diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.tsindex fe79986214e..7fd87959df7 100644--- a/studio/frontend/src/features/settings/index.ts+++ b/studio/frontend/src/features/settings/index.ts@@ -16,6 +16,7 @@ export {updateDownloadTransportSettings,} from "./api/download-transport";export { loadEmbeddingModelSettings } from "./api/embedding-model";+export { notifyRendererReady } from "./api/gpu-rendering";export { updateHubSource } from "./api/hub-settings";export { loadLanAccess, publishLanUrls } from "./api/lan-access";export { lanApiUrls } from "./api/lan-access-state";diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.tsindex 72fff2f0c32..5b2c4b7ec54 100644--- a/studio/frontend/src/features/settings/settings-search.ts+++ b/studio/frontend/src/features/settings/settings-search.ts@@ -386,6 +386,12 @@ export function createSettingsSearchIndex({"settings.general.repairInstall.label","settings.general.fullInstall.label",],+ // Desktop only, like the Rendering section it scrolls to.+ appearance: SETTINGS_SEARCH_INDEX.appearance.flatMap((key) =>+ key === "settings.appearance.sidebarNav.title"+ ? (["settings.appearance.gpuRendering.label", key] as const)+ : [key],+ ),browser: [...SETTINGS_SEARCH_INDEX.browser, "browser.downloadLocationSetting"],about: SETTINGS_SEARCH_INDEX.about.filter((key) => key !== "settings.about.updates",diff --git a/studio/frontend/src/features/settings/tabs/appearance-tab.tsx b/studio/frontend/src/features/settings/tabs/appearance-tab.tsxindex 819551fa220..b827fe0794d 100644--- a/studio/frontend/src/features/settings/tabs/appearance-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/appearance-tab.tsx@@ -2,10 +2,12 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { useEffect, useRef } from "react";+import { Button } from "@/components/ui/button";import { Switch } from "@/components/ui/switch";import { useSidebarPin } from "@/hooks/use-sidebar-pin";import { TrickOrTreatSettingsRow } from "@/features/halloween/trick-or-treat-settings-row";import { useT } from "@/i18n";+import { isTauri } from "@/lib/api-base";import {ActiveColorControl,ChatFontRow,@@ -24,15 +26,124 @@ import {UiFontSizeRow,} from "../components/appearance-custom-controls";import { ColorThemeSelect } from "../components/color-theme-select";+import { GpuRenderingSegmented } from "../components/gpu-rendering-segmented";import { SettingsRow } from "../components/settings-row";import { SidebarMenuCustomizer } from "../components/sidebar-menu-customizer";import { SidebarNavCustomizer } from "../components/sidebar-nav-customizer";import { SettingsSection } from "../components/settings-section";import { ThemeSegmented } from "../components/theme-segmented";+import { gpuRenderingNotes } from "../gpu-rendering-notes";+import { useGpuRenderingSetting } from "../hooks/use-gpu-rendering-setting";import { useSettingsDialogStore } from "../stores/settings-dialog-store";const FONT_CONTROL_CLASS = "flex w-76 max-w-full items-center gap-2";const FONT_SELECT_CLASS = "w-auto min-w-0 flex-1";+const NOTE_CLASS =+ "max-w-[calc(280px*var(--ui-space-scale,1))] text-right text-xs";++function GpuRenderingRow() {+ const t = useT();+ const gpu = useGpuRenderingSetting({+ enabled: isTauri,+ loadError: t("settings.appearance.gpuRendering.loadError"),+ saveError: t("settings.appearance.gpuRendering.saveError"),+ restartError: t("settings.appearance.gpuRendering.restartError"),+ });+ const status = gpu.status;+ const notes = status ? gpuRenderingNotes(status, status.setting) : [];+ const busy = gpu.saving || gpu.restarting;+ const below =+ notes.length > 0 || gpu.error ? (+ <div className="flex flex-col items-end gap-1.5">+ {notes.map((note) => {+ switch (note.kind) {+ case "macNote":+ return (+ <span key={note.kind} className={`${NOTE_CLASS} text-muted-foreground`}>+ {t("settings.appearance.gpuRendering.macNote")}+ </span>+ );+ case "envOverride":+ return (+ <span key={note.kind} className={`${NOTE_CLASS} text-muted-foreground`}>+ {t("settings.appearance.gpuRendering.envOverride", {+ name: note.name,+ })}+ </span>+ );+ case "fallbackNote":+ return (+ <div key={note.kind} className="flex flex-col items-end gap-1.5">+ <span className={`${NOTE_CLASS} text-muted-foreground`}>+ {t("settings.appearance.gpuRendering.fallbackNote")}+ </span>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={busy || !status}+ onClick={() => {+ if (status) void gpu.update(status.setting);+ }}+ >+ {t("settings.appearance.gpuRendering.tryAgain")}+ </Button>+ </div>+ );+ case "oldWebkitWarning":+ return (+ <span key={note.kind} className={`${NOTE_CLASS} text-muted-foreground`}>+ {t("settings.appearance.gpuRendering.oldWebkitWarning", {+ version: note.version,+ })}+ </span>+ );+ case "oldDriverWarning":+ return (+ <span key={note.kind} className={`${NOTE_CLASS} text-muted-foreground`}>+ {t("settings.appearance.gpuRendering.oldDriverWarning", {+ version: note.version,+ })}+ </span>+ );+ case "restartPending":+ return (+ <div key={note.kind} className="flex items-center gap-2">+ <span className={`${NOTE_CLASS} text-muted-foreground`}>+ {t("settings.appearance.gpuRendering.restartPending")}+ </span>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={busy}+ onClick={() => void gpu.relaunch()}+ >+ {t("settings.appearance.gpuRendering.restartNow")}+ </Button>+ </div>+ );+ }+ })}+ {gpu.error ? (+ <span className={`${NOTE_CLASS} text-destructive`}>{gpu.error}</span>+ ) : null}+ </div>+ ) : null;+ return (+ <SettingsRow+ label={t("settings.appearance.gpuRendering.label")}+ description={t("settings.appearance.gpuRendering.description")}+ below={below}+ >+ <GpuRenderingSegmented+ value={status?.setting ?? null}+ onChange={(next) => void gpu.update(next)}+ disabled={!status || !status.configurable || busy}+ />+ </SettingsRow>+ );+}export function AppearanceTab() {const t = useT();@@ -164,6 +275,12 @@ export function AppearanceTab() {</SettingsRow></SettingsSection>+ {isTauri ? (+ <SettingsSection title={t("settings.appearance.gpuRendering.sectionTitle")}>+ <GpuRenderingRow />+ </SettingsSection>+ ) : null}+<div ref={sidebarNavSectionRef} className="scroll-mt-4"><SettingsSectiontitle={t("settings.appearance.sidebarNav.title")}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 1c20dae1cbf..cf6781de4cd 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -2203,6 +2203,26 @@ export const ar = {appearance: {title: "المظهر",description: "كيفية ظهور Unsloth على هذا الجهاز.",+ gpuRendering: {+ sectionTitle: "العرض",+ label: "العرض عبر GPU",+ description: "اعرض Unsloth باستخدام بطاقة الرسومات. يستخدمها الوضع «تلقائي» حيث يُعرف أنها تعمل. تُطبَّق التغييرات بعد إعادة تشغيل Unsloth.",+ auto: "تلقائي",+ on: "تشغيل",+ off: "إيقاف",+ oldWebkitWarning: "WebKitGTK {version} على Wayland: قد يتعطل العرض عبر GPU عند التشغيل على NVIDIA مع التحجيم الكسري (WebKit bug 280210). إذا حدث ذلك، يعود Unsloth تلقائيًا إلى العرض عبر CPU. على WebKitGTK 2.50.4 لم يُحقق أي تسريع ملموس (8 fps في الحالتين)، لذا لا يُنصح بخيار «تشغيل» هنا.",+ oldDriverWarning:+ "برنامج تشغيل NVIDIA {version} على X11: يُبقي Unsloth العرض عبر GPU متوقفًا حتى يصبح برنامج التشغيل 610 أو أحدث. تُسرّب برامج التشغيل الأقدم واصف ملف في كل إطار، فتتوقف النافذة عن الرسم خلال دقائق.",+ fallbackNote: "تعطّل العرض عبر GPU عند التشغيل على هذا النظام، لذا يستخدم Unsloth العرض عبر CPU.",+ tryAgain: "جرّب GPU مرة أخرى",+ envOverride: "مُعيَّن بواسطة متغير البيئة {name}. لا يكون لهذا الإعداد أي تأثير حتى تتم إزالته.",+ macNote: "يعرض macOS دائمًا باستخدام GPU. لا يوفر WebKit أي خيار مدعوم لإيقاف ذلك.",+ restartPending: "أعد تشغيل Unsloth للتطبيق.",+ restartNow: "إعادة التشغيل الآن",+ loadError: "تعذّر تحميل إعداد العرض عبر GPU.",+ saveError: "تعذّر حفظ إعداد العرض عبر GPU.",+ restartError: "تعذّرت إعادة تشغيل Unsloth.",+ },theme: {title: "النمط المرئي",label: "الوضع",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 0a24c7df3e6..a1104031a8e 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -2233,6 +2233,26 @@ export const de = {appearance: {title: "Darstellung",description: "Wie Unsloth auf diesem Gerät aussieht.",+ gpuRendering: {+ sectionTitle: "Rendering",+ label: "GPU-Rendering",+ description: "Unsloth mit der Grafikkarte darstellen. Auto nutzt sie dort, wo sie bekanntermaßen funktioniert. Änderungen gelten nach einem Neustart von Unsloth.",+ auto: "Auto",+ on: "An",+ off: "Aus",+ oldWebkitWarning: "WebKitGTK {version} unter Wayland: GPU-Rendering kann auf NVIDIA mit gebrochener Skalierung beim Start abstürzen (WebKit bug 280210). In diesem Fall wechselt Unsloth von selbst zurück zum CPU-Rendering. Unter WebKitGTK 2.50.4 brachte es keinen messbaren Geschwindigkeitsgewinn (in beiden Fällen 8 fps), daher wird An hier nicht empfohlen.",+ oldDriverWarning:+ "NVIDIA-Treiber {version} unter X11: Unsloth lässt das GPU-Rendering aus, bis der Treiber 610 oder neuer ist. Ältere Treiber verlieren pro Frame einen Dateideskriptor, und das Fenster zeichnet nach wenigen Minuten nicht mehr.",+ fallbackNote: "GPU-Rendering ist auf diesem System beim Start abgestürzt, daher verwendet Unsloth CPU-Rendering.",+ tryAgain: "GPU erneut versuchen",+ envOverride: "Durch die Umgebungsvariable {name} festgelegt. Diese Einstellung hat keine Wirkung, solange sie gesetzt ist.",+ macNote: "macOS rendert immer mit der GPU. WebKit bietet keinen unterstützten Schalter, um das abzuschalten.",+ restartPending: "Starte Unsloth neu, um die Änderung anzuwenden.",+ restartNow: "Jetzt neu starten",+ loadError: "Die Einstellung für GPU-Rendering konnte nicht geladen werden.",+ saveError: "Die Einstellung für GPU-Rendering konnte nicht gespeichert werden.",+ restartError: "Unsloth konnte nicht neu gestartet werden.",+ },theme: {title: "Visueller Stil",label: "Modus",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 43225e70423..40eabe68df4 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -2267,6 +2267,26 @@ export const en = {appearance: {title: "Appearance",description: "How Unsloth looks on this device.",+ gpuRendering: {+ sectionTitle: "Rendering",+ label: "GPU rendering",+ description: "Draw Unsloth with your graphics card. Auto uses it where it is known to work. Changes apply after Unsloth restarts.",+ auto: "Auto",+ on: "On",+ off: "Off",+ oldWebkitWarning: "WebKitGTK {version} on Wayland: GPU rendering can crash at launch on NVIDIA with fractional scaling (WebKit bug 280210). If it does, Unsloth switches back to CPU rendering on its own. On WebKitGTK 2.50.4 it gave no measured speedup (8 fps either way), so On is not recommended here.",+ oldDriverWarning:+ "NVIDIA driver {version} on X11: Unsloth keeps GPU rendering off until the driver is 610 or newer. Older drivers leak a file descriptor per frame, and the window stops drawing within minutes.",+ fallbackNote: "GPU rendering crashed at launch on this system, so Unsloth is using CPU rendering.",+ tryAgain: "Try GPU again",+ envOverride: "Set by the {name} environment variable. This setting has no effect until it is removed.",+ macNote: "macOS always renders with the GPU. WebKit has no supported switch to turn it off.",+ restartPending: "Restart Unsloth to apply.",+ restartNow: "Restart now",+ loadError: "Couldn't load the GPU rendering setting.",+ saveError: "Couldn't save the GPU rendering setting.",+ restartError: "Couldn't restart Unsloth.",+ },theme: {title: "Visual style",label: "Mode",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 1854c217a95..87102038fbf 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -2228,6 +2228,26 @@ export const es = {appearance: {title: "Apariencia",description: "Cómo se ve Unsloth en este dispositivo.",+ gpuRendering: {+ sectionTitle: "Renderizado",+ label: "Renderizado por GPU",+ description: "Dibuja Unsloth con tu tarjeta gráfica. Auto la usa donde se sabe que funciona. Los cambios se aplican al reiniciar Unsloth.",+ auto: "Auto",+ on: "Activado",+ off: "Desactivado",+ oldWebkitWarning: "WebKitGTK {version} en Wayland: el renderizado por GPU puede fallar al iniciar en NVIDIA con escalado fraccionario (WebKit bug 280210). Si ocurre, Unsloth vuelve por sí solo al renderizado por CPU. En WebKitGTK 2.50.4 no mostró ninguna mejora medible (8 fps en ambos casos), así que no se recomienda Activado aquí.",+ oldDriverWarning:+ "Controlador NVIDIA {version} en X11: Unsloth mantiene desactivado el renderizado por GPU hasta que el controlador sea 610 o posterior. Los controladores anteriores pierden un descriptor de archivo por fotograma y la ventana deja de dibujarse en pocos minutos.",+ fallbackNote: "El renderizado por GPU falló al iniciar en este sistema, así que Unsloth usa el renderizado por CPU.",+ tryAgain: "Probar la GPU de nuevo",+ envOverride: "Definido por la variable de entorno {name}. Este ajuste no tiene efecto hasta que se elimine.",+ macNote: "macOS siempre renderiza con la GPU. WebKit no ofrece ninguna opción compatible para desactivarlo.",+ restartPending: "Reinicia Unsloth para aplicarlo.",+ restartNow: "Reiniciar ahora",+ loadError: "No se pudo cargar el ajuste de renderizado por GPU.",+ saveError: "No se pudo guardar el ajuste de renderizado por GPU.",+ restartError: "No se pudo reiniciar Unsloth.",+ },theme: {title: "Estilo visual",label: "Modo",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex dc56abe58ac..b63b84f26af 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -2231,6 +2231,26 @@ export const fr = {appearance: {title: "Apparence",description: "L'apparence d'Unsloth sur cet appareil.",+ gpuRendering: {+ sectionTitle: "Rendu",+ label: "Rendu GPU",+ description: "Afficher Unsloth avec votre carte graphique. Auto l’utilise là où son bon fonctionnement est connu. Les changements s’appliquent au redémarrage d’Unsloth.",+ auto: "Auto",+ on: "Activé",+ off: "Désactivé",+ oldWebkitWarning: "WebKitGTK {version} sous Wayland : le rendu GPU peut planter au lancement sur NVIDIA avec une mise à l’échelle fractionnaire (WebKit bug 280210). Dans ce cas, Unsloth repasse de lui-même au rendu CPU. Sous WebKitGTK 2.50.4, il n’a apporté aucun gain mesurable (8 fps dans les deux cas), donc Activé n’est pas recommandé ici.",+ oldDriverWarning:+ "Pilote NVIDIA {version} sous X11 : Unsloth laisse le rendu GPU désactivé tant que le pilote n'est pas en version 610 ou plus récente. Les pilotes plus anciens perdent un descripteur de fichier par image et la fenêtre cesse de s'afficher en quelques minutes.",+ fallbackNote: "Le rendu GPU a planté au lancement sur ce système, donc Unsloth utilise le rendu CPU.",+ tryAgain: "Réessayer le GPU",+ envOverride: "Défini par la variable d’environnement {name}. Ce réglage n’a aucun effet tant qu’elle n’est pas supprimée.",+ macNote: "macOS effectue toujours le rendu avec le GPU. WebKit ne propose aucune option prise en charge pour le désactiver.",+ restartPending: "Redémarrez Unsloth pour appliquer.",+ restartNow: "Redémarrer maintenant",+ loadError: "Impossible de charger le réglage du rendu GPU.",+ saveError: "Impossible d’enregistrer le réglage du rendu GPU.",+ restartError: "Impossible de redémarrer Unsloth.",+ },theme: {title: "Style visuel",label: "Mode",diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex d96c0013808..67c5bb81a1c 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -2307,6 +2307,26 @@ export const he = {appearance: {title: "מראה",description: "כיצד Unsloth נראה במכשיר זה.",+ gpuRendering: {+ sectionTitle: "רינדור",+ label: "רינדור ב-GPU",+ description: "ציור Unsloth באמצעות כרטיס המסך. מצב אוטומטי משתמש בו במקומות שבהם ידוע שהוא עובד. השינויים יחולו אחרי ש-Unsloth יופעל מחדש.",+ auto: "אוטומטי",+ on: "מופעל",+ off: "כבוי",+ oldWebkitWarning: "WebKitGTK {version} ב-Wayland: רינדור ב-GPU עלול לקרוס בהפעלה על NVIDIA עם קנה מידה חלקי (WebKit bug 280210). אם זה קורה, Unsloth חוזר מעצמו לרינדור ב-CPU. ב-WebKitGTK 2.50.4 לא נמדדה שום האצה (8 fps בשני המקרים), ולכן לא מומלץ לבחור כאן במצב מופעל.",+ oldDriverWarning:+ "מנהל התקן NVIDIA {version} ב-X11: Unsloth משאיר את הרינדור ב-GPU כבוי עד שמנהל ההתקן יהיה 610 ומעלה. מנהלי התקן ישנים יותר מדליפים מתאר קובץ בכל פריים, והחלון מפסיק להצטייר תוך דקות.",+ fallbackNote: "רינדור ב-GPU קרס בהפעלה במערכת הזו, ולכן Unsloth משתמש ברינדור ב-CPU.",+ tryAgain: "לנסות שוב עם GPU",+ envOverride: "נקבע על ידי משתנה הסביבה {name}. להגדרה הזו אין השפעה עד שהוא יוסר.",+ macNote: "macOS תמיד מרנדר באמצעות ה-GPU. ל-WebKit אין מתג נתמך לכיבוי זה.",+ restartPending: "יש להפעיל מחדש את Unsloth כדי להחיל.",+ restartNow: "הפעלה מחדש עכשיו",+ loadError: "לא ניתן לטעון את הגדרת הרינדור ב-GPU.",+ saveError: "לא ניתן לשמור את הגדרת הרינדור ב-GPU.",+ restartError: "לא ניתן להפעיל מחדש את Unsloth.",+ },theme: {title: "סגנון חזותי",label: "מצב",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex ec7a08d5c07..98f73b269e1 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -2209,6 +2209,26 @@ export const hi = {appearance: {title: "रूप-रंग",description: "इस डिवाइस पर Unsloth कैसा दिखता है।",+ gpuRendering: {+ sectionTitle: "रेंडरिंग",+ label: "GPU रेंडरिंग",+ description: "Unsloth को आपके ग्राफ़िक्स कार्ड से दिखाएँ। ऑटो इसका इस्तेमाल वहीं करता है जहाँ यह काम करने के लिए जाना जाता है। बदलाव Unsloth के दोबारा शुरू होने के बाद लागू होते हैं।",+ auto: "ऑटो",+ on: "चालू",+ off: "बंद",+ oldWebkitWarning: "Wayland पर WebKitGTK {version}: फ़्रैक्शनल स्केलिंग वाले NVIDIA पर GPU रेंडरिंग लॉन्च के समय क्रैश हो सकती है (WebKit bug 280210)। ऐसा होने पर Unsloth अपने आप CPU रेंडरिंग पर लौट आता है। WebKitGTK 2.50.4 पर इससे कोई मापने लायक तेज़ी नहीं मिली (दोनों तरह 8 fps), इसलिए यहाँ चालू की सलाह नहीं दी जाती।",+ oldDriverWarning:+ "X11 पर NVIDIA ड्राइवर {version}: ड्राइवर 610 या नया होने तक Unsloth GPU रेंडरिंग बंद रखता है। पुराने ड्राइवर हर फ़्रेम में एक फ़ाइल डिस्क्रिप्टर लीक करते हैं, और कुछ ही मिनटों में विंडो बनना बंद हो जाती है।",+ fallbackNote: "इस सिस्टम पर GPU रेंडरिंग लॉन्च के समय क्रैश हो गई, इसलिए Unsloth CPU रेंडरिंग का इस्तेमाल कर रहा है।",+ tryAgain: "GPU फिर से आज़माएँ",+ envOverride: "{name} एनवायरनमेंट वेरिएबल से सेट है। जब तक इसे हटाया नहीं जाता, इस सेटिंग का कोई असर नहीं होगा।",+ macNote: "macOS हमेशा GPU से रेंडर करता है। WebKit में इसे बंद करने का कोई समर्थित विकल्प नहीं है।",+ restartPending: "लागू करने के लिए Unsloth दोबारा शुरू करें।",+ restartNow: "अभी दोबारा शुरू करें",+ loadError: "GPU रेंडरिंग सेटिंग लोड नहीं हो सकी।",+ saveError: "GPU रेंडरिंग सेटिंग सहेजी नहीं जा सकी।",+ restartError: "Unsloth दोबारा शुरू नहीं हो सका।",+ },theme: {title: "विज़ुअल स्टाइल",label: "मोड",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 8a3edb633e4..adcaac9e012 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -2103,6 +2103,26 @@ export const it = {appearance: {title: "Aspetto",description: "Come si presenta Unsloth su questo dispositivo.",+ gpuRendering: {+ sectionTitle: "Rendering",+ label: "Rendering GPU",+ description: "Disegna Unsloth con la scheda grafica. Auto la usa dove è noto che funziona. Le modifiche si applicano al riavvio di Unsloth.",+ auto: "Auto",+ on: "Attivo",+ off: "Disattivo",+ oldWebkitWarning: "WebKitGTK {version} su Wayland: il rendering GPU può bloccarsi all’avvio su NVIDIA con il ridimensionamento frazionario (WebKit bug 280210). In tal caso Unsloth torna da solo al rendering CPU. Su WebKitGTK 2.50.4 non ha dato alcun miglioramento misurabile (8 fps in entrambi i casi), quindi Attivo qui non è consigliato.",+ oldDriverWarning:+ "Driver NVIDIA {version} su X11: Unsloth mantiene disattivato il rendering GPU finché il driver non è 610 o successivo. I driver precedenti perdono un descrittore di file per fotogramma e la finestra smette di disegnare entro pochi minuti.",+ fallbackNote: "Il rendering GPU si è bloccato all’avvio su questo sistema, quindi Unsloth usa il rendering CPU.",+ tryAgain: "Riprova con la GPU",+ envOverride: "Impostato dalla variabile d’ambiente {name}. Questa impostazione non ha effetto finché non viene rimossa.",+ macNote: "macOS esegue sempre il rendering con la GPU. WebKit non offre un’opzione supportata per disattivarlo.",+ restartPending: "Riavvia Unsloth per applicare.",+ restartNow: "Riavvia ora",+ loadError: "Impossibile caricare l’impostazione del rendering GPU.",+ saveError: "Impossibile salvare l’impostazione del rendering GPU.",+ restartError: "Impossibile riavviare Unsloth.",+ },theme: {title: "Stile visivo",label: "Modalità",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex e9670d32896..8b9734e76c1 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -2185,6 +2185,26 @@ export const ja = {appearance: {title: "外観",description: "このデバイスでの Unsloth の見た目。",+ gpuRendering: {+ sectionTitle: "レンダリング",+ label: "GPU レンダリング",+ description: "グラフィックカードで Unsloth を描画します。自動では、動作が確認されている環境でのみ使用します。変更は Unsloth の再起動後に反映されます。",+ auto: "自動",+ on: "オン",+ off: "オフ",+ oldWebkitWarning: "Wayland 上の WebKitGTK {version}: 分数スケーリングを使う NVIDIA 環境では、GPU レンダリングが起動時にクラッシュすることがあります (WebKit bug 280210)。その場合、Unsloth は自動的に CPU レンダリングに戻ります。WebKitGTK 2.50.4 では測定できる高速化はなかった (どちらも 8 fps) ため、ここではオンはおすすめしません。",+ oldDriverWarning:+ "X11 上の NVIDIA ドライバー {version}: ドライバーが 610 以降になるまで、Unsloth は GPU レンダリングをオフのままにします。古いドライバーはフレームごとにファイル記述子をリークし、数分でウィンドウが描画されなくなります。",+ fallbackNote: "このシステムでは GPU レンダリングが起動時にクラッシュしたため、Unsloth は CPU レンダリングを使用しています。",+ tryAgain: "GPU をもう一度試す",+ envOverride: "環境変数 {name} で設定されています。これを削除するまで、この設定は効果がありません。",+ macNote: "macOS では常に GPU で描画されます。WebKit にはこれをオフにするサポートされた方法がありません。",+ restartPending: "反映するには Unsloth を再起動してください。",+ restartNow: "今すぐ再起動",+ loadError: "GPU レンダリングの設定を読み込めませんでした。",+ saveError: "GPU レンダリングの設定を保存できませんでした。",+ restartError: "Unsloth を再起動できませんでした。",+ },theme: {title: "表示スタイル",label: "モード",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex dd0bee6f4f2..c1449f44cf0 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -2196,6 +2196,26 @@ export const ko = {appearance: {title: "외관",description: "이 기기에서 Unsloth가 표시되는 방식입니다.",+ gpuRendering: {+ sectionTitle: "렌더링",+ label: "GPU 렌더링",+ description: "그래픽 카드로 Unsloth를 그립니다. 자동은 잘 작동하는 것으로 확인된 환경에서만 사용합니다. 변경 사항은 Unsloth를 다시 시작한 후 적용됩니다.",+ auto: "자동",+ on: "켜기",+ off: "끄기",+ oldWebkitWarning: "Wayland의 WebKitGTK {version}: 배율을 소수로 설정한 NVIDIA 환경에서는 GPU 렌더링이 시작 시 충돌할 수 있습니다(WebKit bug 280210). 이 경우 Unsloth가 자동으로 CPU 렌더링으로 돌아갑니다. WebKitGTK 2.50.4에서는 측정 가능한 속도 향상이 없었으므로(두 경우 모두 8 fps) 여기서는 켜기를 권장하지 않습니다.",+ oldDriverWarning:+ "X11의 NVIDIA 드라이버 {version}: 드라이버가 610 이상이 될 때까지 Unsloth는 GPU 렌더링을 끈 상태로 유지합니다. 이전 드라이버는 프레임마다 파일 디스크립터를 누수하며, 몇 분 안에 창이 더 이상 그려지지 않습니다.",+ fallbackNote: "이 시스템에서 GPU 렌더링이 시작 시 충돌하여 Unsloth가 CPU 렌더링을 사용하고 있습니다.",+ tryAgain: "GPU 다시 시도",+ envOverride: "{name} 환경 변수로 설정되어 있습니다. 이 변수를 제거하기 전까지는 이 설정이 적용되지 않습니다.",+ macNote: "macOS는 항상 GPU로 렌더링합니다. WebKit에는 이를 끄는 지원되는 방법이 없습니다.",+ restartPending: "적용하려면 Unsloth를 다시 시작하세요.",+ restartNow: "지금 다시 시작",+ loadError: "GPU 렌더링 설정을 불러오지 못했습니다.",+ saveError: "GPU 렌더링 설정을 저장하지 못했습니다.",+ restartError: "Unsloth를 다시 시작하지 못했습니다.",+ },theme: {title: "시각 스타일",label: "모드",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 28368917285..c5f7790ee59 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -2220,6 +2220,26 @@ export const ptBR = {appearance: {title: "Aparência",description: "A aparência do Unsloth neste dispositivo.",+ gpuRendering: {+ sectionTitle: "Renderização",+ label: "Renderização por GPU",+ description: "Desenhe o Unsloth com a placa de vídeo. Auto a usa onde se sabe que funciona. As alterações valem depois que o Unsloth reiniciar.",+ auto: "Auto",+ on: "Ativado",+ off: "Desativado",+ oldWebkitWarning: "WebKitGTK {version} no Wayland: a renderização por GPU pode travar ao iniciar em NVIDIA com escala fracionária (WebKit bug 280210). Se isso acontecer, o Unsloth volta sozinho para a renderização por CPU. No WebKitGTK 2.50.4 não houve ganho de velocidade mensurável (8 fps nos dois casos), então Ativado não é recomendado aqui.",+ oldDriverWarning:+ "NVIDIA driver {version} on X11: Unsloth keeps GPU rendering off until the driver is 610 or newer. Older drivers leak a file descriptor per frame, and the window stops drawing within minutes.",+ fallbackNote: "A renderização por GPU travou ao iniciar neste sistema, então o Unsloth está usando renderização por CPU.",+ tryAgain: "Tentar a GPU de novo",+ envOverride: "Definido pela variável de ambiente {name}. Esta configuração não tem efeito até que ela seja removida.",+ macNote: "O macOS sempre renderiza com a GPU. O WebKit não tem uma opção compatível para desativar isso.",+ restartPending: "Reinicie o Unsloth para aplicar.",+ restartNow: "Reiniciar agora",+ loadError: "Não foi possível carregar a configuração de renderização por GPU.",+ saveError: "Não foi possível salvar a configuração de renderização por GPU.",+ restartError: "Não foi possível reiniciar o Unsloth.",+ },theme: {title: "Estilo visual",label: "Modo",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex ca09c5bd842..ecec940bcd0 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -2213,6 +2213,26 @@ export const ru = {appearance: {title: "Оформление",description: "Как Unsloth выглядит на этом устройстве.",+ gpuRendering: {+ sectionTitle: "Отрисовка",+ label: "Отрисовка на GPU",+ description: "Отрисовывать Unsloth с помощью видеокарты. В режиме «Авто» она используется там, где известно, что это работает. Изменения вступят в силу после перезапуска Unsloth.",+ auto: "Авто",+ on: "Вкл.",+ off: "Выкл.",+ oldWebkitWarning: "WebKitGTK {version} в Wayland: отрисовка на GPU может аварийно завершаться при запуске на NVIDIA с дробным масштабированием (WebKit bug 280210). В этом случае Unsloth сам вернётся к отрисовке на CPU. На WebKitGTK 2.50.4 измеримого ускорения не было (8 fps в обоих случаях), поэтому режим «Вкл.» здесь не рекомендуется.",+ oldDriverWarning:+ "Драйвер NVIDIA {version} в X11: Unsloth не включает GPU-рендеринг, пока драйвер не будет версии 610 или новее. Старые драйверы теряют по одному файловому дескриптору на кадр, и через несколько минут окно перестаёт отрисовываться.",+ fallbackNote: "Отрисовка на GPU аварийно завершилась при запуске в этой системе, поэтому Unsloth использует отрисовку на CPU.",+ tryAgain: "Попробовать GPU снова",+ envOverride: "Задано переменной окружения {name}. Пока она не удалена, эта настройка ни на что не влияет.",+ macNote: "macOS всегда выполняет отрисовку на GPU. В WebKit нет поддерживаемого способа это отключить.",+ restartPending: "Перезапустите Unsloth, чтобы применить.",+ restartNow: "Перезапустить",+ loadError: "Не удалось загрузить настройку отрисовки на GPU.",+ saveError: "Не удалось сохранить настройку отрисовки на GPU.",+ restartError: "Не удалось перезапустить Unsloth.",+ },theme: {title: "Внешний вид",label: "Режим",diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex 650f7686380..87428e2019b 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -2380,6 +2380,26 @@ export const sv = {appearance: {title: "Utseende",description: "Hur Unsloth ser ut på den här enheten.",+ gpuRendering: {+ sectionTitle: "Rendering",+ label: "GPU-rendering",+ description: "Rita Unsloth med grafikkortet. Auto använder det där det är känt att fungera. Ändringar gäller efter att Unsloth har startats om.",+ auto: "Auto",+ on: "På",+ off: "Av",+ oldWebkitWarning: "WebKitGTK {version} på Wayland: GPU-rendering kan krascha vid start på NVIDIA med skalning i bråkdelar (WebKit bug 280210). Om det händer byter Unsloth själv tillbaka till CPU-rendering. På WebKitGTK 2.50.4 gav det ingen mätbar förbättring (8 fps i båda fallen), så På rekommenderas inte här.",+ oldDriverWarning:+ "NVIDIA-drivrutin {version} på X11: Unsloth håller GPU-rendering avstängd tills drivrutinen är 610 eller nyare. Äldre drivrutiner läcker en filbeskrivare per bildruta, och fönstret slutar ritas inom några minuter.",+ fallbackNote: "GPU-rendering kraschade vid start på det här systemet, så Unsloth använder CPU-rendering.",+ tryAgain: "Försök med GPU igen",+ envOverride: "Anges av miljövariabeln {name}. Den här inställningen har ingen effekt förrän den tas bort.",+ macNote: "macOS renderar alltid med GPU:n. WebKit har inget stött sätt att stänga av det.",+ restartPending: "Starta om Unsloth för att tillämpa.",+ restartNow: "Starta om nu",+ loadError: "Det gick inte att läsa in inställningen för GPU-rendering.",+ saveError: "Det gick inte att spara inställningen för GPU-rendering.",+ restartError: "Det gick inte att starta om Unsloth.",+ },theme: {title: "Visuell stil",label: "Läge",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 8c1d955590e..5f63ea5ac1a 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -2186,6 +2186,26 @@ export const zhCN = {spellCheck: "拼写检查",spellCheckDescription: "输入时在拼写错误的单词下方显示下划线。",},+ gpuRendering: {+ sectionTitle: "渲染",+ label: "GPU 渲染",+ description: "使用显卡绘制 Unsloth。“自动”只在已知可正常工作的环境中使用显卡。更改将在 Unsloth 重启后生效。",+ auto: "自动",+ on: "开启",+ off: "关闭",+ oldWebkitWarning: "Wayland 上的 WebKitGTK {version}:在使用分数缩放的 NVIDIA 环境中,GPU 渲染可能会在启动时崩溃(WebKit bug 280210)。如果发生这种情况,Unsloth 会自动切换回 CPU 渲染。在 WebKitGTK 2.50.4 上未测得任何提速(两种方式都是 8 fps),因此不建议在此开启。",+ oldDriverWarning:+ "X11 上的 NVIDIA 驱动 {version}:在驱动更新到 610 或更高版本之前,Unsloth 会保持 GPU 渲染关闭。旧驱动每帧泄漏一个文件描述符,几分钟内窗口就会停止绘制。",+ fallbackNote: "GPU 渲染在此系统上启动时崩溃,因此 Unsloth 正在使用 CPU 渲染。",+ tryAgain: "重试 GPU",+ envOverride: "由环境变量 {name} 设置。在移除该变量之前,此设置不会生效。",+ macNote: "macOS 始终使用 GPU 渲染。WebKit 没有受支持的开关可以将其关闭。",+ restartPending: "重启 Unsloth 以应用更改。",+ restartNow: "立即重启",+ loadError: "无法加载 GPU 渲染设置。",+ saveError: "无法保存 GPU 渲染设置。",+ restartError: "无法重启 Unsloth。",+ },theme: {title: "视觉样式",label: "模式",diff --git a/studio/frontend/tests/gpu-rendering-setting.test.ts b/studio/frontend/tests/gpu-rendering-setting.test.tsnew file mode 100644index 00000000000..33b58b066f1--- /dev/null+++ b/studio/frontend/tests/gpu-rendering-setting.test.ts@@ -0,0 +1,270 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import type {+ GpuRenderingStatus,+ notifyRendererReady as NotifyRendererReady,+} from "../src/features/settings/api/gpu-rendering.ts";+import {+ type GpuRenderingNote,+ gpuRenderingNotes,+} from "../src/features/settings/gpu-rendering-notes.ts";+import { en } from "../src/i18n/locales/en.ts";+import { loadWithStubs } from "./helpers/module-stubs.ts";++const API = new URL(+ "../src/features/settings/api/gpu-rendering.ts",+ import.meta.url,+);+const PROVIDER = new URL("../src/app/provider.tsx", import.meta.url);+const APPEARANCE_TAB = new URL(+ "../src/features/settings/tabs/appearance-tab.tsx",+ import.meta.url,+);+const SEGMENTED = new URL(+ "../src/features/settings/components/gpu-rendering-segmented.tsx",+ import.meta.url,+);++const BASE: GpuRenderingStatus = {+ setting: "auto",+ configurable: true,+ restartRequired: false,+ fallbackActive: false,+ envOverride: null,+ oldWebkitWarning: null,+ oldDriverWarning: null,+};++const kinds = (notes: GpuRenderingNote[]) => notes.map((note) => note.kind);++test("GPU rendering notes follow the status", () => {+ const rows: {+ name: string;+ status: Partial<GpuRenderingStatus>;+ selected: GpuRenderingStatus["setting"];+ expected: GpuRenderingNote["kind"][];+ }[] = [+ { name: "plain auto", status: {}, selected: "auto", expected: [] },+ {+ name: "macOS shows only its note",+ status: { configurable: false, setting: "on", restartRequired: true },+ selected: "on",+ expected: ["macNote"],+ },+ {+ name: "env override",+ status: { envOverride: "WEBKIT_DISABLE_DMABUF_RENDERER" },+ selected: "auto",+ expected: ["envOverride"],+ },+ {+ name: "fallback",+ status: { fallbackActive: true },+ selected: "auto",+ expected: ["fallbackNote"],+ },+ {+ name: "old WebKit warning needs On",+ status: { oldWebkitWarning: "2.50.4" },+ selected: "auto",+ expected: [],+ },+ {+ name: "old WebKit warning with Off",+ status: { oldWebkitWarning: "2.50.4" },+ selected: "off",+ expected: [],+ },+ {+ name: "old WebKit warning with On",+ status: { oldWebkitWarning: "2.50.4", setting: "on" },+ selected: "on",+ expected: ["oldWebkitWarning"],+ },+ {+ name: "old NVIDIA driver warning needs On",+ status: { oldDriverWarning: "580" },+ selected: "auto",+ expected: [],+ },+ {+ name: "old NVIDIA driver warning with On",+ status: { oldDriverWarning: "580", setting: "on" },+ selected: "on",+ expected: ["oldDriverWarning"],+ },+ {+ name: "On without a warning",+ status: { setting: "on" },+ selected: "on",+ expected: [],+ },+ {+ name: "restart pending",+ status: { restartRequired: true, setting: "off" },+ selected: "off",+ expected: ["restartPending"],+ },+ {+ name: "everything, in display order",+ status: {+ setting: "on",+ envOverride: "WEBKIT_FORCE_SHM",+ fallbackActive: true,+ oldWebkitWarning: "2.50.4",+ restartRequired: true,+ },+ selected: "on",+ expected: [+ "envOverride",+ "fallbackNote",+ "oldWebkitWarning",+ "restartPending",+ ],+ },+ ];+ for (const row of rows) {+ assert.deepEqual(+ kinds(gpuRenderingNotes({ ...BASE, ...row.status }, row.selected)),+ row.expected,+ row.name,+ );+ }++ const notes = gpuRenderingNotes(+ { ...BASE, envOverride: "WEBKIT_FORCE_SHM", oldWebkitWarning: "2.50.4" },+ "on",+ );+ assert.deepEqual(notes, [+ { kind: "envOverride", name: "WEBKIT_FORCE_SHM" },+ { kind: "oldWebkitWarning", version: "2.50.4" },+ ]);+});++test("the note copy carries the placeholders the row fills", () => {+ const copy = en.settings.appearance.gpuRendering;+ assert.ok(copy.oldWebkitWarning.includes("{version}"));+ assert.ok(copy.oldDriverWarning.includes("{version}"));+ assert.ok(copy.envOverride.includes("{name}"));+});++type ApiModule = {+ loadGpuRendering: () => Promise<GpuRenderingStatus>;+ updateGpuRendering: (value: string) => Promise<GpuRenderingStatus>;+ relaunchToApplyGpuRendering: () => Promise<boolean>;+ notifyRendererReady: typeof NotifyRendererReady;+};++function loadApi(+ isTauri: boolean,+ invoke: (command: string, args?: unknown) => Promise<unknown>,+): ApiModule {+ return loadWithStubs<ApiModule>(API, {+ "@/lib/api-base": { isTauri },+ "@tauri-apps/api/core": { invoke },+ });+}++async function withAnimationFrames<T>(+ run: (frames: () => number) => Promise<T>,+): Promise<T> {+ const g = globalThis as { window?: unknown };+ const previous = g.window;+ let frames = 0;+ g.window = {+ requestAnimationFrame: (callback: () => void) => {+ frames += 1;+ setTimeout(callback, 0);+ return frames;+ },+ };+ try {+ return await run(() => frames);+ } finally {+ g.window = previous;+ }+}++test("the api calls the backend commands by name", async () => {+ const calls: [string, unknown][] = [];+ const api = loadApi(true, async (command, args) => {+ calls.push([command, args]);+ if (command === "relaunch_to_apply_gpu_rendering") return true;+ return BASE;+ });++ assert.deepEqual(await api.loadGpuRendering(), BASE);+ await api.updateGpuRendering("off");+ assert.equal(await api.relaunchToApplyGpuRendering(), true);+ await withAnimationFrames(async (frames) => {+ await api.notifyRendererReady();+ assert.equal(frames(), 2, "waits two frames before reporting ready");+ });++ assert.deepEqual(calls, [+ ["get_gpu_rendering", undefined],+ ["set_gpu_rendering", { value: "off" }],+ ["relaunch_to_apply_gpu_rendering", undefined],+ ["renderer_ready", undefined],+ ]);+});++test("renderer ready is a no-op outside Tauri and never throws", async () => {+ const calls: string[] = [];+ const browser = loadApi(false, async (command) => {+ calls.push(command);+ });+ await withAnimationFrames(async (frames) => {+ await browser.notifyRendererReady();+ assert.equal(frames(), 0);+ });+ assert.deepEqual(calls, []);++ const failing = loadApi(true, async () => {+ throw new Error("unknown command renderer_ready");+ });+ await withAnimationFrames(() => failing.notifyRendererReady());+});++test("the provider reports ready after every window show", () => {+ const source = readFileSync(PROVIDER, "utf8");+ const shows = source.match(/await win\.show\(\);/g) ?? [];+ const reported =+ source.match(/await win\.show\(\);\n\s*void notifyRendererReady\(\);/g) ??+ [];+ assert.equal(shows.length, 3);+ assert.equal(reported.length, shows.length);+});++test("the Rendering section renders on desktop only", () => {+ const source = readFileSync(APPEARANCE_TAB, "utf8");+ assert.match(+ source,+ /\{isTauri \? \(\s*<SettingsSection title=\{t\("settings\.appearance\.gpuRendering\.sectionTitle"\)\}>\s*<GpuRenderingRow \/>/,+ );+ // Between Preferences and the sidebar nav section.+ const preferences = source.indexOf(+ "settings.appearance.custom.preferencesTitle",+ );+ const rendering = source.indexOf(+ "settings.appearance.gpuRendering.sectionTitle",+ );+ const sidebarNav = source.indexOf("settings.appearance.sidebarNav.title");+ assert.ok(preferences < rendering && rendering < sidebarNav);+ assert.match(source, /enabled: isTauri/);+});++test("the segmented control offers the three options and can be disabled", () => {+ const source = readFileSync(SEGMENTED, "utf8");+ for (const value of ["auto", "on", "off"]) {+ assert.ok(source.includes(`value: "${value}"`), value);+ }+ assert.ok(source.includes('layoutId="gpu-rendering-pill"'));+ assert.ok(source.includes("aria-pressed={active}"));+ assert.ok(source.includes("disabled={disabled}"));+});diff --git a/studio/frontend/tests/settings-search.test.ts b/studio/frontend/tests/settings-search.test.tsindex 34ba924ad16..00fe7b15322 100644--- a/studio/frontend/tests/settings-search.test.ts+++ b/studio/frontend/tests/settings-search.test.ts@@ -193,3 +193,20 @@ test("the multi-model, image/video idle and keepKv rows are found where they ren// ModelAutoSwitchSection is owner-only on a tab every account sees.assert.ok(!renderedSearchEntries(index, "api-keys", "huggingface", false).includes("settings.general.modelAutoSwitch.keepKv"));});++const GPU_RENDERING_ENTRY = "settings.appearance.gpuRendering.label";++test("GPU rendering is searchable on desktop only", () => {+ // The Rendering section is desktop only, so the browser build has no row to scroll to.+ const desktop = createSettingsSearchIndex({ desktop: true, closeToTray: false, menuBarIcon: true });+ const browser = createSettingsSearchIndex({ desktop: false, closeToTray: false, menuBarIcon: false });++ assert.equal(desktop.appearance.filter((key) => key === GPU_RENDERING_ENTRY).length, 1);+ assert.ok(!browser.appearance.includes(GPU_RENDERING_ENTRY));+ // Indexed in render order: after Preferences, before the sidebar nav section.+ assert.equal(+ desktop.appearance.indexOf(GPU_RENDERING_ENTRY) + 1,+ desktop.appearance.indexOf("settings.appearance.sidebarNav.title"),+ );+ assert.equal(desktop.appearance.length, browser.appearance.length + 1);+});diff --git a/studio/src-tauri/src/browser_webview.rs b/studio/src-tauri/src/browser_webview.rsindex 016970b25b5..433c6c14c12 100644--- a/studio/src-tauri/src/browser_webview.rs+++ b/studio/src-tauri/src/browser_webview.rs@@ -1038,7 +1038,10 @@ fn with_page_profile<R: Runtime>(#[cfg(not(target_os = "macos"))]{#[cfg(windows)]- let builder = builder.additional_browser_args(&page_browser_args(&proxy.to_string()));+ let builder = builder.additional_browser_args(&page_browser_args(+ &proxy.to_string(),+ crate::gpu_rendering::pages_disable_gpu(),+ ));#[cfg(not(windows))]let builder = builder.proxy_url(Url::parse(&format!("http://{proxy}")).map_err(|error| error.to_string())?);@@ -1057,11 +1060,17 @@ fn with_page_profile<R: Runtime>(/// These replace wry's defaults, so repeat them except SmartScreen (kept on for open-web pages)./// Chromium bypasses the proxy for loopback otherwise.#[cfg(any(windows, test))]-fn page_browser_args(proxy: &str) -> String {- format!(+/// `disable_gpu` follows the GPU rendering setting (Off) so pages match the main window.+fn page_browser_args(proxy: &str, disable_gpu: bool) -> String {+ let args = format!("--disable-features=msWebOOUI,msPdfOOUI --proxy-server=http://{proxy} \--proxy-bypass-list=<-loopback>"- )+ );+ if disable_gpu {+ format!("{args} --disable-gpu")+ } else {+ args+ }}/// wry's `url()` panics on macOS while WebKit has none (a failed load).@@ -2864,10 +2873,18 @@ mod tests {#[test]fn windows_pages_keep_smartscreen_and_the_proxy() {- let args = page_browser_args("127.0.0.1:9");+ let args = page_browser_args("127.0.0.1:9", false);assert!(!args.contains("SmartScreen"), "{args}");assert!(args.contains("--proxy-server=http://127.0.0.1:9"), "{args}");assert!(args.contains("--proxy-bypass-list=<-loopback>"), "{args}");+ assert!(!args.contains("--disable-gpu"), "{args}");+ }++ #[test]+ fn windows_pages_drop_the_gpu_only_when_gpu_rendering_is_off() {+ let on = page_browser_args("127.0.0.1:9", false);+ let off = page_browser_args("127.0.0.1:9", true);+ assert_eq!(off, format!("{on} --disable-gpu"));}#[cfg(target_os = "macos")]diff --git a/studio/src-tauri/src/gpu_rendering.rs b/studio/src-tauri/src/gpu_rendering.rsnew file mode 100644index 00000000000..d740ed86b10--- /dev/null+++ b/studio/src-tauri/src/gpu_rendering.rs@@ -0,0 +1,504 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++//! The "GPU rendering" desktop setting (Auto / On / Off). It is read before the webview starts,+//! so a change applies on the next launch.+//!+//! Linux also keeps a crash flag: when a GPU launch dies with Wayland Error 71 before the window+//! is ready (WebKit bug 280210), the supervisor writes it and Auto/On take the CPU path until the+//! host changes or the user picks a setting again.++use log::warn;+use serde::{Deserialize, Serialize};+use std::fs;+use std::io::Write;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicBool, Ordering};+use tauri::Manager;++const SETTING_FILE: &str = "gpu-rendering-v1";+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+const UNSAFE_FLAG_FILE: &str = "gpu-rendering-unsafe-v1";+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+const UNSAFE_REASON: &str = "error71";+/// Below this WebKitGTK the GPU path gave no measured speedup and can crash on NVIDIA Wayland+/// (Error 71 under explicit sync until 2.54.2).+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+const RECOMMENDED_WEBKIT: (u32, u32, u32) = (2, 54, 2);+/// wry's default WebView2 arguments, which any explicit value replaces wholesale.+#[cfg_attr(not(windows), allow(dead_code))]+const WEBVIEW2_DEFAULT_ARGS: &str =+ "--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection";+#[cfg_attr(not(windows), allow(dead_code))]+const WEBVIEW2_DISABLE_GPU: &str = "--disable-gpu";++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum GpuRendering {+ #[default]+ Auto,+ On,+ Off,+}++impl GpuRendering {+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Auto => "auto",+ Self::On => "on",+ Self::Off => "off",+ }+ }++ pub fn parse(text: &str) -> Option<Self> {+ match text.trim().to_ascii_lowercase().as_str() {+ "auto" => Some(Self::Auto),+ "on" => Some(Self::On),+ "off" => Some(Self::Off),+ _ => None,+ }+ }+}++/// Only Windows and Linux can change it: WKWebView has no public switch for GPU compositing.+pub const CONFIGURABLE: bool = cfg!(any(target_os = "windows", target_os = "linux"));++fn setting_path(config_dir: &Path) -> PathBuf {+ config_dir.join(SETTING_FILE)+}++/// Missing, unreadable or invalid reads as Auto.+pub fn read_setting(config_dir: &Path) -> GpuRendering {+ let path = setting_path(config_dir);+ match fs::read_to_string(&path) {+ Ok(text) => GpuRendering::parse(&text).unwrap_or_else(|| {+ warn!("Ignoring invalid GPU rendering setting {}", path.display());+ GpuRendering::Auto+ }),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => GpuRendering::Auto,+ Err(error) => {+ warn!(+ "Could not read GPU rendering setting {}: {error}",+ path.display()+ );+ GpuRendering::Auto+ }+ }+}++/// The setting the next launch applies; macOS has nothing to apply.+pub fn launch_setting(config_dir: Option<&Path>) -> GpuRendering {+ match config_dir {+ Some(dir) if CONFIGURABLE => read_setting(dir),+ _ => GpuRendering::Auto,+ }+}++/// Written to a temp file and renamed, so a crash never leaves half a file.+fn write_atomically(path: &Path, bytes: &[u8]) -> std::io::Result<()> {+ let parent = path+ .parent()+ .ok_or_else(|| std::io::Error::other("no parent folder"))?;+ fs::create_dir_all(parent)?;+ let mut temporary = tempfile::NamedTempFile::new_in(parent)?;+ temporary.write_all(bytes)?;+ temporary+ .persist(path)+ .map(|_| ())+ .map_err(|error| error.error)+}++pub fn write_setting(config_dir: &Path, setting: GpuRendering) -> Result<(), String> {+ let path = setting_path(config_dir);+ write_atomically(&path, format!("{}\n", setting.as_str()).as_bytes()).map_err(|error| {+ format!(+ "Failed to save GPU rendering setting {}: {error}",+ path.display()+ )+ })+}++/// What the crash flag is keyed by: a change to any of these may have fixed the crash.+#[derive(Clone, Debug, PartialEq, Eq)]+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+pub struct HostKey {+ pub webkit_version: (u32, u32, u32),+ /// First line of /proc/driver/nvidia/version.+ pub nvidia_driver: Option<String>,+ pub wayland_session: bool,+}++#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+impl HostKey {+ fn render(&self) -> String {+ let (major, minor, micro) = self.webkit_version;+ format!(+ "webkit={major}.{minor}.{micro}\nnvidia={}\nsession={}\nreason={UNSAFE_REASON}\n",+ self.nvidia_driver.as_deref().unwrap_or("none"),+ if self.wayland_session {+ "wayland"+ } else {+ "x11"+ },+ )+ }+}++#[derive(Debug, PartialEq, Eq)]+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+pub enum FlagState {+ Absent,+ Honoured,+ /// Deleted because it no longer describes this host; holds a log line.+ Cleared(String),+}++fn unsafe_flag_path(config_dir: &Path) -> PathBuf {+ config_dir.join(UNSAFE_FLAG_FILE)+}++/// Honours a flag written for this exact host and deletes any other, so it never outlives a+/// WebKit, driver or session change.+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+pub fn check_unsafe_flag(config_dir: &Path, key: &HostKey) -> FlagState {+ let path = unsafe_flag_path(config_dir);+ let Ok(stored) = fs::read_to_string(&path) else {+ return FlagState::Absent;+ };+ let expected = key.render();+ if stored == expected {+ return FlagState::Honoured;+ }+ let _ = fs::remove_file(&path);+ let changed = stored+ .lines()+ .zip(expected.lines())+ .filter(|(old, new)| old != new)+ .map(|(old, new)| format!("{old} -> {new}"))+ .collect::<Vec<_>>();+ let detail = if changed.is_empty() {+ "unreadable".to_string()+ } else {+ changed.join(", ")+ };+ FlagState::Cleared(format!("GPU rendering fallback flag cleared: {detail}"))+}++#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+pub fn write_unsafe_flag(config_dir: &Path, key: &HostKey) -> std::io::Result<()> {+ write_atomically(&unsafe_flag_path(config_dir), key.render().as_bytes())+}++/// True when a flag was there to remove.+pub fn clear_unsafe_flag(config_dir: &Path) -> bool {+ fs::remove_file(unsafe_flag_path(config_dir)).is_ok()+}++/// Shown next to On: the GPU path did not help on older WebKitGTK and can crash on NVIDIA.+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+pub fn old_webkit_warning(+ webkit_version: (u32, u32, u32),+ wayland_session: bool,+) -> Option<String> {+ let (major, minor, micro) = webkit_version;+ (wayland_session && webkit_version < RECOMMENDED_WEBKIT)+ .then(|| format!("{major}.{minor}.{micro}"))+}++/// WebView2 arguments for the main window: None keeps today's (wry's defaults).+#[cfg_attr(not(windows), allow(dead_code))]+pub fn windows_main_browser_args(setting: GpuRendering) -> Option<String> {+ (setting == GpuRendering::Off)+ .then(|| format!("{WEBVIEW2_DEFAULT_ARGS} {WEBVIEW2_DISABLE_GPU}"))+}++static PAGES_DISABLE_GPU: AtomicBool = AtomicBool::new(false);++/// Whether browser-panel pages should also start WebView2 without the GPU (Windows Off).+#[cfg_attr(not(windows), allow(dead_code))]+pub fn pages_disable_gpu() -> bool {+ PAGES_DISABLE_GPU.load(Ordering::SeqCst)+}++#[cfg_attr(not(windows), allow(dead_code))]+pub fn set_pages_disable_gpu(disabled: bool) {+ PAGES_DISABLE_GPU.store(disabled, Ordering::SeqCst);+}++/// What this launch applied, so the UI can tell a pending change from the running one.+pub struct LaunchState {+ pub setting: GpuRendering,+ pub fallback_active: bool,+ pub env_override: Option<&'static str>,+ pub old_webkit_warning: Option<String>,+ pub old_driver_warning: Option<String>,+ flag_cleared: AtomicBool,+}++impl LaunchState {+ pub fn new(+ setting: GpuRendering,+ fallback_active: bool,+ env_override: Option<&'static str>,+ old_webkit_warning: Option<String>,+ old_driver_warning: Option<String>,+ ) -> Self {+ Self {+ setting,+ fallback_active,+ env_override,+ old_webkit_warning,+ old_driver_warning,+ flag_cleared: AtomicBool::new(false),+ }+ }+}++#[derive(Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct GpuRenderingStatus {+ pub setting: GpuRendering,+ pub configurable: bool,+ pub restart_required: bool,+ pub fallback_active: bool,+ pub env_override: Option<String>,+ pub old_webkit_warning: Option<String>,+ pub old_driver_warning: Option<String>,+}++fn status(launch: &LaunchState, stored: GpuRendering) -> GpuRenderingStatus {+ if !CONFIGURABLE {+ return GpuRenderingStatus {+ setting: GpuRendering::On,+ configurable: false,+ restart_required: false,+ fallback_active: false,+ env_override: None,+ old_webkit_warning: None,+ old_driver_warning: None,+ };+ }+ let flag_cleared = launch.flag_cleared.load(Ordering::SeqCst);+ GpuRenderingStatus {+ setting: stored,+ configurable: true,+ restart_required: stored != launch.setting || (launch.fallback_active && flag_cleared),+ fallback_active: launch.fallback_active && !flag_cleared,+ env_override: launch.env_override.map(str::to_string),+ old_webkit_warning: launch.old_webkit_warning.clone(),+ old_driver_warning: launch.old_driver_warning.clone(),+ }+}++fn config_dir(app: &tauri::AppHandle) -> Result<PathBuf, String> {+ app.path()+ .app_config_dir()+ .map_err(|error| format!("Could not determine app configuration directory: {error}"))+}++#[tauri::command]+pub fn get_gpu_rendering(+ app: tauri::AppHandle,+ launch: tauri::State<'_, LaunchState>,+) -> Result<GpuRenderingStatus, String> {+ let stored = if CONFIGURABLE {+ read_setting(&config_dir(&app)?)+ } else {+ GpuRendering::On+ };+ Ok(status(&launch, stored))+}++/// Picking any value, the current one included, is also how the user retries the GPU path.+#[tauri::command]+pub fn set_gpu_rendering(+ app: tauri::AppHandle,+ launch: tauri::State<'_, LaunchState>,+ value: GpuRendering,+) -> Result<GpuRenderingStatus, String> {+ if !CONFIGURABLE {+ return Err("GPU rendering cannot be changed on macOS".to_string());+ }+ let dir = config_dir(&app)?;+ write_setting(&dir, value)?;+ if clear_unsafe_flag(&dir) {+ log::info!(+ "GPU rendering fallback flag cleared: setting set to {}",+ value.as_str()+ );+ }+ if launch.fallback_active {+ launch.flag_cleared.store(true, Ordering::SeqCst);+ }+ log::info!("GPU rendering setting saved: {}", value.as_str());+ Ok(status(&launch, value))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn key() -> HostKey {+ HostKey {+ webkit_version: (2, 54, 2),+ nvidia_driver: Some("NVRM version: NVIDIA UNIX Open Kernel Module 615.78.08".into()),+ wayland_session: true,+ }+ }++ #[test]+ fn the_setting_defaults_to_auto_and_round_trips() {+ let dir = tempfile::tempdir().unwrap();+ assert_eq!(read_setting(dir.path()), GpuRendering::Auto);+ for value in [GpuRendering::On, GpuRendering::Off, GpuRendering::Auto] {+ write_setting(dir.path(), value).unwrap();+ assert_eq!(read_setting(dir.path()), value);+ }+ assert_eq!(+ fs::read_to_string(setting_path(dir.path())).unwrap(),+ "auto\n"+ );+ }++ #[test]+ fn an_invalid_setting_reads_as_auto() {+ let dir = tempfile::tempdir().unwrap();+ for text in ["maybe\n", "", "1", "gpu"] {+ fs::write(setting_path(dir.path()), text).unwrap();+ assert_eq!(read_setting(dir.path()), GpuRendering::Auto, "{text:?}");+ }+ fs::write(setting_path(dir.path()), " OFF \n").unwrap();+ assert_eq!(read_setting(dir.path()), GpuRendering::Off);+ }++ #[test]+ fn a_flag_for_this_host_is_honoured_and_kept() {+ let dir = tempfile::tempdir().unwrap();+ assert_eq!(check_unsafe_flag(dir.path(), &key()), FlagState::Absent);+ write_unsafe_flag(dir.path(), &key()).unwrap();+ assert_eq!(check_unsafe_flag(dir.path(), &key()), FlagState::Honoured);+ assert_eq!(check_unsafe_flag(dir.path(), &key()), FlagState::Honoured);+ }++ #[test]+ fn a_flag_for_another_webkit_driver_or_session_is_deleted() {+ let mut webkit = key();+ webkit.webkit_version = (2, 54, 3);+ let mut driver = key();+ driver.nvidia_driver = Some("NVRM version: NVIDIA UNIX Open Kernel Module 620.10".into());+ let mut session = key();+ session.wayland_session = false;+ for (changed, needle) in [+ (webkit, "webkit=2.54.2 -> webkit=2.54.3"),+ (driver, "620.10"),+ (session, "session=wayland -> session=x11"),+ ] {+ let dir = tempfile::tempdir().unwrap();+ write_unsafe_flag(dir.path(), &key()).unwrap();+ match check_unsafe_flag(dir.path(), &changed) {+ FlagState::Cleared(line) => assert!(line.contains(needle), "{line}"),+ other => panic!("{other:?}"),+ }+ assert!(!unsafe_flag_path(dir.path()).exists());+ assert_eq!(check_unsafe_flag(dir.path(), &key()), FlagState::Absent);+ }+ }++ #[test]+ fn a_garbled_or_partial_flag_is_deleted_not_honoured() {+ let full = key().render();+ let partial = full.lines().take(3).collect::<Vec<_>>().join("\n") + "\n";+ let wrong_reason = full.replace("reason=error71", "reason=whatever");+ for text in ["", "garbage", partial.as_str(), wrong_reason.as_str()] {+ let dir = tempfile::tempdir().unwrap();+ fs::write(unsafe_flag_path(dir.path()), text).unwrap();+ assert!(+ matches!(check_unsafe_flag(dir.path(), &key()), FlagState::Cleared(_)),+ "{text:?}"+ );+ assert!(!unsafe_flag_path(dir.path()).exists());+ }+ }++ #[test]+ fn clearing_reports_whether_a_flag_was_there() {+ let dir = tempfile::tempdir().unwrap();+ assert!(!clear_unsafe_flag(dir.path()));+ write_unsafe_flag(dir.path(), &key()).unwrap();+ assert!(clear_unsafe_flag(dir.path()));+ assert_eq!(check_unsafe_flag(dir.path(), &key()), FlagState::Absent);+ }++ #[test]+ fn the_old_webkit_warning_is_for_wayland_below_2_54_2() {+ assert_eq!(+ old_webkit_warning((2, 50, 4), true).as_deref(),+ Some("2.50.4")+ );+ assert_eq!(+ old_webkit_warning((2, 53, 99), true).as_deref(),+ Some("2.53.99")+ );+ // 2.54.0 and 2.54.1 still crash with Error 71 under explicit sync.+ assert_eq!(+ old_webkit_warning((2, 54, 1), true).as_deref(),+ Some("2.54.1")+ );+ assert_eq!(old_webkit_warning((2, 54, 2), true), None);+ assert_eq!(old_webkit_warning((2, 50, 4), false), None);+ }++ #[test]+ fn only_off_changes_the_windows_arguments_and_keeps_wrys_defaults() {+ assert_eq!(windows_main_browser_args(GpuRendering::Auto), None);+ assert_eq!(windows_main_browser_args(GpuRendering::On), None);+ let off = windows_main_browser_args(GpuRendering::Off).unwrap();+ assert!(off.contains("--disable-gpu"), "{off}");+ assert!(off.starts_with(WEBVIEW2_DEFAULT_ARGS), "{off}");+ }++ #[cfg(any(target_os = "windows", target_os = "linux"))]+ #[test]+ fn status_reports_a_pending_change_and_a_retried_fallback() {+ let launch = LaunchState::new(GpuRendering::Auto, true, None, Some("2.50.4".into()), None);+ let before = status(&launch, GpuRendering::Auto);+ assert!(before.fallback_active && !before.restart_required);+ // "Try GPU again" re-selects Auto and clears the flag.+ launch.flag_cleared.store(true, Ordering::SeqCst);+ let after = status(&launch, GpuRendering::Auto);+ assert!(!after.fallback_active && after.restart_required);+ let quiet = LaunchState::new(+ GpuRendering::Auto,+ false,+ Some("WEBKIT_DISABLE_DMABUF_RENDERER"),+ None,+ Some("580".into()),+ );+ let changed = status(&quiet, GpuRendering::Off);+ assert!(changed.restart_required && changed.configurable);+ assert_eq!(+ changed.env_override.as_deref(),+ Some("WEBKIT_DISABLE_DMABUF_RENDERER")+ );+ assert_eq!(+ serde_json::to_value(&changed).unwrap()["oldWebkitWarning"],+ serde_json::Value::Null+ );+ assert_eq!(+ serde_json::to_value(&changed).unwrap()["oldDriverWarning"],+ serde_json::Value::from("580")+ );+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn macos_is_fixed_on_and_ignores_a_stored_value() {+ let dir = tempfile::tempdir().unwrap();+ write_setting(dir.path(), GpuRendering::Off).unwrap();+ assert_eq!(launch_setting(Some(dir.path())), GpuRendering::Auto);+ let launch = LaunchState::new(GpuRendering::Auto, false, None, None, None);+ let reported = status(&launch, GpuRendering::Off);+ assert_eq!(reported.setting, GpuRendering::On);+ assert!(!reported.configurable && !reported.restart_required);+ }+}diff --git a/studio/src-tauri/src/linux_gpu_supervisor.rs b/studio/src-tauri/src/linux_gpu_supervisor.rsnew file mode 100644index 00000000000..82debea75aa--- /dev/null+++ b/studio/src-tauri/src/linux_gpu_supervisor.rs@@ -0,0 +1,1252 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++//! Startup supervisor for GPU rendering on NVIDIA Wayland.+//!+//! WebKitGTK's GPU path can die at launch on NVIDIA Wayland: GTK3 logs+//! `Error 71 (Protocol error) dispatching to Wayland display.` and calls `_exit(1)`+//! (gdk/wayland/gdkeventsource.c, gtk-3-24, lines 203-205). Nothing in-process survives that,+//! so on hosts where the GPU path is risky `main()` becomes a small parent that runs the real+//! app as a child, and relaunches it once on the CPU path if the child dies that way before it+//! has shown a window.+//!+//! The parent never builds Tauri or GTK, so it never holds the single-instance D-Bus name.+//! Parent and child talk over an inherited `AF_UNIX` socket whose fd is named by+//! [`SUPERVISOR_FD_ENV`]:+//! - child to parent: `S` (a window was shown), `R` (a window has been on screen for+//! [`READY_GRACE`]), `E` (GDK logged a Wayland protocol error);+//! - parent to child: `T` (the parent got SIGTERM; please shut down cleanly).++use std::convert::Infallible;+use std::ffi::{CStr, OsString};+use std::io::{self, Read, Write};+use std::os::fd::{AsRawFd, FromRawFd, RawFd};+use std::os::unix::net::UnixStream;+use std::os::unix::process::{CommandExt, ExitStatusExt};+use std::process::{Command, ExitStatus};+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};+use std::sync::{Arc, Mutex, OnceLock};+use std::time::Duration;++/// Names the inherited supervisor socket fd in the child.+pub const SUPERVISOR_FD_ENV: &str = "UNSLOTH_GPU_SUPERVISOR_FD";+/// Set on the CPU relaunch; its value is the reason (`error71`).+pub const FALLBACK_ENV: &str = "UNSLOTH_GPU_FALLBACK";+/// Debug builds only: `1` makes a supervised child fake the GTK Error 71 exit.+#[cfg(debug_assertions)]+pub const TEST_ERROR71_ENV: &str = "UNSLOTH_TEST_GPU_ERROR71";++const MSG_SHOWN: u8 = b'S';+const MSG_READY: u8 = b'R';+const MSG_ERROR71: u8 = b'E';+const MSG_TERMINATE: u8 = b'T';+const FALLBACK_REASON: &str = "error71";+/// How long a window must stay up before the child counts the GPU path as working.+const READY_GRACE: Duration = Duration::from_secs(2);++static CHANNEL: OnceLock<UnixStream> = OnceLock::new();++// ---------------------------------------------------------------------------------------------+// Child side+// ---------------------------------------------------------------------------------------------++/// What the parent handed this process.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ChildChannel {+ /// A valid supervisor socket was inherited and is now held in a static.+ pub supervised: bool,+ /// The value of [`FALLBACK_ENV`], if set: the parent relaunched us on the CPU path.+ pub fallback: Option<String>,+}++/// Call first in `main()`, while the process is still single-threaded. Consumes and removes+/// both env vars so the backend and any `process::restart` grandchild start clean, checks the+/// fd is a socket (anything else is ignored and left alone), and marks it close-on-exec.+pub fn take_child_channel() -> ChildChannel {+ let (stream, fallback) = channel_from_env();+ let supervised = match stream {+ Some(stream) => CHANNEL.set(stream).is_ok() || CHANNEL.get().is_some(),+ None => CHANNEL.get().is_some(),+ };+ ChildChannel {+ supervised,+ fallback,+ }+}++fn channel_from_env() -> (Option<UnixStream>, Option<String>) {+ let fd = std::env::var_os(SUPERVISOR_FD_ENV);+ std::env::remove_var(SUPERVISOR_FD_ENV);+ let fallback = std::env::var_os(FALLBACK_ENV).map(|value| value.to_string_lossy().into_owned());+ std::env::remove_var(FALLBACK_ENV);++ let stream = fd+ .and_then(|fd| fd.to_str().and_then(|fd| fd.trim().parse::<RawFd>().ok()))+ .filter(|fd| *fd > 2 && fd_is_socket(*fd))+ .map(|fd| {+ set_cloexec(fd, true);+ // SAFETY: the fd is an open socket inherited from the parent and nothing else in+ // this process owns it.+ unsafe { UnixStream::from_raw_fd(fd) }+ });+ (stream, fallback)+}++fn fd_is_socket(fd: RawFd) -> bool {+ // SAFETY: fstat writes into a zeroed, correctly sized buffer.+ let mut stat: libc::stat = unsafe { std::mem::zeroed() };+ if unsafe { libc::fstat(fd, &mut stat) } != 0 {+ return false;+ }+ stat.st_mode & libc::S_IFMT == libc::S_IFSOCK+}++/// Async-signal-safe (only `fcntl`), so it may run in `pre_exec`.+fn set_cloexec(fd: RawFd, cloexec: bool) -> bool {+ // SAFETY: plain fcntl on an fd; failure is reported through the return value.+ unsafe {+ let flags = libc::fcntl(fd, libc::F_GETFD);+ if flags < 0 {+ return false;+ }+ let flags = if cloexec {+ flags | libc::FD_CLOEXEC+ } else {+ flags & !libc::FD_CLOEXEC+ };+ libc::fcntl(fd, libc::F_SETFD, flags) == 0+ }+}++/// Best effort: a dead parent must not hurt the child, so errors (and SIGPIPE) are ignored.+fn send(byte: u8) {+ if let Some(stream) = CHANNEL.get() {+ // SAFETY: one byte from a valid buffer; MSG_NOSIGNAL turns a closed peer into EPIPE.+ unsafe {+ libc::send(+ stream.as_raw_fd(),+ (&byte as *const u8).cast(),+ 1,+ libc::MSG_NOSIGNAL,+ );+ }+ }+}++/// GTK3 reports a fatal Wayland error with one of (gdk/wayland/gdkeventsource.c, gtk-3-24):+/// - `"Error %d (%s) dispatching to Wayland display."` (203-205)+/// - `"Error flushing display: %s"` (67)+/// - `"Error reading events from display: %s"` (96)+///+/// each followed by `_exit(1)`. Only EPROTO (71) is the GPU-buffer failure; EPIPE and+/// "Lost connection to Wayland compositor." mean the compositor went away and do not count.+pub fn is_wayland_protocol_error(msg: &str) -> bool {+ if msg.contains("Error 71 (") && msg.contains("dispatching to Wayland display") {+ return true;+ }+ let strerror = msg+ .strip_prefix("Error flushing display: ")+ .or_else(|| msg.strip_prefix("Error reading events from display: "));+ match strerror {+ // GLib translates g_strerror, so also compare against this locale's EPROTO text.+ Some(text) => {+ let text = text.trim();+ text == "Protocol error" || localized_eproto().is_some_and(|eproto| text == eproto)+ }+ None => false,+ }+}++fn localized_eproto() -> Option<String> {+ // SAFETY: g_strerror returns a valid, static, NUL-terminated UTF-8 string.+ let text = unsafe { CStr::from_ptr(glib::ffi::g_strerror(libc::EPROTO)) };+ text.to_str().ok().map(str::to_owned)+}++/// Child only (no-op without a channel): reports GDK's Wayland protocol error to the parent+/// before GTK's `_exit(1)`, then hands the message to GLib's default handler as before.+pub fn install_gdk_hook() {+ static INSTALLED: std::sync::Once = std::sync::Once::new();+ if CHANNEL.get().is_none() {+ return;+ }+ INSTALLED.call_once(|| {+ glib::log_set_handler(+ Some("Gdk"),+ glib::LogLevels::LEVEL_MESSAGE,+ false,+ false,+ |domain, level, message| {+ if is_wayland_protocol_error(message) {+ send(MSG_ERROR71);+ }+ glib::log_default_handler(domain, level, Some(message));+ },+ );+ // GTK 3 builds with G_LOG_USE_STRUCTURED, so its own g_message bypasses the handler above+ // and only reaches the writer. The writer can be set once per process, before any logging.+ glib::log_set_writer_func(|level, fields| {+ let field = |key: &str| {+ fields+ .iter()+ .find(|field| field.key() == key)+ .and_then(|field| field.value_str())+ };+ if field("GLIB_DOMAIN") == Some("Gdk")+ && field("MESSAGE").is_some_and(is_wayland_protocol_error)+ {+ send(MSG_ERROR71);+ }+ glib::log_writer_default(level, fields)+ });+ });+}++/// Call when a `--hidden` launch decides to show its window after all (an in-app relaunch).+/// The window's first frame is where Error 71 strikes, so the CPU relaunch must already know+/// not to come back hidden; [`note_window_shown`] still arms the ready timer later.+pub fn note_window_will_show() {+ send(MSG_SHOWN);+}++/// Call whenever the main window is shown. The first call arms a one-shot timer; if the+/// process is still alive [`READY_GRACE`] later it tells the parent the GPU path works.+pub fn note_window_shown() {+ static ARMED: AtomicBool = AtomicBool::new(false);+ if CHANNEL.get().is_none() || ARMED.swap(true, Ordering::SeqCst) {+ return;+ }+ // A CPU relaunch after this must not come back hidden: the user has seen the window.+ send(MSG_SHOWN);+ let spawned = std::thread::Builder::new()+ .name("gpu-supervisor-ready".to_string())+ .spawn(|| {+ std::thread::sleep(READY_GRACE);+ send(MSG_READY);+ });+ if spawned.is_err() {+ // No timer thread: say ready now rather than risk a needless CPU fallback later.+ send(MSG_READY);+ }+}++/// Child only: calls `on_terminate` once on the parent's `T` or a closed/broken control stream.+/// A dead supervisor must not strand the app in its separate process group, even if the parent+/// died before this reader began. Unread window-status messages can turn close into ECONNRESET.+pub fn start_control_reader(on_terminate: impl Fn() + Send + 'static) {+ let Some(stream) = CHANNEL.get() else {+ return;+ };+ let Ok(mut reader) = stream.try_clone() else {+ return;+ };+ let _ = std::thread::Builder::new()+ .name("gpu-supervisor-control".to_string())+ .spawn(move || {+ let mut fired = false;+ let mut buf = [0u8; 16];+ loop {+ match reader.read(&mut buf) {+ Ok(n) if n > 0 => {+ if !fired && buf[..n].contains(&MSG_TERMINATE) {+ fired = true;+ on_terminate();+ }+ }+ Err(error) if error.kind() == io::ErrorKind::Interrupted => {}+ _ => {+ if !fired {+ on_terminate();+ }+ return;+ }+ }+ }+ });+}++/// Debug builds: whether [`TEST_ERROR71_ENV`] asks for the crash simulation, so the caller can+/// make supervision eligible on any host.+pub fn test_hook_requested() -> bool {+ #[cfg(debug_assertions)]+ {+ std::env::var_os(TEST_ERROR71_ENV).is_some_and(|value| value == "1")+ }+ #[cfg(not(debug_assertions))]+ {+ false+ }+}++/// Debug builds: in a supervised child with [`TEST_ERROR71_ENV`]=1, log GTK's exact Error 71+/// line through GLib (so the real [`install_gdk_hook`] path runs) and exit 1 like GTK does.+#[cfg(debug_assertions)]+pub fn maybe_simulate_error71() {+ if CHANNEL.get().is_none() || !test_hook_requested() {+ return;+ }+ // Use GTK's exact structured API with NUL-terminated fields. Older GLib default writers+ // do not reliably print the explicitly sized, non-NUL fields in log_structured!.+ // SAFETY: all pointers are static C strings, and the format has no variadic arguments.+ unsafe {+ glib::ffi::g_log_structured_standard(+ c"Gdk".as_ptr(),+ glib::ffi::G_LOG_LEVEL_MESSAGE,+ c"linux_gpu_supervisor.rs".as_ptr(),+ c"0".as_ptr(),+ c"maybe_simulate_error71".as_ptr(),+ c"Error 71 (Protocol error) dispatching to Wayland display.".as_ptr(),+ );+ }+ std::process::exit(1);+}++// ---------------------------------------------------------------------------------------------+// Parent side+// ---------------------------------------------------------------------------------------------++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Outcome {+ /// The GPU child died of a Wayland protocol error before it was ready: relaunch on CPU.+ FallbackToCpu,+ /// Anything else: pass the child's status on unchanged.+ Propagate,+}++pub fn outcome(status: &ExitStatus, saw_ready: bool, saw_error71: bool) -> Outcome {+ if status.code() == Some(1) && saw_error71 && !saw_ready {+ Outcome::FallbackToCpu+ } else {+ Outcome::Propagate+ }+}++/// The child currently running, for the signal watcher.+#[derive(Default)]+struct Current {+ pid: Option<libc::pid_t>,+ control: Option<UnixStream>,+}++struct Shared {+ current: Mutex<Current>,+ terminations: AtomicUsize,+ /// Any termination signal: start no further child.+ /// Read under `current`'s lock by [`run_attempt`], so a request cannot slip between the+ /// check and the spawn.+ stopping: AtomicBool,+}++impl Shared {+ fn new() -> Arc<Self> {+ Arc::new(Self {+ current: Mutex::new(Current::default()),+ terminations: AtomicUsize::new(0),+ stopping: AtomicBool::new(false),+ })+ }++ /// The child has its own process group, so both PID-directed and group-directed signals+ /// reach it exactly once through this watcher.+ fn on_interrupt(&self, signal: libc::c_int) {+ // A following SIGTERM is a repeat even when the first request was INT/HUP/QUIT.+ self.terminations.fetch_add(1, Ordering::SeqCst);+ let current = self.current.lock().unwrap_or_else(|e| e.into_inner());+ self.stopping.store(true, Ordering::SeqCst);+ if let Some(pid) = current.pid {+ // SAFETY: our own child, still registered under the same lock as spawn/reap.+ unsafe {+ libc::kill(pid, signal);+ }+ }+ }++ fn on_sigterm(&self) {+ let count = self.terminations.fetch_add(1, Ordering::SeqCst) + 1;+ let current = self.current.lock().unwrap_or_else(|e| e.into_inner());+ self.stopping.store(true, Ordering::SeqCst);+ let Some(pid) = current.pid else {+ return;+ };+ let asked = count == 1+ && current+ .control+ .as_ref()+ .is_some_and(|mut control| control.write_all(&[MSG_TERMINATE]).is_ok());+ if !asked {+ // SAFETY: plain kill(2) on our own, not yet reaped, child.+ unsafe {+ libc::kill(pid, libc::SIGTERM);+ }+ }+ }+}++/// The running executable by its real path, so the child keeps the app's process name (`comm`+/// comes from the exec'd path; `/proc/self/exe` would name it "exe"). Falls back to+/// `/proc/self/exe` once the file is gone, e.g. a dpkg upgrade replaced it under us.+fn app_program(resolved: std::io::Result<std::path::PathBuf>) -> std::path::PathBuf {+ match resolved {+ Ok(path) if path.is_file() => path,+ _ => std::path::PathBuf::from("/proc/self/exe"),+ }+}++/// The real app, re-executed with the same argv[0] and arguments, so single-instance and+/// deep-link hand-off see identical argv.+fn app_command(fallback: bool, shown: bool) -> Command {+ let mut args = std::env::args_os();+ let arg0 = args+ .next()+ .unwrap_or_else(|| OsString::from("unsloth-studio"));+ let mut command = Command::new(app_program(std::env::current_exe()));+ command.arg0(arg0).args(relaunch_args(args, shown));+ if fallback {+ command.env(FALLBACK_ENV, FALLBACK_REASON);+ #[cfg(debug_assertions)]+ command.env_remove(TEST_ERROR71_ENV);+ }+ command+}++/// A login start's `--hidden` is dropped once its window was shown, so the CPU relaunch shows+/// the window the user had just opened instead of going back to the tray.+fn relaunch_args(args: impl Iterator<Item = OsString>, shown: bool) -> Vec<OsString> {+ args.filter(|arg| !(shown && arg == "--hidden")).collect()+}++/// Run the app as a supervised child and never return on success: the process exits with the+/// child's status (or re-raises its signal).+///+/// Returns `Err` only when the first child cannot be spawned. The caller should then log it and+/// carry on running the app in-process, unsupervised; the parent's signal watcher is closed.+/// `on_fallback` runs once, before the CPU relaunch (persist the "GPU unsafe" flag there).+pub fn run_parent(on_fallback: impl FnOnce(), log: impl Fn(&str)) -> Result<Infallible, io::Error> {+ let shared = Shared::new();+ // Watch signals before the first spawn, so a request in that window is not lost.+ let watcher = install_parent_signals(&shared);+ match supervise(app_command, &shared, on_fallback, &log) {+ Ok(status) => propagate(status),+ Err(error) => {+ if let Some(handle) = watcher {+ handle.close();+ }+ Err(error)+ }+ }+}++/// Forward interrupts to the child's separate process group via its PID. It does not receive+/// the original terminal/session group delivery, which would otherwise look like a repeat and+/// skip backend cleanup. SIGTERM retains the graceful shutdown control message.+fn install_parent_signals(shared: &Arc<Shared>) -> Option<signal_hook::iterator::Handle> {+ match signal_hook::iterator::Signals::new([+ libc::SIGTERM,+ libc::SIGINT,+ libc::SIGQUIT,+ libc::SIGHUP,+ ]) {+ Ok(mut signals) => {+ let handle = signals.handle();+ let shared = Arc::clone(shared);+ let _ = std::thread::Builder::new()+ .name("gpu-supervisor-signals".to_string())+ .spawn(move || {+ for signal in signals.forever() {+ if signal == libc::SIGTERM {+ shared.on_sigterm();+ } else {+ shared.on_interrupt(signal);+ }+ }+ });+ Some(handle)+ }+ Err(error) => {+ eprintln!("GPU supervisor: could not watch termination signals: {error}");+ None+ }+ }+}++struct Attempt {+ status: ExitStatus,+ saw_shown: bool,+ saw_ready: bool,+ saw_error71: bool,+}++/// What a supervised process exits with when it was asked to stop before a child ran.+fn terminated_status() -> ExitStatus {+ ExitStatus::from_raw((128 + libc::SIGTERM) << 8)+}++/// Spawns `make_command(false, false)`, and on [`Outcome::FallbackToCpu`] exactly one+/// `make_command(true, shown)`. Returns the status to propagate. A termination request before+/// a spawn means that child is never started.+fn supervise(+ mut make_command: impl FnMut(bool, bool) -> Command,+ shared: &Shared,+ on_fallback: impl FnOnce(),+ log: &dyn Fn(&str),+) -> io::Result<ExitStatus> {+ let Some(first) = run_attempt(make_command(false, false), shared)? else {+ log("GPU supervisor: asked to stop before the app started");+ return Ok(terminated_status());+ };+ let decision = outcome(&first.status, first.saw_ready, first.saw_error71);+ if decision == Outcome::Propagate {+ return Ok(first.status);+ }+ if shared.stopping.load(Ordering::SeqCst) {+ log("GPU supervisor: child hit Wayland Error 71 while terminating; not relaunching");+ return Ok(first.status);+ }++ on_fallback();+ log("GPU supervisor: the app exited with Wayland Error 71 before its window was ready");+ log("GPU supervisor: GPU rendering marked unsafe on this host; relaunching with CPU rendering");+ match run_attempt(make_command(true, first.saw_shown), shared) {+ Ok(None) => {+ log("GPU supervisor: asked to stop before the CPU relaunch; not relaunching");+ Ok(first.status)+ }+ Ok(Some(second)) => {+ log(&format!(+ "GPU supervisor: CPU relaunch exited with {}",+ describe(&second.status)+ ));+ Ok(second.status)+ }+ Err(error) => {+ log(&format!(+ "GPU supervisor: CPU relaunch failed to start: {error}"+ ));+ Ok(first.status)+ }+ }+}++/// `Ok(None)` when a termination request arrived before the spawn.+fn run_attempt(mut command: Command, shared: &Shared) -> io::Result<Option<Attempt>> {+ // std creates both ends close-on-exec; only the child's copy is made inheritable.+ let (mut parent_end, child_end) = UnixStream::pair()?;+ let child_fd = child_end.as_raw_fd();+ command.env(SUPERVISOR_FD_ENV, child_fd.to_string());+ command.process_group(0);+ // SAFETY: the closure only calls async-signal-safe fcntl(2) and signal(2).+ unsafe {+ command.pre_exec(move || {+ if !set_cloexec(child_fd, false) {+ return Err(io::Error::last_os_error());+ }+ for signal in [libc::SIGINT, libc::SIGQUIT, libc::SIGHUP, libc::SIGTERM] {+ libc::signal(signal, libc::SIG_DFL);+ }+ Ok(())+ });+ }++ let mut child = {+ // Hold the lock across spawn so SIGTERM cannot miss a child that is just starting.+ let mut current = shared.current.lock().unwrap_or_else(|e| e.into_inner());+ if shared.stopping.load(Ordering::SeqCst) {+ return Ok(None);+ }+ let child = command.spawn()?;+ current.pid = Some(child.id() as libc::pid_t);+ current.control = parent_end.try_clone().ok();+ child+ };+ drop(child_end);++ let status = loop {+ match child.wait() {+ Ok(status) => break status,+ Err(error) if error.kind() == io::ErrorKind::Interrupted => {}+ Err(error) => {+ *shared.current.lock().unwrap_or_else(|e| e.into_inner()) = Current::default();+ return Err(error);+ }+ }+ };+ *shared.current.lock().unwrap_or_else(|e| e.into_inner()) = Current::default();++ // The child writes before it exits, so everything it sent is already queued. Draining+ // after the wait cannot race the exit, and cannot block on a descendant holding the fd.+ let mut saw_shown = false;+ let mut saw_ready = false;+ let mut saw_error71 = false;+ parent_end.set_nonblocking(true)?;+ let mut buf = [0u8; 64];+ loop {+ match parent_end.read(&mut buf) {+ Ok(0) => break,+ Ok(n) => {+ saw_shown |= buf[..n].contains(&MSG_SHOWN);+ saw_ready |= buf[..n].contains(&MSG_READY);+ saw_error71 |= buf[..n].contains(&MSG_ERROR71);+ }+ Err(error) if error.kind() == io::ErrorKind::Interrupted => {}+ Err(_) => break,+ }+ }+ Ok(Some(Attempt {+ status,+ saw_shown,+ saw_ready,+ saw_error71,+ }))+}++fn describe(status: &ExitStatus) -> String {+ match (status.code(), status.signal()) {+ (Some(code), _) => format!("code {code}"),+ (None, Some(signal)) => format!("signal {signal}"),+ _ => "an unknown status".to_string(),+ }+}++/// Exit like the child did: same code, or die of the same signal.+fn propagate(status: ExitStatus) -> ! {+ if let Some(code) = status.code() {+ std::process::exit(code);+ }+ if let Some(signal) = status.signal() {+ // SAFETY: restore the default action and re-raise so our own parent sees the signal.+ unsafe {+ libc::signal(signal, libc::SIG_DFL);+ let mut set: libc::sigset_t = std::mem::zeroed();+ libc::sigemptyset(&mut set);+ libc::sigaddset(&mut set, signal);+ libc::pthread_sigmask(libc::SIG_UNBLOCK, &set, std::ptr::null_mut());+ libc::raise(signal);+ }+ std::process::exit(128 + signal);+ }+ std::process::exit(1);+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::cell::{Cell, RefCell};+ use std::os::fd::IntoRawFd;++ /// Tests that read or write process env hold this.+ static ENV_LOCK: Mutex<()> = Mutex::new(());++ fn exited(code: i32) -> ExitStatus {+ ExitStatus::from_raw(code << 8)+ }++ fn signaled(signal: i32) -> ExitStatus {+ ExitStatus::from_raw(signal)+ }++ #[test]+ fn outcome_truth_table() {+ // E then exit 1 before R.+ assert_eq!(outcome(&exited(1), false, true), Outcome::FallbackToCpu);+ // R then E + exit 1: the GPU path worked, so the crash is just propagated.+ assert_eq!(outcome(&exited(1), true, true), Outcome::Propagate);+ // Exit 1 without E.+ assert_eq!(outcome(&exited(1), false, false), Outcome::Propagate);+ // Other codes, even with E.+ assert_eq!(outcome(&exited(0), false, true), Outcome::Propagate);+ assert_eq!(outcome(&exited(0), false, false), Outcome::Propagate);+ assert_eq!(outcome(&exited(2), false, true), Outcome::Propagate);+ // Killed by a signal.+ assert_eq!(+ outcome(&signaled(libc::SIGKILL), false, true),+ Outcome::Propagate+ );+ assert_eq!(signaled(libc::SIGKILL).signal(), Some(libc::SIGKILL));+ }++ #[test]+ fn classifier_matches_gtk_protocol_errors_only() {+ assert!(is_wayland_protocol_error(+ "Error 71 (Protocol error) dispatching to Wayland display."+ ));+ // Translated strerror, same errno.+ assert!(is_wayland_protocol_error(+ "Error 71 (Protokollfehler) dispatching to Wayland display."+ ));+ assert!(is_wayland_protocol_error(+ "Error flushing display: Protocol error"+ ));+ assert!(is_wayland_protocol_error(+ "Error reading events from display: Protocol error"+ ));+ if let Some(eproto) = localized_eproto() {+ assert!(is_wayland_protocol_error(&format!(+ "Error flushing display: {eproto}"+ )));+ }++ assert!(!is_wayland_protocol_error(+ "Error 32 (Broken pipe) dispatching to Wayland display."+ ));+ assert!(!is_wayland_protocol_error(+ "Error flushing display: Broken pipe"+ ));+ assert!(!is_wayland_protocol_error(+ "Error reading events from display: Connection reset by peer"+ ));+ assert!(!is_wayland_protocol_error(+ "Lost connection to Wayland compositor."+ ));+ assert!(!is_wayland_protocol_error("Error 71 (Protocol error)"));+ assert!(!is_wayland_protocol_error(""));+ }++ #[test]+ fn channel_from_env_accepts_sockets_and_clears_env() {+ let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let (ours, theirs) = UnixStream::pair().unwrap();+ let fd = theirs.into_raw_fd();+ set_cloexec(fd, false);+ std::env::set_var(SUPERVISOR_FD_ENV, fd.to_string());+ std::env::set_var(FALLBACK_ENV, "error71");++ let (stream, fallback) = channel_from_env();+ assert_eq!(fallback.as_deref(), Some("error71"));+ assert!(std::env::var_os(SUPERVISOR_FD_ENV).is_none());+ assert!(std::env::var_os(FALLBACK_ENV).is_none());+ let mut stream = stream.expect("socket fd accepted");+ assert_eq!(stream.as_raw_fd(), fd);+ let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };+ assert_ne!(flags & libc::FD_CLOEXEC, 0, "fd marked close-on-exec");+ stream.write_all(b"R").unwrap();+ let mut byte = [0u8; 1];+ (&ours).read_exact(&mut byte).unwrap();+ assert_eq!(&byte, b"R");+ }++ #[test]+ fn channel_from_env_ignores_non_sockets_and_garbage() {+ let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let file = std::fs::File::open("/proc/self/exe").unwrap();+ std::env::set_var(SUPERVISOR_FD_ENV, file.as_raw_fd().to_string());+ let (stream, fallback) = channel_from_env();+ assert!(stream.is_none());+ assert!(fallback.is_none());+ assert!(std::env::var_os(SUPERVISOR_FD_ENV).is_none());+ // The fd we were wrongly pointed at is left open.+ assert!(unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETFD) } >= 0);++ for value in ["", "abc", "-1", "1", "999999"] {+ std::env::set_var(SUPERVISOR_FD_ENV, value);+ assert!(channel_from_env().0.is_none(), "{value:?}");+ }+ }++ /// Runs `supervise` with `bash -c <script>` children; returns (status, spawn flags, fallback+ /// calls, log lines). Not sh: dash rejects `>&N` once N has two digits, which a parallel test+ /// run reaches.+ fn fake_supervise(scripts: &[&str]) -> (ExitStatus, Vec<bool>, usize, Vec<String>) {+ let spawns = RefCell::new(Vec::new());+ let fallbacks = Cell::new(0);+ let logs = RefCell::new(Vec::new());+ let shared = Shared::new();+ let status = supervise(+ |fallback, _shown| {+ let index = spawns.borrow().len().min(scripts.len() - 1);+ spawns.borrow_mut().push(fallback);+ let mut command = Command::new("bash");+ command.arg("-c").arg(scripts[index]);+ if fallback {+ command.env(FALLBACK_ENV, FALLBACK_REASON);+ }+ command+ },+ &shared,+ || fallbacks.set(fallbacks.get() + 1),+ &|line| logs.borrow_mut().push(line.to_string()),+ )+ .expect("bash spawns");+ (+ status,+ spawns.into_inner(),+ fallbacks.get(),+ logs.into_inner(),+ )+ }++ #[test]+ fn fake_child_error71_falls_back_once() {+ let (status, spawns, fallbacks, logs) = fake_supervise(&[+ "printf E >&$UNSLOTH_GPU_SUPERVISOR_FD; exit 1",+ // The CPU child sees the fallback env and a fresh socket.+ "[ \"$UNSLOTH_GPU_FALLBACK\" = error71 ] && printf x >&$UNSLOTH_GPU_SUPERVISOR_FD && exit 7; exit 9",+ ]);+ assert_eq!(spawns, vec![false, true]);+ assert_eq!(fallbacks, 1);+ assert_eq!(status.code(), Some(7));+ assert!(logs.iter().any(|line| line.contains("CPU rendering")));+ }++ #[test]+ fn fake_child_error71_twice_still_spawns_only_twice() {+ let (status, spawns, fallbacks, _) =+ fake_supervise(&["printf E >&$UNSLOTH_GPU_SUPERVISOR_FD; exit 1"]);+ assert_eq!(spawns.len(), 2);+ assert_eq!(fallbacks, 1);+ assert_eq!(status.code(), Some(1));+ }++ #[test]+ fn fake_child_ready_then_error71_propagates() {+ let (status, spawns, fallbacks, _) =+ fake_supervise(&["printf RE >&$UNSLOTH_GPU_SUPERVISOR_FD; exit 1"]);+ assert_eq!(spawns, vec![false]);+ assert_eq!(fallbacks, 0);+ assert_eq!(status.code(), Some(1));+ }++ #[test]+ fn fake_child_plain_exits_propagate() {+ for (script, code) in [("exit 0", 0), ("exit 1", 1), ("exit 3", 3)] {+ let (status, spawns, fallbacks, _) = fake_supervise(&[script]);+ assert_eq!(spawns.len(), 1, "{script}");+ assert_eq!(fallbacks, 0, "{script}");+ assert_eq!(status.code(), Some(code), "{script}");+ }+ }++ #[test]+ fn fake_child_signal_propagates() {+ let (status, spawns, fallbacks, _) =+ fake_supervise(&["printf E >&$UNSLOTH_GPU_SUPERVISOR_FD; kill -KILL $$"]);+ assert_eq!(spawns.len(), 1);+ assert_eq!(fallbacks, 0);+ assert_eq!(status.signal(), Some(libc::SIGKILL));+ }++ #[test]+ fn fake_child_gets_inheritable_socket_only() {+ // The fd is a socket in the child, and the parent's own end is not inherited.+ let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let (status, _, _, _) = fake_supervise(&[+ "fd=$UNSLOTH_GPU_SUPERVISOR_FD; [ -S /proc/$$/fd/$fd ] || exit 4; \+ for f in /proc/$$/fd/*; do n=${f##*/}; \+ case $n in 0|1|2|$fd) ;; *) [ -S $f ] && exit 5;; esac; done; exit 0",+ ]);+ assert_eq!(status.code(), Some(0));+ }++ /// Re-execs this test binary as the supervised child (the windows_job.rs pattern), so the+ /// real take_child_channel -> install_gdk_hook -> g_log_structured_standard -> exit(1) runs.+ #[cfg(debug_assertions)]+ #[test]+ fn real_gdk_hook_drives_fallback_end_to_end() {+ const CHILD_MARKER: &str = "UNSLOTH_GPU_SUPERVISOR_TEST_CHILD";+ const NAME: &str = "linux_gpu_supervisor::tests::real_gdk_hook_drives_fallback_end_to_end";+ if std::env::var_os(CHILD_MARKER).is_some() {+ let channel = take_child_channel();+ assert!(channel.supervised);+ assert!(std::env::var_os(SUPERVISOR_FD_ENV).is_none());+ install_gdk_hook();+ maybe_simulate_error71(); // exits 1 when the hook env is set+ let code = if channel.fallback.as_deref() == Some(FALLBACK_REASON) {+ 0+ } else {+ 3+ };+ std::process::exit(code);+ }++ let exe = std::env::current_exe().unwrap();+ let spawns = RefCell::new(Vec::new());+ let fallbacks = Cell::new(0);+ let status = supervise(+ |fallback, _shown| {+ spawns.borrow_mut().push(fallback);+ let mut command = Command::new(&exe);+ command+ .args([NAME, "--exact", "--nocapture", "--test-threads=1"])+ .env(CHILD_MARKER, "1");+ if fallback {+ command+ .env(FALLBACK_ENV, FALLBACK_REASON)+ .env_remove(TEST_ERROR71_ENV);+ } else {+ command.env(TEST_ERROR71_ENV, "1");+ }+ command+ },+ &Shared::new(),+ || fallbacks.set(fallbacks.get() + 1),+ &|_| {},+ )+ .unwrap();+ assert_eq!(spawns.into_inner(), vec![false, true]);+ assert_eq!(fallbacks.get(), 1);+ assert_eq!(status.code(), Some(0));+ }++ #[test]+ fn sigterm_asks_child_then_kills() {+ let shared = Shared::new();+ let logs = RefCell::new(Vec::new());+ let shared_for_thread = Arc::clone(&shared);+ let killer = std::thread::spawn(move || {+ // Wait for the child to start, then deliver two "SIGTERM"s to the parent logic.+ loop {+ if shared_for_thread.current.lock().unwrap().pid.is_some() {+ break;+ }+ std::thread::sleep(Duration::from_millis(10));+ }+ std::thread::sleep(Duration::from_millis(200));+ shared_for_thread.on_sigterm();+ });+ // The child exits 143 once it reads T, like the real app.exit(143).+ let status = supervise(+ |_, _| {+ let mut command = Command::new("bash");+ command.arg("-c").arg(+ "c=$(dd bs=1 count=1 <&$UNSLOTH_GPU_SUPERVISOR_FD 2>/dev/null); \+ [ \"$c\" = T ] && exit 143; exit 2",+ );+ command+ },+ &shared,+ || panic!("no fallback"),+ &|line| logs.borrow_mut().push(line.to_string()),+ )+ .unwrap();+ killer.join().unwrap();+ assert_eq!(status.code(), Some(143));++ // Second SIGTERM: a real signal to the child.+ let shared = Shared::new();+ shared.terminations.store(1, Ordering::SeqCst);+ let shared_for_thread = Arc::clone(&shared);+ let killer = std::thread::spawn(move || {+ loop {+ if shared_for_thread.current.lock().unwrap().pid.is_some() {+ break;+ }+ std::thread::sleep(Duration::from_millis(10));+ }+ std::thread::sleep(Duration::from_millis(200));+ shared_for_thread.on_sigterm();+ });+ let status = supervise(+ |_, _| {+ let mut command = Command::new("bash");+ command.arg("-c").arg("exec sleep 30");+ command+ },+ &shared,+ || panic!("no fallback"),+ &|_| {},+ )+ .unwrap();+ killer.join().unwrap();+ assert_eq!(status.signal(), Some(libc::SIGTERM));+ }++ #[test]+ fn child_helpers_are_noops_without_channel() {+ // Tests never set CHANNEL (channel_from_env does not touch the static).+ assert!(CHANNEL.get().is_none());+ note_window_shown();+ note_window_will_show();+ start_control_reader(|| panic!("no channel"));+ install_gdk_hook();+ #[cfg(debug_assertions)]+ maybe_simulate_error71();+ }++ #[test]+ fn app_command_strips_test_hook_on_fallback() {+ let command = app_command(true, false);+ assert_eq!(+ std::path::Path::new(command.get_program()),+ std::env::current_exe().unwrap()+ );+ let envs: Vec<_> = command.get_envs().collect();+ assert!(envs.contains(&(+ std::ffi::OsStr::new(FALLBACK_ENV),+ Some(std::ffi::OsStr::new("error71"))+ )));+ #[cfg(debug_assertions)]+ assert!(envs.contains(&(std::ffi::OsStr::new(TEST_ERROR71_ENV), None)));+ assert!(app_command(false, false).get_envs().next().is_none());+ assert_eq!(+ app_command(false, false).get_args().count(),+ std::env::args_os().count() - 1+ );+ }++ #[test]+ fn the_child_keeps_the_app_name_and_falls_back_once_the_file_is_gone() {+ let exe = std::env::current_exe().unwrap();+ assert_eq!(app_program(Ok(exe.clone())), exe);+ let gone = std::path::PathBuf::from("/nonexistent/unsloth-studio (deleted)");+ assert_eq!(+ app_program(Ok(gone)),+ std::path::PathBuf::from("/proc/self/exe")+ );+ assert_eq!(+ app_program(Err(std::io::Error::other("no exe"))),+ std::path::PathBuf::from("/proc/self/exe")+ );+ }++ #[test]+ fn a_shown_window_drops_hidden_from_the_cpu_relaunch() {+ let args = || {+ ["--hidden", "unsloth://open"]+ .map(OsString::from)+ .into_iter()+ };+ assert_eq!(relaunch_args(args(), false), args().collect::<Vec<_>>());+ assert_eq!(+ relaunch_args(args(), true),+ vec![OsString::from("unsloth://open")]+ );++ // The parent learns about the shown window from the crashed child's S.+ let shown = RefCell::new(Vec::new());+ let status = supervise(+ |fallback, was_shown| {+ shown.borrow_mut().push(was_shown);+ let mut command = Command::new("bash");+ let script = if fallback {+ "exit 0"+ } else {+ "printf SE >&$UNSLOTH_GPU_SUPERVISOR_FD; exit 1"+ };+ command.arg("-c").arg(script);+ command+ },+ &Shared::new(),+ || {},+ &|_| {},+ )+ .unwrap();+ assert_eq!(status.code(), Some(0));+ assert_eq!(shown.into_inner(), vec![false, true]);+ }++ #[test]+ fn a_termination_before_the_first_spawn_starts_nothing() {+ let shared = Shared::new();+ shared.on_sigterm();+ let spawns = Cell::new(0);+ let status = supervise(+ |_, _| {+ spawns.set(spawns.get() + 1);+ Command::new("true")+ },+ &shared,+ || panic!("no fallback"),+ &|_| {},+ )+ .unwrap();+ assert_eq!(spawns.get(), 1, "the command is built, never spawned");+ assert_eq!(status.code(), Some(128 + libc::SIGTERM));+ }++ #[test]+ fn a_termination_between_the_crash_and_the_cpu_relaunch_stops_the_relaunch() {+ // SIGTERM lands while on_fallback runs: no child is registered at that moment.+ let shared = Shared::new();+ let spawned = RefCell::new(Vec::new());+ let logs = RefCell::new(Vec::new());+ let status = supervise(+ |fallback, _| {+ let mut command = Command::new("bash");+ // A CPU child that did start would exit 7.+ let script = if fallback {+ "exit 7"+ } else {+ "printf E >&$UNSLOTH_GPU_SUPERVISOR_FD; exit 1"+ };+ command.arg("-c").arg(script);+ spawned.borrow_mut().push(fallback);+ command+ },+ &shared,+ || shared.on_sigterm(),+ &|line| logs.borrow_mut().push(line.to_string()),+ )+ .unwrap();+ assert_eq!(status.code(), Some(1));+ assert!(logs+ .borrow()+ .iter()+ .any(|line| line.contains("not relaunching")));+ assert_eq!(shared.current.lock().unwrap().pid, None);+ }++ #[test]+ fn interrupts_before_a_spawn_stop_the_supervisor() {+ for signal in [libc::SIGINT, libc::SIGHUP, libc::SIGQUIT] {+ let shared = Shared::new();+ shared.on_interrupt(signal);+ assert!(shared.stopping.load(Ordering::SeqCst));+ assert!(run_attempt(Command::new("false"), &shared)+ .unwrap()+ .is_none());+ }+ }++ /// Separate processes exercise real signal delivery without installing handlers in the+ /// parallel test runner. A duplicate signal would interrupt the child's simulated cleanup.+ #[test]+ fn pid_and_group_signals_reach_the_child_once() {+ const ROLE: &str = "UNSLOTH_SUPERVISOR_SIGNAL_TEST";+ const STATE: &str = "UNSLOTH_SUPERVISOR_SIGNAL_TEST_STATE";+ const NAME: &str =+ "linux_gpu_supervisor::tests::pid_and_group_signals_reach_the_child_once";++ if std::env::var_os(ROLE).is_some() {+ let channel = take_child_channel();+ if !channel.supervised {+ run_parent(|| panic!("no fallback"), |_| {}).unwrap();+ }+ let state = std::path::PathBuf::from(std::env::var_os(STATE).unwrap());+ let received = Arc::new(AtomicUsize::new(0));+ let on_signal = {+ let received = Arc::clone(&received);+ let state = state.clone();+ move |signal: libc::c_int| {+ if received.fetch_add(1, Ordering::SeqCst) != 0 {+ std::process::exit(90);+ }+ let state = state.clone();+ std::thread::spawn(move || {+ std::thread::sleep(Duration::from_millis(200));+ std::fs::write(state.join("cleaned"), signal.to_string()).unwrap();+ std::process::exit(128 + signal);+ });+ }+ };+ let mut signals = signal_hook::iterator::Signals::new([+ libc::SIGINT,+ libc::SIGHUP,+ libc::SIGQUIT,+ libc::SIGTERM,+ ])+ .unwrap();+ let on_control = on_signal.clone();+ start_control_reader(move || on_control(libc::SIGTERM));+ // A real GUI reports its window before the parent drains the channel. If the+ // supervisor is killed with this unread data, Linux resets the peer, not just EOF.+ note_window_will_show();+ // SAFETY: getpgrp only reads the calling process's group ID.+ let pgid = unsafe { libc::getpgrp() };+ std::fs::write(+ state.join("ready"),+ format!("{} {pgid}", std::process::id()),+ )+ .unwrap();+ for signal in signals.forever() {+ on_signal(signal);+ }+ unreachable!();+ }++ for signal in [libc::SIGINT, libc::SIGHUP, libc::SIGQUIT, libc::SIGTERM] {+ for group in [false, true] {+ check_signal(signal, group, false);+ }+ }+ // An uncatchable group signal must not strand the app in its separate group.+ check_signal(libc::SIGKILL, true, true);++ fn check_signal(signal: libc::c_int, group: bool, parent_death: bool) {+ let state = tempfile::tempdir().unwrap();+ let mut supervisor = Command::new(std::env::current_exe().unwrap())+ .args([NAME, "--exact", "--nocapture"])+ .env(ROLE, "1")+ .env(STATE, state.path())+ .process_group(0)+ .spawn()+ .unwrap();+ let supervisor_pid = supervisor.id() as libc::pid_t;+ let deadline = std::time::Instant::now() + Duration::from_secs(10);+ let mut child_pid = None;+ let checked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ let ready = loop {+ if let Ok(ready) = std::fs::read_to_string(state.path().join("ready")) {+ break ready;+ }+ assert!(+ supervisor.try_wait().unwrap().is_none(),+ "supervisor exited early"+ );+ assert!(+ std::time::Instant::now() < deadline,+ "child did not become ready"+ );+ std::thread::sleep(Duration::from_millis(10));+ };+ let ids: Vec<libc::pid_t> = ready+ .split_whitespace()+ .map(|id| id.parse().unwrap())+ .collect();+ child_pid = Some(ids[0]);+ assert_eq!(ids[0], ids[1], "child leads its own process group");+ assert_ne!(+ ids[1], supervisor_pid,+ "child cannot receive the original group signal"+ );+ let target = if group {+ -supervisor_pid+ } else {+ supervisor_pid+ };+ // SAFETY: the test created this isolated process group and waited for its child.+ assert_eq!(unsafe { libc::kill(target, signal) }, 0);+ let status = loop {+ if let Some(status) = supervisor.try_wait().unwrap() {+ break status;+ }+ assert!(+ std::time::Instant::now() < deadline,+ "supervisor ignored signal {signal}"+ );+ std::thread::sleep(Duration::from_millis(10));+ };+ if parent_death {+ assert_eq!(status.signal(), Some(libc::SIGKILL));+ } else {+ assert_eq!(+ status.code(),+ Some(128 + signal),+ "signal {signal}, group={group}"+ );+ }+ let cleaned = loop {+ if let Ok(cleaned) = std::fs::read_to_string(state.path().join("cleaned")) {+ break cleaned;+ }+ assert!(+ std::time::Instant::now() < deadline,+ "child cleanup did not finish"+ );+ std::thread::sleep(Duration::from_millis(10));+ };+ let expected = if parent_death { libc::SIGTERM } else { signal };+ assert_eq!(cleaned, expected.to_string());+ }));+ if checked.is_err() {+ let _ = supervisor.kill();+ if let Some(pid) = child_pid {+ // SAFETY: only the child PID recorded for this test can be killed.+ unsafe { libc::kill(pid, libc::SIGKILL) };+ }+ }+ let _ = supervisor.wait();+ if let Err(error) = checked {+ std::panic::resume_unwind(error);+ }+ }+ }+}diff --git a/studio/src-tauri/src/linux_webkit.rs b/studio/src-tauri/src/linux_webkit.rsindex b96a3b8d318..71934a7eacc 100644--- a/studio/src-tauri/src/linux_webkit.rs+++ b/studio/src-tauri/src/linux_webkit.rs@@ -4,6 +4,8 @@use std::ffi::{OsStr, OsString};use std::os::unix::net::UnixStream;+use crate::gpu_rendering::GpuRendering;+const APPIMAGE: &str = "APPIMAGE";const GLES_V2: &[u8] = b"libGLESv2.so.2\0";@@ -45,6 +47,23 @@ const NVIDIA_APPIMAGE_GLES_REASON: &str =const WAYLAND_REASON: &str = "Wayland session";const APPIMAGE_GLES_REASON: &str = "AppImage without a usable GLES library";const COMPOSITING_FORCED_REASON: &str = "compositing workaround requested by the environment";+const GPU_OFF_REASON: &str = "GPU rendering off (setting)";+const GPU_ON_REASON: &str = "GPU rendering on (setting)";+const GPU_ON_OLD_NVIDIA_REASON: &str =+ "GPU rendering on (setting), held off: NVIDIA drivers before 610 leak with compositing on X11";+const GPU_UNSAFE_REASON: &str = "GPU rendering crashed at launch on this host before";+const NVIDIA_WAYLAND_GPU_REASON: &str = "NVIDIA driver loaded (Wayland session, WebKitGTK 2.54.2+)";+const FORCE_DMABUF_REASON: &str = "DMA-BUF renderer requested by the environment (Wayland session)";+// 2.54.0 and 2.54.1 die with Error 71 under explicit sync (WebKit bug 280210); the fix (bug 324551)+// first shipped in 2.54.2. Other hosts can still crash at launch, so this path is supervised.+const NVIDIA_WAYLAND_GPU_MIN_VERSION: (u32, u32, u32) = (2, 54, 2);++/// The user's "GPU rendering" choice plus whether an earlier launch fell back on this host.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct GpuInputs {+ pub setting: GpuRendering,+ pub unsafe_flag: bool,+}#[derive(Clone, Copy, Debug, PartialEq, Eq)]enum RenderingWorkaround {@@ -55,6 +74,8 @@ enum RenderingWorkaround {/// The same, plus the non-GL video sink the bundled GStreamer needs.ForceSharedMemoryOnNvidiaAppImage,DisableCompositingOnNvidiaX11,+ /// The CPU path on X11 off NVIDIA: SHM keeps a transport, unlike DISABLE_DMABUF.+ DisableCompositingOnX11,/// Compositing off on top of the NVIDIA Wayland transport, not instead of it: since/// WebKitGTK 2.53 non-composited mode still renders over DMA-BUF (#13875).DisableCompositingOnNvidiaWayland,@@ -74,6 +95,7 @@ impl RenderingWorkaround {Self::DisableCompositingOnNvidiaX11 => {&[FORCE_SHARED_MEMORY, FORCE_DMABUF, DISABLE_COMPOSITING]}+ Self::DisableCompositingOnX11 => &[FORCE_SHARED_MEMORY, DISABLE_COMPOSITING],Self::DisableCompositingOnNvidiaWayland => &[DISABLE_DMABUF, DISABLE_COMPOSITING],Self::DisableDmabuf => &[DISABLE_DMABUF],Self::DisableCompositing => &[DISABLE_COMPOSITING],@@ -85,6 +107,59 @@ impl RenderingWorkaround {enum RenderingPlan {Apply(RenderingWorkaround, &'static str),PreserveEnvironment,+ /// Keep WebKit's GPU path. `force_dmabuf` also stands down disable-nvidia-dmabuf.patch.+ Gpu {+ force_dmabuf: bool,+ reason: &'static str,+ },+}++/// Names of the variables an earlier launch of this tree set (see APPLIED_WORKAROUND).+fn claimed_by_this_app(env: &impl Fn(&str) -> Option<OsString>, variable: &str) -> bool {+ env(APPLIED_WORKAROUND)+ .unwrap_or_default()+ .to_string_lossy()+ .split(',')+ .any(|claimed| claimed == variable)+}++/// The operator variable that takes the decision away from the GPU rendering setting, if any.+fn env_override(env: &impl Fn(&str) -> Option<OsString>) -> Option<&'static str> {+ let operator = |variable: &str| env(variable).is_some() && !claimed_by_this_app(env, variable);+ for variable in [DISABLE_DMABUF, FORCE_SHARED_MEMORY, DISABLE_COMPOSITING] {+ if operator(variable) {+ return Some(variable);+ }+ }+ if env(DISABLE_COMPOSITING_SETTING)+ .as_deref()+ .and_then(compositing_setting)+ .is_some()+ {+ return Some(DISABLE_COMPOSITING_SETTING);+ }+ if operator(FORCE_DMABUF)+ && env(FORCE_DMABUF)+ .as_deref()+ .is_some_and(force_dmabuf_requested)+ {+ return Some(FORCE_DMABUF);+ }+ None+}++fn session_is_wayland(+ env: &impl Fn(&str) -> Option<OsString>,+ wayland_socket: bool,+ x11_open: bool,+) -> bool {+ // Decide by which backend opens: WAYLAND_DISPLAY and DISPLAY are inherited and outlive+ // their servers. Unset GDK_BACKEND is GDK's "*" (wayland before x11).+ selected_backend_is_wayland(+ env(GDK_BACKEND).as_deref().unwrap_or(OsStr::new("*")),+ wayland_socket,+ x11_open,+ )}/// Resolve GDK_BACKEND as gdk_display_manager_open_display does: exact comma entries in order,@@ -138,17 +213,12 @@ fn rendering_plan(nvidia_driver_branch: Option<u32>,wayland_socket: bool,x11_open: bool,+ gpu: GpuInputs,) -> RenderingPlan {let nvidia_driver_loaded = nvidia_driver_branch.is_some();// Either variable is an operator override when present (even `=0` or empty) unless the marker// says we wrote it. DISABLE_DMABUF=0 is how a host gets its accelerated path back.- let applied_by_this_app = env(APPLIED_WORKAROUND).unwrap_or_default();- let ours = |variable: &str| {- applied_by_this_app- .to_string_lossy()- .split(',')- .any(|claimed| claimed == variable)- };+ let ours = |variable: &str| claimed_by_this_app(&env, variable);if env(DISABLE_DMABUF).is_some() && !ours(DISABLE_DMABUF) {return RenderingPlan::PreserveEnvironment;@@ -167,21 +237,15 @@ fn rendering_plan(}let operator_compositing_off = operator_compositing.is_some();- // Stands the NVIDIA branch down only, not the missing-GLES fallback below.+ // The operator asked for WebKit's DMA-BUF renderer: only a missing GLES library or a crash+ // at an earlier launch outranks it (see the force_dmabuf branch below).let force_dmabuf = !ours(FORCE_DMABUF)&& env(FORCE_DMABUF).as_deref().is_some_and(force_dmabuf_requested);let is_appimage = env(APPIMAGE).is_some();- // Decide by which backend opens: WAYLAND_DISPLAY and DISPLAY are inherited and outlive- // their servers.- // Unset GDK_BACKEND is GDK's "*" (wayland before x11).- let wayland_session = selected_backend_is_wayland(- env(GDK_BACKEND).as_deref().unwrap_or(OsStr::new("*")),- wayland_socket,- x11_open,- );+ let wayland_session = session_is_wayland(&env, wayland_socket, x11_open);let nvidia_x11 = nvidia_driver_loaded&& !force_dmabuf&& !wayland_session@@ -214,10 +278,108 @@ fn rendering_plan(return RenderingPlan::Apply(workaround, COMPOSITING_FORCED_REASON);}+ // libepoxy loads GLES at runtime; without it no setting can keep DMA-BUF.+ let missing_appimage_gles = is_appimage && !gles_usable;+ // Composited SHM on NVIDIA; an AppImage also needs the non-GL video sink, unless the operator+ // chose one.+ let nvidia_shared_memory = || {+ let operator_sink = env(GST_DISABLE_GL_SINK).is_some() && !ours(GST_DISABLE_GL_SINK);+ if is_appimage && !operator_sink {+ RenderingWorkaround::ForceSharedMemoryOnNvidiaAppImage+ } else {+ RenderingWorkaround::ForceSharedMemoryOnNvidia+ }+ };+ // The operator asked for WebKit's DMA-BUF renderer; only a missing GLES library outranks it.+ // On Wayland that is the path WebKit bug 280210 can crash at launch, so it is supervised+ // like the setting's GPU path, and a crash recorded for this host sends it to the CPU path.+ if force_dmabuf {+ if missing_appimage_gles {+ return RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, APPIMAGE_GLES_REASON);+ }+ if !wayland_session {+ return RenderingPlan::PreserveEnvironment;+ }+ if gpu.unsafe_flag {+ return RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, GPU_UNSAFE_REASON);+ }+ return RenderingPlan::Gpu {+ force_dmabuf: false,+ reason: FORCE_DMABUF_REASON,+ };+ }++ // The GPU rendering setting, only while no operator variable has decided already.+ if setting.as_deref().and_then(compositing_setting).is_none() {+ if missing_appimage_gles && gpu.setting != GpuRendering::Auto {+ let reason = if nvidia_driver_loaded {+ NVIDIA_APPIMAGE_GLES_REASON+ } else {+ APPIMAGE_GLES_REASON+ };+ return RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, reason);+ }+ let shared_memory = gles_usable && supports_force_shared_memory(webkit_version);+ match gpu.setting {+ GpuRendering::Off => {+ // X11 keeps an SHM transport with compositing off; DISABLE_DMABUF can leave none.+ let workaround = if wayland_session || !shared_memory {+ RenderingWorkaround::DisableDmabuf+ } else if nvidia_driver_loaded {+ RenderingWorkaround::DisableCompositingOnNvidiaX11+ } else {+ RenderingWorkaround::DisableCompositingOnX11+ };+ return RenderingPlan::Apply(workaround, GPU_OFF_REASON);+ }+ GpuRendering::On if gpu.unsafe_flag && wayland_session => {+ return RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, GPU_UNSAFE_REASON);+ }+ // NVIDIA X11's hardware transport fails; SHM keeps GPU compositing without it.+ // Below the minimum branch On still keeps compositing off: those drivers leak until the+ // window stops drawing, minutes after launch, where no fallback can catch it.+ GpuRendering::On if nvidia_driver_loaded && !wayland_session && shared_memory => {+ if nvidia_driver_branch+ .is_some_and(|branch| branch >= NVIDIA_COMPOSITING_MIN_BRANCH)+ {+ return RenderingPlan::Apply(nvidia_shared_memory(), GPU_ON_REASON);+ }+ return RenderingPlan::Apply(+ RenderingWorkaround::DisableCompositingOnNvidiaX11,+ GPU_ON_OLD_NVIDIA_REASON,+ );+ }+ GpuRendering::On => {+ return RenderingPlan::Gpu {+ force_dmabuf: nvidia_driver_loaded,+ reason: GPU_ON_REASON,+ };+ }+ GpuRendering::Auto+ if nvidia_driver_loaded+ && wayland_session+ && !missing_appimage_gles+ && webkit_version >= NVIDIA_WAYLAND_GPU_MIN_VERSION =>+ {+ if gpu.unsafe_flag {+ return RenderingPlan::Apply(+ RenderingWorkaround::DisableDmabuf,+ GPU_UNSAFE_REASON,+ );+ }+ // Auto leaves a distribution's NVIDIA DMA-BUF patch in charge.+ return RenderingPlan::Gpu {+ force_dmabuf: false,+ reason: NVIDIA_WAYLAND_GPU_REASON,+ };+ }+ GpuRendering::Auto => {}+ }+ }+// Wayland: DISABLE_DMABUF (FORCE_SHM hits bug 315436). X11: SHM, with compositing off below// the minimum driver branch; DISABLE_DMABUF can leave no transport there.- if nvidia_driver_loaded && !force_dmabuf {- let missing_appimage_gles = is_appimage && !gles_usable;+ if nvidia_driver_loaded {let reason = if missing_appimage_gles {NVIDIA_APPIMAGE_GLES_REASON} else if wayland_session {@@ -236,21 +398,14 @@ fn rendering_plan(} else if requested(false)|| nvidia_driver_branch.is_some_and(|branch| branch >= NVIDIA_COMPOSITING_MIN_BRANCH){- // An operator's own video sink choice stays.- let operator_sink = env(GST_DISABLE_GL_SINK).is_some() && !ours(GST_DISABLE_GL_SINK);- if is_appimage && !operator_sink {- RenderingWorkaround::ForceSharedMemoryOnNvidiaAppImage- } else {- RenderingWorkaround::ForceSharedMemoryOnNvidia- }+ nvidia_shared_memory()} else {RenderingWorkaround::DisableCompositingOnNvidiaX11};return RenderingPlan::Apply(workaround, reason);}- // libepoxy loads GLES at runtime; disabling DMA-BUF handles a missing copy.- if is_appimage && !gles_usable {+ if missing_appimage_gles {return RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, APPIMAGE_GLES_REASON);}@@ -390,33 +545,108 @@ fn release_claimed(drop: impl Fn(&str) -> bool) {std::env::remove_var(APPLIED_WORKAROUND);}-/// Must run before GTK initialization.-pub fn configure_renderer() -> Option<(&'static [&'static str], &'static str)> {+/// What `configure_renderer` decided, for the startup log and the GPU rendering setting.+#[derive(Debug)]+pub struct RendererDecision {+ /// Variables set to 1 and why.+ pub applied: Option<(&'static [&'static str], &'static str)>,+ /// Reason, when WebKit keeps its GPU path because of the setting.+ pub gpu_path: Option<&'static str>,+ pub env_override: Option<&'static str>,+ pub webkit_version: (u32, u32, u32),+ pub wayland_session: bool,+ pub nvidia_driver_branch: Option<u32>,+}++impl RendererDecision {+ /// A GPU path on Wayland can die with Error 71 before the window shows (WebKit bug 280210).+ pub fn wants_supervision(&self) -> bool {+ self.gpu_path.is_some() && self.wayland_session+ }+}++fn claim(variables: &'static [&'static str]) {+ release_claimed(|name| !variables.contains(&name));+ for variable in variables {+ std::env::set_var(variable, "1");+ }+ // Claim them, so the next launch re-decides rather than reading them as overrides.+ std::env::set_var(APPLIED_WORKAROUND, variables.join(","));+}++/// Must run before GTK initialization. `unsafe_flag` gets the runtime WebKitGTK version and+/// whether the session is Wayland, and says whether an earlier GPU launch crashed on this host.+pub fn configure_renderer(+ setting: GpuRendering,+ unsafe_flag: impl FnOnce((u32, u32, u32), bool) -> bool,+) -> RendererDecision {let gles_usable = std::env::var_os(APPIMAGE).is_none() || gles_is_usable();+ let env = |name: &str| std::env::var_os(name);+ let webkit_version = runtime_webkit_version();+ let nvidia = nvidia_driver_branch();+ let wayland_socket = wayland_socket_present();+ let x11_open = x11_display_open(std::env::var_os(X11_DISPLAY), X11_SOCKET_DIR);+ let mut decision = RendererDecision {+ applied: None,+ gpu_path: None,+ env_override: env_override(&env),+ webkit_version,+ wayland_session: session_is_wayland(&env, wayland_socket, x11_open),+ nvidia_driver_branch: nvidia,+ };+ let gpu = GpuInputs {+ setting,+ unsafe_flag: unsafe_flag(webkit_version, decision.wayland_session),+ };match rendering_plan(- |name| std::env::var_os(name),- runtime_webkit_version(),+ env,+ webkit_version,gles_usable,- nvidia_driver_branch(),- wayland_socket_present(),- x11_display_open(std::env::var_os(X11_DISPLAY), X11_SOCKET_DIR),+ nvidia,+ wayland_socket,+ x11_open,+ gpu,) {RenderingPlan::Apply(workaround, reason) => {let variables = workaround.variables();- release_claimed(|name| !variables.contains(&name));- for variable in variables {- std::env::set_var(variable, "1");- }- // Claim them, so the next launch re-decides rather than reading them as overrides.- std::env::set_var(APPLIED_WORKAROUND, variables.join(","));- Some((variables, reason))+ claim(variables);+ decision.applied = Some((variables, reason));+ }+ RenderingPlan::Gpu {+ force_dmabuf: true,+ reason,+ } => {+ claim(&[FORCE_DMABUF]);+ decision.gpu_path = Some(reason);+ }+ RenderingPlan::Gpu { reason, .. } => {+ release_claimed(|_| true);+ decision.gpu_path = Some(reason);}RenderingPlan::PreserveEnvironment => {// Drop the values too, or the next launch would read them as operator overrides.release_claimed(|_| true);- None}}+ decision+}++/// The NVIDIA branch to name next to On, when On keeps compositing off on X11 (unreadable is "unknown").+pub fn old_nvidia_driver_warning(branch: Option<u32>, wayland_session: bool) -> Option<String> {+ let branch =+ branch.filter(|branch| !wayland_session && *branch < NVIDIA_COMPOSITING_MIN_BRANCH)?;+ Some(if branch == 0 {+ "unknown".to_string()+ } else {+ branch.to_string()+ })+}++/// First line of the NVIDIA kernel module banner, which names its version and flavour.+pub fn nvidia_driver_version_line() -> Option<String> {+ let text = std::fs::read_to_string(NVIDIA_DRIVER_VERSION_PATH).ok()?;+ let line = text.lines().next()?.trim();+ (!line.is_empty()).then(|| line.to_string())}#[cfg(test)]@@ -480,6 +710,46 @@ mod tests {nvidia_driver_loaded.then_some(LEAKING_NVIDIA_BRANCH),wayland_socket,x11_open,+ GpuInputs::default(),+ )+ }++ /// A host with the GPU rendering setting applied; displays follow the variables.+ fn plan_with_setting(+ vars: &[(&str, &str)],+ webkit_version: (u32, u32, u32),+ gles_usable: bool,+ nvidia_driver_loaded: bool,+ gpu: GpuInputs,+ ) -> RenderingPlan {+ plan_with_setting_on_branch(+ vars,+ webkit_version,+ gles_usable,+ nvidia_driver_loaded.then_some(LEAKING_NVIDIA_BRANCH),+ gpu,+ )+ }++ fn plan_with_setting_on_branch(+ vars: &[(&str, &str)],+ webkit_version: (u32, u32, u32),+ gles_usable: bool,+ nvidia_driver_branch: Option<u32>,+ gpu: GpuInputs,+ ) -> RenderingPlan {+ rendering_plan(+ |name| {+ vars.iter()+ .find(|(key, _)| *key == name)+ .map(|(_, value)| OsString::from(value))+ },+ webkit_version,+ gles_usable,+ nvidia_driver_branch,+ named(vars, WAYLAND_DISPLAY),+ named(vars, X11_DISPLAY),+ gpu,)}@@ -496,6 +766,7 @@ mod tests {nvidia_driver_loaded.then_some(LEAKING_NVIDIA_BRANCH),live,named(vars, X11_DISPLAY),+ GpuInputs::default(),)}@@ -511,6 +782,7 @@ mod tests {Some(branch),named(vars, WAYLAND_DISPLAY),named(vars, X11_DISPLAY),+ GpuInputs::default(),)}@@ -771,10 +1043,44 @@ mod tests {}#[test]- fn force_dmabuf_still_leaves_the_wayland_workaround_in_place() {+ fn force_dmabuf_on_wayland_keeps_the_gpu_path_under_supervision() {+ // Vendor, packaging and setting do not matter: the operator asked for the DMA-BUF+ // renderer. It stays unclaimed (the operator's value), and a recorded crash wins.+ for nvidia in [true, false] {+ for appimage in [false, true] {+ let mut vars = vec![(FORCE_DMABUF, "1"), (WAYLAND_DISPLAY, "wayland-0")];+ if appimage {+ vars.push((APPIMAGE, "/tmp/Unsloth.AppImage"));+ }+ for setting in [GpuRendering::Auto, GpuRendering::On, GpuRendering::Off] {+ let label = format!("nvidia={nvidia} appimage={appimage} setting={setting:?}");+ assert_eq!(+ plan_with_setting(&vars, MODERN_WEBKIT, true, nvidia, gpu(setting, false)),+ RenderingPlan::Gpu {+ force_dmabuf: false,+ reason: FORCE_DMABUF_REASON+ },+ "{label}"+ );+ assert_eq!(+ plan_with_setting(&vars, MODERN_WEBKIT, true, nvidia, gpu(setting, true)),+ RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, GPU_UNSAFE_REASON),+ "{label}"+ );+ }+ }+ }+ // X11 keeps the operator's environment as before.+ let x11 = [(FORCE_DMABUF, "1"), (X11_DISPLAY, ":0")];assert_eq!(- plan_on_nvidia(&[(FORCE_DMABUF, "1"), (WAYLAND_DISPLAY, "wayland-0")]),- RenderingPlan::Apply(RenderingWorkaround::ForceSharedMemory, WAYLAND_REASON)+ plan_with_setting(+ &x11,+ MODERN_WEBKIT,+ true,+ true,+ gpu(GpuRendering::Off, true)+ ),+ RenderingPlan::PreserveEnvironment);}@@ -1541,4 +1847,429 @@ mod tests {RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, NVIDIA_WAYLAND_REASON));}++ const WEBKIT_2_54: (u32, u32, u32) = (2, 54, 2);+ const WEBKIT_2_53: (u32, u32, u32) = (2, 53, 99);+ const WEBKIT_BUNDLED: (u32, u32, u32) = (2, 50, 4);+ const WAYLAND_HOST: &[(&str, &str)] = &[(WAYLAND_DISPLAY, "wayland-0")];+ const X11_HOST: &[(&str, &str)] = &[(X11_DISPLAY, ":0")];+ const APPIMAGE_WAYLAND_HOST: &[(&str, &str)] = &[+ (WAYLAND_DISPLAY, "wayland-0"),+ (APPIMAGE, "/tmp/Unsloth.AppImage"),+ ];++ fn gpu(setting: GpuRendering, unsafe_flag: bool) -> GpuInputs {+ GpuInputs {+ setting,+ unsafe_flag,+ }+ }++ #[test]+ fn auto_keeps_the_gpu_path_on_nvidia_wayland_from_webkit_2_54_2() {+ for vars in [WAYLAND_HOST, APPIMAGE_WAYLAND_HOST] {+ for version in [WEBKIT_2_54, (2, 54, 3), (2, 56, 0)] {+ assert_eq!(+ plan_with_setting(vars, version, true, true, GpuInputs::default()),+ RenderingPlan::Gpu {+ force_dmabuf: false,+ reason: NVIDIA_WAYLAND_GPU_REASON+ },+ "{version:?} {vars:?}"+ );+ }+ // 2.54.0 and 2.54.1 crash at launch with Error 71 under explicit sync (bug 280210).+ for version in [(2, 54, 0), (2, 54, 1)] {+ assert_eq!(+ plan_with_setting(vars, version, true, true, GpuInputs::default()),+ RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, NVIDIA_WAYLAND_REASON),+ "{version:?} {vars:?}"+ );+ }+ }+ }++ #[test]+ fn auto_below_2_54_2_keeps_todays_nvidia_wayland_workaround() {+ for version in [+ (2, 54, 1),+ (2, 54, 0),+ WEBKIT_2_53,+ WEBKIT_BUNDLED,+ MODERN_WEBKIT,+ ] {+ for vars in [WAYLAND_HOST, APPIMAGE_WAYLAND_HOST] {+ assert_eq!(+ plan_with_setting(vars, version, true, true, GpuInputs::default()),+ RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, NVIDIA_WAYLAND_REASON),+ "{version:?} {vars:?}"+ );+ }+ }+ }++ #[test]+ fn auto_off_nvidia_or_off_wayland_matches_the_plan_without_a_setting() {+ // Every Auto path except NVIDIA Wayland 2.54.2+ is today's plan, flag or not.+ let hosts: &[&[(&str, &str)]] = &[+ WAYLAND_HOST,+ X11_HOST,+ APPIMAGE_WAYLAND_HOST,+ &[(X11_DISPLAY, ":0"), (APPIMAGE, "/tmp/Unsloth.AppImage")],+ &[+ (WAYLAND_DISPLAY, "wayland-0"),+ (GDK_BACKEND, "x11"),+ (X11_DISPLAY, ":0"),+ ],+ ];+ for vars in hosts {+ for version in [WEBKIT_2_54, WEBKIT_BUNDLED, (2, 42, 0)] {+ for gles in [true, false] {+ for nvidia in [false, true] {+ if nvidia+ && named(vars, WAYLAND_DISPLAY)+ && !vars.contains(&(GDK_BACKEND, "x11"))+ && version == WEBKIT_2_54+ && (gles || !named(vars, APPIMAGE))+ {+ continue;+ }+ for unsafe_flag in [false, true] {+ assert_eq!(+ plan_with_setting(vars, version, gles, nvidia, gpu(GpuRendering::Auto, unsafe_flag)),+ plan_on_host(vars, version, gles, nvidia),+ "{vars:?} {version:?} gles={gles} nvidia={nvidia} flag={unsafe_flag}"+ );+ }+ }+ }+ }+ }+ }++ #[test]+ fn a_crash_flag_sends_auto_and_on_to_the_cpu_path() {+ for setting in [GpuRendering::Auto, GpuRendering::On] {+ assert_eq!(+ plan_with_setting(WAYLAND_HOST, WEBKIT_2_54, true, true, gpu(setting, true)),+ RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, GPU_UNSAFE_REASON),+ "{setting:?}"+ );+ }+ assert_eq!(+ plan_with_setting(+ WAYLAND_HOST,+ WEBKIT_2_54,+ true,+ true,+ gpu(GpuRendering::Off, true)+ ),+ RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, GPU_OFF_REASON)+ );+ }++ #[test]+ fn on_forces_the_gpu_path_and_stands_the_distribution_patch_down_on_nvidia() {+ for version in [WEBKIT_BUNDLED, WEBKIT_2_54] {+ for vars in [WAYLAND_HOST, APPIMAGE_WAYLAND_HOST] {+ assert_eq!(+ plan_with_setting(vars, version, true, true, gpu(GpuRendering::On, false)),+ RenderingPlan::Gpu {+ force_dmabuf: true,+ reason: GPU_ON_REASON+ }+ );+ assert_eq!(+ plan_with_setting(vars, version, true, false, gpu(GpuRendering::On, false)),+ RenderingPlan::Gpu {+ force_dmabuf: false,+ reason: GPU_ON_REASON+ }+ );+ }+ }+ assert_eq!(+ plan_with_setting(+ X11_HOST,+ MODERN_WEBKIT,+ true,+ false,+ gpu(GpuRendering::On, false)+ ),+ RenderingPlan::Gpu {+ force_dmabuf: false,+ reason: GPU_ON_REASON+ }+ );+ }++ #[test]+ fn on_nvidia_x11_below_the_minimum_branch_keeps_compositing_off() {+ let appimage_x11: &[(&str, &str)] =+ &[(APPIMAGE, "/tmp/Unsloth.AppImage"), (X11_DISPLAY, ":0")];+ for vars in [X11_HOST, appimage_x11] {+ for branch in [0, 580, 609] {+ assert_eq!(+ plan_with_setting_on_branch(+ vars,+ MODERN_WEBKIT,+ true,+ Some(branch),+ gpu(GpuRendering::On, false)+ ),+ RenderingPlan::Apply(+ RenderingWorkaround::DisableCompositingOnNvidiaX11,+ GPU_ON_OLD_NVIDIA_REASON+ ),+ "{branch} {vars:?}"+ );+ }+ }+ assert_eq!(+ old_nvidia_driver_warning(Some(580), false).as_deref(),+ Some("580")+ );+ assert_eq!(+ old_nvidia_driver_warning(Some(0), false).as_deref(),+ Some("unknown")+ );+ assert_eq!(old_nvidia_driver_warning(Some(610), false), None);+ assert_eq!(old_nvidia_driver_warning(Some(580), true), None);+ assert_eq!(old_nvidia_driver_warning(None, false), None);+ }++ #[test]+ fn on_nvidia_x11_keeps_gpu_compositing_over_shared_memory() {+ assert_eq!(+ plan_with_setting_on_branch(+ X11_HOST,+ MODERN_WEBKIT,+ true,+ Some(615),+ gpu(GpuRendering::On, false)+ ),+ RenderingPlan::Apply(+ RenderingWorkaround::ForceSharedMemoryOnNvidia,+ GPU_ON_REASON+ )+ );+ // The AppImage composites too, so it gets the non-GL video sink its GStreamer needs.+ let appimage_x11: &[(&str, &str)] =+ &[(APPIMAGE, "/tmp/Unsloth.AppImage"), (X11_DISPLAY, ":0")];+ assert_eq!(+ plan_with_setting_on_branch(+ appimage_x11,+ MODERN_WEBKIT,+ true,+ Some(615),+ gpu(GpuRendering::On, false)+ ),+ RenderingPlan::Apply(+ RenderingWorkaround::ForceSharedMemoryOnNvidiaAppImage,+ GPU_ON_REASON+ )+ );+ // Below 2.44 there is no SHM switch, so On is WebKit's own default there.+ assert_eq!(+ plan_with_setting(+ X11_HOST,+ (2, 42, 0),+ true,+ true,+ gpu(GpuRendering::On, false)+ ),+ RenderingPlan::Gpu {+ force_dmabuf: true,+ reason: GPU_ON_REASON+ }+ );+ }++ #[test]+ fn off_takes_the_cpu_path_without_stranding_x11() {+ for nvidia in [false, true] {+ for vars in [WAYLAND_HOST, APPIMAGE_WAYLAND_HOST] {+ assert_eq!(+ plan_with_setting(+ vars,+ WEBKIT_2_54,+ true,+ nvidia,+ gpu(GpuRendering::Off, false)+ ),+ RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, GPU_OFF_REASON)+ );+ }+ }+ assert_eq!(+ plan_with_setting(+ X11_HOST,+ MODERN_WEBKIT,+ true,+ true,+ gpu(GpuRendering::Off, false)+ ),+ RenderingPlan::Apply(+ RenderingWorkaround::DisableCompositingOnNvidiaX11,+ GPU_OFF_REASON+ )+ );+ assert_eq!(+ plan_with_setting(+ X11_HOST,+ MODERN_WEBKIT,+ true,+ false,+ gpu(GpuRendering::Off, false)+ ),+ RenderingPlan::Apply(RenderingWorkaround::DisableCompositingOnX11, GPU_OFF_REASON)+ );+ assert_eq!(+ RenderingWorkaround::DisableCompositingOnX11.variables(),+ &[FORCE_SHARED_MEMORY, DISABLE_COMPOSITING]+ );+ // No SHM switch below 2.44: the renderer switch is the only CPU path there.+ assert_eq!(+ plan_with_setting(+ X11_HOST,+ (2, 42, 0),+ true,+ false,+ gpu(GpuRendering::Off, false)+ ),+ RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, GPU_OFF_REASON)+ );+ }++ #[test]+ fn a_missing_gles_library_outranks_every_setting() {+ let vars = APPIMAGE_WAYLAND_HOST;+ for setting in [GpuRendering::Auto, GpuRendering::On, GpuRendering::Off] {+ assert_eq!(+ plan_with_setting(vars, WEBKIT_2_54, false, true, gpu(setting, false)),+ RenderingPlan::Apply(+ RenderingWorkaround::DisableDmabuf,+ NVIDIA_APPIMAGE_GLES_REASON+ ),+ "{setting:?}"+ );+ assert_eq!(+ plan_with_setting(vars, WEBKIT_2_54, false, false, gpu(setting, false)),+ RenderingPlan::Apply(RenderingWorkaround::DisableDmabuf, APPIMAGE_GLES_REASON),+ "{setting:?}"+ );+ }+ }++ #[test]+ fn operator_variables_outrank_the_setting_and_are_named() {+ let overrides: &[(&str, &str)] = &[+ (DISABLE_DMABUF, "0"),+ (DISABLE_DMABUF, "1"),+ (FORCE_SHARED_MEMORY, "1"),+ (DISABLE_COMPOSITING, "0"),+ (DISABLE_COMPOSITING, "1"),+ (DISABLE_COMPOSITING_SETTING, "1"),+ (DISABLE_COMPOSITING_SETTING, "0"),+ (FORCE_DMABUF, "1"),+ ];+ for &(name, value) in overrides {+ let vars = [(WAYLAND_DISPLAY, "wayland-0"), (name, value)];+ let expected = plan_on_host(&vars, WEBKIT_BUNDLED, true, true);+ // A recorded crash does count for FORCE_DMABUF on Wayland (tested above).+ let flag = name != FORCE_DMABUF;+ for setting in [GpuRendering::Auto, GpuRendering::On, GpuRendering::Off] {+ assert_eq!(+ plan_with_setting(&vars, WEBKIT_BUNDLED, true, true, gpu(setting, flag)),+ expected,+ "{name}={value} {setting:?}"+ );+ }+ let env = |key: &str| {+ vars.iter()+ .find(|(k, _)| *k == key)+ .map(|(_, v)| OsString::from(v))+ };+ assert_eq!(env_override(&env), Some(name), "{name}={value}");+ }+ }++ #[test]+ fn variables_this_app_claimed_are_not_overrides() {+ for (name, claimed) in [+ (DISABLE_DMABUF, DISABLE_DMABUF.to_string()),+ (FORCE_DMABUF, FORCE_DMABUF.to_string()),+ (+ DISABLE_COMPOSITING,+ [FORCE_SHARED_MEMORY, FORCE_DMABUF, DISABLE_COMPOSITING].join(","),+ ),+ ] {+ let vars = [+ (WAYLAND_DISPLAY, "wayland-0"),+ (name, "1"),+ (APPLIED_WORKAROUND, claimed.as_str()),+ ];+ let env = |key: &str| {+ vars.iter()+ .find(|(k, _)| *k == key)+ .map(|(_, v)| OsString::from(v))+ };+ assert_eq!(env_override(&env), None, "{name}");+ // An earlier Off launch relaunched under Auto re-decides as Auto.+ assert_eq!(+ plan_with_setting(&vars, WEBKIT_2_54, true, true, GpuInputs::default()),+ RenderingPlan::Gpu {+ force_dmabuf: false,+ reason: NVIDIA_WAYLAND_GPU_REASON+ },+ "{name}"+ );+ }+ }++ #[test]+ fn setting_decisions_are_a_fixed_point_across_a_relaunch() {+ for setting in [GpuRendering::Auto, GpuRendering::On, GpuRendering::Off] {+ for nvidia in [true, false] {+ for host in [WAYLAND_HOST, X11_HOST, APPIMAGE_WAYLAND_HOST] {+ let inputs = gpu(setting, false);+ let first = plan_with_setting(host, WEBKIT_2_54, true, nvidia, inputs);+ let mut relaunch: Vec<(&str, &str)> = host.to_vec();+ let claimed = match &first {+ RenderingPlan::Apply(workaround, _) => workaround.variables().join(","),+ RenderingPlan::Gpu {+ force_dmabuf: true, ..+ } => FORCE_DMABUF.to_string(),+ _ => String::new(),+ };+ for name in claimed.split(',').filter(|name| !name.is_empty()) {+ relaunch.push((name, "1"));+ }+ if !claimed.is_empty() {+ relaunch.push((APPLIED_WORKAROUND, claimed.as_str()));+ }+ assert_eq!(+ plan_with_setting(&relaunch, WEBKIT_2_54, true, nvidia, inputs),+ first,+ "{setting:?} nvidia={nvidia} {host:?}"+ );+ }+ }+ }+ }++ #[test]+ fn only_a_gpu_path_on_wayland_asks_for_supervision() {+ let decision = |gpu_path: Option<&'static str>, wayland_session: bool| RendererDecision {+ applied: None,+ gpu_path,+ env_override: None,+ webkit_version: WEBKIT_2_54,+ wayland_session,+ nvidia_driver_branch: None,+ };+ assert!(decision(Some(GPU_ON_REASON), true).wants_supervision());+ assert!(!decision(Some(GPU_ON_REASON), false).wants_supervision());+ assert!(!decision(None, true).wants_supervision());+ }}diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rsindex 8792444a5b2..5971410b18e 100644--- a/studio/src-tauri/src/main.rs+++ b/studio/src-tauri/src/main.rs@@ -21,9 +21,12 @@ mod desktop_backend_owner;mod desktop_update_policy;mod desktop_updater;mod diagnostics;+mod gpu_rendering;mod install;mod install_watchdog;#[cfg(target_os = "linux")]+mod linux_gpu_supervisor;+#[cfg(target_os = "linux")]mod linux_webkit;mod long_paths;mod loopback_http;@@ -67,6 +70,36 @@ use tauri_plugin_window_state::{AppHandleExt, StateFlags};/// RunEvent::Exit). Exactly one runs cleanup; the others block, so the process never exits mid-reap.static TERMINATION_CLEANUP: Mutex<bool> = Mutex::new(false);+/// Supervisor control and native signals share the first-request state. A repeated native+/// signal must still force exit when cleanup began through the supervisor's control channel.+#[cfg(unix)]+static UNIX_TERMINATION_REQUESTED: AtomicBool = AtomicBool::new(false);+/// Whether a native signal already arrived. `pkill unsloth-studio` or a session stop signals the+/// supervisor and the app together, so the app's first native signal can land after the+/// supervisor's request: that is the same shutdown, not a repeat.+#[cfg(unix)]+static UNIX_NATIVE_TERMINATION_SEEN: AtomicBool = AtomicBool::new(false);++#[cfg(unix)]+#[derive(Debug, PartialEq, Eq)]+enum NativeTermination {+ StartCleanup,+ JoinCleanup,+ ForceExit,+}++/// Only a second native signal forces exit; a first one after a supervisor request joins it.+#[cfg(unix)]+fn native_termination(native_seen: &AtomicBool, requested: &AtomicBool) -> NativeTermination {+ if native_seen.swap(true, Ordering::SeqCst) {+ NativeTermination::ForceExit+ } else if requested.swap(true, Ordering::SeqCst) {+ NativeTermination::JoinCleanup+ } else {+ NativeTermination::StartCleanup+ }+}+const IN_APP_RELAUNCH_MARKER_FILE: &str = "in-app-relaunch-v1";const CLOSE_TO_TRAY_PREFERENCE_FILE: &str = "close-to-tray-v1";@@ -162,7 +195,14 @@ fn resolve_launched_hidden(app: &tauri::AppHandle) -> bool {let relaunched = in_app_relaunch_config_dir(app).map(|dir| take_in_app_relaunch_marker(&dir)).unwrap_or(false);- argv_has_hidden_flag() && !relaunched+ let hidden = argv_has_hidden_flag();+ // The marker is gone now, so a GPU crash before the window reports in must not relaunch+ // hidden.+ #[cfg(target_os = "linux")]+ if hidden && relaunched {+ linux_gpu_supervisor::note_window_will_show();+ }+ hidden && !relaunched}/// True for a login autostart; false for an in-app relaunch that inherits `--hidden`.@@ -893,6 +933,31 @@ impl Write for RotatingLogFile {}}+fn tauri_log_dir() -> Option<PathBuf> {+ let home = dirs::home_dir()?;+ Some(+ studio_home::chosen_root_for_home(&home)+ .filter(|root| root.is_dir())+ .unwrap_or_else(|| studio_home::default_root_for_home(&home)),+ )+}++#[cfg(target_os = "linux")]+fn tauri_log_path() -> Option<PathBuf> {+ tauri_log_dir().map(|dir| dir.join("tauri.log"))+}++/// The supervisor parent has no logger (it never runs setup_logging), so it appends directly.+#[cfg(target_os = "linux")]+fn append_supervisor_log(path: Option<&Path>, line: &str) {+ eprintln!("[gpu-supervisor] {line}");+ if let Some(path) = path {+ if let Ok(mut file) = fs::OpenOptions::new().create(true).append(true).open(path) {+ let _ = writeln!(file, "[gpu-supervisor] {line}");+ }+ }+}+fn setup_logging() {let mut loggers: Vec<Box<dyn SharedLogger>> = vec![];@@ -904,10 +969,7 @@ fn setup_logging() {));// Try to set up file logging to ~/.unsloth/studio/tauri.log (a chosen root once it exists).- if let Some(home) = dirs::home_dir() {- let log_dir = studio_home::chosen_root_for_home(&home)- .filter(|root| root.is_dir())- .unwrap_or_else(|| studio_home::default_root_for_home(&home));+ if let Some(log_dir) = tauri_log_dir() {if fs::create_dir_all(&log_dir).is_ok() {let log_path = log_dir.join("tauri.log");let rotated_path = log_dir.join("tauri.log.1");@@ -1450,16 +1512,24 @@ fn setup_unix_termination_signals(app: &tauri::App) -> Result<(), Box<dyn std::eapp.exit(exit_code);};- let mut cleanup_started = false;for signal in signals.forever() {let name = signal_hook::low_level::signal_name(signal).unwrap_or("unknown signal");let exit_code = 128 + signal;- if cleanup_started {- // A repeat signal means stop waiting: exit straight away.- warn!("Received {name} ({signal}) while cleaning up, exiting immediately");- std::process::exit(exit_code);+ match native_termination(&UNIX_NATIVE_TERMINATION_SEEN, &UNIX_TERMINATION_REQUESTED)+ {+ NativeTermination::ForceExit => {+ // A repeat signal means stop waiting: exit straight away.+ warn!("Received {name} ({signal}) while cleaning up, exiting immediately");+ // SAFETY: this is an explicit forced exit. libc exit handlers may wait on+ // GTK/driver locks held by the cleanup we are being asked to abandon.+ unsafe { libc::_exit(exit_code) };+ }+ NativeTermination::JoinCleanup => {+ info!("Received {name} ({signal}) during the supervisor's shutdown");+ continue;+ }+ NativeTermination::StartCleanup => {}}- cleanup_started = true;info!("Received Unix termination signal {name} ({signal})");// Clean up on another thread so this one can still observe a repeat signal.@@ -1485,10 +1555,37 @@ fn show_main_window(app: &tauri::AppHandle) {let _ = window.show();let _ = window.unminimize();let _ = window.set_focus();+ #[cfg(target_os = "linux")]+ linux_gpu_supervisor::note_window_shown();}browser_webview::window_changed(app, None);}+/// The frontend calls this once the main window is on screen. Under the GPU supervisor it is+/// the point after which a crash is no longer a launch failure.+#[tauri::command]+fn renderer_ready() {+ #[cfg(target_os = "linux")]+ linux_gpu_supervisor::note_window_shown();+}++/// Restart to apply a new GPU rendering setting, through the same confirmations as Quit.+/// False when a quit is already waiting for an answer.+#[tauri::command]+fn relaunch_to_apply_gpu_rendering(app: tauri::AppHandle) -> bool {+ spawn_quit_confirmation(&app, None, |app, proceed| {+ if !proceed {+ info!("GPU rendering relaunch cancelled");+ return;+ }+ if let Err(error) = mark_in_app_relaunch(app.clone()) {+ warn!("Could not mark the GPU rendering relaunch: {error}");+ }+ info!("Relaunching to apply the GPU rendering setting");+ app.request_restart();+ })+}+struct QuitConfirmationState {in_progress: bool,#[cfg(target_os = "macos")]@@ -2177,9 +2274,99 @@ fn main() {// Must precede any Xlib call; see x11_threads.x11_threads::init_x11_threads();+ let mut context = tauri::generate_context!();+ let config_dir = dirs::config_dir().map(|dir| dir.join(&context.config().identifier));+ // Read before the webview starts: a changed setting applies on the next launch.+ let gpu_setting = gpu_rendering::launch_setting(config_dir.as_deref());++ // A supervised GPU launch (see linux_gpu_supervisor) learns that from inherited state.+ #[cfg(target_os = "linux")]+ let gpu_child = linux_gpu_supervisor::take_child_channel();+ #[cfg(target_os = "linux")]+ linux_gpu_supervisor::install_gdk_hook();+// Pick a WebKitGTK rendering fallback before any GTK/WebKit object is initialized.#[cfg(target_os = "linux")]- let webkit_rendering_workaround = linux_webkit::configure_renderer();+ let mut gpu_notes: Vec<String> = Vec::new();+ #[cfg(target_os = "linux")]+ let mut gpu_fallback_active = gpu_child.fallback.is_some();+ #[cfg(target_os = "linux")]+ let webkit_rendering =+ linux_webkit::configure_renderer(gpu_setting, |webkit_version, wayland_session| {+ let key = gpu_rendering::HostKey {+ webkit_version,+ nvidia_driver: linux_webkit::nvidia_driver_version_line(),+ wayland_session,+ };+ if let Some(dir) = config_dir.as_deref() {+ match gpu_rendering::check_unsafe_flag(dir, &key) {+ gpu_rendering::FlagState::Honoured => gpu_fallback_active = true,+ gpu_rendering::FlagState::Cleared(line) => gpu_notes.push(line),+ gpu_rendering::FlagState::Absent => {}+ }+ }+ gpu_fallback_active+ });++ // Error 71 kills a GPU launch before anything can catch it in-process, so a parent watches+ // and relaunches on the CPU path. It never starts GTK, Tauri or the single-instance lock.+ #[cfg(target_os = "linux")]+ if !gpu_child.supervised+ && (webkit_rendering.wants_supervision() || linux_gpu_supervisor::test_hook_requested())+ {+ if let Some(dir) = config_dir.clone() {+ let key = gpu_rendering::HostKey {+ webkit_version: webkit_rendering.webkit_version,+ nvidia_driver: linux_webkit::nvidia_driver_version_line(),+ wayland_session: webkit_rendering.wayland_session,+ };+ let log_path = tauri_log_path();+ let log = |line: &str| append_supervisor_log(log_path.as_deref(), line);+ // The child re-plans and sees no flag, so a flag this parent dropped is logged here.+ for note in &gpu_notes {+ log(note);+ }+ let started = linux_gpu_supervisor::run_parent(+ || {+ if let Err(error) = gpu_rendering::write_unsafe_flag(&dir, &key) {+ log(&format!("Could not save the GPU rendering fallback flag: {error}"));+ }+ },+ log,+ );+ // run_parent only returns when it could not start the app.+ let Err(error) = started;+ append_supervisor_log(+ tauri_log_path().as_deref(),+ &format!("GPU rendering supervisor could not start the app ({error}); running unsupervised"),+ );+ }+ }++ #[cfg(windows)]+ if let Some(args) = gpu_rendering::windows_main_browser_args(gpu_setting) {+ if let Some(window) = context.config_mut().app.windows.get_mut(0) {+ window.additional_browser_args = Some(args);+ }+ gpu_rendering::set_pages_disable_gpu(true);+ }++ #[cfg(target_os = "linux")]+ let gpu_launch = gpu_rendering::LaunchState::new(+ gpu_setting,+ gpu_fallback_active,+ webkit_rendering.env_override,+ gpu_rendering::old_webkit_warning(+ webkit_rendering.webkit_version,+ webkit_rendering.wayland_session,+ ),+ linux_webkit::old_nvidia_driver_warning(+ webkit_rendering.nvidia_driver_branch,+ webkit_rendering.wayland_session,+ ),+ );+ #[cfg(not(target_os = "linux"))]+ let gpu_launch = gpu_rendering::LaunchState::new(gpu_setting, false, None, None, None);// Fix PATH for GUI apps (macOS .app bundles, Linux AppImage, Windows)// GUI apps don't inherit shell dotfile PATH — this spawns the user's// login shell to source .zshrc/.bashrc/.profile and sets PATH properly.@@ -2192,7 +2379,7 @@ fn main() {macos_event_guard::install();#[cfg(target_os = "linux")]- if let Some((variables, reason)) = webkit_rendering_workaround {+ if let Some((variables, reason)) = webkit_rendering.applied {let applied = variables.iter().map(|variable| format!("{variable}=1"))@@ -2200,9 +2387,34 @@ fn main() {.join(" ");info!("{reason}; set {applied} for WebKitGTK compatibility");}+ #[cfg(target_os = "linux")]+ {+ for note in &gpu_notes {+ info!("{note}");+ }+ if let Some(reason) = &gpu_child.fallback {+ warn!("GPU rendering fell back to the CPU path after a launch crash ({reason})");+ }+ let (major, minor, micro) = webkit_rendering.webkit_version;+ info!(+ "GPU rendering: setting={} path={} reason={} webkit={major}.{minor}.{micro} env_override={} flag={} supervised={}",+ gpu_setting.as_str(),+ if webkit_rendering.gpu_path.is_some() { "gpu" } else { "default-or-cpu" },+ webkit_rendering+ .gpu_path+ .or(webkit_rendering.applied.map(|(_, reason)| reason))+ .unwrap_or("WebKit defaults"),+ webkit_rendering.env_override.unwrap_or("none"),+ gpu_fallback_active,+ gpu_child.supervised,+ );+ }+ #[cfg(windows)]+ if gpu_setting == gpu_rendering::GpuRendering::Off {+ info!("GPU rendering: setting=off; WebView2 starts with --disable-gpu");+ }windows_job::initialize();- let mut context = tauri::generate_context!();extend_csp_with_hf_endpoints(&mut context);// Restore while hidden, else the 760x560 setup size overwrites the saved layout.let restore_initial_layout = dirs::config_dir().is_some_and(|dir| {@@ -2249,6 +2461,7 @@ fn main() {.manage(update::new_update_state()).manage(desktop_updater::new_desktop_update_state()).manage(new_close_to_tray_state())+ .manage(gpu_launch).manage(native_file_dialogs::ChatImportRegistry::default()).manage(native_file_dialogs::NativeSaveRegistry::default()).manage(browser_webview::new_browser_views())@@ -2362,6 +2575,10 @@ fn main() {has_saved_window_state,was_launched_hidden,mark_in_app_relaunch,+ gpu_rendering::get_gpu_rendering,+ gpu_rendering::set_gpu_rendering,+ relaunch_to_apply_gpu_rendering,+ renderer_ready,clear_in_app_relaunch,reveal_main_window,get_close_to_tray,@@ -2386,6 +2603,26 @@ fn main() {}initialize_close_to_tray(app.handle());+ #[cfg(target_os = "linux")]+ {+ let handle = app.handle().clone();+ linux_gpu_supervisor::start_control_reader(move || {+ // A control close after a native signal is a duplicate shutdown request.+ if UNIX_TERMINATION_REQUESTED.swap(true, Ordering::SeqCst) {+ return;+ }+ info!("GPU rendering supervisor asked the app to exit");+ let handle = handle.clone();+ let _ = std::thread::Builder::new()+ .name("supervisor-termination".to_string())+ .spawn(move || {+ cleanup_child_processes(&handle);+ handle.exit(128 + libc::SIGTERM);+ });+ });+ #[cfg(debug_assertions)]+ linux_gpu_supervisor::maybe_simulate_error71();+ }reconcile_autostart_entry(app.handle());if let Err(error) = process::with_studio_runtime_launch_guard(|| {staged_update::reconcile_legacy_at_launch(&diagnostics::studio_dir());@@ -2490,6 +2727,32 @@ fn main() {mod tests {use super::*;+ #[cfg(unix)]+ #[test]+ fn a_first_native_signal_joins_a_supervisor_shutdown_and_only_a_repeat_forces_exit() {+ // Native signal alone: the first cleans up, the second forces exit.+ let (native, requested) = (AtomicBool::new(false), AtomicBool::new(false));+ assert_eq!(+ native_termination(&native, &requested),+ NativeTermination::StartCleanup+ );+ assert_eq!(+ native_termination(&native, &requested),+ NativeTermination::ForceExit+ );++ // The supervisor asked first (pkill or a session stop reaching both processes).+ let (native, requested) = (AtomicBool::new(false), AtomicBool::new(true));+ assert_eq!(+ native_termination(&native, &requested),+ NativeTermination::JoinCleanup+ );+ assert_eq!(+ native_termination(&native, &requested),+ NativeTermination::ForceExit+ );+ }+#[test]fn log_file_rotates_mid_session_and_keeps_one_generation() {let directory = tempfile::tempdir().unwrap();