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.

31.8 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 { shouldUseCustomWindowTitlebar } from "@/components/tauri/window-titlebar";
import {
  ChatBackground,
  WindowMaterialMount,
} from "@/features/chat-background";
import { ImageViewer } from "@/components/image-viewer";
import { useAppShellReadySignal } from "@/components/app-readiness";
import { LazyImportFailure } from "@/components/lazy-import-boundary";
import { AppSidebar } from "@/components/app-sidebar";
import { CommandPalette } from "@/components/command-palette";
import { Navbar } from "@/components/navbar";
import { SidebarEdgeTrigger } from "@/components/sidebar-edge-trigger";
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
import { fetchDeviceType, usePlatformStore } from "@/config/env";
import { routeNeedsHardware, videoNavHint } from "@/config/hardware-verdict";
import { ApiMonitorOverlay } from "@/features/api-monitor/api-monitor-overlay";
import { DownloadApprovalDialog } from "@/features/browser/download-approval";
import {
  AUTH_SESSION_CLEARED_EVENT,
  AUTH_SESSION_STORED_EVENT,
  hasAuthToken,
  hasSettledAuthSession,
  useIsAccountOwner,
} from "@/features/auth";
import type { ChatSearch } from "@/features/chat/chat-search";
import { loadChatPage, loadedChatPage } from "@/features/chat/load-chat-page";
import {
  openFolderAsProject,
  useOpeningFolder,
} from "@/features/chat/utils/open-folder-as-project";
import { startLlamaCppAutoReload } from "@/features/chat/llama-cpp-auto-reload";
import { StopRunningChatsDialog } from "@/features/chat/components/stop-running-chats-dialog";
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
import { usePinnedChatsSync } from "@/features/chat/hooks/use-pinned-chats-sync";
import { useExportRuntimeLifecycle } from "@/features/export";
import { FIND_SCOPE_ATTRIBUTE, FindInPage } from "@/features/find-in-page";
import { HfTokenWarningDialog } from "@/features/hf-auth";
import { InterfaceZoom, zoomInterfaceFromMenu } from "@/features/interface-zoom";
import {
  bootstrapPersistedCredentials,
  takeStartupCredentialBootstrap,
} from "@/features/credentials/bootstrap";
import { ManagedEngineOfferDialog } from "@/features/model-picker/components/managed-engine-offer-dialog";
import { SharedRunConfigLinkHandler } from "@/features/model-picker/sharing/link-handler";
import { backfillModelOverrides } from "@/features/model-picker/api/migrate-model-overrides";
import { hydratePins } from "@/lib/pins-mirror";
import { usePersonalizationSync } from "@/features/profile";
import { useDeviceSettingsSync } from "@/features/settings/hooks/use-device-settings-sync";
import { ScheduledTaskRunNotifier } from "@/features/scheduled-tasks/run-notifier";
import { RemoteCodeConsentDialog } from "@/features/security";
import {
  SETTINGS_TABS,
  useSettingsDialogStore,
} from "@/features/settings/stores/settings-dialog-store";
import { SettingsDialogMount } from "@/features/settings/settings-dialog-mount";
import { settingsTabVisible } from "@/features/settings/settings-tab-visibility";
import {
  triggerShortcut,
  useShortcut,
  useShortcutAvailable,
} from "@/features/settings/hooks/use-shortcut";
import { useHubSourceNotice } from "@/features/settings/hooks/use-hub-source-notice";
import { useVoiceSettingsStore } from "@/features/settings/stores/voice-settings-store";
import { reconcileSttDevicePreference } from "@/features/settings/api/stt-device";
import { useLowDiskNotice } from "@/features/settings/hooks/use-low-disk-notice";
import { useTrainingUnloadGuard } from "@/features/training/hooks/use-training-unload-guard";
import { TransformersUpgradeDialog } from "@/features/transformers-upgrade";
import { LlmCompressorConsentDialog } from "@/features/export/components/llm-compressor-consent-dialog";
import { useNativePathLeasesSupported } from "@/features/native-intents";
import { useRagAvailabilityStore } from "@/features/rag/api/rag-availability";
import { useIsMobileShell } from "@/hooks/use-mobile";
import { useSidebarPin } from "@/hooks/use-sidebar-pin";
import { useTypeToActivate } from "@/hooks/use-type-to-activate";
import { type TranslationKey, useT } from "@/i18n";
import { createNavigationNonce } from "@/lib/navigation-nonce";
import {
  Outlet,
  createRootRoute,
  redirect,
  useMatches,
  useNavigate,
  useRouterState,
} from "@tanstack/react-router";
import { AnimatePresence, motion } from "motion/react";
import {
  type ComponentType,
  lazy,
  memo,
  type ReactNode,
  Suspense,
  useCallback,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,

  useState,
} from "react";
import { FIND_SCOPE_SURFACE, useSurfaceRef } from "@/lib/surface-registry";
import { AppProvider } from "../provider";
import { useDesktopShellReady } from "../desktop-shell-ready";
import { type HelpAction, helpActionAvailable, runHelpAction } from "@/components/help-actions";
import type { SettingsMenuAction } from "../app-menu-chords";
import { hasAppMenus, useAppMenuActions } from "../use-app-menu-actions";

declare module "@tanstack/react-router" {
  interface StaticDataRouteOption {
    titleKey?: TranslationKey;
    isAuthFlow?: boolean;
  }
}

function RouteFallback() {
  const t = useT();

  return (
    <div className="flex h-full min-h-0 flex-1 items-center justify-center text-muted-foreground text-sm">
      {t("common.loading")}
    </div>
  );
}

function InitialReadyPage({
  children,
}: {
  children: (signalReady: () => void) => ReactNode;
}) {
  return children(useAppShellReadySignal());
}

function ReloadSnapshotReady() {
  const signalReady = useAppShellReadySignal();
  useLayoutEffect(() => {
    signalReady();
  }, [signalReady]);
  return null;
}

// reload-snapshot.js runs outside React; mirror privacy state so Temporary Chat is never serialized.
function ReloadSnapshotPrivacy() {
  const incognito = useChatRuntimeStore((state) => state.incognito);

  useLayoutEffect(() => {
    document.documentElement.toggleAttribute(
      "data-reload-snapshot-private",
      incognito,
    );
    return () => {
      document.documentElement.removeAttribute(
        "data-reload-snapshot-private",
      );
    };
  }, [incognito]);

  return null;
}

function RouteBoundary({
  children,
  readyWhenCommitted = true,
}: {
  children: ReactNode;
  readyWhenCommitted?: boolean;
}) {
  return (
    <Suspense fallback={<RouteFallback />}>
      {readyWhenCommitted && <ReloadSnapshotReady />}
      {children}
    </Suspense>
  );
}

type ChatPageProps = { search: ChatSearch; active: boolean };
type ChatPageAttemptProps = ChatPageProps & { onRetry: () => void };

function ChatPageLoadFailure({
  active,
  onRetry,
}: {
  active: boolean;
  onRetry: () => void;
}) {
  const t = useT();
  const signalReady = useAppShellReadySignal();
  useLayoutEffect(() => {
    signalReady();
  }, [signalReady]);
  const wasActive = useRef(active);
  useEffect(() => {
    if (active && !wasActive.current) {
      onRetry();
    }
    wasActive.current = active;
  }, [active, onRetry]);
  return (
    <LazyImportFailure
      message={t("settings.dialog.panelFailed")}
      reloadLabel={t("settings.dialog.panelReload")}
      testId="chat-page-load-failure"
      className="flex h-full min-h-0 flex-1 flex-col items-center justify-center p-6 text-center text-muted-foreground"
    />
  );
}

// Recreate lazy() after failure because it caches failed imports.
function chatPageAttempt(): ComponentType<ChatPageAttemptProps> {
  return (
    loadedChatPage() ??
    lazy<ComponentType<ChatPageAttemptProps>>(() =>
      loadChatPage().then(
        (m) => ({ default: m.ChatPage }),
        () => ({ default: ChatPageLoadFailure }),
      ),
    )
  );
}

function ChatPage(props: ChatPageProps) {
  const [Page, setPage] = useState(chatPageAttempt);
  const retry = useCallback(() => setPage(() => chatPageAttempt()), []);
  return (
    <Suspense fallback={<RouteFallback />}>
      <Page {...props} onRetry={retry} />
    </Suspense>
  );
}

// The layout re-renders on its own state (the Settings flag gating every route shortcut, a route
// change): without these, each of those re-rendered the sidebar, the navbar and the whole chat
// page with it. A component that takes no props is one element, made once: React skips a subtree
// whose element is the one it rendered last. Neither form adds a fiber level, so the useId paths
// the reload snapshot relies on are unchanged.
const appSidebar = <AppSidebar />;
const navbar = <Navbar />;
const commandPalette = <CommandPalette />;
const hfTokenWarningDialog = <HfTokenWarningDialog />;
const remoteCodeConsentDialog = <RemoteCodeConsentDialog />;
const downloadApprovalDialog = <DownloadApprovalDialog />;
const transformersUpgradeDialog = <TransformersUpgradeDialog />;
const managedEngineOfferDialog = <ManagedEngineOfferDialog />;
const llmCompressorConsentDialog = <LlmCompressorConsentDialog />;
const stopRunningChatsDialog = <StopRunningChatsDialog />;
const imageViewer = <ImageViewer />;
const ChatPageSlot = memo(ChatPage);

const ImagesPage = lazy(() =>
  import("@/features/images").then((m) => ({ default: m.ImagesPage })),
);

const VideoPage = lazy(() =>
  import("@/features/video").then((m) => ({ default: m.VideoPage })),
);

const AudioPage = lazy(() =>
  import("@/features/audio").then((m) => ({ default: m.AudioPage })),
);

// Enabled once the session settles: a read refused mid password change would never retry until reload.
function PersonalizationSyncMount() {
  useRouterState({ select: (s) => s.location.pathname });
  const settled = hasSettledAuthSession();
  usePersonalizationSync(settled);
  useDeviceSettingsSync(settled);
  return null;
}

// Wait for the Desktop port and sign-in before mirroring STT device preference (#15280).
function SttDeviceSyncMount() {
  useRouterState({ select: (s) => s.location.pathname });
  const settled = hasSettledAuthSession();
  useEffect(() => {
    if (!settled) return;
    void reconcileSttDevicePreference(
      useVoiceSettingsStore.getState().sttDevice,
      (sttDevice) => useVoiceSettingsStore.setState({ sttDevice }),
    );
  }, [settled]);
  return null;
}

function LowDiskNoticeMount() {
  useLowDiskNotice();
  return null;
}

function HubSourceNoticeMount() {
  useHubSourceNotice();
  return null;
}

function ChatSettingsHydrationMount() {
  usePinnedChatsSync();
  const hydratePersistedSettings = useChatRuntimeStore(
    (state) => state.hydratePersistedSettings,
  );
  useEffect(() => {
    void hydratePersistedSettings();
  }, [hydratePersistedSettings]);
  return null;
}


function CredentialBootstrapGate({
  active,
  children,
}: {
  active: boolean;
  children: ReactNode;
}) {
  const [ready, setReady] = useState(false);
  const runRevision = useRef(0);

  useEffect(() => {
    if (!active) {
      runRevision.current += 1;
      setReady(false);
      return;
    }
    let mounted = true;
    const reconcile = () => {
      const revision = ++runRevision.current;
      if (!hasAuthToken()) {
        setReady(false);
        return;
      }
      setReady(false);
      void (
        takeStartupCredentialBootstrap() ?? bootstrapPersistedCredentials()
      ).finally(() => {
        if (
          mounted &&
          revision === runRevision.current &&
          hasAuthToken()
        ) {
          setReady(true);
        }
      });
    };

    window.addEventListener(AUTH_SESSION_CLEARED_EVENT, reconcile);
    window.addEventListener(AUTH_SESSION_STORED_EVENT, reconcile);
    reconcile();
    return () => {
      mounted = false;
      runRevision.current += 1;
      window.removeEventListener(AUTH_SESSION_CLEARED_EVENT, reconcile);
      window.removeEventListener(AUTH_SESSION_STORED_EVENT, reconcile);
    };
  }, [active]);
  useEffect(() => {
    if (active && ready) return startLlamaCppAutoReload();
  }, [active, ready]);

  return (
    <>
      <SettingsDialogMount active={active && ready} />
      {active && !ready ? <RouteFallback /> : children}
    </>
  );
}

const CHAT_ONLY_ALLOWED = new Set([
  "/",
  "/chat",
  "/projects",
  "/library",
  "/tasks",
  "/hub",
  "/login",
  "/signup",
  "/change-password",
  "/export",
  "/api-monitor",
]);

// Wait for measured admission: redirecting on an initial guess strands healthy hosts on /chat.
const SELF_GATED_WHILE_UNKNOWN = ["/studio", "/video"];

function waitsOutUnknownVerdict(pathname: string): boolean {
  return SELF_GATED_WHILE_UNKNOWN.some(
    (base) => pathname === base || pathname.startsWith(`${base}/`),
  );
}

function isChatOnlyAllowed(pathname: string, trainAvailable: boolean): boolean {
  if (CHAT_ONLY_ALLOWED.has(pathname)) return true;
  if (trainAvailable && (pathname === "/studio" || pathname.startsWith("/studio/")))
    return true;
  if (pathname === "/data-recipes" || pathname.startsWith("/data-recipes/"))
    return true;
  if (pathname === "/images" || pathname.startsWith("/images/")) return true;
  if (pathname === "/audio" || pathname.startsWith("/audio/")) return true;
  if (pathname === "/video" || pathname.startsWith("/video/")) return true;
  return false;
}

export const Route = createRootRoute({
  beforeLoad: async ({ location, preload }) => {
    await fetchDeviceType({
      // Hover preloads must leave an idle session cold.
      detectHardware: !preload && routeNeedsHardware(location.pathname),
    });
    const { isChatOnly, isTrainUnavailable, capabilitiesUnknown, detectionDeferred } =
      usePlatformStore.getState();
    const unmeasured = capabilitiesUnknown();
    if (
      isChatOnly() &&
      !isChatOnlyAllowed(location.pathname, !isTrainUnavailable()) &&
      // A deferred chat_only is provisional; hardware routes requested detection above.
      !(unmeasured && (detectionDeferred || waitsOutUnknownVerdict(location.pathname)))
    ) {
      throw redirect({ to: "/chat" });
    }
  },
  component: RootLayout,
});

const HIDDEN_NAVBAR_ROUTES = ["/login", "/change-password"];

const DEFAULT_DOCUMENT_TITLE = "Unsloth";

function RootLayout() {
  const t = useT();
  const findScopeRef = useSurfaceRef<HTMLDivElement>(FIND_SCOPE_SURFACE);
  const pathname = useRouterState({ select: (s) => s.location.pathname });
  const hideNavbar = HIDDEN_NAVBAR_ROUTES.includes(pathname);
  const routeOwnsReloadReadiness =
    pathname === "/hub" ||
    pathname === "/projects" ||
    pathname === "/export" ||
    pathname === "/studio" ||
    pathname === "/api-monitor" ||
    pathname === "/login" ||
    pathname === "/change-password" ||
    pathname === "/data-recipes" ||
    pathname.startsWith("/data-recipes/");
  const isAuthFlowRoute = useMatches({
    select: (matches) => matches.some((match) => match.staticData.isAuthFlow),
  });
  const chatOnlyMeasured = usePlatformStore(
    (s) => s.isChatOnly() && !s.capabilitiesUnknown(),
  );
  const trainBlocked = usePlatformStore(
    (s) => s.isTrainUnavailable() && !s.capabilitiesUnknown(),
  );
  const chatOnlyReason = usePlatformStore((s) => s.chatOnlyReason);
  const videoCpuOptIn = usePlatformStore((s) => s.videoCpuOptIn);
  const cpuTraining = usePlatformStore((s) => s.cpuTraining);
  const videoDisabled =
    videoNavHint(chatOnlyMeasured, chatOnlyReason, videoCpuOptIn, cpuTraining) !== undefined;
  const isChatRoute = pathname === "/chat";
  // The in-page titlebar, shared by Windows and Linux; the data-windows-* names predate Linux using it.
  const windowsTitlebar = shouldUseCustomWindowTitlebar();
  const windowsWallpaperPage = !isChatRoute && windowsTitlebar;
  const { pinned, setPinned, togglePinned } = useSidebarPin();
  const navigate = useNavigate();

  const rawSearch = useRouterState({ select: (s) => s.location.search }) as
    | Record<string, unknown>
    | undefined;
  const rawThread =
    typeof rawSearch?.thread === "string" ? rawSearch.thread : undefined;
  const rawCompare =
    typeof rawSearch?.compare === "string" ? rawSearch.compare : undefined;
  const rawNew = typeof rawSearch?.new === "string" ? rawSearch.new : undefined;
  const rawProject =
    typeof rawSearch?.project === "string" ? rawSearch.project : undefined;
  const liveChatSearch = useMemo<ChatSearch>(
    () => ({
      thread: rawThread,
      compare: rawCompare,
      new: rawNew,
      project: rawProject,
    }),
    [rawThread, rawCompare, rawNew, rawProject],
  );
  // Seed search only on /chat; another route's ?project= must not create a phantom chat.
  const [frozenChatSearch, setFrozenChatSearch] = useState<ChatSearch>({});
  const [chatMounted, setChatMounted] = useState(isChatRoute);
  if (isChatRoute && frozenChatSearch !== liveChatSearch) {
    setFrozenChatSearch(liveChatSearch);
  }
  if (isChatRoute && !chatMounted) {
    setChatMounted(true);
  }
  const chatSearch = isChatRoute ? liveChatSearch : frozenChatSearch;
  const shouldMountChat = isChatRoute || chatMounted;

  const isImagesRoute = pathname === "/images";
  const [imagesMounted, setImagesMounted] = useState(isImagesRoute);
  if (isImagesRoute && !imagesMounted) {
    setImagesMounted(true);
  }
  const shouldMountImages = isImagesRoute || imagesMounted;

  const isVideoRoute = pathname === "/video";
  const [videoMounted, setVideoMounted] = useState(isVideoRoute);
  if (isVideoRoute && !videoMounted) {
    setVideoMounted(true);
  }
  const shouldMountVideo = isVideoRoute || videoMounted;

  const isAudioRoute = pathname === "/audio";
  const isLibraryRoute = pathname === "/library";
  const [audioMounted, setAudioMounted] = useState(isAudioRoute);
  if (isAudioRoute && !audioMounted) {
    setAudioMounted(true);
  }
  const shouldMountAudio = isAudioRoute || audioMounted;
  const isChatLike = isChatRoute || isImagesRoute || isVideoRoute || isAudioRoute;
  const mobileShell = useIsMobileShell();
  const nonChatTopInset = mobileShell
    ? "pt-14"
    : "pt-[calc(var(--studio-non-chat-content-top-inset,var(--studio-content-top-inset,0px))-var(--studio-non-chat-scroller-top,0px))] [--studio-titlebar-height:var(--studio-non-chat-content-top-inset,var(--studio-content-top-inset,0px))]";

  useTrainingUnloadGuard();
  useTypeToActivate();
  useExportRuntimeLifecycle();

  const matchedTitle = useMatches({
    select: (matches) => {
      for (let i = matches.length - 1; i >= 0; i--) {
        const { titleKey } = matches[i].staticData;
        if (titleKey) return t(titleKey);
      }
      return null;
    },
  });

  const settingsDialogOpen = useSettingsDialogStore((s) => s.open);
  const documentTitle =
    settingsDialogOpen && !isAuthFlowRoute ? t("settings.title") : matchedTitle;

  useLayoutEffect(() => {
    document.title = documentTitle
      ? `${documentTitle} - ${DEFAULT_DOCUMENT_TITLE}`
      : DEFAULT_DOCUMENT_TITLE;
  }, [documentTitle]);

  // Desktop mounts this root before the port exists; authFetch retries keep the URL it started with.
  const desktopShellReady = useDesktopShellReady();

  useEffect(() => {
    if (isAuthFlowRoute || !desktopShellReady) {
      return;
    }
    void backfillModelOverrides();
    void hydratePins();
  }, [isAuthFlowRoute, desktopShellReady]);

  useEffect(() => {
    if (isAuthFlowRoute) {
      useSettingsDialogStore.getState().closeDialog();
    }
  }, [isAuthFlowRoute]);

  useShortcut(
    "openSettings",
    () => useSettingsDialogStore.getState().openDialog(),
    { enabled: !isAuthFlowRoute },
  );
  useShortcut(
    "openKeyboardShortcuts",
    () =>
      useSettingsDialogStore.getState().openDialog("keyboard-shortcuts"),
    { enabled: !isAuthFlowRoute },
  );
  const startNewChat = (options?: {
    incognito?: boolean;
    standalone?: boolean;
  }) => {
    const chatRuntime = useChatRuntimeStore.getState();
    // Off Chat, the hidden runtime project must not become the new chat's project.
    const openProjectId = isChatRoute ? chatRuntime.activeProjectId : null;
    const projectId = options?.standalone ? null : openProjectId;
    chatRuntime.setActiveThreadId(null);
    chatRuntime.setActiveProjectId(projectId);
    chatRuntime.setIncognito(Boolean(options?.incognito));
    void navigate({
      to: "/chat",
      search: projectId ? { project: projectId } : { new: createNavigationNonce() },
    });
  };

  const routeShortcutEnabled = !isAuthFlowRoute && !settingsDialogOpen;
  useShortcut("newChat", () => startNewChat(), {
    enabled: routeShortcutEnabled,
  });
  useShortcut(
    "newTemporaryChat",
    () => startNewChat({ incognito: true, standalone: true }),
    { enabled: routeShortcutEnabled },
  );
  useShortcut("newStandaloneChat", () => startNewChat({ standalone: true }), {
    enabled: routeShortcutEnabled,
  });

  const pathLeasesSupported = useNativePathLeasesSupported();
  const ragUnavailable = useRagAvailabilityStore((s) => s.isUnavailable());
  const openingFolder = useOpeningFolder();
  const sidebarMounted = useShortcutAvailable("toggleSidebar", hasAppMenus);
  const findMounted = useShortcutAvailable("findInPage", hasAppMenus);
  const previousChatMounted = useShortcutAvailable("previousChat", hasAppMenus);
  const nextChatMounted = useShortcutAvailable("nextChat", hasAppMenus);
  const viaShortcut = (id: Parameters<typeof triggerShortcut>[0], mounted: boolean) =>
    mounted ? () => void triggerShortcut(id) : null;
  const isOwner = useIsAccountOwner();
  const helpAction = (action: HelpAction) =>
    isAuthFlowRoute || !helpActionAvailable(action, isOwner) ? null : () => runHelpAction(action);
  const goTo = (to: string) => () => void navigate({ to });
  const goAction = (enabled: boolean, go: () => void) => (enabled ? go : null);
  const settingsActions = Object.fromEntries(
    SETTINGS_TABS.map((tab) => [
      `settings-${tab}`,
      !isAuthFlowRoute && settingsTabVisible(tab, isOwner)
        ? () => useSettingsDialogStore.getState().openDialog(tab)
        : null,
    ]),
  ) as Record<SettingsMenuAction, (() => void) | null>;
  useAppMenuActions({
    "new-chat": routeShortcutEnabled ? () => startNewChat() : null,
    "new-temporary-chat": routeShortcutEnabled
      ? () => startNewChat({ incognito: true, standalone: true })
      : null,
    "open-folder":
      routeShortcutEnabled && pathLeasesSupported && !ragUnavailable && !openingFolder
        ? () =>
            void openFolderAsProject().then((project) => {
              if (!project) return;
              const chatRuntime = useChatRuntimeStore.getState();
              chatRuntime.setActiveThreadId(null);
              chatRuntime.setActiveProjectId(project.id);
              void navigate({ to: "/chat", search: { project: project.id } });
            })
        : null,
    "toggle-sidebar": viaShortcut("toggleSidebar", sidebarMounted),
    "find": viaShortcut("findInPage", findMounted),
    "previous-chat": viaShortcut("previousChat", previousChatMounted),
    "next-chat": viaShortcut("nextChat", nextChatMounted),
    "back": routeShortcutEnabled ? () => window.history.back() : null,
    "forward": routeShortcutEnabled ? () => window.history.forward() : null,
    "zoom-in": () => zoomInterfaceFromMenu(1),
    "zoom-out": () => zoomInterfaceFromMenu(-1),
    "actual-size": () => zoomInterfaceFromMenu(0),
    "help-documentation": helpAction("help-documentation"),
    "help-keyboard-shortcuts": helpAction("help-keyboard-shortcuts"),
    "help-whats-new": helpAction("help-whats-new"),
    "help-troubleshooting": helpAction("help-troubleshooting"),
    "help-system-status": helpAction("help-system-status"),
    "help-send-feedback": helpAction("help-send-feedback"),
    "go-chat": goAction(
      routeShortcutEnabled,
      () => void navigate({ to: "/chat", search: chatSearch }),
    ),
    "go-projects": goAction(routeShortcutEnabled, goTo("/projects")),
    "go-library": goAction(routeShortcutEnabled, goTo("/library")),
    "go-hub": goAction(routeShortcutEnabled, goTo("/hub")),
    "go-train": goAction(routeShortcutEnabled && !trainBlocked, goTo("/studio")),
    "go-recipes": goAction(routeShortcutEnabled, goTo("/data-recipes")),
    "go-images": goAction(routeShortcutEnabled, goTo("/images")),
    "go-video": goAction(routeShortcutEnabled && !videoDisabled, goTo("/video")),
    "go-audio": goAction(routeShortcutEnabled, goTo("/audio")),
    "go-export": goAction(routeShortcutEnabled, goTo("/export")),
    ...settingsActions,
  }, desktopShellReady);

  useShortcut(
    "switchToChat",
    () => void navigate({ to: "/chat", search: chatSearch }),
    { enabled: routeShortcutEnabled },
  );
  useShortcut("switchToProjects", goTo("/projects"), {
    enabled: routeShortcutEnabled,
  });
  useShortcut("switchToHub", goTo("/hub"), {
    enabled: routeShortcutEnabled,
  });
  useShortcut("switchToTrain", goTo("/studio"), {
    enabled: routeShortcutEnabled && !trainBlocked,
  });
  useShortcut("switchToRecipes", goTo("/data-recipes"), {
    enabled: routeShortcutEnabled,
  });
  useShortcut("switchToImages", goTo("/images"), {
    enabled: routeShortcutEnabled,
  });
  useShortcut("switchToVideo", goTo("/video"), {
    enabled: routeShortcutEnabled && !videoDisabled,
  });
  useShortcut("switchToAudio", goTo("/audio"), {
    enabled: routeShortcutEnabled,
  });
  useShortcut("switchToExport", goTo("/export"), {
    enabled: routeShortcutEnabled,
  });

  useEffect(() => {
    if (isChatRoute) return;
    const chatRuntime = useChatRuntimeStore.getState();
    // Clearing the thread id mid-generation remounts the provider and cancels the stream.
    const anyRunning = Object.values(chatRuntime.runningByThreadId).some(
      Boolean,
    );
    if (anyRunning) return;
    chatRuntime.setActiveProjectId(null);
    chatRuntime.setActiveThreadId(null);
    chatRuntime.setIncognito(false);
  }, [isChatRoute]);

  const content = (
    <>
      <PersonalizationSyncMount />
      <SttDeviceSyncMount />
      <InterfaceZoom />
      <WindowMaterialMount route={hideNavbar ? undefined : isChatRoute ? "chat" : "page"} />
      <ReloadSnapshotPrivacy />
      {!isAuthFlowRoute && <ChatSettingsHydrationMount />}
      {!isAuthFlowRoute && <LowDiskNoticeMount />}
      {!isAuthFlowRoute && <ApiMonitorOverlay />}
      {hfTokenWarningDialog}
      {remoteCodeConsentDialog}
      {downloadApprovalDialog}
      {transformersUpgradeDialog}
      {managedEngineOfferDialog}
      {llmCompressorConsentDialog}
      {stopRunningChatsDialog}
      {imageViewer}
      {!hideNavbar && commandPalette}
      {hideNavbar ? (
        <main className="h-dvh flex-1 overflow-y-auto pt-[var(--studio-hidden-route-top-inset,0px)] [--studio-titlebar-height:var(--studio-hidden-route-top-inset,0px)]">
          <RouteBoundary readyWhenCommitted={!routeOwnsReloadReadiness}>
            <Outlet />
          </RouteBoundary>
        </main>
      ) : (
        <SidebarProvider
          pinned={pinned}
          setPinned={setPinned}
          togglePinned={togglePinned}
          data-wallpaper-workspace=""
          data-windows-wallpaper-page={windowsWallpaperPage || undefined}
          data-wallpaper-route={isChatRoute ? "chat" : "page"}
          data-wallpaper-media={isImagesRoute || isVideoRoute || isAudioRoute || undefined}
          className="relative !min-h-0 h-[calc(100dvh-var(--studio-titlebar-height,0px))] overflow-hidden"
        >
          <ChatBackground route={isChatRoute ? "chat" : "page"} backdrop />
          {appSidebar}
          <SidebarEdgeTrigger />
          {windowsWallpaperPage && (
            <div
              data-slot="page-wallpaper-blur"
              // AppSidebar's data-windows-glass-frame, which sits under this page only off the mobile sheet.
              data-sidebar-frame={(pinned && !mobileShell) || undefined}
              aria-hidden="true"
            />
          )}
          <SidebarInset
            className={
              isChatLike
                ? "overflow-hidden"
                :
                  isLibraryRoute
                  ? "mt-[var(--studio-non-chat-scroller-top,0px)] overflow-y-auto [scrollbar-gutter:stable]"
                  : "mt-[var(--studio-non-chat-scroller-top,0px)] overflow-y-auto"
            }
          >
            {navbar}
            <div
              ref={findScopeRef}
              {...{ [FIND_SCOPE_ATTRIBUTE]: "" }}
              className={`relative flex min-h-0 min-w-0 flex-1 basis-0 flex-col ${isChatLike ? "overflow-hidden" : "overflow-visible"} ${isChatLike ? "" : nonChatTopInset}`}
            >
              <FindInPage enabled={routeShortcutEnabled} />
              {/* Keep generation mounted across routes; active closes hidden page overlays. */}
              {shouldMountChat && (
                <div
                  className={
                    isChatRoute
                      ? "flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden"
                      : "hidden"
                  }
                  inert={!isChatRoute || undefined}
                >
                  <ChatPageSlot search={chatSearch} active={isChatRoute} />
                </div>
              )}
              {shouldMountImages && (
                <div
                  className={
                    isImagesRoute
                      ? "flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden"
                      : "hidden"
                  }
                  inert={!isImagesRoute || undefined}
                >
                  <Suspense fallback={<RouteFallback />}>
                    <InitialReadyPage>
                      {(signalReady) => (
                        <ImagesPage active={isImagesRoute} onInitialReady={signalReady} />
                      )}
                    </InitialReadyPage>
                  </Suspense>
                </div>
              )}
              {shouldMountVideo && (
                <div
                  className={
                    isVideoRoute
                      ? "flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden"
                      : "hidden"
                  }
                  inert={!isVideoRoute || undefined}
                >
                  <Suspense fallback={<RouteFallback />}>
                    <InitialReadyPage>
                      {(signalReady) => (
                        <VideoPage active={isVideoRoute} onInitialReady={signalReady} />
                      )}
                    </InitialReadyPage>
                  </Suspense>
                </div>
              )}
              {shouldMountAudio && (
                <div
                  className={
                    isAudioRoute
                      ? "flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden"
                      : "hidden"
                  }
                  inert={!isAudioRoute || undefined}
                >
                  <Suspense fallback={<RouteFallback />}>
                    <InitialReadyPage>
                      {(signalReady) => (
                        <AudioPage active={isAudioRoute} onInitialReady={signalReady} />
                      )}
                    </InitialReadyPage>
                  </Suspense>
                </div>
              )}
              {/* wait mode froze navigation behind slow page exits (#5850). */}
              {!isChatRoute && !isImagesRoute && !isVideoRoute && !isAudioRoute && (
                <AnimatePresence initial={false} mode="popLayout">
                  <motion.div
                    key={pathname}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                    transition={{ duration: 0.06 }}
                    className="flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-visible"
                  >
                    <RouteBoundary readyWhenCommitted={!routeOwnsReloadReadiness}>
                      <Outlet />
                    </RouteBoundary>
                  </motion.div>
                </AnimatePresence>
              )}
            </div>
          </SidebarInset>
        </SidebarProvider>
      )}
      {/* These side-effect-only mounts stay last so they cannot shift existing React useId paths. */}
      {!isAuthFlowRoute && <HubSourceNoticeMount />}
      {!isAuthFlowRoute && <ScheduledTaskRunNotifier />}
    </>
  );

  return (
    <AppProvider>
      <CredentialBootstrapGate active={!isAuthFlowRoute}>
        <SharedRunConfigLinkHandler
          chatSearch={shouldMountChat ? chatSearch : null}
        />
        {content}
      </CredentialBootstrapGate>
    </AppProvider>
  );
}