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.

Studio: answer shortcut availability checks from registered surfaces, not the whole document (#17005)

Daniel Han9545522f01b6
diff --git a/studio/frontend/smoke-find-in-page-main.tsx b/studio/frontend/smoke-find-in-page-main.tsx
index 24c5d7fbd3a..64e4a6f7b8b 100644
--- a/studio/frontend/smoke-find-in-page-main.tsx
+++ b/studio/frontend/smoke-find-in-page-main.tsx
@@ -19,6 +19,12 @@ import {
import "@/index.css";
import { StrictMode, useCallback, useEffect, useRef, useState } from "react";
import { createRoot } from "react-dom/client";
+import {
+ COMPOSER_SURFACE,
+ FIND_SCOPE_SURFACE,
+ trustSurfaceRegistry,
+ useSurfaceRef,
+} from "@/lib/surface-registry";
declare global {
interface Window {
@@ -158,6 +164,8 @@ function Harness() {
const [outerScroll, setOuterScroll] = useState(false);
const scrollerRef = useRef<HTMLDivElement>(null);
const scopeRef = useRef<HTMLDivElement>(null);
+ const scopeSurfaceRef = useSurfaceRef(FIND_SCOPE_SURFACE, scopeRef);
+ const composerRef = useSurfaceRef<HTMLTextAreaElement>(COMPOSER_SURFACE);
const stream = useCallback((text: string, msPerChar = 12) => {
setStreamed((rows) => [...rows, ""]);
@@ -250,7 +258,7 @@ function Harness() {
}
>
<div
- ref={scopeRef}
+ ref={scopeSurfaceRef}
{...{ [FIND_SCOPE_ATTRIBUTE]: "" }}
aria-hidden={modal || undefined}
className={
@@ -277,6 +285,7 @@ function Harness() {
className="shrink-0 border-border border-t p-2"
>
<textarea
+ ref={composerRef}
className="aui-composer-input w-full resize-none bg-transparent text-sm outline-none"
placeholder="Message"
rows={2}
@@ -298,7 +307,10 @@ function Harness() {
}
// StrictMode as in main.tsx: effects mount, unmount and remount in development.
-createRoot(document.getElementById("root") as HTMLElement).render(
+const rootElement = document.getElementById("root") as HTMLElement;
+// As main.tsx: the checks read registered surfaces, so the smoke covers the path the app takes.
+trustSurfaceRegistry(rootElement);
+createRoot(rootElement).render(
<StrictMode>
<Harness />
</StrictMode>,
diff --git a/studio/frontend/smoke-shortcuts-main.tsx b/studio/frontend/smoke-shortcuts-main.tsx
index 52441d850c1..42ec30838c8 100644
--- a/studio/frontend/smoke-shortcuts-main.tsx
+++ b/studio/frontend/smoke-shortcuts-main.tsx
@@ -14,6 +14,7 @@ import * as shortcutStore from "@/features/settings/stores/keyboard-shortcuts-st
/* eslint-enable no-restricted-imports */
import { useState } from "react";
import { createRoot } from "react-dom/client";
+import { trustSurfaceRegistry, useSurfaceRef } from "@/lib/surface-registry";
const SELECTION_ACTION_GRACE_MS = 750;
@@ -95,6 +96,7 @@ function GenericRow({ id }: { id: registry.ShortcutId }) {
}
function Harness() {
+ const composerRef = useSurfaceRef<HTMLTextAreaElement>(COMPOSER_INPUT_SELECTOR);
const [selectionCount, setSelectionCount] = useState(0);
const [toolPending, setToolPending] = useState(true);
@@ -175,6 +177,7 @@ function Harness() {
</a>
<input id="smoke-input" aria-label="plain field" />
<textarea
+ ref={composerRef}
id="smoke-composer"
aria-label="composer"
className="aui-composer-input"
@@ -212,4 +215,7 @@ window.__shortcutsSmoke = {
},
};
-createRoot(document.getElementById("root") as HTMLElement).render(<Harness />);
+// As main.tsx: the checks read registered surfaces, so the smoke covers the path the app takes.
+const rootElement = document.getElementById("root") as HTMLElement;
+trustSurfaceRegistry(rootElement);
+createRoot(rootElement).render(<Harness />);
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsx
index 2929642e38a..df6c6c8fc7b 100644
--- a/studio/frontend/src/app/provider.tsx
+++ b/studio/frontend/src/app/provider.tsx
@@ -86,6 +86,7 @@ import {
useRef,
useState,
} from "react";
+import { MODAL_SURFACE, useSurfaceRef } from "@/lib/surface-registry";
import {
type LogicalWindowSize,
PREFERRED_SETUP_WINDOW_SIZE,
@@ -695,6 +696,7 @@ function DesktopChromeVarsEffect({
function TauriWrapper({ children }: { children: ReactNode }) {
const pathname = useRouterState({ select: (s) => s.location.pathname });
+ const blockingScreenRef = useSurfaceRef<HTMLDivElement>(MODAL_SURFACE);
const {
status,
logs,
@@ -1007,6 +1009,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {
)}
{!showApp && (
<div
+ ref={blockingScreenRef}
data-blocking-screen=""
className="fixed inset-0 z-40 bg-background"
>
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index 3c917ba8055..153d53fcecf 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -99,6 +99,7 @@ import {
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";
@@ -405,6 +406,7 @@ 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 =
@@ -747,6 +749,7 @@ function RootLayout() {
>
<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}`}
>
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index c55ebbb23a4..30db94b2cd0 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -97,6 +97,7 @@ import {
type AudioWorkflowId,
} from "@/features/audio/workflows";
/* eslint-enable no-restricted-imports */
+import { SIDEBAR_SURFACE } from "@/lib/surface-registry";
import { cn } from "@/lib/utils";
import { createNavigationNonce } from "@/lib/navigation-nonce";
import { copyToClipboardFrom } from "@/lib/copy-to-clipboard";
@@ -274,6 +275,7 @@ import { useSettingsDialogStore } from "@/features/settings/stores/settings-dial
import { useVoiceSettingsStore } from "@/features/settings/stores/voice-settings-store";
import {
isSurfaceBackgrounded,
+ surfaceElements,
useShortcutLabel,
useShortcut,
} from "@/features/settings/hooks/use-shortcut";
@@ -778,7 +780,7 @@ const WORKFLOW_UNAVAILABLE = "The loaded model cannot do this";
// a spinner, so it is re-read sooner than the background MLX self-heal check. A re-read outstanding
// longer than the stall window is given up on rather than latching the poll off.
const SELECTION_ACTION_GRACE_MS = 750;
-const SIDEBAR_SELECTOR = '[data-slot="sidebar"]';
+const SIDEBAR_SELECTOR = SIDEBAR_SURFACE;
const VERDICT_UNKNOWN_POLL_MS = 3000;
const SELF_HEAL_POLL_MS = 15000;
const VERDICT_POLL_STALL_MS = 30000;
@@ -4124,7 +4126,7 @@ export function AppSidebar() {
// open drawer is itself a dialog hiding the root, and the sidebar in it is the foreground.
return (
typeof document !== "undefined" &&
- document.querySelector(SIDEBAR_SELECTOR) === null &&
+ surfaceElements(SIDEBAR_SELECTOR).length === 0 &&
isSurfaceBackgrounded("#root")
);
};
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 7202c6307dc..d760982d4de 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -433,6 +433,7 @@ import {
} from "@/lib/action-bar-icons";
import { ForkIcon } from "@/lib/fork-icon";
import { markComposerScrollable, markComposerScrollEdges } from "@/lib/composer-scroll-fade";
+import { useSurfaceRef } from "@/lib/surface-registry";
import { cn } from "@/lib/utils";
import {
ActionBarMorePrimitive,
@@ -3245,6 +3246,7 @@ const Composer: FC<{
: null;
// Expand only once the input wraps, latched so it cannot flip-flop at the wrap boundary.
const inputRef = useRef<HTMLTextAreaElement>(null);
+ const composerSurfaceRef = useSurfaceRef(COMPOSER_INPUT_SELECTOR, inputRef);
const editorRef = useRef<HTMLDivElement>(null);
const inputId = useId();
const uiSpaceScale = useUiSpaceScale();
@@ -5819,7 +5821,7 @@ const Composer: FC<{
placeholder={
overlay ? "Type your edits for your image" : "Ask anything"
}
- ref={inputRef}
+ ref={composerSurfaceRef}
data-type-to-activate="composer"
className="aui-composer-input unsloth-composer-input"
minRows={1}
diff --git a/studio/frontend/src/components/tauri/startup-screen.tsx b/studio/frontend/src/components/tauri/startup-screen.tsx
index f8d2565ea18..9d798424f8c 100644
--- a/studio/frontend/src/components/tauri/startup-screen.tsx
+++ b/studio/frontend/src/components/tauri/startup-screen.tsx
@@ -25,6 +25,7 @@ import {
import { AnimatePresence, motion } from "motion/react";
import { type ReactNode, useEffect, useRef, useState } from "react";
+import { MODAL_SURFACE, useSurfaceRef } from "@/lib/surface-registry";
interface StartupScreenProps {
status: BackendStatus;
@@ -624,10 +625,12 @@ function StartupSurface({ children }: { children: ReactNode }) {
*/
export function ClosingScreen() {
useDocumentFlag("data-blocking-screen-open", true);
+ const blockingScreenRef = useSurfaceRef<HTMLDivElement>(MODAL_SURFACE);
return (
// pointer-events-auto: Radix parks pointer-events:none on <body> while a modal is open, which
// would make this overlay click-through onto the hidden dialog.
<div
+ ref={blockingScreenRef}
data-blocking-screen=""
className="pointer-events-auto modal-pe-live fixed inset-0 z-[9999]"
>
diff --git a/studio/frontend/src/components/ui/alert-dialog.tsx b/studio/frontend/src/components/ui/alert-dialog.tsx
index 7e32a3eef60..f74d16c352a 100644
--- a/studio/frontend/src/components/ui/alert-dialog.tsx
+++ b/studio/frontend/src/components/ui/alert-dialog.tsx
@@ -11,6 +11,7 @@ import {
DropdownGlowContext,
dialogDropdownGlow,
} from "@/components/ui/dropdown-glow";
+import { MODAL_SURFACE, useSurfaceRef } from "@/lib/surface-registry";
import { cn } from "@/lib/utils";
function AlertDialog({
@@ -39,10 +40,13 @@ function AlertDialogPortal({
function AlertDialogOverlay({
className,
+ ref,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
+ const surfaceRef = useSurfaceRef(MODAL_SURFACE, ref);
return (
<AlertDialogPrimitive.Overlay
+ ref={surfaceRef}
data-slot="alert-dialog-overlay"
data-viewport-backdrop={true}
className={cn(
@@ -60,6 +64,7 @@ function AlertDialogContent({
size = "default",
overlayClassName,
onOverlayClick,
+ ref,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content> & {
size?: "default" | "sm";
@@ -67,10 +72,12 @@ function AlertDialogContent({
onOverlayClick?: () => void;
}) {
const glow = dialogDropdownGlow(className, useContext(DropdownGlowContext));
+ const surfaceRef = useSurfaceRef(MODAL_SURFACE, ref);
return (
<AlertDialogPortal>
<AlertDialogOverlay className={overlayClassName} onClick={onOverlayClick} />
<AlertDialogPrimitive.Content
+ ref={surfaceRef}
data-slot="alert-dialog-content"
data-size={size}
className={cn(
diff --git a/studio/frontend/src/components/ui/dialog.tsx b/studio/frontend/src/components/ui/dialog.tsx
index e72960d73d6..d8bf58a20c0 100644
--- a/studio/frontend/src/components/ui/dialog.tsx
+++ b/studio/frontend/src/components/ui/dialog.tsx
@@ -14,6 +14,7 @@ import {
DropdownGlowContext,
dialogDropdownGlow,
} from "@/components/ui/dropdown-glow";
+import { MODAL_SURFACE, useSurfaceRef } from "@/lib/surface-registry";
import { cn } from "@/lib/utils";
import { Cancel01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -55,12 +56,15 @@ function DialogClose({
function DialogOverlay({
className,
position = "fixed",
+ ref,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay> & {
position?: "fixed" | "absolute";
}) {
+ const surfaceRef = useSurfaceRef(MODAL_SURFACE, ref);
return (
<DialogPrimitive.Overlay
+ ref={surfaceRef}
data-slot="dialog-overlay"
data-viewport-backdrop={position === "fixed" ? true : undefined}
className={cn(
@@ -83,6 +87,7 @@ function DialogContent({
overlayPosition,
overlayTone,
onInteractOutside,
+ ref,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean;
@@ -94,6 +99,7 @@ function DialogContent({
overlayTone?: "strong" | "dense";
}) {
const resolvedContainer = container ?? null;
+ const surfaceRef = useSurfaceRef(MODAL_SURFACE, ref);
const inheritedGlow = useContext(DropdownGlowContext);
const glow =
resolvedContainer === null
@@ -108,6 +114,7 @@ function DialogContent({
data-viewport-backdrop-tone={overlayTone}
/>
<DialogPrimitive.Content
+ ref={surfaceRef}
data-slot="dialog-content"
className={cn(
// max-h + scroll keeps tall dialogs reachable on short viewports; a call site
diff --git a/studio/frontend/src/components/ui/sheet.tsx b/studio/frontend/src/components/ui/sheet.tsx
index 230847d64ea..c626048826a 100644
--- a/studio/frontend/src/components/ui/sheet.tsx
+++ b/studio/frontend/src/components/ui/sheet.tsx
@@ -8,6 +8,7 @@ import { useState } from "react";
import { Button } from "@/components/ui/button";
import { DialogPortalContainerContext } from "@/components/ui/dialog";
+import { MODAL_SURFACE, useMergedRefs, useSurfaceRef } from "@/lib/surface-registry";
import { cn } from "@/lib/utils";
import { Cancel01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -59,12 +60,15 @@ function SheetPortal({
function SheetOverlay({
className,
position = "fixed",
+ ref,
...props
}: React.ComponentProps<typeof SheetPrimitive.Overlay> & {
position?: "fixed" | "absolute";
}) {
+ const surfaceRef = useSurfaceRef(MODAL_SURFACE, ref);
return (
<SheetPrimitive.Overlay
+ ref={surfaceRef}
data-slot="sheet-overlay"
data-viewport-backdrop={position === "fixed" ? true : undefined}
className={cn(
@@ -87,6 +91,7 @@ function SheetContent({
overlayClassName,
overlayPosition,
onInteractOutside,
+ ref,
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left";
@@ -97,6 +102,8 @@ function SheetContent({
overlayPosition?: "fixed" | "absolute";
}) {
const [contentEl, setContentEl] = useState<HTMLDivElement | null>(null);
+ // A caller's ref (the mobile sidebar registers through one) reaches the element too.
+ const contentRef = useMergedRefs(setContentEl, ref);
return (
<SheetPortal container={container ?? undefined}>
<SheetOverlay
@@ -104,7 +111,7 @@ function SheetContent({
position={overlayPosition ?? position}
/>
<SheetPrimitive.Content
- ref={setContentEl}
+ ref={contentRef}
data-slot="sheet-content"
data-side={side}
className={cn(
diff --git a/studio/frontend/src/components/ui/sidebar.tsx b/studio/frontend/src/components/ui/sidebar.tsx
index da94a716bc6..2d45ad69293 100644
--- a/studio/frontend/src/components/ui/sidebar.tsx
+++ b/studio/frontend/src/components/ui/sidebar.tsx
@@ -8,6 +8,12 @@ import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "radix-ui"
import { cn } from "@/lib/utils"
+import {
+ hasTrackedSurface,
+ MODAL_SURFACE,
+ SIDEBAR_SURFACE,
+ useSurfaceRef,
+} from "@/lib/surface-registry"
// Deep import: the feature barrel pulls in SettingsDialog and closes an import cycle.
import { useShortcut } from "@/features/settings/hooks/use-shortcut"
import { Button } from "@/components/ui/button"
@@ -144,7 +150,7 @@ function SidebarProvider({
// Not behind an open dialog (Settings leaves the app un-hidden); the mobile drawer is itself one.
useShortcut("toggleSidebar", toggleSidebar, {
claims: () =>
- (isMobile && openMobile) || document.querySelector(OPEN_DIALOG_SELECTOR) === null,
+ (isMobile && openMobile) || !hasTrackedSurface(MODAL_SURFACE, OPEN_DIALOG_SELECTOR),
})
const pinned = pinnedProp ?? false
@@ -237,6 +243,11 @@ function Sidebar({
const { isMobile, state, openMobile, setOpenMobile, hasPinMode, pinned, peeking, setPeeking } =
useSidebar()
const { width, scale: widthScale } = useSidebarWidth()
+ // Only the "none" sidebar is the element props land on; the others pass them further in.
+ const surfaceRef = useSurfaceRef<HTMLDivElement>(
+ SIDEBAR_SURFACE,
+ collapsible === "none" ? props.ref : undefined,
+ )
// Only a sidebar that collapses to nothing has an edge to be held out from.
const holdsOut = hasPinMode && !pinned && collapseToZero
const heldOut = holdsOut && peeking
@@ -256,6 +267,7 @@ function Sidebar({
className
)}
{...props}
+ ref={surfaceRef}
>
{children}
</div>
@@ -266,6 +278,7 @@ function Sidebar({
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetContent
+ ref={surfaceRef}
dir={dir}
data-sidebar="sidebar"
data-slot="sidebar"
@@ -302,6 +315,7 @@ function Sidebar({
data-variant={variant}
data-side={side}
data-slot="sidebar"
+ ref={surfaceRef}
style={scopedWidthStyle}
// Held out, it is on screen and must answer the pointer again.
aria-hidden={(holdsOut && !heldOut) || undefined}
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index f32a7ba7734..ddfbdf8c122 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -102,6 +102,7 @@ import { chatModelLoaded } from "./lib/chat-model-loaded";
import { hasKnownContextWindow } from "./lib/context-window-known";
import { isDownloadCancelled } from "@/lib/native-files";
import { toast } from "@/lib/toast";
+import { MODAL_SURFACE, useSurfaceRef } from "@/lib/surface-registry";
import { cn } from "@/lib/utils";
import { setInAppLinkHandler } from "@/lib/open-link";
import {
@@ -435,6 +436,7 @@ const BrowserOverlaidContext = createContext(false);
function BrowserOverlay(): ReactElement {
const t = useT();
const dialogRef = useRef<HTMLDivElement>(null);
+ const modalRef = useSurfaceRef(MODAL_SURFACE, dialogRef);
useDocumentFlag("data-browser-overlay-open", true);
useEffect(() => {
const previous = document.activeElement;
@@ -482,7 +484,7 @@ function BrowserOverlay(): ReactElement {
}}
>
<div
- ref={dialogRef}
+ ref={modalRef}
role="dialog"
aria-modal={true}
aria-label={t("browser.title")}
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index 914925410fc..382ee3b9011 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -39,6 +39,7 @@ import { MicIcon } from "@/lib/mic-icon";
import { MenuTickIcon, Tick02Icon } from "@/lib/tick-icon";
import { BrowserAgentMenuItem, BrowserAgentPill } from "@/features/browser/agent/lazy-composer-toggle";
import { markComposerScrollEdges } from "@/lib/composer-scroll-fade";
+import { useSurfaceRef } from "@/lib/surface-registry";
import { cn } from "@/lib/utils";
import {
DropdownMenu,
@@ -777,6 +778,7 @@ export function SharedComposer({
);
const sendRef = useRef<(() => void) | null>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
+ const composerSurfaceRef = useSurfaceRef(COMPOSER_INPUT_SELECTOR, textareaRef);
const pendingFixPrompt = useChatArtifactsStore(
(state) => state.pendingFixPrompt,
);
@@ -3080,7 +3082,7 @@ export function SharedComposer({
<textarea
{...skillMentions.inputProps}
id={inputId}
- ref={textareaRef}
+ ref={composerSurfaceRef}
data-type-to-activate="composer"
value={text}
onChange={(e) => {
diff --git a/studio/frontend/src/features/find-in-page/lib/find-backgrounded.ts b/studio/frontend/src/features/find-in-page/lib/find-backgrounded.ts
index 25861c824b7..fd23bbabb10 100644
--- a/studio/frontend/src/features/find-in-page/lib/find-backgrounded.ts
+++ b/studio/frontend/src/features/find-in-page/lib/find-backgrounded.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { isSurfaceBackgrounded } from "@/features/settings/hooks/use-shortcut";
+import { hasTrackedSurface, MODAL_SURFACE } from "@/lib/surface-registry";
import { FIND_SCOPE_ATTRIBUTE } from "./find-attributes.ts";
export const MODAL_BACKDROP_SELECTOR = [
@@ -16,7 +17,7 @@ export const MODAL_BACKDROP_SELECTOR = [
export function isFindScopeBackgrounded(): boolean {
if (typeof document === "undefined") return false;
return (
- document.querySelector(MODAL_BACKDROP_SELECTOR) !== null ||
+ hasTrackedSurface(MODAL_SURFACE, MODAL_BACKDROP_SELECTOR) ||
isSurfaceBackgrounded(`[${FIND_SCOPE_ATTRIBUTE}]`)
);
}
diff --git a/studio/frontend/src/features/settings/hooks/use-shortcut.ts b/studio/frontend/src/features/settings/hooks/use-shortcut.ts
index 04a73722e69..a2febb85e38 100644
--- a/studio/frontend/src/features/settings/hooks/use-shortcut.ts
+++ b/studio/frontend/src/features/settings/hooks/use-shortcut.ts
@@ -2,6 +2,12 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
+import {
+ COMPOSER_SURFACE,
+ FIND_SCOPE_SURFACE,
+ SIDEBAR_SURFACE,
+ trackedSurfaces,
+} from "@/lib/surface-registry";
import { zoomTypedOffZoomKey } from "../../interface-zoom/lib/zoom-chords";
import {
SHORTCUT_SLOTS,
@@ -19,7 +25,23 @@ import {
useKeyboardShortcutsStore,
} from "../stores/keyboard-shortcuts-store";
-export const COMPOSER_INPUT_SELECTOR = ".aui-composer-input";
+export const COMPOSER_INPUT_SELECTOR = COMPOSER_SURFACE;
+
+// Every element these can match registers itself (useSurfaceRef), so a check reads a handful of
+// elements, not the whole document; any other selector is still a document query.
+const TRACKED_SURFACE_SELECTORS: ReadonlySet<string> = new Set([
+ COMPOSER_SURFACE,
+ SIDEBAR_SURFACE,
+ FIND_SCOPE_SURFACE,
+]);
+
+/** What `document.querySelectorAll(selector)` matches, in no particular order. */
+export function surfaceElements(selector: string): Element[] {
+ const tracked = TRACKED_SURFACE_SELECTORS.has(selector)
+ ? trackedSurfaces(selector, selector)
+ : null;
+ return tracked ?? [...document.querySelectorAll(selector)];
+}
export function isTextEntryFocused(exceptFor?: string): boolean {
if (typeof document === "undefined") return false;
@@ -56,7 +78,7 @@ export function isSurfaceInForeground(selector: string): boolean {
if (typeof document === "undefined") return false;
// Every match: Compare keeps an inert base composer mounted; Radix aria-hides the page under a modal.
return answerOncePerPass(`foreground\0${selector}`, () =>
- [...document.querySelectorAll(selector)].some(
+ surfaceElements(selector).some(
(el) => !el.closest('[aria-hidden="true"], [inert]'),
),
);
@@ -67,7 +89,7 @@ export function isSurfaceInForeground(selector: string): boolean {
export function isSurfaceBackgrounded(selector: string): boolean {
if (typeof document === "undefined") return false;
return answerOncePerPass(`backgrounded\0${selector}`, () => {
- const found = [...document.querySelectorAll(selector)];
+ const found = surfaceElements(selector);
return (
found.length > 0 &&
found.every((el) => el.closest('[aria-hidden="true"], [inert]') !== null)
diff --git a/studio/frontend/src/features/tour/components/guided-tour.tsx b/studio/frontend/src/features/tour/components/guided-tour.tsx
index 950f53dee88..75572aea035 100644
--- a/studio/frontend/src/features/tour/components/guided-tour.tsx
+++ b/studio/frontend/src/features/tour/components/guided-tour.tsx
@@ -13,6 +13,7 @@ import {
import { Dialog as DialogPrimitive } from "radix-ui";
import { AnimatePresence, motion } from "motion/react";
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { MODAL_SURFACE, useSurfaceRef } from "@/lib/surface-registry";
import { cssEscape, toRect } from "../lib/dom";
import { fireConfettiFireworks } from "../lib/confetti-fireworks";
import { computeCardPos, padded, pickPlacement } from "../lib/layout";
@@ -41,6 +42,7 @@ export function GuidedTour({
top: 12,
});
const cardRef = useRef<HTMLDivElement>(null);
+ const overlayRef = useSurfaceRef<HTMLDivElement>(MODAL_SURFACE);
const closeLockRef = useRef(false);
const rafRef = useRef<number | null>(null);
const lastRectRef = useRef<Rect | null>(null);
@@ -241,6 +243,7 @@ export function GuidedTour({
<>
<DialogPrimitive.Overlay asChild>
<motion.div
+ ref={overlayRef}
// The shared slot, so modal checks see the tour.
data-slot="dialog-overlay"
data-viewport-backdrop={true}
diff --git a/studio/frontend/src/lib/surface-registry.ts b/studio/frontend/src/lib/surface-registry.ts
new file mode 100644
index 00000000000..0fae25d0213
--- /dev/null
+++ b/studio/frontend/src/lib/surface-registry.ts
@@ -0,0 +1,152 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { type Ref, type RefCallback, useCallback } from "react";
+
+// Shortcut checks read the elements that register here plus whatever is outside the app root
+// (third-party portals), instead of walking a long chat's whole document on every press.
+
+/** Every element that can match MODAL_BACKDROP_SELECTOR or an open dialog's content. */
+export const MODAL_SURFACE = "modal";
+/** Surfaces keyed by the selector their checks ask for. */
+export const COMPOSER_SURFACE = ".aui-composer-input";
+export const SIDEBAR_SURFACE = '[data-slot="sidebar"]';
+export const FIND_SCOPE_SURFACE = "[data-find-scope]";
+
+const surfaces = new Map<string, Map<Element, number>>();
+let appRoot: Element | null = null;
+
+/** Called once by the app entry; without it every check reads the document as before. */
+export function trustSurfaceRegistry(root: Element | null): void {
+ appRoot = root;
+}
+
+/** Refcounted: one element may register twice while a ref hands over. Returns the unregister. */
+export function registerSurface(key: string, element: Element): () => void {
+ let elements = surfaces.get(key);
+ if (!elements) {
+ elements = new Map();
+ surfaces.set(key, elements);
+ }
+ const held = elements;
+ held.set(element, (held.get(element) ?? 0) + 1);
+ let dropped = false;
+ return () => {
+ if (dropped) return;
+ dropped = true;
+ const left = (held.get(element) ?? 1) - 1;
+ if (left > 0) held.set(element, left);
+ else held.delete(element);
+ };
+}
+
+function pushOutsideRoot(
+ root: Element,
+ selector: string,
+ out: Set<Element>,
+ firstOnly: boolean,
+): void {
+ let node: Element = root;
+ for (
+ let parent = node.parentElement;
+ parent;
+ node = parent, parent = parent.parentElement
+ ) {
+ if (parent.matches(selector)) {
+ out.add(parent);
+ if (firstOnly) return;
+ }
+ for (const sibling of parent.children) {
+ if (sibling === node) continue;
+ if (sibling.matches(selector)) {
+ out.add(sibling);
+ if (firstOnly) return;
+ }
+ if (firstOnly) {
+ const hit = sibling.querySelector(selector);
+ if (hit) {
+ out.add(hit);
+ return;
+ }
+ } else {
+ for (const hit of sibling.querySelectorAll(selector)) out.add(hit);
+ }
+ }
+ }
+}
+
+/** The elements `document.querySelectorAll(selector)` would return, in no particular order, read
+ * from the registry under `key` plus the document outside the app root. Null when the registry is
+ * not trusted, so the caller queries the document itself. */
+export function trackedSurfaces(
+ key: string,
+ selector: string,
+ firstOnly = false,
+): Element[] | null {
+ if (typeof document === "undefined") return null;
+ const root = appRoot;
+ if (!root?.isConnected) return null;
+ const out = new Set<Element>();
+ for (const element of surfaces.get(key)?.keys() ?? []) {
+ if (element.isConnected && element.matches(selector)) {
+ out.add(element);
+ if (firstOnly) return [element];
+ }
+ }
+ pushOutsideRoot(root, selector, out, firstOnly);
+ return [...out];
+}
+
+/** `document.querySelector(selector) !== null` for a selector only `key`'s producers match. */
+export function hasTrackedSurface(key: string, selector: string): boolean {
+ if (typeof document === "undefined") return false;
+ const found = trackedSurfaces(key, selector, true);
+ return found ? found.length > 0 : document.querySelector(selector) !== null;
+}
+
+function attachRef<T>(ref: Ref<T> | undefined, value: T): () => void {
+ if (typeof ref === "function") {
+ const cleanup = ref(value);
+ return typeof cleanup === "function" ? cleanup : () => ref(null);
+ }
+ if (ref && typeof ref === "object") {
+ ref.current = value;
+ return () => {
+ ref.current = null;
+ };
+ }
+ return () => undefined;
+}
+
+/** One ref feeding several, so a primitive's own ref and a caller's both see the element. */
+export function useMergedRefs<T>(
+ ...refs: (Ref<T> | undefined)[]
+): RefCallback<T> {
+ // biome-ignore lint/correctness/useExhaustiveDependencies: the refs are the dependencies.
+ return useCallback((element: T | null) => {
+ if (element === null) return;
+ const detach = refs.map((ref) => attachRef(ref, element));
+ return () => {
+ for (const undo of detach) undo();
+ };
+ }, refs);
+}
+
+/** A ref that registers the element under `key` while mounted and still reaches `forwarded`. */
+export function useSurfaceRef<T extends Element>(
+ key: string,
+ forwarded?: Ref<T>,
+): RefCallback<T> {
+ return useCallback(
+ (element: T | null) => {
+ if (element === null) return;
+ const unregister = registerSurface(key, element);
+ const detach = attachRef(forwarded, element);
+ return () => {
+ unregister();
+ detach();
+ };
+ },
+ [key, forwarded],
+ );
+}
diff --git a/studio/frontend/src/main.tsx b/studio/frontend/src/main.tsx
index d41bf82f407..82eb7354ef9 100644
--- a/studio/frontend/src/main.tsx
+++ b/studio/frontend/src/main.tsx
@@ -46,6 +46,7 @@ import { watchModalPointerLock } from "./lib/modal-pointer-lock";
import { watchOverlayScrollbarGutter } from "./lib/overlay-scrollbar";
import { pinPointerListenerRegions } from "./lib/pointer-listener-pin";
import { watchSpellCheck } from "./lib/spellcheck";
+import { trustSurfaceRegistry } from "./lib/surface-registry";
import { watchTimeFormat } from "./lib/time-format";
markAppSessionStart();
@@ -65,6 +66,8 @@ const rootElement = document.getElementById("root");
if (!rootElement) {
throw new Error("Root element not found");
}
+// Everything rendered into the root that a shortcut check looks for registers itself.
+trustSurfaceRegistry(rootElement);
const root = createRoot(rootElement);
if (isTauri) {
diff --git a/studio/frontend/tests/dialog-toast-outside.test.ts b/studio/frontend/tests/dialog-toast-outside.test.ts
index 4993e3c7307..7635b40caf4 100644
--- a/studio/frontend/tests/dialog-toast-outside.test.ts
+++ b/studio/frontend/tests/dialog-toast-outside.test.ts
@@ -62,6 +62,11 @@ test("an interaction on a toast does not dismiss the dialog under it", () => {
DropdownGlowContext: { Provider: "Provider" },
dialogDropdownGlow: () => null,
},
+ "@/lib/surface-registry": {
+ MODAL_SURFACE: "modal",
+ useMergedRefs: () => undefined,
+ useSurfaceRef: () => undefined,
+ },
"@/lib/utils": { cn: (...classes: unknown[]) => classes.join(" ") },
"@hugeicons/core-free-icons": { Cancel01Icon: {} },
"@/lib/folder-icons": { Cancel01Icon: {} },
@@ -109,6 +114,11 @@ test("an interaction on a toast does not dismiss the sheet under it", () => {
"@/components/ui/dialog": {
DialogPortalContainerContext: { Provider: "Provider" },
},
+ "@/lib/surface-registry": {
+ MODAL_SURFACE: "modal",
+ useMergedRefs: () => undefined,
+ useSurfaceRef: () => undefined,
+ },
"@/lib/utils": { cn: (...classes: unknown[]) => classes.join(" ") },
"@hugeicons/core-free-icons": { Cancel01Icon: {} },
"@/lib/folder-icons": { Cancel01Icon: {} },
diff --git a/studio/frontend/tests/shortcut-dispatch-guards.test.ts b/studio/frontend/tests/shortcut-dispatch-guards.test.ts
index 178b96ff208..38718453cc7 100644
--- a/studio/frontend/tests/shortcut-dispatch-guards.test.ts
+++ b/studio/frontend/tests/shortcut-dispatch-guards.test.ts
@@ -333,7 +333,7 @@ test("the sidebar's mutating chords refuse to fire under a dialog", async () =>
assert.match(APP_SIDEBAR, /isSurfaceBackgrounded\(SIDEBAR_SELECTOR\)/);
assert.match(
APP_SIDEBAR,
- /document\.querySelector\(SIDEBAR_SELECTOR\) === null &&\n\s*isSurfaceBackgrounded\("#root"\)/,
+ /surfaceElements\(SIDEBAR_SELECTOR\)\.length === 0 &&\n\s*isSurfaceBackgrounded\("#root"\)/,
);
});
diff --git a/studio/frontend/tests/shortcut-layout-and-recorder.test.ts b/studio/frontend/tests/shortcut-layout-and-recorder.test.ts
index 552a31a7b55..5d8cf910dfc 100644
--- a/studio/frontend/tests/shortcut-layout-and-recorder.test.ts
+++ b/studio/frontend/tests/shortcut-layout-and-recorder.test.ts
@@ -359,6 +359,6 @@ test("search chats fires from the composer, and toggleSidebar not behind a modal
);
assert.match(
readSrc("components/ui/sidebar.tsx"),
- /useShortcut\("toggleSidebar", toggleSidebar, \{\n\s*claims: \(\) =>\n\s*\(isMobile && openMobile\) \|\| document\.querySelector\(OPEN_DIALOG_SELECTOR\) === null,/,
+ /useShortcut\("toggleSidebar", toggleSidebar, \{\n\s*claims: \(\) =>\n\s*\(isMobile && openMobile\) \|\| !hasTrackedSurface\(MODAL_SURFACE, OPEN_DIALOG_SELECTOR\),/,
);
});
diff --git a/studio/frontend/tests/shortcut-surface-registry.test.ts b/studio/frontend/tests/shortcut-surface-registry.test.ts
new file mode 100644
index 00000000000..c55b4c85a5d
--- /dev/null
+++ b/studio/frontend/tests/shortcut-surface-registry.test.ts
@@ -0,0 +1,402 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Shortcut availability is asked on every press and every menu re-render. Each check used to be a
+// document query, a whole-tree walk that on a long chat cost tens of ms per press. The elements the
+// checks look for now register themselves, so a check reads those plus what sits outside the app
+// root, and never walks the root's subtree.
+
+import assert from "node:assert/strict";
+import { readdirSync, readFileSync, statSync } from "node:fs";
+import { join } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const {
+ COMPOSER_INPUT_SELECTOR,
+ isSurfaceBackgrounded,
+ isSurfaceInForeground,
+ surfaceElements,
+} = await import("../src/features/settings/hooks/use-shortcut.ts");
+const { isFindScopeBackgrounded, MODAL_BACKDROP_SELECTOR } = await import(
+ "../src/features/find-in-page/lib/find-backgrounded.ts"
+);
+const {
+ FIND_SCOPE_SURFACE,
+ hasTrackedSurface,
+ MODAL_SURFACE,
+ registerSurface,
+ SIDEBAR_SURFACE,
+ trustSurfaceRegistry,
+} = await import("../src/lib/surface-registry.ts");
+
+const OPEN_DIALOG_SELECTOR = /const OPEN_DIALOG_SELECTOR =\n\s*'([^']+)'/.exec(
+ readSrc("components/ui/sidebar.tsx"),
+)?.[1] as string;
+
+// Enough of the DOM for these selectors: attribute, :not(attribute), class, id; comma lists.
+type Simple = {
+ not: boolean;
+ attr?: string;
+ value?: string;
+ cls?: string;
+ id?: string;
+};
+function parseCompound(text: string): Simple[] {
+ const out: Simple[] = [];
+ const re =
+ /(:not\()?(?:\[([\w-]+)(?:="([^"]*)")?\]|\.([\w-]+)|#([\w-]+))\)?/g;
+ for (const m of text.matchAll(re)) {
+ out.push({
+ not: Boolean(m[1]),
+ attr: m[2],
+ value: m[3],
+ cls: m[4],
+ id: m[5],
+ });
+ }
+ return out;
+}
+
+let walks = 0;
+let fakeDocument: FakeDocument;
+
+class FakeElement {
+ parentElement: FakeElement | null = null;
+ children: FakeElement[] = [];
+ attrs = new Map<string, string>();
+ constructor(attrs: Record<string, string> = {}) {
+ for (const [k, v] of Object.entries(attrs)) this.attrs.set(k, v);
+ }
+ append(...kids: FakeElement[]): this {
+ for (const kid of kids) {
+ kid.parentElement = this;
+ this.children.push(kid);
+ }
+ return this;
+ }
+ remove(): void {
+ const parent = this.parentElement;
+ if (!parent) return;
+ parent.children = parent.children.filter((kid) => kid !== this);
+ this.parentElement = null;
+ }
+ get isConnected(): boolean {
+ let node: FakeElement | null = this;
+ while (node.parentElement) node = node.parentElement;
+ return node === fakeDocument.documentElement;
+ }
+ matches(selector: string): boolean {
+ return selector.split(",").some((part) =>
+ parseCompound(part.trim()).every((s) => {
+ let hit: boolean;
+ if (s.cls)
+ hit = (this.attrs.get("class") ?? "").split(" ").includes(s.cls);
+ else if (s.id) hit = this.attrs.get("id") === s.id;
+ else
+ hit =
+ this.attrs.has(s.attr as string) &&
+ (s.value === undefined ||
+ this.attrs.get(s.attr as string) === s.value);
+ return s.not ? !hit : hit;
+ }),
+ );
+ }
+ closest(selector: string): FakeElement | null {
+ for (let node: FakeElement | null = this; node; node = node.parentElement) {
+ if (node.matches(selector)) return node;
+ }
+ return null;
+ }
+ *descendants(): Generator<FakeElement> {
+ for (const kid of this.children) {
+ yield kid;
+ yield* kid.descendants();
+ }
+ }
+ querySelectorAll(selector: string): FakeElement[] {
+ const out: FakeElement[] = [];
+ for (const node of this.descendants()) {
+ walks += 1;
+ if (node.matches(selector)) out.push(node);
+ }
+ return out;
+ }
+ querySelector(selector: string): FakeElement | null {
+ for (const node of this.descendants()) {
+ walks += 1;
+ if (node.matches(selector)) return node;
+ }
+ return null;
+ }
+}
+
+class FakeDocument {
+ documentElement = new FakeElement();
+ body = new FakeElement();
+ documentQueries = 0;
+ constructor() {
+ this.documentElement.append(this.body);
+ }
+ querySelectorAll(selector: string): FakeElement[] {
+ this.documentQueries += 1;
+ return [
+ this.documentElement,
+ ...this.documentElement.querySelectorAll(selector),
+ ].filter((node) => node.matches(selector));
+ }
+ querySelector(selector: string): FakeElement | null {
+ return this.querySelectorAll(selector)[0] ?? null;
+ }
+}
+
+/** A long chat: thousands of rows inside the root, plus the surfaces the checks look for. */
+function longChat() {
+ fakeDocument = new FakeDocument();
+ const root = new FakeElement({ id: "root" });
+ const sidebar = new FakeElement({ "data-slot": "sidebar" });
+ const scope = new FakeElement({ "data-find-scope": "" });
+ const composer = new FakeElement({
+ class: "aui-composer-input unsloth-composer-input",
+ });
+ const thread = new FakeElement();
+ for (let i = 0; i < 3000; i += 1)
+ thread.append(new FakeElement({ class: "row" }));
+ scope.append(thread, composer);
+ root.append(sidebar, scope);
+ fakeDocument.body.append(root);
+ const drops = [
+ registerSurface(SIDEBAR_SURFACE, sidebar as unknown as Element),
+ registerSurface(FIND_SCOPE_SURFACE, scope as unknown as Element),
+ registerSurface(COMPOSER_INPUT_SELECTOR, composer as unknown as Element),
+ ];
+ return {
+ root,
+ sidebar,
+ scope,
+ composer,
+ drop: () => {
+ for (const d of drops) d();
+ },
+ };
+}
+
+/** Radix portals a modal to <body> and aria-hides the root. */
+function openModal(
+ root: FakeElement,
+ kind: "dialog" | "alert-dialog" | "sheet" = "dialog",
+) {
+ const portal = new FakeElement();
+ const overlay = new FakeElement({
+ "data-slot": `${kind}-overlay`,
+ "data-state": "open",
+ });
+ const content = new FakeElement({
+ "data-slot": `${kind}-content`,
+ "data-state": "open",
+ });
+ portal.append(overlay, content);
+ fakeDocument.body.append(portal);
+ root.attrs.set("aria-hidden", "true");
+ const drops = [
+ registerSurface(MODAL_SURFACE, overlay as unknown as Element),
+ registerSurface(MODAL_SURFACE, content as unknown as Element),
+ ];
+ return {
+ overlay,
+ content,
+ close: () => {
+ overlay.attrs.set("data-state", "closed");
+ content.attrs.set("data-state", "closed");
+ root.attrs.delete("aria-hidden");
+ },
+ unmount: () => {
+ for (const d of drops) d();
+ portal.remove();
+ },
+ };
+}
+
+/** Every answer the shortcut checks give, read from the live (fake) document. */
+function viaDocument() {
+ const q = (s: string) =>
+ fakeDocument.querySelectorAll(s) as unknown as Element[];
+ const backgrounded = (s: string) => {
+ const found = q(s);
+ return (
+ found.length > 0 &&
+ found.every((el) => el.closest('[aria-hidden="true"], [inert]') !== null)
+ );
+ };
+ return {
+ findBackgrounded:
+ q(MODAL_BACKDROP_SELECTOR).length > 0 || backgrounded(FIND_SCOPE_SURFACE),
+ openDialog: q(OPEN_DIALOG_SELECTOR).length > 0,
+ composerForeground: q(COMPOSER_INPUT_SELECTOR).some(
+ (el) => !el.closest('[aria-hidden="true"], [inert]'),
+ ),
+ sidebarBackgrounded: backgrounded(SIDEBAR_SURFACE),
+ sidebarCount: q(SIDEBAR_SURFACE).length,
+ };
+}
+
+function viaChecks() {
+ return {
+ findBackgrounded: isFindScopeBackgrounded(),
+ openDialog: hasTrackedSurface(MODAL_SURFACE, OPEN_DIALOG_SELECTOR),
+ composerForeground: isSurfaceInForeground(COMPOSER_INPUT_SELECTOR),
+ sidebarBackgrounded: isSurfaceBackgrounded(SIDEBAR_SURFACE),
+ sidebarCount: surfaceElements(SIDEBAR_SURFACE).length,
+ };
+}
+
+function withDocument(run: () => void) {
+ const saved = (globalThis as { document?: unknown }).document;
+ try {
+ run();
+ } finally {
+ (globalThis as { document?: unknown }).document = saved;
+ trustSurfaceRegistry(null);
+ }
+}
+
+test("checks on a long chat answer without a single document query or root walk", () => {
+ assert.ok(
+ OPEN_DIALOG_SELECTOR,
+ "sidebar.tsx still names the open dialog selector",
+ );
+ withDocument(() => {
+ const chat = longChat();
+ (globalThis as { document?: unknown }).document = fakeDocument;
+ trustSurfaceRegistry(chat.root as unknown as Element);
+
+ const check = (label: string) => {
+ const expected = viaDocument();
+ walks = 0;
+ fakeDocument.documentQueries = 0;
+ assert.deepEqual(viaChecks(), expected, label);
+ assert.equal(
+ fakeDocument.documentQueries,
+ 0,
+ `${label}: a document query`,
+ );
+ // Only what is outside the root may be walked: portals, a handful of nodes.
+ assert.ok(walks < 20, `${label}: walked ${walks} nodes`);
+ };
+ check("idle");
+ for (const kind of ["dialog", "alert-dialog", "sheet"] as const) {
+ const modal = openModal(chat.root, kind);
+ check(`${kind} open`);
+ modal.close();
+ check(`${kind} closing (still mounted, data-state closed)`);
+ modal.unmount();
+ check(`${kind} gone`);
+ }
+
+ // A third-party portal (a fullscreen table) cannot register; it is outside the root, so read.
+ const fullscreen = new FakeElement({ "aria-modal": "true" });
+ fakeDocument.body.append(fullscreen);
+ check("unregistered aria-modal portal");
+ assert.equal(isFindScopeBackgrounded(), true);
+ fullscreen.remove();
+
+ // A detached element left registered (an unmount mid-handover) is not counted.
+ chat.sidebar.remove();
+ check("sidebar unmounted");
+ assert.equal(surfaceElements(SIDEBAR_SURFACE).length, 0);
+ chat.drop();
+ });
+});
+
+test("without the app entry trusting it, every check still reads the document", () => {
+ withDocument(() => {
+ const chat = longChat();
+ (globalThis as { document?: unknown }).document = fakeDocument;
+ const modal = openModal(chat.root);
+ fakeDocument.documentQueries = 0;
+ assert.deepEqual(viaChecks(), viaDocument());
+ assert.ok(fakeDocument.documentQueries > 0);
+ modal.unmount();
+ chat.drop();
+ });
+});
+
+test("registration is refcounted and its unregister idempotent", () => {
+ withDocument(() => {
+ const chat = longChat();
+ (globalThis as { document?: unknown }).document = fakeDocument;
+ trustSurfaceRegistry(chat.root as unknown as Element);
+ const extra = registerSurface(
+ SIDEBAR_SURFACE,
+ chat.sidebar as unknown as Element,
+ );
+ extra();
+ extra();
+ assert.equal(
+ surfaceElements(SIDEBAR_SURFACE).length,
+ 1,
+ "the first registration holds",
+ );
+ chat.drop();
+ assert.equal(surfaceElements(SIDEBAR_SURFACE).length, 0);
+ });
+});
+
+// The registry is only as good as its producers: every element in the app a check can match must
+// register through useSurfaceRef, or a check would miss it inside the root.
+test("every producer of a tracked selector registers itself", () => {
+ const srcDir = fileURLToPath(new URL("../src", import.meta.url));
+ const files: string[] = [];
+ const walk = (dir: string) => {
+ for (const name of readdirSync(dir)) {
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) walk(path);
+ else if (/\.tsx$/.test(name)) files.push(path);
+ }
+ };
+ walk(srcDir);
+ const producers = [
+ // Not after "[": that is a selector reading them, not an element.
+ /(?<!\[)data-slot="(?:alert-)?dialog-(?:overlay|content)"/,
+ /(?<!\[)data-slot="sheet-overlay"/,
+ /(?<!\[)data-slot="sidebar"/,
+ /(?<!\[)aria-modal(?:=\{true\}|="true")/,
+ /(?<!\[)data-blocking-screen=""/,
+ /className="[^"]*\baui-composer-input\b/,
+ /\[FIND_SCOPE_ATTRIBUTE\]: ""/,
+ ];
+ let seen = 0;
+ for (const path of files) {
+ const lines = readFileSync(path, "utf8").split("\n");
+ const refs = new Set(
+ [...lines.join("\n").matchAll(/const (\w+) = useSurfaceRef\b/g)].map(
+ (m) => m[1],
+ ),
+ );
+ lines.forEach((line, i) => {
+ if (/^\s*(\/\/|\*)/.test(line) || !producers.some((re) => re.test(line)))
+ return;
+ seen += 1;
+ // From the element's opening "<Tag" to just past the attribute: a ref may sit either side.
+ let start = i;
+ while (start > 0 && !/^\s*<[A-Za-z][\w.]*(\s|$)/.test(lines[start]))
+ start -= 1;
+ const tag = lines.slice(start, i + 10).join("\n");
+ const registered = [...tag.matchAll(/\bref=\{(\w+)\}/g)].some((m) =>
+ refs.has(m[1]),
+ );
+ assert.ok(
+ registered,
+ `${path}:${i + 1} renders a tracked surface without useSurfaceRef`,
+ );
+ });
+ }
+ assert.ok(
+ seen >= 12,
+ `found only ${seen} producers; the scan lost track of them`,
+ );
+});