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
Lazy-load Studio entry surfaces (#10236)
Wasim Yousef Saide8a88546ddef
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsxindex 4bb84e319c1..63f8f564b3e 100644--- a/studio/frontend/src/app/routes/__root.tsx+++ b/studio/frontend/src/app/routes/__root.tsx@@ -28,7 +28,7 @@ import { backfillModelOverrides } from "@/features/model-picker/api/migrate-modeimport { usePersonalizationSync } from "@/features/profile";import { RemoteCodeConsentDialog } from "@/features/security";import {- SettingsDialog,+ SettingsDialogMount,useSettingsDialogStore,useShortcut,} from "@/features/settings";@@ -162,12 +162,23 @@ function ChatSettingsHydrationMount() {}-function CredentialBootstrapGate({ children }: { children: ReactNode }) {+function CredentialBootstrapGate({+ active,+ children,+}: {+ active: boolean;+ children: ReactNode;+}) {const [ready, setReady] = useState(false);const runRevision = useRef(0);useEffect(() => {- let active = true;+ if (!active) {+ runRevision.current += 1;+ setReady(false);+ return;+ }+ let mounted = true;const reconcile = () => {const revision = ++runRevision.current;if (!hasAuthToken()) {@@ -177,7 +188,7 @@ function CredentialBootstrapGate({ children }: { children: ReactNode }) {setReady(false);void bootstrapPersistedCredentials().finally(() => {if (- active &&+ mounted &&revision === runRevision.current &&hasAuthToken()) {@@ -190,13 +201,18 @@ function CredentialBootstrapGate({ children }: { children: ReactNode }) {window.addEventListener(AUTH_SESSION_STORED_EVENT, reconcile);reconcile();return () => {- active = false;+ mounted = false;runRevision.current += 1;window.removeEventListener(AUTH_SESSION_CLEARED_EVENT, reconcile);window.removeEventListener(AUTH_SESSION_STORED_EVENT, reconcile);};- }, []);- return ready ? children : <RouteFallback />;+ }, [active]);+ return (+ <>+ <SettingsDialogMount active={active && ready} />+ {active && !ready ? <RouteFallback /> : children}+ </>+ );}const CHAT_ONLY_ALLOWED = new Set([@@ -522,7 +538,6 @@ function RootLayout() {<PersonalizationSyncMount /><ReloadSnapshotPrivacy />{!isAuthFlowRoute && <ChatSettingsHydrationMount />}- {!isAuthFlowRoute && <SettingsDialog />}{/* Opens itself when API traffic arrives; hides on the full monitor page. */}{!isAuthFlowRoute && <ApiMonitorOverlay />}<HfTokenWarningDialog />@@ -656,11 +671,9 @@ function RootLayout() {return (<AppProvider>- {!isAuthFlowRoute ? (- <CredentialBootstrapGate>{content}</CredentialBootstrapGate>- ) : (- content- )}+ <CredentialBootstrapGate active={!isAuthFlowRoute}>+ {content}+ </CredentialBootstrapGate></AppProvider>);}diff --git a/studio/frontend/src/components/lazy-import-boundary.tsx b/studio/frontend/src/components/lazy-import-boundary.tsxnew file mode 100644index 00000000000..ee094c5b181--- /dev/null+++ b/studio/frontend/src/components/lazy-import-boundary.tsx@@ -0,0 +1,71 @@+// 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 { Component, type ReactNode, useEffect, useRef } from "react";++interface LazyImportBoundaryProps {+ fallback: ReactNode;+ children: ReactNode;+}++interface LazyImportBoundaryState {+ failed: boolean;+}++export class LazyImportBoundary extends Component<+ LazyImportBoundaryProps,+ LazyImportBoundaryState+> {+ state: LazyImportBoundaryState = { failed: false };++ static getDerivedStateFromError(): LazyImportBoundaryState {+ return { failed: true };+ }++ render() {+ return this.state.failed ? this.props.fallback : this.props.children;+ }+}++export function LazyImportFailure({+ message,+ reloadLabel,+ testId,+ className,+ dismissLabel,+ onDismiss,+}: {+ message: string;+ reloadLabel: string;+ testId: string;+ className: string;+ dismissLabel?: string;+ onDismiss?: () => void;+}) {+ const reloadRef = useRef<HTMLButtonElement>(null);+ useEffect(() => reloadRef.current?.focus(), []);+ return (+ <div role="alert" data-testid={testId} className={className}>+ <p className="text-sm">{message}</p>+ <div className="mt-2 flex gap-2">+ <button+ ref={reloadRef}+ type="button"+ onClick={() => window.location.reload()}+ className="rounded-md border border-border bg-background px-3 py-1.5 font-medium text-xs hover:bg-accent"+ >+ {reloadLabel}+ </button>+ {dismissLabel && onDismiss ? (+ <button+ type="button"+ onClick={onDismiss}+ className="rounded-md border border-border bg-background px-3 py-1.5 font-medium text-xs hover:bg-accent"+ >+ {dismissLabel}+ </button>+ ) : null}+ </div>+ </div>+ );+}diff --git a/studio/frontend/src/features/find-in-page/components/find-bar-loader.tsx b/studio/frontend/src/features/find-in-page/components/find-bar-loader.tsxnew file mode 100644index 00000000000..ef663576bc0--- /dev/null+++ b/studio/frontend/src/features/find-in-page/components/find-bar-loader.tsx@@ -0,0 +1,14 @@+// 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 FindBar, { type FindBarProps } from "./find-bar.tsx";++/**+ * A stable lazy entry that keeps the controller independent of the on-demand UI and engine.+ * Keeping the implementation static inside this entry lets Vite fetch every dependency in+ * parallel, rather than making the first Ctrl/Cmd+F wait through a second network waterfall.+ */+// biome-ignore lint/style/noDefaultExport: React.lazy requires the component as a default export.+export default function FindBarLoader(props: FindBarProps) {+ return <FindBar {...props} />;+}diff --git a/studio/frontend/src/features/find-in-page/components/find-bar.tsx b/studio/frontend/src/features/find-in-page/components/find-bar.tsxnew file mode 100644index 00000000000..8fc2dd9661a--- /dev/null+++ b/studio/frontend/src/features/find-in-page/components/find-bar.tsx@@ -0,0 +1,280 @@+// 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 { Button } from "@/components/ui/button";+import { isImeComposing, isSurfaceBackgrounded } from "@/features/settings";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { Cancel01Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+// lucide supplies the directional arrows used throughout the app.+import { ArrowDownIcon, ArrowUpIcon } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { useFindInPage } from "../hooks/use-find-in-page.ts";+import { FIND_SCOPE_ATTRIBUTE } from "../lib/find-attributes.ts";+import {+ resolveDismissiblePortalSurfaces,+ resolveFindScope,+} from "../lib/find-dom.ts";+export type FindBarProps = {+ query: string;+ setQuery: (query: string) => void;+ close: () => void;+ focusToken: number;+ restoreSelection: (input: HTMLInputElement) => boolean;+ pendingSteps: { query: string; delta: -1 | 1 }[];+ clearPendingSteps: () => void;+};++/** Keep the caret in the field when a walk button is clicked. */+function keepFocusInField(event: { preventDefault: () => void }): void {+ event.preventDefault();+}++/** Show the start of a long query again once the field loses focus. */+function rewindToStart(event: { currentTarget: HTMLInputElement }): void {+ const input = event.currentTarget;+ input.setSelectionRange(0, 0);+ input.scrollLeft = 0;+}++/** The wash reads on both the light and dark find-bar surfaces. */+const FIND_BUTTON_CLASS = "size-8 hover:bg-black/[0.06] dark:hover:bg-white/10";++/** Coalesce a typing burst before the DOM search/highlight work runs. */+export const FIND_QUERY_SETTLE_MS = 100;++function useSettledQuery(query: string): [string, () => void] {+ const [settled, setSettled] = useState(query);+ useEffect(() => {+ if (query.length === 0) {+ setSettled("");+ return;+ }+ const timer = setTimeout(() => setSettled(query), FIND_QUERY_SETTLE_MS);+ return () => clearTimeout(timer);+ }, [query]);+ return [settled, () => setSettled(query)];+}++/** The on-demand UI and engine for an open find session. */+// biome-ignore lint/style/noDefaultExport: React.lazy requires the component as a default export.+export default function FindBar({+ query,+ setQuery,+ close,+ focusToken,+ restoreSelection,+ pendingSteps,+ clearPendingSteps,+}: FindBarProps) {+ const t = useT();+ const [settledQuery, settleQuery] = useSettledQuery(query);++ const [completedQuery, setCompletedQuery] = useState<string | null>(null);+ const queryPending = query !== settledQuery;+ const { count, active, capped, truncated, next, previous } = useFindInPage(+ settledQuery,+ queryPending,+ );++ useEffect(() => {+ if (!queryPending) {+ setCompletedQuery(settledQuery);+ }+ }, [queryPending, settledQuery]);+ const inputRef = useRef<HTMLInputElement>(null);+ const queuedStepsRef = useRef([...pendingSteps]);+ useEffect(() => {+ queuedStepsRef.current = [...pendingSteps];+ }, [pendingSteps]);+ const stepWhenSettled = (delta: -1 | 1) => {+ if (queryPending) {+ queuedStepsRef.current.push({ query, delta });+ settleQuery();+ return;+ }+ if (delta < 0) previous();+ else next();+ };+ useEffect(() => {+ const matchingSteps = queuedStepsRef.current.filter(+ (step) => step.query === query,+ );+ if (matchingSteps.length === queuedStepsRef.current.length) {+ return;+ }+ queuedStepsRef.current = matchingSteps;+ if (matchingSteps.length === 0) {+ clearPendingSteps();+ }+ }, [clearPendingSteps, query]);++ useEffect(() => {+ if (+ queryPending ||+ completedQuery !== settledQuery ||+ queuedStepsRef.current.length === 0+ )+ return;+ const steps = queuedStepsRef.current;+ queuedStepsRef.current = [];+ if (count > 0) {+ for (const step of steps) {+ if (step.delta < 0) previous();+ else next();+ }+ }+ clearPendingSteps();+ }, [+ clearPendingSteps,+ completedQuery,+ count,+ next,+ previous,+ queryPending,+ settledQuery,+ ]);+ // Hand focus back to whatever had it, usually the composer, so closing a search leaves the reader+ // typing. Declared above the focus effect so it reads `activeElement` before the field takes it.+ const barRef = useRef<HTMLDivElement>(null);+ const originRef = useRef<HTMLElement | null>(null);+ useEffect(() => {+ const active = document.activeElement as HTMLElement | null;+ // First answer only, and never anything in the bar: StrictMode replays this effect, and by the+ // second run the field has focus, so the bar would try to hand focus back to its own input.+ if (+ originRef.current === null &&+ active !== null &&+ barRef.current?.contains(active) !== true+ ) {+ originRef.current = active;+ }+ return () => {+ const origin = originRef.current;+ if (!origin?.isConnected || typeof origin.focus !== "function") return;+ // Only when closing dropped focus on the floor. Anywhere else and the reader moved it.+ const focused = document.activeElement;+ if (focused !== null && focused !== document.body) return;+ origin.focus();+ };+ }, []);++ // Capture on the window so closing the bar cannot carry on to another bare-Escape action. A+ // modal owns Escape while it backgrounds the scope; a transient popover/menu/listbox owns its+ // first Escape. Persistent monitor panels deliberately do not trap the find bar.+ useEffect(() => {+ const onEscape = (event: KeyboardEvent) => {+ if (event.key !== "Escape" || isImeComposing(event)) return;+ if (isSurfaceBackgrounded(`[${FIND_SCOPE_ATTRIBUTE}]`)) return;+ if (resolveDismissiblePortalSurfaces(resolveFindScope()).length > 0)+ return;+ event.preventDefault();+ event.stopPropagation();+ close();+ };+ window.addEventListener("keydown", onEscape, true);+ return () => window.removeEventListener("keydown", onEscape, true);+ }, [close]);++ // Every press of the chord, not just the one that opened the bar, selects the current query.+ // biome-ignore lint/correctness/useExhaustiveDependencies: each token requests a fresh focus/select.+ useEffect(() => {+ const input = inputRef.current;+ if (!input) return;+ input.focus();+ if (!restoreSelection(input)) input.select();+ }, [focusToken, restoreSelection]);++ const searching = query.length > 0;+ const empty = !queryPending && searching && count === 0;+ // A pending query has no count of its own yet, so the settled one's zero must not disable the+ // walk: `stepWhenSettled` queues the press and runs it once the count arrives.+ const canStep = searching && (count > 0 || queryPending);+ const counter =+ searching && !queryPending+ ? `${count === 0 ? 0 : active + 1}/${count}${capped ? "+" : ""}`+ : "";++ return (+ // `data-find-skip` keeps the bar out of its own index: without it every keystroke finds itself.+ <div+ ref={barRef}+ data-find-skip=""+ // biome-ignore lint/a11y/useSemanticElements: this landmark contains the field and its navigation controls.+ role="search"+ aria-label={t("shell.find.label")}+ className="find-bar-surface fixed top-[calc(var(--studio-content-top-inset,0px)+3.5rem)] right-4 z-50 flex h-13 w-[22.25rem] max-w-[calc(100vw-2rem)] items-center gap-1 rounded-full pr-4 pl-5 sm:w-[28.25rem]"+ >+ <input+ ref={inputRef}+ type="text"+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ // The Enter committing an IME candidate arrives here too; taken, it walks to the next+ // match and throws away the word.+ if (isImeComposing(event.nativeEvent)) return;+ event.preventDefault();+ stepWhenSettled(event.shiftKey ? -1 : 1);+ }+ }}+ onBlur={rewindToStart}+ placeholder={t("shell.find.label")}+ aria-label={t("shell.find.label")}+ spellCheck={false}+ autoComplete="off"+ autoCorrect="off"+ className={cn(+ "min-w-0 flex-1 bg-transparent text-ui-15 outline-none placeholder:text-muted-foreground",+ empty && "text-destructive",+ )}+ />+ <span+ aria-live="polite"+ title={truncated ? t("shell.find.truncated") : undefined}+ className={cn(+ "min-w-12 shrink-0 pr-3 text-right text-muted-foreground text-sm tabular-nums",+ truncated && "cursor-help underline decoration-dotted",+ )}+ >+ {counter}+ </span>+ <Button+ variant="ghost"+ size="icon"+ className={FIND_BUTTON_CLASS}+ disabled={!canStep}+ onMouseDown={keepFocusInField}+ onClick={() => stepWhenSettled(-1)}+ aria-label={t("shell.find.previous")}+ title={t("shell.find.previous")}+ >+ <ArrowUpIcon strokeWidth={1.75} className="size-[18px]" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ className={FIND_BUTTON_CLASS}+ disabled={!canStep}+ onMouseDown={keepFocusInField}+ onClick={() => stepWhenSettled(1)}+ aria-label={t("shell.find.next")}+ title={t("shell.find.next")}+ >+ <ArrowDownIcon strokeWidth={1.75} className="size-[18px]" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ className={FIND_BUTTON_CLASS}+ onClick={close}+ aria-label={t("shell.find.close")}+ title={t("shell.find.close")}+ >+ <HugeiconsIcon icon={Cancel01Icon} className="size-[18px]" />+ </Button>+ </div>+ );+}diff --git a/studio/frontend/src/features/find-in-page/components/find-in-page.tsx b/studio/frontend/src/features/find-in-page/components/find-in-page.tsxindex 315d29f866c..b25771a0532 100644--- a/studio/frontend/src/features/find-in-page/components/find-in-page.tsx+++ b/studio/frontend/src/features/find-in-page/components/find-in-page.tsx@@ -1,177 +1,92 @@// 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 { Button } from "@/components/ui/button";+import {+ LazyImportBoundary,+ LazyImportFailure,+} from "@/components/lazy-import-boundary";++import { useT } from "@/i18n";+import {isImeComposing,isSurfaceBackgrounded,useShortcut,} from "@/features/settings";-import { useT } from "@/i18n";-import { cn } from "@/lib/utils";-import { Cancel01Icon } from "@hugeicons/core-free-icons";-import { HugeiconsIcon } from "@hugeicons/react";-// lucide for the two arrows, which is where #10129 moved every directional arrow in the app: the-// hugeicons shaft is a bezier that bows out rather than meeting at a point, and after that change-// there is no other use of the pair left to match.-import { ArrowDownIcon, ArrowUpIcon } from "lucide-react";-import { useEffect, useRef, useState } from "react";-import { useFindInPage } from "../hooks/use-find-in-page.ts";import {- resolveDismissiblePortalSurfaces,- resolveFindScope,-} from "../lib/find-dom.ts";-import { FIND_SCOPE_ATTRIBUTE } from "../lib/find-text-index.ts";-import { useFindInPageStore } from "../stores/find-in-page-store.ts";+ type ReactNode,+ Suspense,+ lazy,+ useCallback,+ useEffect,+ useLayoutEffect,+ useRef,+ useState,+} from "react";+import { FIND_SCOPE_ATTRIBUTE } from "../lib/find-attributes.ts";-/**- * The find bar, and the chord that raises it.- *- * Split in two: this component is always mounted and holds nothing but the shortcut, while- * `FindBar` owns the index, the observer and the highlights and exists only while the bar is open.- * A Studio nobody is searching runs one keydown listener and no engine.- */-export function FindInPage({ enabled = true }: { enabled?: boolean }) {- const open = useFindInPageStore((state) => state.open);- const requestFocus = useFindInPageStore((state) => state.requestFocus);- const reset = useFindInPageStore((state) => state.reset);-- // Leaving the shell for good, which on the web means signing out: the store is module-global and- // keeps the query across a close, so without this the next person to sign in in the same tab is- // handed the last one's search. Unmount, not `enabled`, which a dialog also turns off.- useEffect(() => reset, [reset]);+const DISMISSIBLE_SURFACE_SELECTOR =+ '[data-slot="popover-content"], [role="menu"], [role="listbox"]';- // Not `skipInTextFields`: the chord has to work from the composer, and pressing it inside the- // find field is how a find bar is asked to start over.- useShortcut("findInPage", requestFocus, {- enabled,- // Every modal, not just Settings: Radix marks the shell `aria-hidden`/`inert` while one is up,- // so a bar behind it is unreachable. As `claims`, not a return from the handler, which runs- // after the event is prevented: declining there would leave the chord dead and native find- // suppressed.- claims: () => !isSurfaceBackgrounded(`[${FIND_SCOPE_ATTRIBUTE}]`),- });-- if (!enabled || !open) return null;- return <FindBar />;-}--/**- * Keep the caret in the field when a walk button is clicked. Without this, one click on the down- * arrow and Enter stops working, because the field no longer has the key.- */-function keepFocusInField(event: { preventDefault: () => void }): void {- event.preventDefault();-}--/**- * Show the start of the query again once the field loses focus. A query longer than the field- * scrolls as it is typed, which is right while typing and wrong once the caret is gone: what is- * left is the tail of a word. The caret goes home too, so the scroll does not spring back.- */-function rewindToStart(event: { currentTarget: HTMLInputElement }): void {- const input = event.currentTarget;- input.setSelectionRange(0, 0);- input.scrollLeft = 0;+function hasOpenDismissibleSurface(): boolean {+ const scope = document.querySelector(`[${FIND_SCOPE_ATTRIBUTE}]`);+ return [...document.querySelectorAll(DISMISSIBLE_SURFACE_SELECTOR)].some(+ (surface) =>+ scope?.contains(surface) !== true &&+ surface.getAttribute("data-state") !== "closed",+ );}-/**- * The walk and close buttons. The ghost variant's `--muted/50` hover resolves to within a shade of- * this bar's background, so in dark mode nothing visibly happens; a plain wash reads on either- * surface. Same one the outline variant uses.- */-const FIND_BUTTON_CLASS = "size-8 hover:bg-black/[0.06] dark:hover:bg-white/10";--/** Coalesce a typing burst before the DOM search/highlight work runs. */-export const FIND_QUERY_SETTLE_MS = 100;+const FindBar = lazy(() => import("./find-bar-loader.tsx"));-function useSettledQuery(query: string): [string, () => void] {- const [settled, setSettled] = useState(query);- useEffect(() => {- if (query.length === 0) {- setSettled("");- return;- }- const timer = setTimeout(() => setSettled(query), FIND_QUERY_SETTLE_MS);- return () => clearTimeout(timer);- }, [query]);- return [settled, () => setSettled(query)];+function FindBarAfterComposition({+ handoffBlock,+ children,+}: {+ handoffBlock: Promise<void> | null;+ children: ReactNode;+}) {+ if (handoffBlock) {+ throw handoffBlock;+ }+ return children;}-function FindBar() {+function FindBarLoading({+ query,+ setQuery,+ close,+ focusToken,+ rememberSelection,+ queueStep,+ beginComposition,+ endComposition,+}: {+ query: string;+ setQuery: (query: string) => void;+ close: () => void;+ focusToken: number;+ rememberSelection: (input: HTMLInputElement) => void;+ queueStep: (delta: -1 | 1) => void;+ beginComposition: () => void;+ endComposition: () => void;+}) {const t = useT();- const query = useFindInPageStore((state) => state.query);- const setQuery = useFindInPageStore((state) => state.setQuery);- const close = useFindInPageStore((state) => state.close);- const focusToken = useFindInPageStore((state) => state.focusToken);- const [settledQuery, settleQuery] = useSettledQuery(query);- const queryPending = query !== settledQuery;- const { count, active, capped, truncated, next, previous } = useFindInPage(- settledQuery,- queryPending,- );const inputRef = useRef<HTMLInputElement>(null);- const queuedStepRef = useRef(0);- const stepWhenSettled = (delta: -1 | 1) => {- if (queryPending) {- queuedStepRef.current = delta;- settleQuery();- return;- }- if (delta < 0) previous();- else next();- };- useEffect(() => {- if (queryPending || queuedStepRef.current === 0) return;- const delta = queuedStepRef.current;- queuedStepRef.current = 0;- if (delta < 0) previous();- else next();- }, [queryPending, next, previous]);- // Hand focus back to whatever had it, usually the composer, so closing a search leaves the reader- // typing. Declared above the focus effect so it reads `activeElement` before the field takes it.- const barRef = useRef<HTMLDivElement>(null);- const originRef = useRef<HTMLElement | null>(null);- useEffect(() => {- const active = document.activeElement as HTMLElement | null;- // First answer only, and never anything in the bar: StrictMode replays this effect, and by the- // second run the field has focus, so the bar would try to hand focus back to its own input.- // The bar's own element, not `data-find-skip`, which the composer carries too.- if (- originRef.current === null &&- active !== null &&- barRef.current?.contains(active) !== true- ) {- originRef.current = active;- }- return () => {- const origin = originRef.current;- if (!origin?.isConnected || typeof origin.focus !== "function") return;- // Only when closing dropped focus on the floor. Anywhere else and the reader moved it.- const focused = document.activeElement;- if (focused !== null && focused !== document.body) return;- origin.focus();- };- }, []);+ // biome-ignore lint/correctness/useExhaustiveDependencies: focus per token.+ useLayoutEffect(() => {+ const input = inputRef.current;+ if (!input) return;+ input.focus();+ input.select();+ return () => rememberSelection(input);+ }, [focusToken, rememberSelection]);- // Escape closes the bar for as long as it is open, wherever focus is.- //- // On the bar it only reached presses that started inside it, so clicking a message to read it- // left the reader with a bar Escape would not close -- and with a tool request waiting, that- // same unprevented Escape carried on to `declineToolRequest` (bare Escape, and- // `isTextEntryFocused` is false on a message body) and denied the call. Closing a find bar must- // not be able to answer a tool request.- //- // Capture on the window, so it runs before the registry's own keydown listener rather than- // racing it, and two things are deliberately left alone: a modal above the bar backgrounds the- // scope and owns Escape, and an open popover, menu or listbox is dismissed by its own Escape- // first. Composition is left to the IME, as before.useEffect(() => {const onEscape = (event: KeyboardEvent) => {if (event.key !== "Escape" || isImeComposing(event)) return;if (isSurfaceBackgrounded(`[${FIND_SCOPE_ATTRIBUTE}]`)) return;- if (resolveDismissiblePortalSurfaces(resolveFindScope()).length > 0)- return;+ if (hasOpenDismissibleSurface()) return;event.preventDefault();event.stopPropagation();close();@@ -180,113 +95,203 @@ function FindBar() {return () => window.removeEventListener("keydown", onEscape, true);}, [close]);- // Every press of the chord, not just the one that opened the bar: pressing it again selects what- // is in the field so the next keystroke replaces the last search.- // biome-ignore lint/correctness/useExhaustiveDependencies: each token requests a fresh focus/select.- useEffect(() => {- const input = inputRef.current;- if (!input) return;- input.focus();- input.select();- }, [focusToken]);-- const searching = query.length > 0;- const empty = !queryPending && searching && count === 0;- // A pending query has no count of its own yet, so the settled one's zero must not disable the- // walk: `stepWhenSettled` queues the press and runs it once the count arrives.- const canStep = searching && (count > 0 || queryPending);- const counter =- searching && !queryPending- ? `${count === 0 ? 0 : active + 1}/${count}${capped ? "+" : ""}`- : "";-return (- // `data-find-skip` keeps the bar out of its own index: without it every keystroke finds itself.<div- ref={barRef}data-find-skip=""- // biome-ignore lint/a11y/useSemanticElements: this landmark contains the field and navigation controls.-+ data-testid="find-in-page-loading"+ // biome-ignore lint/a11y/useSemanticElements: loading shell is a search landmark.role="search"+ aria-busy="true"aria-label={t("shell.find.label")}- // Escape is handled on the window for the lifetime of the bar (see the effect above), which- // covers the walk buttons and the field as well as everything outside it, so there is no- // handler here to also reach the presses that start inside.- className="find-bar-surface fixed top-[calc(var(--studio-content-top-inset,0px)+3.5rem)] right-4 z-50 flex h-13 w-[22.25rem] max-w-[calc(100vw-2rem)] items-center gap-1 rounded-full pr-4 pl-5 sm:w-[28.25rem]"+ className="find-bar-surface fixed top-[calc(var(--studio-content-top-inset,0px)+3.5rem)] right-4 z-50 flex h-13 max-w-[calc(100vw-2rem)] items-center rounded-full px-5"><inputref={inputRef}type="text"value={query}onChange={(event) => setQuery(event.target.value)}+ onCompositionStart={beginComposition}+ onCompositionEnd={endComposition}+ onSelect={(event) => rememberSelection(event.currentTarget)}onKeyDown={(event) => {- if (event.key === "Enter") {- // The Enter committing an IME candidate arrives here too; taken, it walks to the next- // match and throws away the word.- if (isImeComposing(event.nativeEvent)) return;- event.preventDefault();- stepWhenSettled(event.shiftKey ? -1 : 1);- }+ if (event.key !== "Enter" || isImeComposing(event.nativeEvent))+ return;+ event.preventDefault();+ queueStep(event.shiftKey ? -1 : 1);}}- onBlur={rewindToStart}- // The same string the landmark is labelled with: one phrase, one key to translate.placeholder={t("shell.find.label")}aria-label={t("shell.find.label")}spellCheck={false}autoComplete="off"autoCorrect="off"- className={cn(- // Narrow by default so the whole bar clears a small window, wide once there is room.- // `min-w-0` lets the field, rather than the bar, give way if it still does not fit.- // `text-ui-15`, not a raw pixel size, which ignores the UI font size preference.- "min-w-0 flex-1 bg-transparent text-ui-15 outline-none placeholder:text-muted-foreground",- empty && "text-destructive",- )}+ className="w-40 min-w-0 bg-transparent text-ui-15 outline-none placeholder:text-muted-foreground sm:w-64"/>- <span- aria-live="polite"- title={truncated ? t("shell.find.truncated") : undefined}- className={cn(- "min-w-12 shrink-0 pr-3 text-right text-muted-foreground text-sm tabular-nums",- truncated && "cursor-help underline decoration-dotted",- )}- >- {counter}- </span>- <Button- variant="ghost"- size="icon"- className={FIND_BUTTON_CLASS}- disabled={!canStep}- onMouseDown={keepFocusInField}- onClick={() => stepWhenSettled(-1)}- aria-label={t("shell.find.previous")}- title={t("shell.find.previous")}- >- <ArrowUpIcon strokeWidth={1.75} className="size-[18px]" />- </Button>- <Button- variant="ghost"- size="icon"- className={FIND_BUTTON_CLASS}- disabled={!canStep}- onMouseDown={keepFocusInField}- onClick={() => stepWhenSettled(1)}- aria-label={t("shell.find.next")}- title={t("shell.find.next")}- >- <ArrowDownIcon strokeWidth={1.75} className="size-[18px]" />- </Button>- <Button- variant="ghost"- size="icon"- className={FIND_BUTTON_CLASS}- onClick={close}- aria-label={t("shell.find.close")}- title={t("shell.find.close")}- >- <HugeiconsIcon icon={Cancel01Icon} className="size-[18px]" />- </Button></div>);}++/**+ * Lightweight controller; the bar and search engine load only when opened.+ */+export function FindInPage({ enabled = true }: { enabled?: boolean }) {+ const t = useT();+ // Session state belongs to the mounted shell: closing keeps the query, while signing out and+ // unmounting the shell drops it without keeping a module-global user value.+ const [open, setOpen] = useState(false);+ const [query, setQuery] = useState("");+ const [focusToken, setFocusToken] = useState(0);+ const loadingSelectionRef = useRef<{+ start: number;+ end: number;+ direction: "forward" | "backward" | "none";+ } | null>(null);++ const [pendingSteps, setPendingSteps] = useState<+ { query: string; delta: -1 | 1 }[]+ >([]);++ const [handoffBlock, setHandoffBlock] = useState<Promise<void> | null>(null);+ const releaseHandoffRef = useRef<(() => void) | null>(null);++ const releaseHandoffTimerRef = useRef<number | null>(null);+ const beginLoadingComposition = useCallback(() => {+ if (releaseHandoffTimerRef.current !== null) {+ window.clearTimeout(releaseHandoffTimerRef.current);+ releaseHandoffTimerRef.current = null;+ }+ if (releaseHandoffRef.current) {+ return;+ }+ let release: () => void = () => undefined;+ const block = new Promise<void>((resolve) => {+ release = resolve;+ });+ releaseHandoffRef.current = release;+ setHandoffBlock(block);+ }, []);+ const endLoadingComposition = useCallback(() => {+ releaseHandoffTimerRef.current = window.setTimeout(() => {+ releaseHandoffTimerRef.current = null;+ releaseHandoffRef.current?.();+ releaseHandoffRef.current = null;+ setHandoffBlock(null);+ }, 0);+ }, []);+ useEffect(+ () => () => {+ if (releaseHandoffTimerRef.current !== null) {+ window.clearTimeout(releaseHandoffTimerRef.current);+ }+ releaseHandoffRef.current?.();+ releaseHandoffRef.current = null;+ },+ [],+ );+ const originRef = useRef<HTMLElement | null>(null);+ const requestFocus = useCallback(() => {+ const active = document.activeElement;+ if (+ originRef.current === null &&+ active instanceof HTMLElement &&+ active.closest('[role="search"]') === null+ ) {+ originRef.current = active;+ }+ loadingSelectionRef.current = null;++ setPendingSteps([]);+ setOpen(true);+ setFocusToken((token) => token + 1);+ }, []);+ const rememberLoadingSelection = useCallback((input: HTMLInputElement) => {+ loadingSelectionRef.current = {+ start: input.selectionStart ?? input.value.length,+ end: input.selectionEnd ?? input.value.length,+ direction: input.selectionDirection ?? "none",+ };+ }, []);++ const queueLoadingStep = useCallback(+ (delta: -1 | 1) => {+ setPendingSteps((steps) => [...steps, { query, delta }]);+ },+ [query],+ );+ const clearPendingSteps = useCallback(() => setPendingSteps([]), []);+ const restoreLoadingSelection = useCallback((input: HTMLInputElement) => {+ const selection = loadingSelectionRef.current;+ if (!selection) return false;+ const length = input.value.length;+ input.setSelectionRange(+ Math.min(selection.start, length),+ Math.min(selection.end, length),+ selection.direction,+ );+ return true;+ }, []);+ const close = useCallback(() => {+ const origin = originRef.current;+ originRef.current = null;+ setOpen(false);+ requestAnimationFrame(() => {+ const active = document.activeElement;+ if (+ origin?.isConnected &&+ typeof origin.focus === "function" &&+ (active === null || active === document.body)+ ) {+ origin.focus();+ }+ });+ }, []);++ // The chord works from text fields, including the composer and an already-open find input.+ useShortcut("findInPage", requestFocus, {+ enabled,+ // A modal backgrounds the shell and owns the chord while its surface is active.+ claims: () => !isSurfaceBackgrounded(`[${FIND_SCOPE_ATTRIBUTE}]`),+ });++ if (!enabled || !open) return null;+ return (+ <LazyImportBoundary+ fallback={+ <LazyImportFailure+ message={t("settings.dialog.panelFailed")}+ reloadLabel={t("settings.dialog.panelReload")}+ dismissLabel={t("common.close")}+ onDismiss={close}+ testId="find-in-page-load-failure"+ className="fixed top-3 right-3 z-[100] max-w-xs rounded-xl border border-border bg-popover p-4 text-popover-foreground shadow-lg"+ />+ }+ >+ <Suspense+ fallback={+ <FindBarLoading+ query={query}+ setQuery={setQuery}+ close={close}+ focusToken={focusToken}+ rememberSelection={rememberLoadingSelection}+ queueStep={queueLoadingStep}+ beginComposition={beginLoadingComposition}+ endComposition={endLoadingComposition}+ />+ }+ >+ <FindBarAfterComposition handoffBlock={handoffBlock}>+ <FindBar+ query={query}+ setQuery={setQuery}+ close={close}+ focusToken={focusToken}+ restoreSelection={restoreLoadingSelection}+ pendingSteps={pendingSteps}+ clearPendingSteps={clearPendingSteps}+ />+ </FindBarAfterComposition>+ </Suspense>+ </LazyImportBoundary>+ );+}diff --git a/studio/frontend/src/features/find-in-page/index.ts b/studio/frontend/src/features/find-in-page/index.tsindex 9eed763f062..ee7c8371806 100644--- a/studio/frontend/src/features/find-in-page/index.ts+++ b/studio/frontend/src/features/find-in-page/index.ts@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0export { FindInPage } from "./components/find-in-page.tsx";-export { useFindInPageStore } from "./stores/find-in-page-store.ts";export {FIND_SCOPE_ATTRIBUTE,FIND_SKIP_ATTRIBUTE,diff --git a/studio/frontend/src/features/find-in-page/stores/find-in-page-store.ts b/studio/frontend/src/features/find-in-page/stores/find-in-page-store.tsdeleted file mode 100644index df2e6d85bb7..00000000000--- a/studio/frontend/src/features/find-in-page/stores/find-in-page-store.ts+++ /dev/null@@ -1,35 +0,0 @@-// 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 { create } from "zustand";--/**- * Whether the bar is up and what is typed in it. Nothing else: the index, matches and ranges are- * refs inside the bar, which only exists while it is open.- */-interface FindInPageStore {- open: boolean;- query: string;- /**- * Bumped on every press of the chord, so pressing it again re-focuses the field and selects what- * is in it. A counter rather than a boolean: two presses in a row have to be two events.- */- focusToken: number;- requestFocus: () => void;- close: () => void;- setQuery: (query: string) => void;- /** Forget the search entirely, query included. For leaving the shell, not for closing the bar. */- reset: () => void;-}--export const useFindInPageStore = create<FindInPageStore>((set) => ({- open: false,- query: "",- focusToken: 0,- requestFocus: () =>- set((state) => ({ open: true, focusToken: state.focusToken + 1 })),- // The query survives a close, so re-opening offers the last search again, selected.- close: () => set({ open: false }),- setQuery: (query) => set({ query }),- reset: () => set({ open: false, query: "" }),-}));diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.tsindex df3e484b77c..72be54f65cd 100644--- a/studio/frontend/src/features/settings/index.ts+++ b/studio/frontend/src/features/settings/index.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-export { SettingsDialog } from "./settings-dialog";+export { SettingsDialogMount } from "./settings-dialog-mount";export {type DownloadTransportMode,type DownloadTransportSettings,diff --git a/studio/frontend/src/features/settings/settings-dialog-mount.tsx b/studio/frontend/src/features/settings/settings-dialog-mount.tsxnew file mode 100644index 00000000000..399c37c3dde--- /dev/null+++ b/studio/frontend/src/features/settings/settings-dialog-mount.tsx@@ -0,0 +1,132 @@+// 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 {+ LazyImportBoundary,+ LazyImportFailure,+} from "@/components/lazy-import-boundary";+import { useT } from "@/i18n";+import {+ Suspense,+ lazy,+ useEffect,+ useLayoutEffect,+ useRef,+ useState,+} from "react";+import { isImeComposing } from "./hooks/use-shortcut";++import { useMonitorOverlayStore } from "./stores/monitor-overlay-store";+import { useSettingsDialogStore } from "./stores/settings-dialog-store";++const SettingsDialog = lazy(() =>+ import("./settings-dialog").then((module) => ({+ default: module.SettingsDialog,+ })),+);++function restoreSettingsOpener(+ opener: HTMLElement | null,+ openerFallback: HTMLElement | null,+): void {+ requestAnimationFrame(() => {+ const focusTarget = [opener, openerFallback].find(+ (element) =>+ element?.isConnected && !element.closest("[inert], [hidden]"),+ );+ focusTarget?.focus({ preventScroll: true });+ });+}++function SettingsDialogLoading({ active }: { active: boolean }) {+ const t = useT();++ const dialogRef = useRef<HTMLDialogElement>(null);+ const closeDialog = useSettingsDialogStore((state) => state.closeDialog);+ useEffect(() => {+ if (!active) return;+ const cancel = (event: KeyboardEvent) => {+ if (event.key !== "Escape" || isImeComposing(event)) return;+ event.preventDefault();+ event.stopPropagation();+ closeDialog();+ };+ window.addEventListener("keydown", cancel, true);+ return () => window.removeEventListener("keydown", cancel, true);+ }, [active, closeDialog]);+ useLayoutEffect(() => {+ const dialog = dialogRef.current;+ if (!active || !dialog) return;+ dialog.showModal();+ dialog.focus();+ return () => dialog.close();+ }, [active]);++ if (!active) return null;+ return (+ <dialog+ ref={dialogRef}+ tabIndex={-1}+ className="fixed inset-0 z-[100] m-0 grid h-full max-h-none w-full max-w-none place-items-center border-0 bg-black/50 p-4"+ data-testid="settings-dialog-loading"+ aria-label={t("common.loading")}+ onCancel={(event) => {+ event.preventDefault();+ closeDialog();+ }}+ onPointerDown={(event) => {+ if (event.target === event.currentTarget) closeDialog();+ }}+ >+ <div className="rounded-xl border border-border bg-popover px-6 py-4 text-popover-foreground shadow-xl">+ {t("common.loading")}+ </div>+ </dialog>+ );+}++export function SettingsDialogMount({ active }: { active: boolean }) {+ const t = useT();++ const closeDialog = useSettingsDialogStore((state) => state.closeDialog);++ const opener = useSettingsDialogStore((state) => state.opener);+ const openerFallback = useSettingsDialogStore(+ (state) => state.openerFallback,+ );+ const open = useSettingsDialogStore((state) => state.open);+ const monitorOpen = useMonitorOverlayStore((state) => state.isOpen);++ const setMonitorOpen = useMonitorOverlayStore((state) => state.setIsOpen);+ const [mounted, setMounted] = useState(open || monitorOpen);++ useEffect(() => {+ if (open || monitorOpen) setMounted(true);+ }, [open, monitorOpen]);++ if (!active || !mounted) return null;+ return (+ <LazyImportBoundary+ fallback={+ open || monitorOpen ? (+ <LazyImportFailure+ message={t("settings.dialog.panelFailed")}+ reloadLabel={t("settings.dialog.panelReload")}+ dismissLabel={t("common.close")}+ onDismiss={() => {+ closeDialog();+ setMonitorOpen(false);+ restoreSettingsOpener(opener, openerFallback);+ }}+ testId="settings-dialog-load-failure"+ className="fixed top-1/2 left-1/2 z-[100] max-w-sm -translate-x-1/2 -translate-y-1/2 rounded-xl border border-border bg-popover p-5 text-popover-foreground shadow-xl"+ />+ ) : null+ }+ >+ <Suspense fallback={<SettingsDialogLoading active={open} />}>+ <SettingsDialog />+ </Suspense>+ </LazyImportBoundary>+ );+}diff --git a/studio/frontend/tests/credential-persistence.test.ts b/studio/frontend/tests/credential-persistence.test.tsindex 94512cd2e3e..2a35ffa2696 100644--- a/studio/frontend/tests/credential-persistence.test.ts+++ b/studio/frontend/tests/credential-persistence.test.ts@@ -729,7 +729,18 @@ test("credential gate follows authentication session transitions", () => {assert.match(rootSource, /AUTH_SESSION_CLEARED_EVENT, reconcile/);assert.match(rootSource, /AUTH_SESSION_STORED_EVENT, reconcile/);- assert.match(rootSource, /\{!isAuthFlowRoute \? \(/);+ assert.match(+ rootSource,+ /<CredentialBootstrapGate active=\{!isAuthFlowRoute\}>/,+ );+ assert.match(+ rootSource,+ /<SettingsDialogMount active=\{active && ready\} \/>/,+ );+ assert.match(+ rootSource,+ /\{active && !ready \? <RouteFallback \/> : children\}/,+ );assert.match(sessionSource, /const sessionStarted = !localStorage\.getItem\(AUTH_TOKEN_KEY\)/);assert.match(sessionSource, /dispatchEvent\(new Event\(AUTH_SESSION_STORED_EVENT\)\)/);const bootstrapSource = readFileSync(diff --git a/studio/frontend/tests/find-in-page.test.ts b/studio/frontend/tests/find-in-page.test.tsindex c8d4431ca0c..6c32162e51e 100644--- a/studio/frontend/tests/find-in-page.test.ts+++ b/studio/frontend/tests/find-in-page.test.ts@@ -1538,7 +1538,7 @@ test("registered ranges are cleared and repainted before deletion or replacementtest("the bar keeps itself out of the region it searches", async () => {const bar = await readFile(new URL(- "../src/features/find-in-page/components/find-in-page.tsx",+ "../src/features/find-in-page/components/find-bar.tsx",import.meta.url,),"utf8",@@ -1643,7 +1643,7 @@ test("dark mode sits above the cards it floats over", async () => {test("the bar stays out of a backgrounded scope, and off the document origin", async () => {const bar = await readFile(new URL(- "../src/features/find-in-page/components/find-in-page.tsx",+ "../src/features/find-in-page/components/find-bar.tsx",import.meta.url,),"utf8",@@ -1847,7 +1847,7 @@ test("re-indexing while the document changes is a throttle, and says so", asynctest("the bar has no border, and its buttons have a hover that shows", async () => {const bar = await readFile(new URL(- "../src/features/find-in-page/components/find-in-page.tsx",+ "../src/features/find-in-page/components/find-bar.tsx",import.meta.url,),"utf8",@@ -1870,7 +1870,7 @@ test("a long query rewinds to its first character when focus leaves", async () =// nothing about what was searched for.const bar = await readFile(new URL(- "../src/features/find-in-page/components/find-in-page.tsx",+ "../src/features/find-in-page/components/find-bar.tsx",import.meta.url,),"utf8",@@ -2037,7 +2037,7 @@ test("the rows progressive completion adds are re-anchored, not renumbered", asytest("Escape closes the bar from the walk buttons, not just the field", async () => {const bar = await readFile(new URL(- "../src/features/find-in-page/components/find-in-page.tsx",+ "../src/features/find-in-page/components/find-bar.tsx",import.meta.url,),"utf8",@@ -2124,7 +2124,7 @@ test("the chord is left to the browser when the scope is behind a modal", asynctest("the Enter that commits an IME candidate is left alone", async () => {const bar = await readFile(new URL(- "../src/features/find-in-page/components/find-in-page.tsx",+ "../src/features/find-in-page/components/find-bar.tsx",import.meta.url,),"utf8",@@ -2139,7 +2139,7 @@ test("the Enter that commits an IME candidate is left alone", async () => {test("closing the bar hands focus back to where it came from", async () => {const bar = await readFile(new URL(- "../src/features/find-in-page/components/find-in-page.tsx",+ "../src/features/find-in-page/components/find-bar.tsx",import.meta.url,),"utf8",@@ -2236,7 +2236,7 @@ test("every navigation waits for the query to settle, buttons included", async (// will not paint until it settles, so calling `next`/`previous` from a click dropped it silently.const bar = await readFile(new URL(- "../src/features/find-in-page/components/find-in-page.tsx",+ "../src/features/find-in-page/components/find-bar.tsx",import.meta.url,),"utf8",@@ -2256,8 +2256,15 @@ test("every navigation waits for the query to settle, buttons included", async (// The helper queues the step and forces the settle rather than dropping it.assert.match(bar,- /if \(queryPending\) \{\s*queuedStepRef\.current = delta;\s*settleQuery\(\);/,+ /if \(queryPending\) \{\s*queuedStepsRef\.current\.push\(\{ query, delta \}\);[\s\S]*?settleQuery\(\);/,);++ assert.match(bar, /filter\([\s\S]*?\(step\) => step\.query === query/);++ assert.match(bar, /queuedStepsRef\.current = \[\.\.\.pendingSteps\]/);+ assert.match(bar, /for \(const step of steps\)/);++ assert.match(bar, /if \(count > 0\) \{\s*for \(const step of steps\)/);});test("the seam between the workspace and the surfaces in front of it is recorded", () => {@@ -2444,9 +2451,13 @@ test("closing preserves the query while leaving the shell forgets the session",),"utf8",);- assert.match(controller, /useEffect\(\(\) => reset, \[reset\]\);/);+ assert.match(controller, /const \[query, setQuery\] = useState\(""\);/);+ assert.match(+ controller,+ /const close = useCallback\(\(\) => \{[\s\S]*?setOpen\(false\);[\s\S]*?\}, \[\]\);/,+ );assert.equal(controller.includes('setQuery("")'), false);- assert.match(controller, /useFindInPageStore/);+ assert.equal(controller.includes("useFindInPageStore"), false);});test("the capped window follows the reader, not the top of the document", () => {@@ -2623,7 +2634,7 @@ test("the cap flag is what the bar renders, not the count", async () => {assert.match(engine, /anchoredAt = viewportOffset\(index\);/);const bar = await readFile(new URL(- "../src/features/find-in-page/components/find-in-page.tsx",+ "../src/features/find-in-page/components/find-bar.tsx",import.meta.url,),"utf8",@@ -2637,7 +2648,7 @@ test("Escape is left to the IME while it is composing", async () => {// being typed, and the candidate window never sees the key it was aimed at.const bar = await readFile(new URL(- "../src/features/find-in-page/components/find-in-page.tsx",+ "../src/features/find-in-page/components/find-bar.tsx",import.meta.url,),"utf8",@@ -2778,3 +2789,25 @@ test("a container query resizing the scope invalidates the index", async () => {/if \(!measured\) \{\s*\n\s*measured = true;\s*\n\s*return;/,);});++test("nothing of the engine is mounted while the bar is closed", async () => {+ const controller = await readFile(+ new URL(+ "../src/features/find-in-page/components/find-in-page.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(controller, /if \(!enabled \|\| !open\) return null;/);+ assert.match(controller, /lazy\(\(\) => import\("\.\/find-bar-loader\.tsx"\)\)/);+ assert.equal(controller.includes("useFindInPage("), false);++ const loadedBar = await readFile(+ new URL(+ "../src/features/find-in-page/components/find-bar.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.equal((loadedBar.match(/useFindInPage\(/g) ?? []).length, 1);+});diff --git a/studio/frontend/tests/monitor-frame-ownership.test.ts b/studio/frontend/tests/monitor-frame-ownership.test.tsindex 23904b6d681..3127629bea9 100644--- a/studio/frontend/tests/monitor-frame-ownership.test.ts+++ b/studio/frontend/tests/monitor-frame-ownership.test.ts@@ -28,6 +28,21 @@ const PANEL_SOURCE = readFileSync("utf8",);++const ROOT_SOURCE = readFileSync(+ fileURLToPath(new URL("../src/app/routes/__root.tsx", import.meta.url)),+ "utf8",+);+const SETTINGS_MOUNT_SOURCE = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/settings/settings-dialog-mount.tsx",+ import.meta.url,+ ),+ ),+ "utf8",+);+/** The Live monitor where it opens by default: bottom-right, w-64, inset-4. */function corner(height = 300): MonitorFrame {return { left: 1168, top: 884 - height, right: 1424, bottom: 884 };@@ -191,3 +206,41 @@ test("the publish hook drops an unmeasurable box rather than publishing it", ()assert.match(HOOK, /observer\?\.disconnect\(\)/, "and it must unsubscribe");assert.match(HOOK, /clearFrame\(publisher\);\s*\n\s*\};/, "and clear on unmount");});+++// Once Settings has loaded the monitor, an auth-route round trip must not+// forget that lazy-entry latch. The inner dialog still unmounts on /login so+// its open monitor remains dormant there, then resumes after authentication.+test("the lazy Settings mount survives an auth-route round trip", () => {+ assert.match(+ ROOT_SOURCE,+ /<CredentialBootstrapGate active=\{!isAuthFlowRoute\}>/,+ );+ assert.match(+ ROOT_SOURCE,+ /<SettingsDialogMount active=\{active && ready\} \/>/,+ );+ assert.match(+ SETTINGS_MOUNT_SOURCE,+ /if \(!active \|\| !mounted\) return null;/,++ );+ assert.match(+ SETTINGS_MOUNT_SOURCE,+ /const \[mounted, setMounted\] = useState\(open \|\| monitorOpen\)/,+ );++ assert.match(SETTINGS_MOUNT_SOURCE, /dismissLabel=\{t\("common\.close"\)\}/);+ assert.match(SETTINGS_MOUNT_SOURCE, /data-testid="settings-dialog-loading"/);+ assert.match(SETTINGS_MOUNT_SOURCE, /dialog\.showModal\(\)/);+ assert.match(SETTINGS_MOUNT_SOURCE, /tabIndex=\{-1\}/);++ assert.match(SETTINGS_MOUNT_SOURCE, /onCancel=\{\(event\) =>/);+ assert.match(SETTINGS_MOUNT_SOURCE, /event\.target === event\.currentTarget/);+ assert.match(SETTINGS_MOUNT_SOURCE, /restoreSettingsOpener\(opener, openerFallback\)/);++ assert.match(+ SETTINGS_MOUNT_SOURCE,+ /onDismiss=\{\(\) => \{\s*closeDialog\(\);\s*setMonitorOpen\(false\);/,+ );+});diff --git a/studio/frontend/vite.config.ts b/studio/frontend/vite.config.tsindex c99ae849ac8..ccd22278d28 100644--- a/studio/frontend/vite.config.ts+++ b/studio/frontend/vite.config.ts@@ -4,11 +4,29 @@import path from "node:path";import tailwindcss from "@tailwindcss/vite";import react from "@vitejs/plugin-react";-import { defineConfig } from "vite";+import { type Plugin, defineConfig } from "vite";++function smokeModuleDelay(): Plugin {+ const match = process.env.SMOKE_MODULE_DELAY_MATCH;+ const delayMs = Number(process.env.SMOKE_MODULE_DELAY_MS ?? "0");+ return {+ name: "smoke-module-delay",+ configureServer(server) {+ if (!match || !Number.isFinite(delayMs) || delayMs <= 0) return;+ server.middlewares.use((request, _response, next) => {+ if (!request.url?.includes(match)) {+ next();+ return;+ }+ setTimeout(next, delayMs);+ });+ },+ };+}// https://vite.dev/config/export default defineConfig({- plugins: [react(), tailwindcss()],+ plugins: [react(), tailwindcss(), smokeModuleDelay()],// Keep an unrelated PostCSS config in an ancestor directory from leaking// into Unsloth installs. Tailwind is provided by its dedicated Vite plugin.css: {diff --git a/tests/studio/playwright_find_in_page.py b/tests/studio/playwright_find_in_page.pyindex 2139a6d7608..73145d53f59 100644--- a/tests/studio/playwright_find_in_page.py+++ b/tests/studio/playwright_find_in_page.py@@ -125,9 +125,14 @@ def check_chord(page, engine: str, mode: str, mod: str) -> None:page.locator('[role="search"]').count() == 1,)- # Re-pressing it while the field has focus restarts the search rather than- # handing the chord back to the browser.+ # Re-pressing the chord keeps the search open and returns focus to its field.page.evaluate("() => document.activeElement?.blur()")+ check(+ engine,+ mode,+ "the field can lose focus while the bar stays open",+ state(page).get("focused") is False,+ )page.keyboard.press(f"{mod}+f")page.wait_for_timeout(200)check(@@ -735,7 +740,16 @@ def run_entry_chunk_failure(browser, engine: str) -> None:engine,mode,"the failure offers reload recovery",- failure.get_by_role("button").count() == 1,+ failure.get_by_role("button").count() == 2,+ )++ check(+ engine,+ mode,+ "the failure recovery receives keyboard focus",+ failure.get_by_role("button", name = "Reload").evaluate(+ "button => button === document.activeElement",+ ),)check(engine,@@ -750,9 +764,18 @@ def run_entry_chunk_failure(browser, engine: str) -> None:"the failed bar does not leave a search landmark",page.locator('[role="search"]').count() == 0,)+if ENTRY_SCREENSHOT:Path(ENTRY_SCREENSHOT.format(engine = engine)).parent.mkdir(parents = True, exist_ok = True)page.screenshot(path = ENTRY_SCREENSHOT.format(engine = engine), full_page = False)++ failure.get_by_role("button", name = "Close").click()+ check(+ engine,+ mode,+ "the failed bar can be dismissed without reloading",+ failure.count() == 0,+ )context.close()@@ -782,6 +805,8 @@ def run_entry_chunk_delay(browser, engine: str) -> None:})""")composer_value = composer.input_value()++ field.press("Enter")loading.wait_for(state = "detached",timeout = max(15000, ENTRY_DELAY_MS + 10000),@@ -828,12 +853,137 @@ def run_entry_chunk_delay(browser, engine: str) -> None:check(engine,mode,- "Enter queued by the loading shell advances after handoff",- "2/28" in page.locator('[role="search"]').inner_text(),+ "every Enter queued by the loading shell advances after handoff",+ "3/28" in page.locator('[role="search"]').inner_text(),+ page.locator('[role="search"]').inner_text(),+ )+ loaded.fill("studio")+ loaded.evaluate(+ """input => {+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));+ input.dispatchEvent(new KeyboardEvent('keydown', {+ key: 'f',+ code: 'KeyF',+ ctrlKey: true,+ bubbles: true,+ }));+ }""",+ )+ page.wait_for_timeout(500)+ check(+ engine,+ mode,+ "a repeated find chord clears pending navigation",+ "1/8" in page.locator('[role="search"]').inner_text(),+ page.locator('[role="search"]').inner_text(),+ )++ context.close()++ context = browser.new_context(user_agent = PLATFORMS["Linux"][1])+ page = new_page(context)+ page.locator('textarea[placeholder="Message"]').focus()+ page.keyboard.press("Control+f")+ loading = page.get_by_test_id("find-in-page-loading")+ loading.wait_for(state = "visible", timeout = 5000)+ field = loading.locator("input")+ field.fill("definitely-no-such-match")+ field.press("Enter")+ loading.wait_for(+ state = "detached",+ timeout = max(15000, ENTRY_DELAY_MS + 10000),+ )+ page.evaluate(+ "() => window.__findSmoke.stream("+ "'definitely-no-such-match definitely-no-such-match', 1)",+ )+ page.wait_for_timeout(1600)+ check(+ engine,+ mode,+ "a zero-result search consumes queued navigation",+ "1/2" in page.locator('[role="search"]').inner_text(),+ page.locator('[role="search"]').inner_text(),+ )+ loaded = page.locator('[role="search"] input')+ loaded.fill("unsloth")+ page.wait_for_timeout(500)+ check(+ engine,+ mode,+ "a queued step for an empty result does not advance a later query",+ "1/28" in page.locator('[role="search"]').inner_text(),page.locator('[role="search"]').inner_text(),)context.close()+ context = browser.new_context(user_agent = PLATFORMS["Linux"][1])+ page = new_page(context)+ page.locator('textarea[placeholder="Message"]').focus()+ page.keyboard.press("Control+f")+ loading = page.get_by_test_id("find-in-page-loading")+ loading.wait_for(state = "visible", timeout = 5000)+ field = loading.locator("input")+ field.fill("definitely-no-such-match")+ field.press("Enter")+ field.fill("unsloth")+ loading.wait_for(+ state = "detached",+ timeout = max(15000, ENTRY_DELAY_MS + 10000),+ )+ page.wait_for_timeout(500)+ check(+ engine,+ mode,+ "a loading-shell step does not advance a query typed after it",+ "1/28" in page.locator('[role="search"]').inner_text(),+ page.locator('[role="search"]').inner_text(),+ )+ context.close()++ context = browser.new_context(user_agent = PLATFORMS["Linux"][1])+ page = new_page(context)+ page.locator('textarea[placeholder="Message"]').focus()+ page.keyboard.press("Control+f")+ loading = page.get_by_test_id("find-in-page-loading")+ loading.wait_for(state = "visible", timeout = 5000)+ field = loading.locator("input")+ field.dispatch_event("compositionstart", {"data": "u"})+ page.wait_for_timeout(ENTRY_DELAY_MS + 500)+ check(+ engine,+ mode,+ "an active IME composition keeps the loading input mounted",+ loading.count() == 1 and field.evaluate("input => input.isConnected"),+ )+ field.evaluate(+ """input => {+ input.dispatchEvent(new CompositionEvent('compositionend', { data: '語', bubbles: true }));+ const setValue = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ 'value',+ ).set;+ setValue.call(input, '語');+ input.dispatchEvent(new InputEvent('input', {+ data: '語',+ inputType: 'insertCompositionText',+ bubbles: true,+ }));+ }""",+ )+ loading.wait_for(+ state = "detached",+ timeout = max(15000, ENTRY_DELAY_MS + 10000),+ )+ check(+ engine,+ mode,+ "the loaded bar takes over after composition ends",+ page.locator('[role="search"] input').count() == 1+ and page.locator('[role="search"] input').input_value() == "語",+ )+ context.close()+context = browser.new_context(user_agent = PLATFORMS["Linux"][1])page = new_page(context)page.locator('textarea[placeholder="Message"]').focus()diff --git a/tests/studio/test_auth_form_input_count.py b/tests/studio/test_auth_form_input_count.pyindex cf7ef351e74..cc5ddbdb7ed 100644--- a/tests/studio/test_auth_form_input_count.py+++ b/tests/studio/test_auth_form_input_count.py@@ -170,7 +170,10 @@ def test_login_jsx_declares_exactly_one_password_input():def test_auth_flow_routes_do_not_mount_global_settings():root = (FRONTEND / "app/routes/__root.tsx").read_text(encoding = "utf-8")- assert "{!isAuthFlowRoute && <SettingsDialog />}" in root+ mount = (FRONTEND / "features/settings/settings-dialog-mount.tsx").read_text(encoding = "utf-8")+ assert "<SettingsDialogMount active={active && ready} />" in root+ assert "<CredentialBootstrapGate active={!isAuthFlowRoute}>" in root+ assert "if (!active || !mounted) return null;" in mountassert "useSettingsDialogStore.getState().closeDialog();" in root# The settings chord must stay inert on the auth routes. That used to be an# early return inside a hand-rolled keydown handler; once the chords becamediff --git a/tests/studio/test_remote_connection_models_contract.py b/tests/studio/test_remote_connection_models_contract.pyindex f19e7133b7d..a03c85e0a2a 100644--- a/tests/studio/test_remote_connection_models_contract.py+++ b/tests/studio/test_remote_connection_models_contract.py@@ -99,7 +99,7 @@ def test_connections_are_hydrated_on_startup():), "nothing calls the credential bootstrap, so no page hydrates connections"# The call lives inside CredentialBootstrapGate, so the gate has to be# rendered too: dropping it stops hydration while the call still exists.- assert "<CredentialBootstrapGate>" in root+ assert "<CredentialBootstrapGate active={!isAuthFlowRoute}>" in root# The chat page still hydrates its own persisted settings.assert "hydratePersistedSettings()" in CHAT_PAGE.read_text(encoding = "utf-8")