Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

40.9 KB
Raw Blame
// 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 { AppReadinessBoundary } from "@/components/app-readiness";
import { LlamaUpdateBanner } from "@/components/llama-update-banner";
import {
  ClosingScreen,
  StartupScreen,
} from "@/components/tauri/startup-screen";
import { UpdateBanner } from "@/components/tauri/update-banner";
import { UpdateScreen } from "@/components/tauri/update-screen";
import {
  WindowTitlebar,
  shouldUseCustomWindowTitlebar,
  shouldUseNativeMacWindowTitlebar,
} from "@/components/tauri/window-titlebar";
import { Toaster } from "@/components/ui/sonner";
import { TitleTooltipLayer } from "@/components/ui/title-tooltip";
import { TooltipProvider } from "@/components/ui/tooltip";
import { WebUpdateBanner } from "@/components/web/update-banner";
import {
  fetchDeviceType,
  forgetMeasuredVerdict,
  usePlatformStore,
} from "@/config/env";
import { routeNeedsHardware } from "@/config/hardware-verdict";
import { getTauriAuthFailure, tauriAutoAuth } from "@/features/auth";
import { resyncInferenceStatusAfterServerModelChange } from "@/features/chat/hooks/resync-inference-status-lazy";
import { DeepLinkHandler } from "@/features/deep-links";
import { receiveSharedRunConfigUrls } from "@/features/model-picker/sharing/receive-link";
import {
  DownloadManagerPanel,
  dismissStartToasts,
} from "@/features/hub/download-manager";
import { LoadedModelsIndicator } from "@/features/loaded-models";
import { NativeIntentDrain } from "@/features/native-intents/native-intent-drain";
import {
  NATIVE_MAC_TITLEBAR_HEIGHT_VAR,
  NATIVE_MAC_TRAFFIC_LIGHT_INSET_VAR,
  getAppliedInterfaceZoom,
  subscribeAppliedInterfaceZoom,
} from "@/features/settings/lib/interface-scale-runtime";
import {
  applyCustomizationToDocument,
  useAppearanceCustomStore,
} from "@/features/settings/stores/appearance-custom-store";
import {
  applyInterfaceScale,
  useInterfaceScaleStore,
} from "@/features/settings/stores/interface-scale-store";
import { notifyRendererReady } from "@/features/settings/api/gpu-rendering";
import { usePalette, useTheme } from "@/features/settings/stores/theme-store";
import { SttDownloadPrompt } from "@/features/settings/components/stt-download-prompt";
import { TauriRepairContext } from "@/hooks/tauri-repair-context";
import { TauriUpdateContext } from "@/hooks/tauri-update-context";
import { type BackendStatus, useTauriBackend } from "@/hooks/use-tauri-backend";
import { useTauriUpdate } from "@/hooks/use-tauri-update";
import { useUiSpaceScale } from "@/hooks/use-ui-space-scale";
import { isTauri } from "@/lib/api-base";
import {
  getDesktopFullscreen,
  subscribeDesktopFullscreen,
} from "@/lib/desktop-fullscreen";
import { followDesktopUpdateScreen } from "@/lib/desktop-update-activity";
import { installDismissClickStreakGuard } from "@/lib/dismiss-click-streak";
import { useDocumentFlag } from "@/lib/document-flag";
import { refreshWindowChromeTop } from "@/lib/window-chrome";
import {
  CHAT_SETTINGS_INSET_VAR,
  COMPOSER_CLEARANCE_VAR,
  cornerInsetScope,
  getToastOffsets,
  insetPastChatSettings,
} from "@/lib/toast-offset";
import { Z_LAYER } from "@/lib/z-layers";
import { useRouterState } from "@tanstack/react-router";
import { setDesktopShellReady } from "./desktop-shell-ready";
import {
  measureThinScrollbar,
  watchLowDeviceScale,
  watchThreadScrollbarGutter,
} from "./low-device-scale";
import { MotionConfig } from "motion/react";
import {
  type CSSProperties,
  type ReactNode,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  useSyncExternalStore,
} from "react";
import { MODAL_SURFACE, useSurfaceRef } from "@/lib/surface-registry";
import {
  type LogicalWindowSize,
  PREFERRED_SETUP_WINDOW_SIZE,
  type WindowSizeBounds,
  calculateCenteredPosition,
  calculateFirstAppWindowSize,
  constrainWindowSize,
  fitWindowSize,
} from "./window-layout";
import {
  type MeasuredWindowLayout,
  type MinimumSizeApplier,
  type PixelRatioSource,
  type WindowLayoutGuard,
  createMinimumSizeApplier,
  finalizeAppWindowLayout,
  measureWindowLayout,
  observeDevicePixelRatio,
  prepareSetupWindow,
  shouldFinishWindowLayoutWait,
} from "./window-layout-lifecycle";

interface AppProviderProps {
  children: ReactNode;
}

type TauriWindowMode = "setup" | "app";
type WindowModule = typeof import("@tauri-apps/api/window");
type TauriWindow = Awaited<ReturnType<WindowModule["getCurrentWindow"]>>;
type TauriMonitor = NonNullable<
  Awaited<ReturnType<WindowModule["currentMonitor"]>>
>;

// Keep in step with MOBILE_BREAKPOINT in hooks/use-mobile.ts.
const MIN_DESKTOP_LAYOUT_WIDTH = 768;

// Gutters keep the rail's overflow clip from cutting card shadows (#9246), sized to the dark-mode
// shadow (22px left, 14px above); only the left and top edges show, and both come out of the cap,
// never the cards.
const STACK_SHADOW_GUTTER_BOTTOM = 16;
const STACK_SHADOW_GUTTER_TOP = 16;
const STACK_SHADOW_GUTTER_LEFT = 28;
const STACK_CARD_INSET_RIGHT = 16;
// Rail stays flush with the corner; only its padding grows past the open Run settings panel.
const STACK_CARD_INSET_RIGHT_PAST_PANEL = `calc(${STACK_CARD_INSET_RIGHT}px + var(${CHAT_SETTINGS_INSET_VAR}, 0px))`;
const STACK_SHADOW_GUTTER_BOTTOM_PAST_COMPOSER = `calc(${STACK_SHADOW_GUTTER_BOTTOM}px + var(${COMPOSER_CLEARANCE_VAR}, 0px))`;

function BlockingScreenFlag() {
  useDocumentFlag("data-blocking-screen-open", true);
  return null;
}

// macos page zoom does not change dpr; windows already includes zoom in its dpr.
function logicalPerCssPx(monitorScale: number): number {
  const zoom = Math.max(1, getAppliedInterfaceZoom());
  if (typeof window === "undefined" || !(monitorScale > 0)) return zoom;
  const ratio = window.devicePixelRatio / monitorScale;
  return Math.max(zoom, Number.isFinite(ratio) ? ratio : 1);
}

// Autostart passes --hidden: layout still applies, but the window stays in the tray.
let launchedHidden: Promise<boolean> | null = null;
function wasLaunchedHidden(): Promise<boolean> {
  launchedHidden ??= import("@tauri-apps/api/core")
    .then(({ invoke }) => invoke<boolean>("was_launched_hidden"))
    .catch(() => false);
  return launchedHidden;
}

type WindowLayoutObserver = {
  waitForSettled: () => Promise<void>;
  dispose: () => void;
};

const WINDOW_LAYOUT_POLL_MS = 50;
const WINDOW_LAYOUT_TIMEOUT_MS = 1000;

function delay(milliseconds: number): Promise<void> {
  return new Promise((resolve) => window.setTimeout(resolve, milliseconds));
}

async function observeWindowLayout(
  win: TauriWindow,
  isCurrent: WindowLayoutGuard,
): Promise<WindowLayoutObserver | null> {
  let revision = 0;
  const noteChange = () => {
    revision += 1;
  };
  const unlistenResized = await win.onResized(noteChange);
  let unlistenMoved: (() => void) | undefined;
  try {
    unlistenMoved = await win.onMoved(noteChange);
  } catch (error) {
    unlistenResized();
    throw error;
  }
  if (!isCurrent()) {
    unlistenResized();
    unlistenMoved();
    return null;
  }

  return {
    waitForSettled: async () => {
      let observedRevision = 0;
      let sawNativeChange = revision > 0;
      for (
        let elapsed = 0;
        elapsed < WINDOW_LAYOUT_TIMEOUT_MS && isCurrent();
        elapsed += WINDOW_LAYOUT_POLL_MS
      ) {
        await delay(WINDOW_LAYOUT_POLL_MS);
        if (revision !== observedRevision) {
          observedRevision = revision;
          sawNativeChange = true;
          continue;
        }
        if (shouldFinishWindowLayoutWait(sawNativeChange)) {
          return;
        }
      }
    },
    dispose: () => {
      unlistenResized();
      unlistenMoved();
    },
  };
}

function measureTauriWindowLayout(
  windowModule: WindowModule,
  win: TauriWindow,
  isCurrent: WindowLayoutGuard,
): Promise<MeasuredWindowLayout<TauriMonitor> | null> {
  return measureWindowLayout(
    {
      currentMonitor: () => windowModule.currentMonitor(),
      primaryMonitor: () => windowModule.primaryMonitor(),
      innerSize: () => win.innerSize(),
      outerSize: () => win.outerSize(),
    },
    isCurrent,
    logicalPerCssPx,
  );
}

let minimumSizeApplier: MinimumSizeApplier | null = null;

// One per app: the main window is the only one sized here.
function windowMinimumSize(win: TauriWindow): MinimumSizeApplier {
  minimumSizeApplier ??= createMinimumSizeApplier({
    isRestored: async () => {
      const [maximized, fullscreen, minimized] = await Promise.all([
        win.isMaximized(),
        win.isFullscreen(),
        win.isMinimized(),
      ]);
      return !maximized && !fullscreen && !minimized;
    },
    onResized: (handler) => win.onResized(handler),
    applyFloor: (minimum) =>
      win.setSizeConstraints({
        minWidth: minimum.width,
        minHeight: minimum.height,
      }),
  });
  return minimumSizeApplier;
}

async function placeWindow(
  win: TauriWindow,
  { LogicalSize, PhysicalPosition }: WindowModule,
  { monitor, frameSize }: MeasuredWindowLayout<TauriMonitor>,
  size: LogicalWindowSize,
  isCurrent: WindowLayoutGuard,
): Promise<void> {
  await win.setSize(new LogicalSize(size.width, size.height));
  if (!isCurrent()) return;
  if (!monitor) {
    await win.center();
    return;
  }
  // Center from the requested size because GTK may still report stale geometry.
  const scaleFactor = await win.scaleFactor();
  if (!isCurrent()) return;
  const position = calculateCenteredPosition(monitor.workArea, {
    width: Math.round(size.width * scaleFactor) + frameSize.width,
    height: Math.round(size.height * scaleFactor) + frameSize.height,
  });
  await win.setPosition(new PhysicalPosition(position.x, position.y));
}

function windowPixelRatioSource(): PixelRatioSource | null {
  if (
    typeof window === "undefined" ||
    typeof window.matchMedia !== "function"
  ) {
    return null;
  }
  return {
    devicePixelRatio: () => window.devicePixelRatio,
    matchResolution: (dppx) => window.matchMedia(`(resolution: ${dppx}dppx)`),
  };
}

/** Reapplies the CSS-pixel floor after a zoom change (Windows text scaling). */
async function reapplyWindowSizeConstraints(
  isCurrent: WindowLayoutGuard,
): Promise<void> {
  const windowModule = await import("@tauri-apps/api/window");
  if (!isCurrent()) return;

  const win = windowModule.getCurrentWindow();
  const measured = await measureTauriWindowLayout(windowModule, win, isCurrent);
  if (!measured || !isCurrent()) return;

  const { minimum } = measured.bounds;
  await windowMinimumSize(win).apply(minimum);
  if (!isCurrent()) return;
  // No maximum: capping here would fight a user's own larger size.
  await enforceWindowSizeBounds(win, windowModule.LogicalSize, isCurrent, {
    minimum,
  });
}

async function showSetupWindow(isCurrent: WindowLayoutGuard): Promise<void> {
  const windowModule = await import("@tauri-apps/api/window");
  const { invoke } = await import("@tauri-apps/api/core");
  if (!isCurrent()) return;

  const win = windowModule.getCurrentWindow();
  if (
    !(await prepareSetupWindow({
      resetLayout: () => invoke("reset_app_window_layout_initialized"),
      unmaximize: () => win.unmaximize(),
      clearConstraints: () => {
        windowMinimumSize(win).cancel();
        return win.setSizeConstraints(null);
      },
      enableResize: () => win.setResizable(true),
      resizeForSetup: async () => {
        const measured = await measureTauriWindowLayout(
          windowModule,
          win,
          isCurrent,
        );
        if (!measured) return false;
        const setupSize = fitWindowSize(
          PREFERRED_SETUP_WINDOW_SIZE,
          measured.bounds.maximum,
        );
        await placeWindow(win, windowModule, measured, setupSize, isCurrent);
        return isCurrent();
      },
      disableResize: () => win.setResizable(false),
      isCurrent,
    }))
  ) {
    return;
  }
  if (await wasLaunchedHidden()) return;
  if (!isCurrent()) return;
  await win.show();
  void notifyRendererReady();
}

async function enforceWindowSizeBounds(
  win: TauriWindow,
  LogicalSize: WindowModule["LogicalSize"],
  isCurrent: WindowLayoutGuard,
  bounds: WindowSizeBounds,
  requestedSize: LogicalWindowSize = bounds.minimum,
): Promise<void> {
  const [innerSize, scaleFactor, isMaximized, isFullscreen] = await Promise.all(
    [win.innerSize(), win.scaleFactor(), win.isMaximized(), win.isFullscreen()],
  );
  if (!isCurrent()) return;
  if (isMaximized || isFullscreen) return;

  const currentSize = {
    width: Math.round(innerSize.width / scaleFactor),
    height: Math.round(innerSize.height / scaleFactor),
  };
  // Linux can briefly report the pre-resize size from its GTK cache.
  const nextSize = constrainWindowSize(currentSize, requestedSize, bounds);
  if (
    nextSize.width !== currentSize.width ||
    nextSize.height !== currentSize.height
  ) {
    await win.setSize(new LogicalSize(nextSize.width, nextSize.height));
  }
}

async function applyAppWindowLayout(
  isCurrent: WindowLayoutGuard,
): Promise<void> {
  const windowModule = await import("@tauri-apps/api/window");
  const { invoke } = await import("@tauri-apps/api/core");
  const { restoreStateCurrent, StateFlags } = await import(
    "@tauri-apps/plugin-window-state"
  );
  if (!isCurrent()) return;

  const win = windowModule.getCurrentWindow();
  // Setup-window activity can create plugin state before the full app is shown, so use a dedicated marker.
  const [hasInitializedAppLayout, hasSavedState] = await Promise.all([
    invoke<boolean>("has_initialized_app_window_layout"),
    invoke<boolean>("has_saved_window_state"),
  ]);
  if (!isCurrent()) return;

  await win.setResizable(true);
  if (!isCurrent()) return;
  const measured = await measureTauriWindowLayout(windowModule, win, isCurrent);
  if (!measured) return;

  let requestedSize: LogicalWindowSize | undefined;
  let restored = false;
  let nativeRestored = false;
  let layoutObserver: WindowLayoutObserver | null = null;
  try {
    if (hasInitializedAppLayout && hasSavedState) {
      restored = true;
      nativeRestored = await invoke<boolean>("take_native_layout_restored");
      if (!isCurrent()) return;
      // Subscribe before restoring so native events cannot race listener setup.
      layoutObserver = await observeWindowLayout(win, isCurrent);
      if (!layoutObserver) return;
      if (!nativeRestored) {
        await restoreStateCurrent(
          StateFlags.SIZE | StateFlags.POSITION | StateFlags.MAXIMIZED,
        );
        if (!isCurrent()) return;
      }
    } else {
      const cssSafeLogicalWidth = measured.monitor
        ? Math.round(
            MIN_DESKTOP_LAYOUT_WIDTH *
              logicalPerCssPx(measured.monitor.scaleFactor),
          )
        : undefined;
      requestedSize = calculateFirstAppWindowSize(
        measured.bounds,
        cssSafeLogicalWidth,
      );
      await placeWindow(win, windowModule, measured, requestedSize, isCurrent);
    }
    const hiddenAtLaunch = await wasLaunchedHidden();
    if (!isCurrent()) return;
    await finalizeAppWindowLayout({
      restored,
      nativeRestored,
      measured,
      show: async () => {
        if (hiddenAtLaunch) return false;
        if (!isCurrent()) return false;
        await win.show();
        void notifyRendererReady();
        return true;
      },
      waitForSettled: hiddenAtLaunch
        ? undefined
        : layoutObserver?.waitForSettled,
      measure: () => measureTauriWindowLayout(windowModule, win, isCurrent),
      setMinimumConstraints: (minimum) => windowMinimumSize(win).apply(minimum),
      enforceBounds: (bounds) =>
        enforceWindowSizeBounds(
          win,
          windowModule.LogicalSize,
          isCurrent,
          bounds,
          requestedSize,
        ),
      isCurrent,
    });

    if (!isCurrent()) return;
    await invoke("mark_app_window_layout_initialized");
  } finally {
    layoutObserver?.dispose();
  }
}

async function showWindowFallback(): Promise<void> {
  const { getCurrentWindow } = await import("@tauri-apps/api/window");
  const win = getCurrentWindow();
  await win.setResizable(true);
  if (await wasLaunchedHidden()) return;
  await win.show();
  void notifyRendererReady();
}

function getTauriWindowMode(
  status: BackendStatus,
  hasEnteredAppMode: boolean,
): TauriWindowMode | null {
  switch (status) {
    case "checking":
      return null;
    case "not-installed":
    case "installing":
    case "install-error":
    case "needs-elevation":
    case "repairing":
    case "repair-error":
      return "setup";
    case "starting":
    case "running":
    case "stopped":
      return "app";
    case "error":
      return hasEnteredAppMode ? "app" : "setup";
  }
}

function TauriUpdateLayer({
  externalServerPort,
  children,
  appContent,
  onUpdateScreenChange,
}: {
  externalServerPort: number | null;
  children?: ReactNode;
  appContent: ReactNode;
  onUpdateScreenChange: (shown: boolean) => void;
}) {
  const update = useTauriUpdate(externalServerPort);
  const isUpdating =
    update.status === "updating-backend" ||
    update.status === "downloading" ||
    update.status === "installing" ||
    (update.status === "error" && !update.dismissed);

  const wasUpdatingRef = useRef(false);
  useEffect(() => {
    const wasUpdating = wasUpdatingRef.current;
    wasUpdatingRef.current = isUpdating;
    return followDesktopUpdateScreen(
      isUpdating,
      wasUpdating,
      resyncInferenceStatusAfterServerModelChange,
    );
  }, [isUpdating]);

  // Sync the parent titlebar before paint to avoid flashing sidebar chrome.
  useLayoutEffect(() => {
    onUpdateScreenChange(isUpdating);
    return () => onUpdateScreenChange(false);
  }, [isUpdating, onUpdateScreenChange]);

  const content = isUpdating ? (
    <UpdateScreen
      status={update.status}
      logs={update.logs}
      progress={update.progress}
      error={update.error}
      onRetry={update.retryUpdate}
      onSkipRestart={update.skipAndRestart}
      onCopyDiagnostics={update.copyDiagnostics}
    />
  ) : (
    <div
      ref={cornerInsetScope}
      // Scrolls at the cap rather than spilling cards off screen; the gutter keeps the card shadows out of that clip.
      className="pointer-events-none fixed bottom-0 right-0 flex max-h-[calc(100dvh-var(--studio-window-chrome-top,0px))] flex-col items-end gap-2 overflow-y-auto overflow-x-hidden overscroll-contain"
      data-testid="overlay-rail"
      // Its cards stay clickable over a macOS browser page (native-view.ts).
      data-native-rail=""
      // Gutters in px, never a spacing utility: those are rem, and the cards would drift off the corner.
      style={{
        paddingTop: STACK_SHADOW_GUTTER_TOP,
        paddingBottom: STACK_SHADOW_GUTTER_BOTTOM_PAST_COMPOSER,
        paddingLeft: STACK_SHADOW_GUTTER_LEFT,
        paddingRight: STACK_CARD_INSET_RIGHT_PAST_PANEL,
        zIndex: Z_LAYER.OVERLAY_STACK,
      }}
    >
      <UpdateBanner
        status={update.status}
        info={update.info}
        dismissed={update.dismissed}
        lastFailure={update.lastFailure}
        externalServerPort={externalServerPort}
        updatePolicyMode={update.updatePolicyMode}
        manualReleaseUrl={update.manualReleaseUrl}
        releasePageUrl={update.releasePageUrl}
        positioned={false}
        onInstall={update.installUpdate}
        onDismiss={update.dismiss}
        onCopyDiagnostics={update.copyDiagnostics}
      />
      {children}
    </div>
  );

  return (
    <TauriUpdateContext.Provider value={update}>
      {content}
      {appContent}
    </TauriUpdateContext.Provider>
  );
}

const HIDDEN_TITLEBAR_SIDEBAR_ROUTES = new Set([
  "/login",
  "/change-password",
  "/signup",
]);

const WEB_UPDATE_HIDDEN_ROUTES = new Set([
  "/login",
  "/change-password",
  "/signup",
]);

const MAC_NATIVE_CHROME_STYLE = {
  "--studio-titlebar-height": "0px",
  "--studio-mac-titlebar-height": NATIVE_MAC_TITLEBAR_HEIGHT_VAR,
  "--studio-desktop-titlebar-height": NATIVE_MAC_TITLEBAR_HEIGHT_VAR,
  "--studio-titlebar-navigation-margin-top": "4px",
  "--studio-titlebar-navigation-offset-y": "4px",
  "--studio-mac-traffic-light-inset": NATIVE_MAC_TRAFFIC_LIGHT_INSET_VAR,
  "--studio-collapsed-chat-controls-inset": `calc(110px + ${NATIVE_MAC_TRAFFIC_LIGHT_INSET_VAR})`,
  "--studio-startup-top-inset": `calc(24px + ${NATIVE_MAC_TITLEBAR_HEIGHT_VAR})`,
  "--studio-content-top-inset": "0px",
  "--studio-non-chat-content-top-inset": NATIVE_MAC_TITLEBAR_HEIGHT_VAR,
  "--studio-hidden-route-top-inset": NATIVE_MAC_TITLEBAR_HEIGHT_VAR,
  // Chat chrome follows the UI font size; window geometry is the OS window's and does not.
  "--studio-chat-header-height": "calc(44px * var(--ui-space-scale, 1))",
  "--studio-chat-header-padding-top": "calc(9px * var(--ui-space-scale, 1))",
  "--studio-media-header-left-inset": "calc(0.5rem * var(--ui-space-scale, 1))",
  "--studio-chat-control-height": "calc(33px * var(--ui-space-scale, 1))",
  "--studio-chat-header-right-inset": "0px",
} as CSSProperties;

const CUSTOM_CHROME_STYLE = {
  "--studio-titlebar-height": "0px",
  "--studio-custom-titlebar-height": "34px",
  "--studio-desktop-titlebar-height": "34px",
  "--studio-sidebar-expanded-width": "17.5rem",
  "--studio-sidebar-collapsed-width": "3rem",
  "--studio-collapsed-chat-controls-inset": "12px",
  "--studio-startup-top-inset": "42px",
  "--studio-content-top-inset": "34px",
  "--studio-non-chat-content-top-inset": "34px",
  "--studio-non-chat-scroller-top": "34px",
  "--studio-chat-scroller-top": "34px",
  "--studio-hidden-route-top-inset": "34px",
  // Same split as the native-mac block: chat chrome scales, window chrome does not.
  "--studio-chat-header-height": "calc(48px * var(--ui-space-scale, 1))",
  "--studio-chat-header-padding-top": "calc(9px * var(--ui-space-scale, 1))",
  "--studio-media-header-left-inset": "calc(0.5rem * var(--ui-space-scale, 1))",
  "--studio-chat-control-height": "calc(33px * var(--ui-space-scale, 1))",
  "--studio-chat-header-right-inset": "0px",
  "--studio-window-control-inset": "138px",
} as CSSProperties;

// Fullscreen hides the titlebar (it slides back in from the top edge), so content takes its band.
const CUSTOM_CHROME_FULLSCREEN_STYLE = {
  ...CUSTOM_CHROME_STYLE,
  "--studio-custom-titlebar-height": "0px",
  "--studio-desktop-titlebar-height": "0px",
  "--studio-startup-top-inset": "8px",
  "--studio-content-top-inset": "0px",
  "--studio-non-chat-content-top-inset": "0px",
  "--studio-non-chat-scroller-top": "0px",
  "--studio-chat-scroller-top": "0px",
  "--studio-hidden-route-top-inset": "0px",
  "--studio-window-control-inset": "0px",
} as CSSProperties;

// Mirrored onto <html>: overlays portalled into document.body cannot read the wrapper styles.
function DesktopChromeVarsEffect({
  usesCustomTitlebar,
  usesNativeMacTitlebar,
  customTitlebarHidden,
}: {
  usesCustomTitlebar: boolean;
  usesNativeMacTitlebar: boolean;
  customTitlebarHidden: boolean;
}) {
  useEffect(() => {
    const el = document.documentElement;
    const set = (name: string, value: string | null) =>
      value === null
        ? el.style.removeProperty(name)
        : el.style.setProperty(name, value);
    const customTop = customTitlebarHidden ? "0px" : "34px";
    set("--studio-custom-titlebar-height", usesCustomTitlebar ? customTop : null);
    set(
      "--studio-mac-titlebar-height",
      usesNativeMacTitlebar ? NATIVE_MAC_TITLEBAR_HEIGHT_VAR : null,
    );
    set(
      "--studio-window-control-inset",
      usesCustomTitlebar ? (customTitlebarHidden ? "0px" : "138px") : null,
    );
    // The toaster renders outside the wrapper.
    set("--studio-content-top-inset", usesCustomTitlebar ? customTop : null);
    set(
      "--studio-window-chrome-top",
      usesCustomTitlebar
        ? customTop
        : usesNativeMacTitlebar
          ? NATIVE_MAC_TITLEBAR_HEIGHT_VAR
          : null,
    );
    refreshWindowChromeTop();
    const stopZoom = usesNativeMacTitlebar
      ? subscribeAppliedInterfaceZoom(refreshWindowChromeTop)
      : null;
    return () => {
      stopZoom?.();
      set("--studio-custom-titlebar-height", null);
      set("--studio-mac-titlebar-height", null);
      set("--studio-window-control-inset", null);
      set("--studio-content-top-inset", null);
      set("--studio-window-chrome-top", null);
      refreshWindowChromeTop();
    };
  }, [usesCustomTitlebar, usesNativeMacTitlebar, customTitlebarHidden]);
  return null;
}

function TauriWrapper({ children }: { children: ReactNode }) {
  const pathname = useRouterState({ select: (s) => s.location.pathname });
  const blockingScreenRef = useSurfaceRef<HTMLDivElement>(MODAL_SURFACE);
  const {
    status,
    logs,
    error,
    installDiskFull,
    isExternalServer,
    externalServerPort,
    currentStepIndex,
    progressDetail,
    startupMessage,
    elevationPackages,
    closing,
    startInstall,
    retry,
    retryInstall,
    approveElevation,
    copyDiagnostics,
    startRepair,
  } = useTauriBackend();

  // Manual repair reruns the installer so a CPU-only venv is rebuilt; via ref since startRepair churns.
  const startRepairRef = useRef(startRepair);
  startRepairRef.current = startRepair;
  const [upgradingToFull, setUpgradingToFull] = useState(false);
  const repairController = useMemo(
    () => ({
      repairInstall: () => {
        setUpgradingToFull(usePlatformStore.getState().chatOnlyReason === "no_torch");
        return startRepairRef.current({ forceInstaller: true });
      },
      isExternalServer,
    }),
    [isExternalServer],
  );
  if (upgradingToFull && status === "running") setUpgradingToFull(false);

  const appliedWindowModeRef = useRef<TauriWindowMode | null>(null);
  const hasEnteredAppModeRef = useRef(false);
  const windowLayoutGenerationRef = useRef(0);
  const [desktopAuthReady, setDesktopAuthReady] = useState(!isTauri);
  const [desktopAuthRetry, setDesktopAuthRetry] = useState(0);
  const [nativeMacControlsHidden, setNativeMacControlsHidden] = useState(false);
  const [appShellReady, setAppShellReady] = useState(false);
  const [updateScreenShown, setUpdateScreenShown] = useState(false);
  const canMountApp = status === "running" && desktopAuthReady;
  useEffect(() => {
    if (!isTauri) return;
    setDesktopShellReady(canMountApp && appShellReady);
    return () => setDesktopShellReady(false);
  }, [canMountApp, appShellReady]);

  // Readiness comes from the mounted boundary, so an obsolete async load cannot reveal us.

  useEffect(() => {
    if (!isTauri) return;
    if (!canMountApp) {
      setAppShellReady(false);
      return;
    }
    if (appShellReady) return;
    // A failed chunk must not strand the user behind the splash; never bypass credential auth.
    const timeout = window.setTimeout(() => setAppShellReady(true), 15_000);
    return () => window.clearTimeout(timeout);
  }, [canMountApp, appShellReady]);

  const [windowRevealRevision, setWindowRevealRevision] = useState(0);
  const usesCustomTitlebar = shouldUseCustomWindowTitlebar();
  const usesNativeMacTitlebar = shouldUseNativeMacWindowTitlebar();
  const windowFullscreen = useSyncExternalStore(
    subscribeDesktopFullscreen,
    getDesktopFullscreen,
    () => false,
  );
  const customTitlebarHidden = usesCustomTitlebar && windowFullscreen;
  const hidesTitlebarSidebar = HIDDEN_TITLEBAR_SIDEBAR_ROUTES.has(pathname);

  useEffect(() => {
    if (!isTauri) return;
    return () => {
      windowLayoutGenerationRef.current += 1;
      appliedWindowModeRef.current = null;
    };
  }, []);

  useEffect(() => {
    if (!isTauri) return;
    let disposed = false;
    let stopListening: (() => void) | undefined;

    void wasLaunchedHidden().then(async (hiddenAtLaunch) => {
      if (!hiddenAtLaunch || disposed) return;
      const { getCurrentWindow } = await import("@tauri-apps/api/window");
      const unlisten = await getCurrentWindow().onFocusChanged(
        ({ payload }) => {
          if (!payload || disposed) return;
          stopListening?.();
          stopListening = undefined;
          launchedHidden = Promise.resolve(false);
          appliedWindowModeRef.current = null;
          setWindowRevealRevision((revision) => revision + 1);
        },
      );
      if (disposed) unlisten();
      else stopListening = unlisten;
    });

    return () => {
      disposed = true;
      stopListening?.();
    };
  }, []);

  useEffect(() => {
    if (!isTauri) return;

    const nextMode = getTauriWindowMode(status, hasEnteredAppModeRef.current);
    if (!nextMode) {
      appliedWindowModeRef.current = null;
      windowLayoutGenerationRef.current += 1;
      return;
    }
    if (appliedWindowModeRef.current === nextMode) return;

    appliedWindowModeRef.current = nextMode;
    if (nextMode === "app") hasEnteredAppModeRef.current = true;

    const layoutGeneration = windowLayoutGenerationRef.current + 1;
    windowLayoutGenerationRef.current = layoutGeneration;
    const isCurrent = () =>
      windowLayoutGenerationRef.current === layoutGeneration;
    const applyWindowMode =
      nextMode === "setup" ? showSetupWindow : applyAppWindowLayout;
    applyWindowMode(isCurrent).catch(async () => {
      if (!isCurrent()) return;
      try {
        await showWindowFallback();
      } catch {
        /* swallow; window may still be functional */
      }
    });
  }, [status, windowRevealRevision]);

  // Mounted once: the layout effect returns early on mode-preserving changes and would drop it.
  useEffect(() => {
    if (!isTauri) return;
    const ratioSource = windowPixelRatioSource();
    if (!ratioSource) return;

    let disposed = false;
    const refresh = () => {
      if (disposed || appliedWindowModeRef.current !== "app") return;
      // Read on change: a newer layout pass owns the constraints and this one stands down.
      const generation = windowLayoutGenerationRef.current;
      reapplyWindowSizeConstraints(
        () => !disposed && windowLayoutGenerationRef.current === generation,
      ).catch(() => {
        /* swallow; the floor in force stands */
      });
    };
    const stop = observeDevicePixelRatio(ratioSource, refresh);
    const stopZoom = subscribeAppliedInterfaceZoom(refresh);
    return () => {
      disposed = true;
      stop();
      stopZoom();
    };
  }, []);

  useEffect(() => {
    if (!isTauri) {
      setDesktopAuthReady(true);
      return;
    }
    if (status !== "running") {
      setDesktopAuthReady(false);
      setDesktopAuthRetry(0);
      return;
    }

    let disposed = false;
    setDesktopAuthReady(false);
    tauriAutoAuth({ force: true }).then((authenticated) => {
      if (disposed) return;
      if (authenticated) {
        setDesktopAuthReady(true);
        return;
      }
      if (!getTauriAuthFailure()) {
        window.setTimeout(() => {
          if (!disposed) setDesktopAuthRetry((value) => value + 1);
        }, 500);
      }
    });

    return () => {
      disposed = true;
    };
  }, [status, desktopAuthRetry]);

  // Set once a backend that already answered goes away: the next one measures its hardware again.
  const servedRef = useRef(false);
  const verdictStaleRef = useRef(false);
  // Read at reconnect time only: a navigation must not trigger another health read.
  const pathnameRef = useRef(pathname);
  pathnameRef.current = pathname;
  useEffect(() => {
    if (status === "running") servedRef.current = true;
    else if (servedRef.current) verdictStaleRef.current = true;
  }, [status]);

  useEffect(() => {
    if (!isTauri || status !== "running" || !desktopAuthReady) return;
    if (verdictStaleRef.current) {
      verdictStaleRef.current = false;
      forgetMeasuredVerdict();
    }
    void fetchDeviceType({
      force: true,
      // The open page's beforeLoad will not rerun, so it asks for detection here.
      detectHardware: routeNeedsHardware(pathnameRef.current),
    }).catch(() => undefined);
  }, [status, desktopAuthReady]);

  useEffect(() => {
    if (!usesNativeMacTitlebar) return;
    let active = true;
    const refresh = () => {
      void import("@tauri-apps/api/window")
        .then(({ getCurrentWindow }) => getCurrentWindow().isFullscreen())
        .then((fullscreen) => {
          if (active) setNativeMacControlsHidden(fullscreen);
        })
        .catch(() => undefined);
    };
    const handleResize = () => {
      refresh();
    };
    refresh();
    window.addEventListener("resize", handleResize);

    return () => {
      active = false;
      window.removeEventListener("resize", handleResize);
    };
  }, [usesNativeMacTitlebar]);

  if (!isTauri) {
    return (
      <>
        {children}
        {/* Capped to the viewport: a long download list plus expanded notes would
            push the top of the stack off screen. */}
        <div
          ref={cornerInsetScope}
          // Scrolls at the cap rather than spilling cards off screen; the gutter keeps the card shadows out of that clip.
          className="pointer-events-none fixed bottom-0 right-0 flex max-h-[100dvh] flex-col items-end gap-2 overflow-y-auto overflow-x-hidden overscroll-contain"
          data-testid="overlay-rail"
          // Gutters in px, never a spacing utility: those are rem, and the cards would drift off the corner.
          style={{
            paddingTop: STACK_SHADOW_GUTTER_TOP,
            paddingBottom: STACK_SHADOW_GUTTER_BOTTOM_PAST_COMPOSER,
            paddingLeft: STACK_SHADOW_GUTTER_LEFT,
            paddingRight: STACK_CARD_INSET_RIGHT_PAST_PANEL,
            zIndex: Z_LAYER.OVERLAY_STACK,
          }}
        >
          <WebUpdateBanner
            positioned={false}
            enabled={!WEB_UPDATE_HIDDEN_ROUTES.has(pathname)}
          />
          <LlamaUpdateBanner
            positioned={false}
            enabled={!WEB_UPDATE_HIDDEN_ROUTES.has(pathname)}
          />
          <DownloadManagerPanel positioned={false} />
          {/* Last in the stack, so the persistent card sits at the corner. */}
          <LoadedModelsIndicator positioned={false} />
        </div>
      </>
    );
  }

  const showApp = canMountApp && appShellReady;
  const startupStatus = status === "running" ? "starting" : status;
  const startupProgressDetail = progressDetail;

  const shell = (
    <>
      {canMountApp && (
        <div
          className="h-full min-h-0"
          style={{ visibility: showApp ? "visible" : "hidden" }}
          inert={!showApp}
          aria-hidden={!showApp}
        >
          <AppReadinessBoundary onReady={setAppShellReady} revealed={showApp}>
            <TauriUpdateLayer
              externalServerPort={externalServerPort}
              onUpdateScreenChange={setUpdateScreenShown}
              appContent={
                <>
                  {showApp && <NativeIntentDrain />}
                  {children}
                </>
              }
            >
              <LlamaUpdateBanner
                positioned={false}
                enabled={!hidesTitlebarSidebar}
              />
              <DownloadManagerPanel positioned={false} />
              <LoadedModelsIndicator positioned={false} />
            </TauriUpdateLayer>
          </AppReadinessBoundary>
        </div>
      )}
      {!showApp && (
        <div
          ref={blockingScreenRef}
          data-blocking-screen=""
          className="fixed inset-0 z-40 bg-background"
        >
          <BlockingScreenFlag />
          <StartupScreen
            status={startupStatus}
            logs={logs}
            error={error}
            diskFull={installDiskFull}
            currentStepIndex={currentStepIndex}
            progressDetail={startupProgressDetail}
            startupMessage={startupMessage}
            elevationPackages={elevationPackages}
            upgradingToFull={upgradingToFull}
            onInstall={startInstall}
            onRetry={retry}
            onRetryInstall={retryInstall}
            onApproveElevation={approveElevation}
            onStartServer={retry}
            onCopyDiagnostics={copyDiagnostics}
          />
        </div>
      )}
    </>
  );

  // Over the shell, not instead of it: a declined quit must not remount the tree.
  const content = (
    <TauriRepairContext.Provider value={repairController}>
      {shell}
      {closing && <ClosingScreen />}
    </TauriRepairContext.Provider>
  );

  const chromeVars = (
    <DesktopChromeVarsEffect
      usesCustomTitlebar={usesCustomTitlebar}
      usesNativeMacTitlebar={usesNativeMacTitlebar}
      customTitlebarHidden={customTitlebarHidden}
    />
  );

  if (!usesCustomTitlebar) {
    // macOS returns here before the custom-titlebar branch, so mount the updater banner too.
    if (usesNativeMacTitlebar) {
      return (
        <div
          className={
            hidesTitlebarSidebar
              ? "relative h-dvh min-h-0 overflow-x-hidden overflow-y-auto bg-background"
              : "relative h-dvh min-h-0 overflow-hidden bg-background"
          }
          style={
            nativeMacControlsHidden
              ? ({
                  ...MAC_NATIVE_CHROME_STYLE,
                  "--studio-mac-traffic-light-inset": "6px",
                } as CSSProperties)
              : MAC_NATIVE_CHROME_STYLE
          }
        >
          {!showApp || hidesTitlebarSidebar ? (
            <div
              data-tauri-drag-region={true}
              aria-hidden="true"
              className="pointer-events-auto modal-pe-live fixed inset-x-0 top-0 z-50 h-[var(--studio-mac-titlebar-height,34px)] select-none"
            />
          ) : null}
          {chromeVars}
          {content}
        </div>
      );
    }

    return (
      <>
        {chromeVars}
        {content}
      </>
    );
  }

  const showSidebarSurface =
    showApp && !hidesTitlebarSidebar && !updateScreenShown;

  return (
    <div
      className="relative h-dvh min-h-0 overflow-hidden bg-background"
      style={
        customTitlebarHidden ? CUSTOM_CHROME_FULLSCREEN_STYLE : CUSTOM_CHROME_STYLE
      }
    >
      {chromeVars}
      <WindowTitlebar
        showSidebarSurface={showSidebarSurface}
        fullscreen={customTitlebarHidden}
      />
      <div
        className={
          hidesTitlebarSidebar
            ? "h-full min-h-0 overflow-x-hidden overflow-y-auto"
            : "h-full min-h-0 overflow-hidden"
        }
      >
        {content}
      </div>
    </div>
  );
}

/** Mirrors the appearance customization store onto <html>; colors are per resolved light/dark mode. */
function AppearanceCustomizationEffect() {
  const { theme, resolved } = useTheme();
  const { palette } = usePalette();
  const customization = useAppearanceCustomStore((s) => s.customization);
  const interfaceScale = useInterfaceScaleStore((s) => s.scale);
  useEffect(() => {
    applyCustomizationToDocument(customization, resolved, palette);
  }, [customization, resolved, palette]);
  useEffect(() => {
    if (!isTauri) return;
    void import("@tauri-apps/api/window")
      .then(({ getCurrentWindow }) =>
        getCurrentWindow().setTheme(theme === "system" ? null : theme),
      )
      .catch(() => undefined);
  }, [theme]);
  useEffect(() => {
    void applyInterfaceScale(interfaceScale).catch(() => undefined);
  }, [interfaceScale]);
  return null;
}

function LowDeviceScaleEffect() {
  useLayoutEffect(() => {
    const root = document.documentElement;
    if (!root.classList.contains("client-windows")) return;
    const source = windowPixelRatioSource();
    if (!source) return;
    const stopFlag = watchLowDeviceScale({
      source,
      interfaceZoom: getAppliedInterfaceZoom,
      subscribeInterfaceZoom: subscribeAppliedInterfaceZoom,
      root,
    });
    let gutterSheet: HTMLStyleElement | null = null;
    let stopGutter: (() => void) | undefined;
    if (CSS.supports("selector(::-webkit-scrollbar)")) {
      gutterSheet = document.createElement("style");
      gutterSheet.textContent =
        ":is(.aui-thread-viewport, .aui-thread-composer-dock, .compare-pane-fade, [data-side-panel-inset]):not(.chat-full-view-dock *) {}";
      document.head.append(gutterSheet);
      const rule = gutterSheet.sheet?.cssRules[0] as CSSStyleRule | undefined;
      if (rule) {
        stopGutter = watchThreadScrollbarGutter({
          source,
          measure: measureThinScrollbar,
          style: rule.style,
        });
      }
    }
    return () => {
      stopFlag();
      stopGutter?.();
      gutterSheet?.remove();
    };
  }, []);
  return null;
}

const REDUCED_MOTION_MAP = {
  system: "user",
  on: "always",
  off: "never",
} as const;

export function AppProvider({ children }: AppProviderProps) {
  const pathname = useRouterState({ select: (s) => s.location.pathname });
  const uiSpaceScale = useUiSpaceScale();
  const toastOffsets = getToastOffsets(
    pathname,
    isTauri,
    shouldUseCustomWindowTitlebar(),
    uiSpaceScale,
  );
  const reduceMotion = useAppearanceCustomStore(
    (s) => s.customization.reduceMotion,
  );
  useEffect(() => {
    dismissStartToasts();
  }, [pathname]);
  useEffect(() => installDismissClickStreakGuard(), []);
  return (
    <MotionConfig reducedMotion={REDUCED_MOTION_MAP[reduceMotion]}>
      <TooltipProvider>
        <TitleTooltipLayer />
        <AppearanceCustomizationEffect />
        <LowDeviceScaleEffect />
        <DeepLinkHandler onOpenUrls={receiveSharedRunConfigUrls} />
        <TauriWrapper>{children}</TauriWrapper>
        <SttDownloadPrompt />
        <Toaster
          position="top-right"
          visibleToasts={2}
          expand={true}
          closeButton={true}
          offset={insetPastChatSettings(toastOffsets.default)}
          mobileOffset={toastOffsets.mobile}
        />
      </TooltipProvider>
    </MotionConfig>
  );
}