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
Studio: make the chat and sidebar menus open without freezing the page (#10262)
Nilayb48b6025d88f
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.ymlindex cbbdbfcc7f5..c8d1067c112 100644--- a/.github/workflows/studio-frontend-ci.yml+++ b/.github/workflows/studio-frontend-ci.yml@@ -24,6 +24,7 @@ on:- 'tests/studio/playwright_research_freeze.py'- 'tests/studio/playwright_heavy_thread.py'- 'tests/studio/probe_dismiss_guard.py'+ - 'tests/studio/playwright_nonmodal_menus.py'- 'tests/studio/playwright_settings_tabs.py'- 'tests/studio/playwright_keyboard_shortcuts.py'- 'tests/studio/playwright_find_in_page.py'@@ -437,6 +438,15 @@ jobs:working-directory: ${{ github.workspace }}run: python3 tests/studio/probe_dismiss_guard.py --label ci --engine chromium+ # The AST tests pin which menus are non-modal; only a browser answers what that then+ # does to a scroll behind an open menu, to the click that dismisses it, and to focus.+ # Chromium because that is what this job installs; PW_ENGINE=firefox or webkit runs+ # the same checks on the other two. The page mounts one still-modal menu as a+ # control, so a shared result is Radix rather than the wrapper.+ - name: Browser checks for the non-modal dropdown wrapper+ working-directory: ${{ github.workspace }}+ run: python3 tests/studio/playwright_nonmodal_menus.py+# The settings panels are fetched on first view, so only a browser can answer whether# every tab renders and deep-opens land (and abandoned ones do not come back).- name: Browser smoke for the settings tab panels@@ -508,6 +518,7 @@ jobs:logs/playwright-*logs/settings_tabs_report.jsonlogs/settings_tabs_blocked_report.json+ logs/nonmodal_menus_report.jsonlogs/pw/retention-days: 3if-no-files-found: ignorediff --git a/studio/frontend/smoke-nonmodal-menus-main.tsx b/studio/frontend/smoke-nonmodal-menus-main.tsxnew file mode 100644index 00000000000..871054ad5d4--- /dev/null+++ b/studio/frontend/smoke-nonmodal-menus-main.tsx@@ -0,0 +1,237 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Harness for tests/studio/playwright_nonmodal_menus.py: the real NonModalDropdownMenu on a real+// overflowing list, so the behaviour measured is the component's own. No backend, no auth.++import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { NonModalDropdownMenu } from "@/components/ui/non-modal-dropdown-menu";+import { type ReactElement, StrictMode, useEffect, useState } from "react";+import { createRoot } from "react-dom/client";+import "./src/index.css";++// Counts document listeners so a leak across opens is measurable. Before React, to see them all.+const listenerCounts: Record<string, number> = {};+const realAdd = document.addEventListener.bind(document);+const realRemove = document.removeEventListener.bind(document);+document.addEventListener = ((type: string, fn: never, opts: never) => {+ listenerCounts[type] = (listenerCounts[type] ?? 0) + 1;+ return realAdd(type, fn, opts);+}) as typeof document.addEventListener;+document.removeEventListener = ((type: string, fn: never, opts: never) => {+ listenerCounts[type] = (listenerCounts[type] ?? 0) - 1;+ return realRemove(type, fn, opts);+}) as typeof document.removeEventListener;++// The guard swallows in the capture phase, so a swallowed click never reaches this one.+let documentClicks = 0;+document.addEventListener("click", () => {+ documentClicks += 1;+});++const ROWS = Array.from({ length: 60 }, (_, index) => index);+// Named once so every list below maps over identities, not over positions.+const MENU_ITEMS = Array.from({ length: 40 }, (_, index) => `item-${index}`);++function RowMenu({ row }: { row: number }): ReactElement {+ return (+ <NonModalDropdownMenu+ side="bottom"+ align="start"+ sideOffset={0}+ className="w-56"+ trigger={(triggerRef) => (+ <button+ ref={triggerRef}+ type="button"+ data-row={String(row)}+ aria-label={`Row options ${row}`}+ >+ options+ </button>+ )}+ >+ <DropdownMenuItem data-testid={`rename-${row}`}>Rename</DropdownMenuItem>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger data-testid={`export-${row}`}>+ Export+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-40">+ {MENU_ITEMS.map((id) => (+ <DropdownMenuItem key={id} data-testid={`export-${row}-${id}`}>+ Format {id}+ </DropdownMenuItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuSeparator />+ <DropdownMenuItem data-testid={`delete-${row}`}>Delete</DropdownMenuItem>+ </NonModalDropdownMenu>+ );+}++/** The unconverted shape, as a control: whatever this does too is Radix, not the wrapper. */+function ControlRowMenu(): ReactElement {+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild={true}>+ <button type="button" aria-label="Control options">+ control+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent side="bottom" align="start" className="w-56">+ <DropdownMenuItem data-testid="control-rename">Rename</DropdownMenuItem>+ <DropdownMenuItem data-testid="control-delete">Delete</DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++/** A menu whose own content overflows, so scrolling its viewport is a real scroll event. */+function TallMenu(): ReactElement {+ return (+ <NonModalDropdownMenu+ side="bottom"+ align="start"+ className="max-h-40 w-56"+ trigger={(triggerRef) => (+ <button ref={triggerRef} type="button" aria-label="Tall menu">+ tall+ </button>+ )}+ >+ {MENU_ITEMS.map((id) => (+ <DropdownMenuItem key={id} data-testid={`tall-${id}`}>+ Item {id}+ </DropdownMenuItem>+ ))}+ </NonModalDropdownMenu>+ );+}++function Harness(): ReactElement {+ const [rows, setRows] = useState<number[]>(ROWS);++ useEffect(() => {+ const api = {+ /** Drop a row while its menu is open, to strand the portal if anything can. */+ removeRow(row: number): void {+ setRows((current) => current.filter((value) => value !== row));+ },+ reset(): void {+ setRows(ROWS);+ documentClicks = 0;+ },+ documentClicks: (): number => documentClicks,+ resetClicks(): void {+ documentClicks = 0;+ },+ scrollListeners: (): number => listenerCounts.scroll ?? 0,+ /** Everything a modal Radix menu writes to the document when it opens. */+ documentState: () => ({+ bodyPointerEvents: document.body.style.pointerEvents,+ scrollLocked: document.body.hasAttribute("data-scroll-locked"),+ ariaHidden: document.querySelectorAll("[aria-hidden='true']").length,+ openMenus: document.querySelectorAll("[role='menu']").length,+ activeLabel:+ document.activeElement?.getAttribute("aria-label") ??+ document.activeElement?.tagName ??+ null,+ }),+ supportsPreventScroll: (): boolean => {+ let supported = false;+ const probe = document.createElement("div");+ probe.tabIndex = 0;+ document.body.append(probe);+ probe.focus({+ get preventScroll(): boolean {+ supported = true;+ return true;+ },+ } as FocusOptions);+ probe.remove();+ return supported;+ },+ };+ (window as unknown as { probe: typeof api }).probe = api;+ }, []);++ return (+ <div style={{ display: "flex", gap: 24, padding: 16 }}>+ <div+ id="list"+ style={{+ height: 360,+ width: 260,+ overflowY: "auto",+ border: "1px solid",+ }}+ >+ {rows.map((row) => (+ <div+ key={row}+ data-testid={`row-${row}`}+ style={{+ display: "flex",+ justifyContent: "space-between",+ height: 40,+ }}+ >+ <span>Chat {row}</span>+ <RowMenu row={row} />+ </div>+ ))}+ </div>+ <div+ id="other"+ style={{+ height: 360,+ width: 200,+ overflowY: "auto",+ border: "1px solid",+ }}+ >+ {ROWS.map((row) => (+ <div key={`other-${row}`} style={{ height: 40 }}>+ Other {row}+ </div>+ ))}+ </div>+ <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>+ <TallMenu />+ <input id="outside-input" defaultValue="text" />+ <button id="outside-button" type="button">+ outside+ </button>+ {/* Last, so its modal menu drops below the controls instead of over them. */}+ <ControlRowMenu />+ </div>+ {/* Page-level overflow, so a window scroll is reachable too. */}+ <div style={{ height: 3000, width: 1 }} />+ </div>+ );+}++const rootElement = document.getElementById("root");+if (!rootElement) {+ throw new Error("Root element not found");+}+const strict = !new URLSearchParams(window.location.search).has("nostrict");+createRoot(rootElement).render(+ strict ? (+ <StrictMode>+ <Harness />+ </StrictMode>+ ) : (+ <Harness />+ ),+);diff --git a/studio/frontend/smoke-nonmodal-menus.html b/studio/frontend/smoke-nonmodal-menus.htmlnew file mode 100644index 00000000000..8d098c6ab69--- /dev/null+++ b/studio/frontend/smoke-nonmodal-menus.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <script src="/crypto-boot.js"></script>+ <title>non-modal menu smoke</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/smoke-nonmodal-menus-main.tsx"></script>+ </body>+</html>diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsxindex 025a67889f8..a46ac2ad3aa 100644--- a/studio/frontend/src/components/app-sidebar.tsx+++ b/studio/frontend/src/components/app-sidebar.tsx@@ -42,6 +42,7 @@ import {DropdownMenuSubTrigger,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";+import { NonModalDropdownMenu } from "@/components/ui/non-modal-dropdown-menu";import {Dialog,DialogContent,@@ -2919,64 +2920,63 @@ export function AppSidebar() {includeOrganize?: boolean;}) {return (- <DropdownMenu>- <DropdownMenuTrigger asChild>+ <NonModalDropdownMenu+ side="bottom"+ align="end"+ sideOffset={2}+ className="unsloth-plus-menu w-56"+ trigger={(triggerRef) => (<button+ ref={triggerRef}type="button"aria-label={options.ariaLabel}className="sidebar-header-action"><HugeiconsIcon icon={MoreHorizontalIcon} strokeWidth={1.75} className="size-icon" /></button>- </DropdownMenuTrigger>- <DropdownMenuContent- side="bottom"- align="end"- sideOffset={2}- className="unsloth-plus-menu w-56"+ )}+ >+ {options.includeOrganize && (+ <>+ <DropdownMenuLabel>+ {t("shell.organize.sidebarHeading")}+ </DropdownMenuLabel>+ <DropdownMenuRadioGroup+ value={organizeBy}+ onValueChange={(value) =>+ setOrganizeBy(value as SidebarOrganizeBy)+ }+ >+ {ORGANIZE_OPTIONS.map((option) => (+ <DropdownMenuRadioItem+ key={option.value}+ value={option.value}+ className={menuRadioItemClass}+ >+ {t(option.key)}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </>+ )}+ <DropdownMenuLabel>{options.sortLabel}</DropdownMenuLabel>+ <DropdownMenuRadioGroup+ value={options.sortValue}+ onValueChange={(value) =>+ options.onSortChange(value as SidebarChatSort)+ }>- {options.includeOrganize && (- <>- <DropdownMenuLabel>- {t("shell.organize.sidebarHeading")}- </DropdownMenuLabel>- <DropdownMenuRadioGroup- value={organizeBy}- onValueChange={(value) =>- setOrganizeBy(value as SidebarOrganizeBy)- }- >- {ORGANIZE_OPTIONS.map((option) => (- <DropdownMenuRadioItem- key={option.value}- value={option.value}- className={menuRadioItemClass}- >- {t(option.key)}- </DropdownMenuRadioItem>- ))}- </DropdownMenuRadioGroup>- </>- )}- <DropdownMenuLabel>{options.sortLabel}</DropdownMenuLabel>- <DropdownMenuRadioGroup- value={options.sortValue}- onValueChange={(value) =>- options.onSortChange(value as SidebarChatSort)- }- >- {CHAT_SORT_OPTIONS.map((option) => (- <DropdownMenuRadioItem- key={option.value}- value={option.value}- className={menuRadioItemClass}- >- {t(option.key)}- </DropdownMenuRadioItem>- ))}- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>+ {CHAT_SORT_OPTIONS.map((option) => (+ <DropdownMenuRadioItem+ key={option.value}+ value={option.value}+ className={menuRadioItemClass}+ >+ {t(option.key)}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </NonModalDropdownMenu>);}@@ -3250,9 +3250,14 @@ export function AppSidebar() {</span></button>)}- <DropdownMenu>- <DropdownMenuTrigger asChild>+ <NonModalDropdownMenu+ side="bottom"+ align="start"+ sideOffset={0}+ className="unsloth-plus-menu menu-flat-destructive w-56"+ trigger={(triggerRef) => (<button+ ref={triggerRef}type="button"onClick={(e) => e.stopPropagation()}aria-label="Chat options"@@ -3262,191 +3267,185 @@ export function AppSidebar() {<HugeiconsIcon icon={MoreVerticalIcon} strokeWidth={1.75} className="size-icon" /></span></button>- </DropdownMenuTrigger>- <DropdownMenuContent- side="bottom"- align="start"- sideOffset={0}- className="unsloth-plus-menu menu-flat-destructive w-56"- >- <DropdownMenuItem onSelect={() => openRenameChat(item)}>- <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />- <span>Rename</span>- </DropdownMenuItem>- <DropdownMenuItem onSelect={() => togglePinnedChat(item.id)}>- <HugeiconsIcon icon={isPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />- <span>{isPinned ? "Unpin chat" : "Pin chat"}</span>- </DropdownMenuItem>- {drag &&- renderMoveRowItems(- drag.scope,- drag.orderedIds,- item.id,- drag.index,- )}- {sandboxSessionId ? (- isTauri ? (- <DropdownMenuItem- title="Open the folder this chat's tool calls read and write"- onSelect={() => {- void (async () => {- try {- // A chat moved between projects keeps the sandbox it- // wrote to, so its own history names the folder, not- // current membership. A failed read is reported- // below rather than caught per pane, which would- // read as "never ran a tool" and fall back to- // membership, the answer the recorded id overrides.- const ids =- threadIds.length > 0 ? threadIds : [item.id];- const distinct = await sandboxSessionIdsHolding(ids);- if (distinct.length > 1) {- toast.error("This chat wrote to more than one folder.", {- description:- "It ran tools on both sides of a move, so open the folder from a tool card instead.",- });- return;- }- await revealSandbox(distinct[0] ?? sandboxSessionId);- } catch (error) {- toast.error("Could not open the chat folder.", {+ )}+ >+ <DropdownMenuItem onSelect={() => openRenameChat(item)}>+ <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />+ <span>Rename</span>+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => togglePinnedChat(item.id)}>+ <HugeiconsIcon icon={isPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />+ <span>{isPinned ? "Unpin chat" : "Pin chat"}</span>+ </DropdownMenuItem>+ {drag &&+ renderMoveRowItems(+ drag.scope,+ drag.orderedIds,+ item.id,+ drag.index,+ )}+ {sandboxSessionId ? (+ isTauri ? (+ <DropdownMenuItem+ title="Open the folder this chat's tool calls read and write"+ onSelect={() => {+ void (async () => {+ try {+ // A chat moved between projects keeps the sandbox it+ // wrote to, so its own history names the folder, not+ // current membership. A failed read is reported+ // below rather than caught per pane, which would+ // read as "never ran a tool" and fall back to+ // membership, the answer the recorded id overrides.+ const ids =+ threadIds.length > 0 ? threadIds : [item.id];+ const distinct = await sandboxSessionIdsHolding(ids);+ if (distinct.length > 1) {+ toast.error("This chat wrote to more than one folder.", {description:- error instanceof Error- ? error.message- : String(error),+ "It ran tools on both sides of a move, so open the folder from a tool card instead.",});+ return;}- })();- }}- >- <HugeiconsIcon icon={FolderOpenIcon} strokeWidth={1.75} className="size-icon" />- <span>Open chat folder</span>- </DropdownMenuItem>- ) : (- <OpenChatFolderUnavailableItem />- )- ) : null}- <DropdownMenuSub>- <DropdownMenuSubTrigger>- <HugeiconsIcon icon={FolderExportIcon} strokeWidth={1.75} className="size-icon" />- <span>Move to project</span>- </DropdownMenuSubTrigger>- <DropdownMenuSubContent- sideOffset={0}- alignOffset={-4}- className="unsloth-plus-menu w-52"+ await revealSandbox(distinct[0] ?? sandboxSessionId);+ } catch (error) {+ toast.error("Could not open the chat folder.", {+ description:+ error instanceof Error+ ? error.message+ : String(error),+ });+ }+ })();+ }}+ >+ <HugeiconsIcon icon={FolderOpenIcon} strokeWidth={1.75} className="size-icon" />+ <span>Open chat folder</span>+ </DropdownMenuItem>+ ) : (+ <OpenChatFolderUnavailableItem />+ )+ ) : null}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <HugeiconsIcon icon={FolderExportIcon} strokeWidth={1.75} className="size-icon" />+ <span>Move to project</span>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent+ sideOffset={0}+ alignOffset={-4}+ className="unsloth-plus-menu w-52"+ >+ <DropdownMenuItem+ onSelect={() => {+ setProjectCreateMoveTarget(item);+ setCreatingProject(true);+ }}+ >+ <HugeiconsIcon icon={FolderAddIcon} strokeWidth={1.75} className="size-icon" />+ <span>New project</span>+ </DropdownMenuItem>+ <DropdownMenuItem+ disabled={!item.projectId}+ onSelect={() => void moveChatToProject(item, null)}>+ <span>Recents</span>+ </DropdownMenuItem>+ {projects.map((project) => (<DropdownMenuItem- onSelect={() => {- setProjectCreateMoveTarget(item);- setCreatingProject(true);- }}+ key={project.id}+ disabled={item.projectId === project.id}+ onSelect={() => void moveChatToProject(item, project.id)}>- <HugeiconsIcon icon={FolderAddIcon} strokeWidth={1.75} className="size-icon" />- <span>New project</span>+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />+ <span className="truncate">{project.name}</span></DropdownMenuItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-icon" />+ <span>Export</span>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent sideOffset={8} alignOffset={-4} className="unsloth-plus-menu w-52">+ {CHAT_EXPORT_OPTIONS.map(({ label, format }) => (<DropdownMenuItem- disabled={!item.projectId}- onSelect={() => void moveChatToProject(item, null)}+ key={label}+ onSelect={async () => {+ try {+ const ids = item.type === "single"+ ? [item.id]+ : (await listStoredChatThreads({ pairId: item.id })).map((t) => t.id);+ for (const id of ids) {+ await exportConversationByFormat(id, format);+ }+ } catch (error) {+ if (!isDownloadCancelled(error)) {+ toast.error("Export failed.");+ }+ }+ }}>- <span>Recents</span>+ {label}</DropdownMenuItem>- {projects.map((project) => (- <DropdownMenuItem- key={project.id}- disabled={item.projectId === project.id}- onSelect={() => void moveChatToProject(item, project.id)}- >- <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />- <span className="truncate">{project.name}</span>- </DropdownMenuItem>- ))}- </DropdownMenuSubContent>- </DropdownMenuSub>- <DropdownMenuSub>- <DropdownMenuSubTrigger>- <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-icon" />- <span>Export</span>- </DropdownMenuSubTrigger>- <DropdownMenuSubContent sideOffset={8} alignOffset={-4} className="unsloth-plus-menu w-52">- {CHAT_EXPORT_OPTIONS.map(({ label, format }) => (- <DropdownMenuItem- key={label}- onSelect={async () => {- try {- const ids = item.type === "single"- ? [item.id]- : (await listStoredChatThreads({ pairId: item.id })).map((t) => t.id);- for (const id of ids) {- await exportConversationByFormat(id, format);- }- } catch (error) {- if (!isDownloadCancelled(error)) {- toast.error("Export failed.");- }- }- }}- >- {label}- </DropdownMenuItem>- ))}- <DropdownMenuSeparator />- {/* Bulk export and import live in Settings -> Data. */}+ ))}+ <DropdownMenuSeparator />+ {/* Bulk export and import live in Settings -> Data. */}+ <DropdownMenuItem+ onSelect={() =>+ useSettingsDialogStore.getState().openDialog("data")+ }+ >+ Export all chats…+ </DropdownMenuItem>+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <HugeiconsIcon icon={BookOpen01Icon} strokeWidth={1.75} className="size-icon" />+ <span>Save to project sources</span>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent sideOffset={8} alignOffset={-4} className="unsloth-plus-menu w-52">+ {projects.length === 0 && (+ <DropdownMenuItem disabled>No projects yet</DropdownMenuItem>+ )}+ {projects.map((project) => (<DropdownMenuItem- onSelect={() =>- useSettingsDialogStore.getState().openDialog("data")- }+ key={project.id}+ onSelect={async () => {+ try {+ await saveChatToProjectSources(item, project.id);+ } catch {+ toast.error("Failed to save to project sources.");+ }+ }}>- Export all chats…+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />+ <span className="truncate">{project.name}</span></DropdownMenuItem>- </DropdownMenuSubContent>- </DropdownMenuSub>- <DropdownMenuSub>- <DropdownMenuSubTrigger>- <HugeiconsIcon icon={BookOpen01Icon} strokeWidth={1.75} className="size-icon" />- <span>Save to project sources</span>- </DropdownMenuSubTrigger>- <DropdownMenuSubContent sideOffset={8} alignOffset={-4} className="unsloth-plus-menu w-52">- {projects.length === 0 && (- <DropdownMenuItem disabled>No projects yet</DropdownMenuItem>- )}- {projects.map((project) => (- <DropdownMenuItem- key={project.id}- onSelect={async () => {- try {- await saveChatToProjectSources(item, project.id);- } catch {- toast.error("Failed to save to project sources.");- }- }}- >- <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />- <span className="truncate">{project.name}</span>- </DropdownMenuItem>- ))}- </DropdownMenuSubContent>- </DropdownMenuSub>- <DropdownMenuSeparator />- <DropdownMenuItem onSelect={() => void handleArchiveThread(item)}>- <HugeiconsIcon icon={Archive03Icon} strokeWidth={1.75} className="size-icon" />- <span>Archive</span>- </DropdownMenuItem>- <DropdownMenuItem- variant="destructive"- onSelect={() =>- confirmDeleteChats- ? openDeleteDialog({ kind: "chat", item })- : void deleteChatWithCleanup(item, {- deleteFiles: alwaysDeleteChatFiles,- })- }- >- <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />- <span>Delete</span>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuSeparator />+ <DropdownMenuItem onSelect={() => void handleArchiveThread(item)}>+ <HugeiconsIcon icon={Archive03Icon} strokeWidth={1.75} className="size-icon" />+ <span>Archive</span>+ </DropdownMenuItem>+ <DropdownMenuItem+ variant="destructive"+ onSelect={() =>+ confirmDeleteChats+ ? openDeleteDialog({ kind: "chat", item })+ : void deleteChatWithCleanup(item, {+ deleteFiles: alwaysDeleteChatFiles,+ })+ }+ >+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />+ <span>Delete</span>+ </DropdownMenuItem>+ </NonModalDropdownMenu></SidebarMenuItem></ContextMenuTrigger>{renderChatContextMenu()}@@ -4022,9 +4021,14 @@ export function AppSidebar() {</span></button>{/* Project options */}- <DropdownMenu>- <DropdownMenuTrigger asChild>+ <NonModalDropdownMenu+ side="bottom"+ align="start"+ sideOffset={0}+ className="unsloth-plus-menu menu-flat-destructive w-56"+ trigger={(triggerRef) => (<button+ ref={triggerRef}type="button"onClick={(e) => e.stopPropagation()}aria-label="Project options"@@ -4034,58 +4038,52 @@ export function AppSidebar() {<HugeiconsIcon icon={MoreVerticalIcon} strokeWidth={1.75} className="size-icon" /></span></button>- </DropdownMenuTrigger>- <DropdownMenuContent- side="bottom"- align="start"- sideOffset={0}- className="unsloth-plus-menu menu-flat-destructive w-56"+ )}+ >+ <DropdownMenuItem onSelect={() => openProject(project.id)}>+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />+ <span>Project home</span>+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => openNewChat(project.id)}>+ <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} className="size-icon" />+ <span>New chat</span>+ </DropdownMenuItem>+ <DropdownMenuItem+ onSelect={() => {+ // Seed the shared draft so the dialog opens with the current name, not stale text.+ setRenameDraft(project.name);+ setRenamingTarget({+ kind: "project",+ project,+ current: project.name,+ });+ }}>- <DropdownMenuItem onSelect={() => openProject(project.id)}>- <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />- <span>Project home</span>- </DropdownMenuItem>- <DropdownMenuItem onSelect={() => openNewChat(project.id)}>- <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} className="size-icon" />- <span>New chat</span>- </DropdownMenuItem>- <DropdownMenuItem- onSelect={() => {- // Seed the shared draft so the dialog opens with the current name, not stale text.- setRenameDraft(project.name);- setRenamingTarget({- kind: "project",- project,- current: project.name,- });- }}- >- <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />- <span>Rename project</span>- </DropdownMenuItem>- {renderMoveRowItems(- PROJECT_ORDER_SCOPE,- projectRowIds,- project.id,- projectIndex,- )}- <DropdownMenuItem onSelect={() => toggleProjectPin(project.id)}>- <HugeiconsIcon icon={isProjectPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />- <span>{isProjectPinned ? "Unpin project" : "Pin project"}</span>- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem- variant="destructive"- onSelect={() => {- // Start each delete with the file toggle off: Cancel closes programmatically and skips the- openDeleteDialog({ kind: "project", project });- }}- >- <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />- <span>Delete project</span>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />+ <span>Rename project</span>+ </DropdownMenuItem>+ {renderMoveRowItems(+ PROJECT_ORDER_SCOPE,+ projectRowIds,+ project.id,+ projectIndex,+ )}+ <DropdownMenuItem onSelect={() => toggleProjectPin(project.id)}>+ <HugeiconsIcon icon={isProjectPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />+ <span>{isProjectPinned ? "Unpin project" : "Pin project"}</span>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ onSelect={() => {+ // Start each delete with the file toggle off: Cancel closes programmatically and skips the+ openDeleteDialog({ kind: "project", project });+ }}+ >+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />+ <span>Delete project</span>+ </DropdownMenuItem>+ </NonModalDropdownMenu></SidebarMenuItem></ContextMenuTrigger>{renderProjectContextMenu()}@@ -4273,9 +4271,14 @@ export function AppSidebar() {{run.dataset_name}</span></SidebarMenuButton>- <DropdownMenu>- <DropdownMenuTrigger asChild>+ <NonModalDropdownMenu+ side="bottom"+ align="end"+ sideOffset={0}+ className="app-user-menu menu-soft-surface menu-flat-destructive ring-0 w-44 py-2 font-heading rounded-full border-0"+ trigger={(triggerRef) => (<button+ ref={triggerRef}type="button"onClick={(e) => e.stopPropagation()}aria-label={t("shell.aria.runOptions")}@@ -4285,29 +4288,23 @@ export function AppSidebar() {<HugeiconsIcon icon={MoreVerticalIcon} strokeWidth={1.75} className="size-icon" /></span></button>- </DropdownMenuTrigger>- <DropdownMenuContent- side="bottom"- align="end"- sideOffset={0}- className="app-user-menu menu-soft-surface menu-flat-destructive ring-0 w-44 py-2 font-heading rounded-full border-0"+ )}+ >+ <DropdownMenuItem onSelect={() => openRenameRun(run)}>+ <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />+ <span>{t("common.rename")}</span>+ </DropdownMenuItem>+ <DropdownMenuItem+ variant="destructive"+ disabled={run.status === "running"}+ onSelect={() =>+ openDeleteDialog({ kind: "run", run })+ }>- <DropdownMenuItem onSelect={() => openRenameRun(run)}>- <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />- <span>{t("common.rename")}</span>- </DropdownMenuItem>- <DropdownMenuItem- variant="destructive"- disabled={run.status === "running"}- onSelect={() =>- openDeleteDialog({ kind: "run", run })- }- >- <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />- <span>{t("common.delete")}</span>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />+ <span>{t("common.delete")}</span>+ </DropdownMenuItem>+ </NonModalDropdownMenu></SidebarMenuItem>);})}@@ -4409,9 +4406,14 @@ export function AppSidebar() {}}/><SidebarMenuItem>- <DropdownMenu>- <DropdownMenuTrigger asChild>+ <NonModalDropdownMenu+ side="top"+ align="center"+ sideOffset={8}+ className="app-user-menu menu-soft-surface-up ring-0 w-[16rem] rounded-[20px] border border-transparent px-2.5 py-2.5 font-heading dark:border-white/[0.05]"+ trigger={(triggerRef) => (<SidebarMenuButton+ ref={triggerRef}size="lg"aria-label={t("shell.accountMenu", { name: displayTitle })}className="sidebar-nav-btn !h-[44px] -my-[3px] gap-[9px] pl-2 pr-[45px] py-[3px] rounded-[14px] group-data-[collapsible=icon]:!size-[34px] group-data-[collapsible=icon]:!rounded-full group-data-[collapsible=icon]:!p-0 group-data-[collapsible=icon]:mx-auto group-data-[collapsible=icon]:justify-center"@@ -4431,122 +4433,116 @@ export function AppSidebar() {<span className="truncate text-ui-11p5 tracking-nav text-muted-foreground">Unsloth</span></div></SidebarMenuButton>- </DropdownMenuTrigger>- <DropdownMenuContent- side="top"- align="center"- sideOffset={8}- className="app-user-menu menu-soft-surface-up ring-0 w-[16rem] rounded-[20px] border border-transparent px-2.5 py-2.5 font-heading dark:border-white/[0.05]"- >- <DropdownMenuGroup>- <DropdownMenuItem- onSelect={() => useSettingsDialogStore.getState().openDialog()}- >- <HugeiconsIcon icon={Settings02Icon} strokeWidth={1.75} className="size-icon" />- <span>{t("shell.navigation.settings")}</span>- {settingsShortcutLabel && (- <DropdownMenuShortcut>- {settingsShortcutLabel}- </DropdownMenuShortcut>- )}- </DropdownMenuItem>- {/* Optional items follow the order and visibility set in- Appearance settings; Settings above and the block after- the separator are pinned. */}- {sidebarMenu.map((item) => {- if (!item.visible) return null;- if (item.id === "api") {- return (- <DropdownMenuItem- key={item.id}- onSelect={() => useSettingsDialogStore.getState().openDialog("api-keys")}- >- <HugeiconsIcon icon={Globe02Icon} strokeWidth={1.75} className="size-[18px]" />- <span>{t("shell.navigation.api")}</span>- </DropdownMenuItem>- );- }- if (item.id === "darkMode") {- return (- <DropdownMenuItem- key={item.id}- ref={anchorRef as React.Ref<HTMLDivElement>}- onSelect={(e) => { e.preventDefault(); toggleTheme(); }}- >- {isDark ? <HugeiconsIcon icon={Sun03Icon} strokeWidth={1.75} className="size-icon" /> : <Moon strokeWidth={1.75} className="size-icon" />}- <span>- {isDark- ? t("shell.navigation.lightMode")- : t("shell.navigation.darkMode")}- </span>- </DropdownMenuItem>- );- }- if (item.id === "guidedTour") {- if (!getTourId(pathname)) return null;- return (- <DropdownMenuItem- key={item.id}- onSelect={() => {- const tourId = getTourId(pathname);- if (!tourId) return;- window.dispatchEvent(- new CustomEvent(TOUR_OPEN_EVENT, {- detail: { id: tourId },- }),- );- }}- >- <HugeiconsIcon icon={CursorInfo02Icon} strokeWidth={1.75} className="size-icon" />- <span>{t("shell.navigation.guidedTour")}</span>- </DropdownMenuItem>- );- }- // Remaining ids are settings tabs shown by their tab name.- const settingsTabId = item.id;- const tab = SETTINGS_TAB_MENU_ITEMS[settingsTabId];+ )}+ >+ <DropdownMenuGroup>+ <DropdownMenuItem+ onSelect={() => useSettingsDialogStore.getState().openDialog()}+ >+ <HugeiconsIcon icon={Settings02Icon} strokeWidth={1.75} className="size-icon" />+ <span>{t("shell.navigation.settings")}</span>+ {settingsShortcutLabel && (+ <DropdownMenuShortcut>+ {settingsShortcutLabel}+ </DropdownMenuShortcut>+ )}+ </DropdownMenuItem>+ {/* Optional items follow the order and visibility set in+ Appearance settings; Settings above and the block after+ the separator are pinned. */}+ {sidebarMenu.map((item) => {+ if (!item.visible) return null;+ if (item.id === "api") {return (<DropdownMenuItemkey={item.id}- onSelect={() => useSettingsDialogStore.getState().openDialog(settingsTabId)}+ onSelect={() => useSettingsDialogStore.getState().openDialog("api-keys")}>- <HugeiconsIcon icon={tab.icon} strokeWidth={1.75} className="size-icon" />- <span>{t(tab.labelKey)}</span>+ <HugeiconsIcon icon={Globe02Icon} strokeWidth={1.75} className="size-[18px]" />+ <span>{t("shell.navigation.api")}</span></DropdownMenuItem>);- })}- </DropdownMenuGroup>- <DropdownMenuSeparator className="mx-1! my-2.5! h-0! border-t border-border/70 bg-transparent! dark:border-white/15" />+ }+ if (item.id === "darkMode") {+ return (+ <DropdownMenuItem+ key={item.id}+ ref={anchorRef as React.Ref<HTMLDivElement>}+ onSelect={(e) => { e.preventDefault(); toggleTheme(); }}+ >+ {isDark ? <HugeiconsIcon icon={Sun03Icon} strokeWidth={1.75} className="size-icon" /> : <Moon strokeWidth={1.75} className="size-icon" />}+ <span>+ {isDark+ ? t("shell.navigation.lightMode")+ : t("shell.navigation.darkMode")}+ </span>+ </DropdownMenuItem>+ );+ }+ if (item.id === "guidedTour") {+ if (!getTourId(pathname)) return null;+ return (+ <DropdownMenuItem+ key={item.id}+ onSelect={() => {+ const tourId = getTourId(pathname);+ if (!tourId) return;+ window.dispatchEvent(+ new CustomEvent(TOUR_OPEN_EVENT, {+ detail: { id: tourId },+ }),+ );+ }}+ >+ <HugeiconsIcon icon={CursorInfo02Icon} strokeWidth={1.75} className="size-icon" />+ <span>{t("shell.navigation.guidedTour")}</span>+ </DropdownMenuItem>+ );+ }+ // Remaining ids are settings tabs shown by their tab name.+ const settingsTabId = item.id;+ const tab = SETTINGS_TAB_MENU_ITEMS[settingsTabId];+ return (+ <DropdownMenuItem+ key={item.id}+ onSelect={() => useSettingsDialogStore.getState().openDialog(settingsTabId)}+ >+ <HugeiconsIcon icon={tab.icon} strokeWidth={1.75} className="size-icon" />+ <span>{t(tab.labelKey)}</span>+ </DropdownMenuItem>+ );+ })}+ </DropdownMenuGroup>+ <DropdownMenuSeparator className="mx-1! my-2.5! h-0! border-t border-border/70 bg-transparent! dark:border-white/15" />+ <DropdownMenuItem+ onSelect={() => useSettingsDialogStore.getState().openDialog("about")}+ >+ <HugeiconsIcon icon={HelpCircleIcon} strokeWidth={1.75} className="size-icon" />+ <span>{t("common.help")}</span>+ </DropdownMenuItem>+ {!isTauri && (<DropdownMenuItem- onSelect={() => useSettingsDialogStore.getState().openDialog("about")}+ onSelect={async () => {+ // Best-effort server revocation; ignore network errors so the local clear still runs.+ try {+ await logout();+ } catch {+ clearAuthTokens();+ }+ void navigate({ to: "/login" });+ }}>- <HugeiconsIcon icon={HelpCircleIcon} strokeWidth={1.75} className="size-icon" />- <span>{t("common.help")}</span>+ <HugeiconsIcon icon={Logout05Icon} strokeWidth={1.75} className="size-icon" />+ <span>{t("shell.navigation.logOut")}</span></DropdownMenuItem>- {!isTauri && (- <DropdownMenuItem- onSelect={async () => {- // Best-effort server revocation; ignore network errors so the local clear still runs.- try {- await logout();- } catch {- clearAuthTokens();- }- void navigate({ to: "/login" });- }}- >- <HugeiconsIcon icon={Logout05Icon} strokeWidth={1.75} className="size-icon" />- <span>{t("shell.navigation.logOut")}</span>- </DropdownMenuItem>- )}- {!isTauri && (- <DropdownMenuItem onSelect={() => setShutdownOpen(true)}>- <HugeiconsIcon icon={PowerIcon} strokeWidth={1.75} className="size-icon" />- <span>{t("common.shutdown")}</span>- </DropdownMenuItem>- )}- </DropdownMenuContent>- </DropdownMenu>+ )}+ {!isTauri && (+ <DropdownMenuItem onSelect={() => setShutdownOpen(true)}>+ <HugeiconsIcon icon={PowerIcon} strokeWidth={1.75} className="size-icon" />+ <span>{t("common.shutdown")}</span>+ </DropdownMenuItem>+ )}+ </NonModalDropdownMenu>{/* settings cog; sibling of the trigger (buttons cannot nest),overlaid on the row's right edge, opens settings directly */}<buttondiff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 12d59afdb6d..2916dd45e88 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -251,6 +251,7 @@ import { applyQwenThinkingParams } from "@/features/chat/utils/qwen-params";import { isTauri } from "@/lib/api-base";import { copyToClipboard } from "@/lib/copy-to-clipboard";import { MenuDismissGuard } from "@/lib/menu-dismiss-guard";+import { NonModalDropdownMenu } from "@/components/ui/non-modal-dropdown-menu";import { MicIcon } from "@/lib/mic-icon";import { downloadFile, isDownloadCancelled } from "@/lib/native-files";import { toast } from "@/lib/toast";@@ -5289,9 +5290,14 @@ const ReasoningToggle: FC<{ side?: "top" | "bottom" }> = ({if (useDropdown) {return (- <DropdownMenu>- <DropdownMenuTrigger asChild={true}>+ <NonModalDropdownMenu+ side={side}+ align="end"+ avoidCollisions={true}+ className="unsloth-plus-menu unsloth-thinking-menu min-w-0 w-[176px]"+ trigger={(triggerRef) => (<button+ ref={triggerRef}type="button"disabled={disabled}className="unsloth-thinking-pill"@@ -5311,126 +5317,120 @@ const ReasoningToggle: FC<{ side?: "top" | "bottom" }> = ({) : null}<ChevronDownIcon strokeWidth={1.5} className="unsloth-thinking-caret size-[15px]" /></button>- </DropdownMenuTrigger>- <DropdownMenuContent- side={side}- align="end"- avoidCollisions={true}- className="unsloth-plus-menu unsloth-thinking-menu min-w-0 w-[176px]"- >- {isEffort ? (- <>- {effectiveSupportsReasoningOff && (- <DropdownMenuItem- onSelect={() => {- setReasoningEnabled(false);- applyQwenThinkingParams(false);- // Preserve thinking needs thinking on, so turn it off too.- setPreserveThinking(false);- }}- >- <HugeiconsIcon- icon={Tick02Icon}- strokeWidth={2}- className={cn(- "unsloth-tick size-4",- effectiveReasoningVisualEnabled && "opacity-0",- )}- />- None- </DropdownMenuItem>- )}- {effectiveReasoningEffortLevels- // 'none' is a real template level for models like Inkling- // (effort 0 = thinking off); show it as a pick unless the- // dedicated off item above already covers it.- .filter(- (level) =>- level !== "none" || !effectiveSupportsReasoningOff,- )- .map((level) => (- <DropdownMenuItem- key={level}- onSelect={() => {- setReasoningEffort(level);- setReasoningEnabled(true);- applyQwenThinkingParams(true);- // Kimi's $web_search builtin forbids thinking, so- // enabling thinking flips the Search pill off.- if (isKimiExternal && toolsEnabled) {- setToolsEnabled(false, { persist: false });- }- }}- >- <HugeiconsIcon- icon={Tick02Icon}- strokeWidth={2}- className={cn(- "unsloth-tick size-4",- !(- effectiveReasoningVisualEnabled &&- reasoningEffort === level- ) && "opacity-0",- )}- />- {formatEffortLabel(level)}- </DropdownMenuItem>- ))}- </>- ) : (- effectiveSupportsReasoningOff &&- !reasoningLockedOn && (+ )}+ >+ {isEffort ? (+ <>+ {effectiveSupportsReasoningOff && (<DropdownMenuItemonSelect={() => {- const next = !reasoningEnabled;- setReasoningEnabled(next);- applyQwenThinkingParams(next);- // Preserve thinking cannot run without thinking.- if (!next) setPreserveThinking(false);- if (isKimiExternal && next && toolsEnabled) {- setToolsEnabled(false, { persist: false });- }+ setReasoningEnabled(false);+ applyQwenThinkingParams(false);+ // Preserve thinking needs thinking on, so turn it off too.+ setPreserveThinking(false);}}><HugeiconsIcon- icon={Tick02Icon}- strokeWidth={2}+ icon={Tick02Icon}+ strokeWidth={2}className={cn("unsloth-tick size-4",- !effectiveReasoningEnabled && "opacity-0",+ effectiveReasoningVisualEnabled && "opacity-0",)}/>- Thinking+ None</DropdownMenuItem>- )- )}- {supportsPreserveThinking && (+ )}+ {effectiveReasoningEffortLevels+ // 'none' is a real template level for models like Inkling+ // (effort 0 = thinking off); show it as a pick unless the+ // dedicated off item above already covers it.+ .filter(+ (level) =>+ level !== "none" || !effectiveSupportsReasoningOff,+ )+ .map((level) => (+ <DropdownMenuItem+ key={level}+ onSelect={() => {+ setReasoningEffort(level);+ setReasoningEnabled(true);+ applyQwenThinkingParams(true);+ // Kimi's $web_search builtin forbids thinking, so+ // enabling thinking flips the Search pill off.+ if (isKimiExternal && toolsEnabled) {+ setToolsEnabled(false, { persist: false });+ }+ }}+ >+ <HugeiconsIcon+ icon={Tick02Icon}+ strokeWidth={2}+ className={cn(+ "unsloth-tick size-4",+ !(+ effectiveReasoningVisualEnabled &&+ reasoningEffort === level+ ) && "opacity-0",+ )}+ />+ {formatEffortLabel(level)}+ </DropdownMenuItem>+ ))}+ </>+ ) : (+ effectiveSupportsReasoningOff &&+ !reasoningLockedOn && (<DropdownMenuItem- disabled={disabled}- onSelect={(e) => {- e.preventDefault();- const next = !preserveThinking;- setPreserveThinking(next);- // Preserve thinking requires thinking on.- if (next) {- setReasoningEnabled(true);- applyQwenThinkingParams(true);+ onSelect={() => {+ const next = !reasoningEnabled;+ setReasoningEnabled(next);+ applyQwenThinkingParams(next);+ // Preserve thinking cannot run without thinking.+ if (!next) setPreserveThinking(false);+ if (isKimiExternal && next && toolsEnabled) {+ setToolsEnabled(false, { persist: false });}}}><HugeiconsIcon- icon={Tick02Icon}- strokeWidth={2}+ icon={Tick02Icon}+ strokeWidth={2}className={cn("unsloth-tick size-4",- !preserveThinking && "opacity-0",+ !effectiveReasoningEnabled && "opacity-0",)}/>- Preserve thinking+ Thinking</DropdownMenuItem>- )}- </DropdownMenuContent>- </DropdownMenu>+ )+ )}+ {supportsPreserveThinking && (+ <DropdownMenuItem+ disabled={disabled}+ onSelect={(e) => {+ e.preventDefault();+ const next = !preserveThinking;+ setPreserveThinking(next);+ // Preserve thinking requires thinking on.+ if (next) {+ setReasoningEnabled(true);+ applyQwenThinkingParams(true);+ }+ }}+ >+ <HugeiconsIcon+ icon={Tick02Icon}+ strokeWidth={2}+ className={cn(+ "unsloth-tick size-4",+ !preserveThinking && "opacity-0",+ )}+ />+ Preserve thinking+ </DropdownMenuItem>+ )}+ </NonModalDropdownMenu>);}diff --git a/studio/frontend/src/components/ui/non-modal-dropdown-menu.tsx b/studio/frontend/src/components/ui/non-modal-dropdown-menu.tsxnew file mode 100644index 00000000000..62a59489365--- /dev/null+++ b/studio/frontend/src/components/ui/non-modal-dropdown-menu.tsx@@ -0,0 +1,78 @@+// 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 { ComponentProps, ReactNode, RefObject } from "react";+import { useEffect, useRef, useState } from "react";++import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { MenuDismissGuard } from "@/lib/menu-dismiss-guard";++/** A dropdown that leaves `<body>` alone: modal writes an inherited `pointer-events` there, so+ * every open restyles the whole subtree. `trigger` takes the ref so a per-row menu owns one. */+export function NonModalDropdownMenu({+ trigger,+ children,+ onCloseAutoFocus,+ ...contentProps+}: {+ trigger: (ref: RefObject<HTMLButtonElement | null>) => ReactNode;+ children: ReactNode;+} & ComponentProps<typeof DropdownMenuContent>) {+ const triggerRef = useRef<HTMLButtonElement>(null);+ // Gates the guard. The content animates out, so it outlives the close, and a mount-scoped+ // guard left watching `document` swallows the next click the user makes.+ const [open, setOpen] = useState(false);+ // Nothing locks scroll here, and Radix pins the content to the viewport edge once the trigger+ // scrolls out, leaving a menu acting on a row the user cannot see. Close on a scroll of a+ // trigger ancestor; the menu's own viewport does not contain it, so it scrolls untouched.+ const closedByScroll = useRef(false);+ useEffect(() => {+ if (!open) return;+ const onScroll = (event: Event) => {+ const trigger = triggerRef.current;+ const target = event.target;+ if (!trigger || !(target instanceof Node) || !target.contains(trigger)) return;+ closedByScroll.current = true;+ setOpen(false);+ };+ document.addEventListener("scroll", onScroll, { capture: true, passive: true });+ return () => document.removeEventListener("scroll", onScroll, { capture: true });+ }, [open]);+ return (+ <DropdownMenu modal={false} open={open} onOpenChange={setOpen}>+ <DropdownMenuTrigger asChild={true}>+ {trigger(triggerRef)}+ </DropdownMenuTrigger>+ <DropdownMenuContent+ {...contentProps}+ // Focus alone: returning it would scroll the trigger back and undo the closing scroll.+ onCloseAutoFocus={(event) => {+ onCloseAutoFocus?.(event);+ if (!closedByScroll.current) return;+ closedByScroll.current = false;+ if (event.defaultPrevented) return;+ event.preventDefault();+ // The content stays mounted for the exit animation, so the user can click into+ // something else before this runs. Radix's own restore checks that; preventing+ // its default skips the check, so make it here or the trigger steals the caret.+ const active = document.activeElement;+ const claimedByTheUser =+ active !== null &&+ active !== document.body &&+ active !== document.documentElement &&+ active.closest("[data-slot='dropdown-menu-content']") === null;+ if (claimedByTheUser) return;+ triggerRef.current?.focus({ preventScroll: true });+ }}+ >+ {/* Arming survives this unmount: `arm` registers on `document`. */}+ {open ? <MenuDismissGuard triggerRef={triggerRef} /> : null}+ {children}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex aed78fc9bb8..e19d58383b2 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -22,15 +22,13 @@ import { ProjectComposer, Thread } from "@/components/assistant-ui/thread";import { usePlatformStore } from "@/config/env";import { CopyableErrorChip } from "@/components/ui/copyable-error-chip";import {- DropdownMenu,- DropdownMenuContent,DropdownMenuItem,DropdownMenuSeparator,DropdownMenuSub,DropdownMenuSubContent,DropdownMenuSubTrigger,- DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";+import { NonModalDropdownMenu } from "@/components/ui/non-modal-dropdown-menu";import {AlertDialog,AlertDialogAction,@@ -1722,61 +1720,60 @@ function ProjectLanding({<h1 className="min-w-0 flex-1 truncate font-sans text-ui-30 font-medium leading-tight tracking-normal text-foreground">{projectName}</h1>- <DropdownMenu>- <DropdownMenuTrigger asChild={true}>+ <NonModalDropdownMenu+ side="bottom"+ align="end"+ sideOffset={6}+ className="unsloth-plus-menu menu-flat-destructive w-52"+ trigger={(triggerRef) => (<button+ ref={triggerRef}type="button"aria-label="Project options"className="inline-flex size-9 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[state=open]:bg-muted data-[state=open]:text-foreground"><HugeiconsIcon icon={MoreHorizontalIcon} strokeWidth={1.75} className="size-5" /></button>- </DropdownMenuTrigger>- <DropdownMenuContent- side="bottom"- align="end"- sideOffset={6}- className="unsloth-plus-menu menu-flat-destructive w-52"+ )}+ >+ <DropdownMenuItem+ onSelect={() => {+ setProjectNameDraft(projectName);+ setRenamingProject(true);+ }}>- <DropdownMenuItem- onSelect={() => {- setProjectNameDraft(projectName);- setRenamingProject(true);- }}- >- <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />- <span>Rename project</span>- </DropdownMenuItem>- <DropdownMenuItem onSelect={() => togglePinProject(projectId)}>- <HugeiconsIcon icon={projectPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />- <span>{projectPinned ? "Unpin project" : "Pin project"}</span>- </DropdownMenuItem>- <DropdownMenuSub>- <DropdownMenuSubTrigger>- <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-icon" />- <span>Export</span>- </DropdownMenuSubTrigger>- <DropdownMenuSubContent className="unsloth-plus-menu w-48">- {PROJECT_CHAT_EXPORT_OPTIONS.map(({ label, format }) => (- <DropdownMenuItem- key={format}- onSelect={() => void handleProjectExport(format)}- >- {label}- </DropdownMenuItem>- ))}- </DropdownMenuSubContent>- </DropdownMenuSub>- <DropdownMenuSeparator />- <DropdownMenuItem- variant="destructive"- onSelect={() => setDeletingProject(true)}- >- <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />- <span>Delete project</span>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />+ <span>Rename project</span>+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => togglePinProject(projectId)}>+ <HugeiconsIcon icon={projectPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />+ <span>{projectPinned ? "Unpin project" : "Pin project"}</span>+ </DropdownMenuItem>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-icon" />+ <span>Export</span>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="unsloth-plus-menu w-48">+ {PROJECT_CHAT_EXPORT_OPTIONS.map(({ label, format }) => (+ <DropdownMenuItem+ key={format}+ onSelect={() => void handleProjectExport(format)}+ >+ {label}+ </DropdownMenuItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ onSelect={() => setDeletingProject(true)}+ >+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />+ <span>Delete project</span>+ </DropdownMenuItem>+ </NonModalDropdownMenu></div><ProjectComposer@@ -1897,9 +1894,14 @@ function ProjectLanding({formatProjectChatDate(item.createdAt)}</span></button>- <DropdownMenu>- <DropdownMenuTrigger asChild>+ <NonModalDropdownMenu+ side="bottom"+ align="end"+ sideOffset={4}+ className="unsloth-plus-menu menu-flat-destructive w-56"+ trigger={(triggerRef) => (<button+ ref={triggerRef}type="button"onClick={(event) => event.stopPropagation()}aria-label="Chat options"@@ -1911,133 +1913,127 @@ function ProjectLanding({className="size-icon"/></button>- </DropdownMenuTrigger>- <DropdownMenuContent- side="bottom"- align="end"- sideOffset={4}- className="unsloth-plus-menu menu-flat-destructive w-56"+ )}+ >+ <DropdownMenuItem onSelect={() => openRename(item)}>+ <HugeiconsIcon+ icon={Edit03Icon}+ strokeWidth={1.75}+ className="size-icon"+ />+ <span>Rename</span>+ </DropdownMenuItem>+ <DropdownMenuItem+ onSelect={() => togglePinnedChat(item.id)}>- <DropdownMenuItem onSelect={() => openRename(item)}>+ <HugeiconsIcon+ icon={+ pinnedChatIdSet.has(item.id)+ ? PinOffIcon+ : PinIcon+ }+ strokeWidth={1.75}+ className="size-icon"+ />+ <span>+ {pinnedChatIdSet.has(item.id)+ ? "Unpin chat"+ : "Pin chat"}+ </span>+ </DropdownMenuItem>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger><HugeiconsIcon- icon={Edit03Icon}+ icon={FolderExportIcon}strokeWidth={1.75}className="size-icon"/>- <span>Rename</span>- </DropdownMenuItem>- <DropdownMenuItem- onSelect={() => togglePinnedChat(item.id)}- >- <HugeiconsIcon- icon={- pinnedChatIdSet.has(item.id)- ? PinOffIcon- : PinIcon+ <span>Move to project</span>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="unsloth-plus-menu w-52">+ <DropdownMenuItem+ disabled={item.projectId !== projectId}+ onSelect={() =>+ void handleMoveToProject(item, null)}- strokeWidth={1.75}- className="size-icon"- />- <span>- {pinnedChatIdSet.has(item.id)- ? "Unpin chat"- : "Pin chat"}- </span>- </DropdownMenuItem>- <DropdownMenuSub>- <DropdownMenuSubTrigger>- <HugeiconsIcon- icon={FolderExportIcon}- strokeWidth={1.75}- className="size-icon"- />- <span>Move to project</span>- </DropdownMenuSubTrigger>- <DropdownMenuSubContent className="unsloth-plus-menu w-52">+ >+ <span>Recents</span>+ </DropdownMenuItem>+ {projects.map((p) => (<DropdownMenuItem- disabled={item.projectId !== projectId}+ key={p.id}+ disabled={item.projectId === p.id}onSelect={() =>- void handleMoveToProject(item, null)+ void handleMoveToProject(item, p.id)}>- <span>Recents</span>+ <HugeiconsIcon+ icon={Folder01Icon}+ strokeWidth={1.75}+ className="size-icon"+ />+ <span className="truncate">{p.name}</span></DropdownMenuItem>- {projects.map((p) => (+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <HugeiconsIcon+ icon={Download01Icon}+ strokeWidth={1.75}+ className="size-icon"+ />+ <span>Export</span>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="unsloth-plus-menu w-52">+ {PROJECT_CHAT_EXPORT_OPTIONS.map(+ ({ label, format }) => (<DropdownMenuItem- key={p.id}- disabled={item.projectId === p.id}+ key={format}onSelect={() =>- void handleMoveToProject(item, p.id)+ void handleExport(item, format)}>- <HugeiconsIcon- icon={Folder01Icon}- strokeWidth={1.75}- className="size-icon"- />- <span className="truncate">{p.name}</span>+ {label}</DropdownMenuItem>- ))}- </DropdownMenuSubContent>- </DropdownMenuSub>- <DropdownMenuSub>- <DropdownMenuSubTrigger>- <HugeiconsIcon- icon={Download01Icon}- strokeWidth={1.75}- className="size-icon"- />- <span>Export</span>- </DropdownMenuSubTrigger>- <DropdownMenuSubContent className="unsloth-plus-menu w-52">- {PROJECT_CHAT_EXPORT_OPTIONS.map(- ({ label, format }) => (- <DropdownMenuItem- key={format}- onSelect={() =>- void handleExport(item, format)- }- >- {label}- </DropdownMenuItem>- ),- )}- </DropdownMenuSubContent>- </DropdownMenuSub>- <DropdownMenuItem- onSelect={() => void handleSaveAsSource(item)}- >- <HugeiconsIcon- icon={BookOpen01Icon}- strokeWidth={1.75}- className="size-icon"- />- <span>Save to project sources</span>- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem- onSelect={() => void handleArchive(item)}- >- <HugeiconsIcon- icon={Archive03Icon}- strokeWidth={1.75}- className="size-icon"- />- <span>Archive</span>- </DropdownMenuItem>- <DropdownMenuItem- variant="destructive"- onSelect={() => handleDelete(item)}- >- <HugeiconsIcon- icon={Delete02Icon}- strokeWidth={1.75}- className="size-icon"- />- <span>Delete</span>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ ),+ )}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuItem+ onSelect={() => void handleSaveAsSource(item)}+ >+ <HugeiconsIcon+ icon={BookOpen01Icon}+ strokeWidth={1.75}+ className="size-icon"+ />+ <span>Save to project sources</span>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onSelect={() => void handleArchive(item)}+ >+ <HugeiconsIcon+ icon={Archive03Icon}+ strokeWidth={1.75}+ className="size-icon"+ />+ <span>Archive</span>+ </DropdownMenuItem>+ <DropdownMenuItem+ variant="destructive"+ onSelect={() => handleDelete(item)}+ >+ <HugeiconsIcon+ icon={Delete02Icon}+ strokeWidth={1.75}+ className="size-icon"+ />+ <span>Delete</span>+ </DropdownMenuItem>+ </NonModalDropdownMenu></div>);})}diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex 33c403d0548..05c9ac32f69 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -28,6 +28,7 @@ import {DropdownMenuSubTrigger,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";+import { NonModalDropdownMenu } from "@/components/ui/non-modal-dropdown-menu";import { applyQwenThinkingParams } from "@/features/chat/utils/qwen-params";import { FIND_SKIP_ATTRIBUTE } from "@/features/find-in-page";import { DRAFT_N_MAX_SPEC_TYPES } from "@/lib/speculative-modes";@@ -2566,9 +2567,16 @@ export function SharedComposer({<div className="ml-auto mr-0.5 flex items-center gap-1.5">{showReasoningControl ? (isEffort || supportsPreserveThinking ? (- <DropdownMenu>- <DropdownMenuTrigger asChild={true}>+ <NonModalDropdownMenu+ side="top"+ align="end"+ className={cn(+ "unsloth-plus-menu",+ narrowEffortMenu ? "min-w-40" : "min-w-44",+ )}+ trigger={(triggerRef) => (<button+ ref={triggerRef}type="button"disabled={reasoningDisabled}className="unsloth-thinking-pill"@@ -2593,129 +2601,121 @@ export function SharedComposer({) : null}<ChevronDownIcon strokeWidth={1.5} className="unsloth-thinking-caret size-[15px]" /></button>- </DropdownMenuTrigger>- <DropdownMenuContent- side="top"- align="end"- className={cn(- "unsloth-plus-menu",- narrowEffortMenu ? "min-w-40" : "min-w-44",- )}- >- {isEffort ? (- <>- {effectiveSupportsReasoningOff && (+ )}+ >+ {isEffort ? (+ <>+ {effectiveSupportsReasoningOff && (+ <DropdownMenuItem+ onSelect={() => {+ setReasoningEnabled(false);+ applyQwenThinkingParams(false);+ // Preserve thinking needs thinking on, so turn it off too.+ setPreserveThinking(false);+ }}+ >+ <HugeiconsIcon+ icon={Tick02Icon}+ strokeWidth={2}+ className={cn(+ "unsloth-tick size-4",+ effectiveReasoningVisualEnabled && "opacity-0",+ )}+ />+ {formatReasoningDisabledLabel(+ effectiveSupportsReasoningOff,+ isExternalOpenAIReasoning,+ checkpoint,+ )}+ </DropdownMenuItem>+ )}+ {effectiveReasoningEffortLevels+ .filter((level) => level !== "none")+ .map((level) => (<DropdownMenuItem+ key={level}onSelect={() => {- setReasoningEnabled(false);- applyQwenThinkingParams(false);- // Preserve thinking needs thinking on, so turn it off too.- setPreserveThinking(false);+ setReasoningEffort(level);+ setReasoningEnabled(true);+ applyQwenThinkingParams(true);+ // Mutual exclusion: turning thinking on for a Kimi model forces its+ // web_search builtin off.+ if (isKimiExternal && toolsEnabled) {+ setToolsEnabled(false, { persist: false });+ }}}><HugeiconsIcon- icon={Tick02Icon}- strokeWidth={2}+ icon={Tick02Icon}+ strokeWidth={2}className={cn("unsloth-tick size-4",- effectiveReasoningVisualEnabled && "opacity-0",+ !(+ effectiveReasoningVisualEnabled &&+ reasoningEffort === level+ ) && "opacity-0",)}/>- {formatReasoningDisabledLabel(- effectiveSupportsReasoningOff,- isExternalOpenAIReasoning,- checkpoint,+ {formatReasoningEffortLabel(+ level,+ externalSelection?.modelId,)}</DropdownMenuItem>- )}- {effectiveReasoningEffortLevels- .filter((level) => level !== "none")- .map((level) => (- <DropdownMenuItem- key={level}- onSelect={() => {- setReasoningEffort(level);- setReasoningEnabled(true);- applyQwenThinkingParams(true);- // Mutual exclusion: turning thinking on for a Kimi model forces its- // web_search builtin off.- if (isKimiExternal && toolsEnabled) {- setToolsEnabled(false, { persist: false });- }- }}- >- <HugeiconsIcon- icon={Tick02Icon}- strokeWidth={2}- className={cn(- "unsloth-tick size-4",- !(- effectiveReasoningVisualEnabled &&- reasoningEffort === level- ) && "opacity-0",- )}- />- {formatReasoningEffortLabel(- level,- externalSelection?.modelId,- )}- </DropdownMenuItem>- ))}- </>- ) : (- effectiveSupportsReasoningOff &&- !reasoningLockedOn && (- <DropdownMenuItem- onSelect={() => {- const next = !reasoningEnabled;- setReasoningEnabled(next);- applyQwenThinkingParams(next);- // Preserve thinking cannot run without thinking.- if (!next) setPreserveThinking(false);- if (isKimiExternal && next && toolsEnabled) {- setToolsEnabled(false, { persist: false });- }- }}- >- <HugeiconsIcon- icon={Tick02Icon}- strokeWidth={2}- className={cn(- "unsloth-tick size-4",- !effectiveReasoningEnabled && "opacity-0",- )}- />- Thinking- </DropdownMenuItem>- )- )}- {supportsPreserveThinking && (+ ))}+ </>+ ) : (+ effectiveSupportsReasoningOff &&+ !reasoningLockedOn && (<DropdownMenuItem- disabled={!modelLoaded}- onSelect={(e) => {- e.preventDefault();- const next = !preserveThinking;- setPreserveThinking(next);- // Preserve thinking requires thinking on.- if (next) {- setReasoningEnabled(true);- applyQwenThinkingParams(true);+ onSelect={() => {+ const next = !reasoningEnabled;+ setReasoningEnabled(next);+ applyQwenThinkingParams(next);+ // Preserve thinking cannot run without thinking.+ if (!next) setPreserveThinking(false);+ if (isKimiExternal && next && toolsEnabled) {+ setToolsEnabled(false, { persist: false });}}}><HugeiconsIcon- icon={Tick02Icon}- strokeWidth={2}+ icon={Tick02Icon}+ strokeWidth={2}className={cn("unsloth-tick size-4",- !preserveThinking && "opacity-0",+ !effectiveReasoningEnabled && "opacity-0",)}/>- Preserve thinking+ Thinking</DropdownMenuItem>- )}- </DropdownMenuContent>- </DropdownMenu>+ )+ )}+ {supportsPreserveThinking && (+ <DropdownMenuItem+ disabled={!modelLoaded}+ onSelect={(e) => {+ e.preventDefault();+ const next = !preserveThinking;+ setPreserveThinking(next);+ // Preserve thinking requires thinking on.+ if (next) {+ setReasoningEnabled(true);+ applyQwenThinkingParams(true);+ }+ }}+ >+ <HugeiconsIcon+ icon={Tick02Icon}+ strokeWidth={2}+ className={cn(+ "unsloth-tick size-4",+ !preserveThinking && "opacity-0",+ )}+ />+ Preserve thinking+ </DropdownMenuItem>+ )}+ </NonModalDropdownMenu>) : (<buttontype="button"diff --git a/studio/frontend/tests/chat-menus-nonmodal.test.ts b/studio/frontend/tests/chat-menus-nonmodal.test.tsnew file mode 100644index 00000000000..11d57a38c0c--- /dev/null+++ b/studio/frontend/tests/chat-menus-nonmodal.test.ts@@ -0,0 +1,122 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The menus a long chat opens constantly must not be modal: the scroll lock and the inherited+// `pointer-events` write cost a pause and a layout shift that scale with the thread. Parsed+// rather than scanned, or re-modalising in any other spelling reads as untouched.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import ts from "typescript";++/** Keyed by a marker on the menu's trigger. */+const NON_MODAL = [+ ["components/assistant-ui/thread.tsx", "thinkEffortAriaLabel({"],+ ["components/app-sidebar.tsx", "aria-label={options.ariaLabel}"],+ ["components/app-sidebar.tsx", 'aria-label="Chat options"'],+ ["components/app-sidebar.tsx", 'aria-label="Project options"'],+ ["components/app-sidebar.tsx", 't("shell.aria.runOptions")'],+ ["components/app-sidebar.tsx", 't("shell.accountMenu"'],+ ["features/chat/chat-page.tsx", 'aria-label="Project options"'],+ ["features/chat/chat-page.tsx", 'aria-label="Chat options"'],+ ["features/chat/shared-composer.tsx", "thinkEffortAriaLabel({"],+] as const;++/** Both spellings of a menu root, so the enclosing one is found whichever it is. */+const MENU_ROOTS = new Set(["NonModalDropdownMenu", "DropdownMenu"]);++const parse = (relative: string): ts.SourceFile =>+ ts.createSourceFile(+ relative,+ readFileSync(new URL(`../src/${relative}`, import.meta.url), "utf8"),+ ts.ScriptTarget.ESNext,+ true,+ ts.ScriptKind.TSX,+ );++const tagOf = (node: ts.Node): string | undefined =>+ ts.isJsxElement(node)+ ? node.openingElement.tagName.getText()+ : ts.isJsxSelfClosingElement(node)+ ? node.tagName.getText()+ : undefined;++/** The innermost menu root containing `position`, by tag name. */+function enclosingMenuRoot(+ source: ts.SourceFile,+ position: number,+): string | undefined {+ let found: string | undefined;+ const visit = (node: ts.Node): void => {+ if (node.getStart() > position || node.getEnd() < position) return;+ const tag = tagOf(node);+ if (tag && MENU_ROOTS.has(tag)) found = tag;+ ts.forEachChild(node, visit);+ };+ ts.forEachChild(source, visit);+ return found;+}++for (const [file, marker] of NON_MODAL) {+ test(`${file}: the menu at ${marker} is non-modal`, () => {+ const source = parse(file);+ // Every occurrence: a second copy of the same trigger is how one drifts back unnoticed.+ const positions: number[] = [];+ for (let at = source.text.indexOf(marker); at !== -1; ) {+ positions.push(at);+ at = source.text.indexOf(marker, at + marker.length);+ }+ assert.ok(+ positions.length > 0,+ "marker not found; the menu moved or was renamed",+ );+ for (const at of positions) {+ const root = enclosingMenuRoot(source, at);+ assert.ok(root, `no menu root encloses ${marker}`);+ assert.equal(+ root,+ "NonModalDropdownMenu",+ `this trigger sits inside <${root}>; a modal menu locks body scroll and ` ++ "aria-hides the document on every open",+ );+ }+ });+}++test("NonModalDropdownMenu is non-modal and guards its own dismissal", () => {+ const source = parse("components/ui/non-modal-dropdown-menu.tsx");+ const text = source.text;+ assert.match(text, /<DropdownMenu[^>]*\bmodal=\{false\}/);+ assert.match(text, /<MenuDismissGuard triggerRef=\{triggerRef\} \/>/);+ // Each mount owns its ref, or a per-row menu restores focus to another row's trigger.+ assert.match(text, /const triggerRef = useRef<HTMLButtonElement>\(null\)/);+ assert.match(text, /trigger\(triggerRef\)/);+});++test("the dismiss guard is mounted only while the menu is open", () => {+ // The content outlives the close by its exit animation, and an ungated guard left watching+ // `document` swallows the next click the user makes anywhere on the page.+ const source = parse("components/ui/non-modal-dropdown-menu.tsx");+ const text = source.text;+ assert.match(+ text,+ /\{open \? <MenuDismissGuard triggerRef=\{triggerRef\} \/> : null\}/,+ "the guard must be gated on the open state, not mounted for the content's lifetime",+ );+ assert.match(+ text,+ /<DropdownMenu[^>]*\bonOpenChange=\{setOpen\}/,+ "the open state must come from the menu itself",+ );+});++test("the menu content still animates out, which is why the guard is gated", () => {+ // Without the animation the gate above is merely harmless; revisit it rather than drop it.+ const content = readFileSync(+ new URL("../src/components/ui/dropdown-menu.tsx", import.meta.url),+ "utf8",+ );+ assert.match(content, /data-closed:animate-out/);+});diff --git a/tests/studio/playwright_nonmodal_menus.py b/tests/studio/playwright_nonmodal_menus.pynew file mode 100644index 00000000000..35a416d220e--- /dev/null+++ b/tests/studio/playwright_nonmodal_menus.py@@ -0,0 +1,470 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Browser checks for NonModalDropdownMenu, driven against smoke-nonmodal-menus.html.++The AST tests pin which menus use the wrapper; only a browser answers what it then does to a+scroll behind an open menu, to the dismissing click and to focus. Each has regressed once+already (#9243, #9772, and twice inside the change that added the wrapper).++The page also mounts one UNCONVERTED modal menu, the shape every converted one had before, so+a case behaving the same on both is Radix and not this wrapper, and the lock it still writes+to <body> proves the probe can see a lock at all.++ PW_ENGINE=webkit python3 tests/studio/playwright_nonmodal_menus.py+"""++from __future__ import annotations++import json+import os+import sys+from pathlib import Path++from playwright.sync_api import sync_playwright++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _playwright_robust import ( # noqa: E402+ chromium_launch_args,+ start_vite,+ stop_process,+ wait_for_smoke_page,+)++ENGINE = os.environ.get("PW_ENGINE", "chromium")+PORT = int(os.environ.get("PW_PORT", "5401"))+OUT = Path(os.environ.get("PW_OUT", "logs/nonmodal_menus_report.json"))+ENTRY = "/smoke-nonmodal-menus-main.tsx"+PAGE = "/smoke-nonmodal-menus.html"++# Both sides of the `duration-100` exit window: a guard outliving the close swallows the+# next click.+EXIT_WINDOW_MS = (30, 75, 125)+++class Checks:+ def __init__(self) -> None:+ self.results: list[dict[str, object]] = []++ def record(+ self,+ name: str,+ ok: bool,+ detail: object = "",+ ) -> None:+ self.results.append({"case": name, "ok": bool(ok), "detail": detail})+ print(f"{'PASS' if ok else 'FAIL'} {name} {detail}", flush = True)++ @property+ def failed(self) -> list[dict[str, object]]:+ return [r for r in self.results if not r["ok"]]+++def menus_open(page) -> int:+ return page.locator("[role=menu]").count()+++def state(page) -> dict:+ return page.evaluate("() => window.probe.documentState()")+++def open_row(page, row: int) -> None:+ page.get_by_label(f"Row options {row}", exact = True).click()+ page.wait_for_selector("[role=menu]", state = "visible")+++def open_control(page) -> None:+ page.get_by_label("Control options", exact = True).click()+ page.wait_for_selector("[role=menu]", state = "visible")+++def raw_click(page, selector: str) -> None:+ """A real pointer press at the element's centre, with no actionability wait.++ A modal menu puts `pointer-events: none` on <body>, so Playwright's own click refuses to act+ there; the control arm has to bypass that to be measurable at all.+ """+ box = page.locator(selector).bounding_box()+ if box is None:+ raise RuntimeError(f"{selector} has no box")+ page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)+++def close_all(page) -> None:+ for _ in range(6):+ if menus_open(page) == 0:+ return+ page.keyboard.press("Escape")+ page.wait_for_timeout(200)+++def reset_list(page) -> None:+ page.evaluate("() => { document.getElementById('list').scrollTop = 0; }")+ page.wait_for_timeout(250)+++def check_document_is_untouched(page, checks: Checks) -> None:+ baseline = state(page)+ open_row(page, 0)+ opened = state(page)+ checks.record(+ "opening a converted menu writes nothing to <body>",+ opened["bodyPointerEvents"] == "" and not opened["scrollLocked"],+ opened,+ )+ checks.record(+ "opening a converted menu aria-hides nothing new",+ opened["ariaHidden"] <= baseline["ariaHidden"],+ f"{baseline['ariaHidden']} -> {opened['ariaHidden']}",+ )+ close_all(page)++ open_control(page)+ control = state(page)+ checks.record(+ "the unconverted menu still locks the document, so the probe can see a lock",+ control["bodyPointerEvents"] == "none"+ and control["scrollLocked"]+ and control["ariaHidden"] > 0,+ control,+ )+ close_all(page)+++def check_scroll_closes(page, checks: Checks) -> None:+ reset_list(page)+ open_row(page, 1)+ page.mouse.move(120, 300)+ page.mouse.wheel(0, 400)+ page.wait_for_timeout(400)+ scrolled = page.evaluate("() => document.getElementById('list').scrollTop")+ checks.record("a wheel behind an open menu closes it", menus_open(page) == 0)+ checks.record("the list keeps the scroll the wheel gave it", scrolled > 0, scrolled)+ page.wait_for_timeout(300)+ settled = page.evaluate("() => document.getElementById('list').scrollTop")+ checks.record(+ "closing does not snap the list back to the trigger",+ settled == scrolled,+ f"{scrolled} -> {settled}",+ )++ reset_list(page)+ open_row(page, 2)+ page.evaluate("() => { document.getElementById('list').scrollTop = 500; }")+ page.wait_for_timeout(400)+ checks.record("a programmatic scroll closes the menu", menus_open(page) == 0)++ reset_list(page)+ open_row(page, 3)+ page.evaluate("() => document.getElementById('list').scrollBy({top: 200, behavior: 'smooth'})")+ page.wait_for_timeout(600)+ checks.record("a smooth scroll closes the menu", menus_open(page) == 0)++ reset_list(page)+ open_row(page, 6)+ page.evaluate("() => window.scrollTo(0, 200)")+ page.wait_for_timeout(400)+ checks.record("a window scroll closes the menu", menus_open(page) == 0)+ page.evaluate("() => window.scrollTo(0, 0)")+++def check_scrolls_that_must_not_close(page, checks: Checks) -> None:+ reset_list(page)+ page.get_by_label("Tall menu", exact = True).click()+ page.wait_for_selector("[role=menu]", state = "visible")+ page.evaluate(+ "() => { const v = document.querySelector('[data-slot=dropdown-menu-viewport]');"+ " v.scrollTop = 120; }"+ )+ page.wait_for_timeout(400)+ checks.record("scrolling the menu's own viewport leaves it open", menus_open(page) >= 1)+ close_all(page)++ open_row(page, 4)+ page.evaluate("() => { document.getElementById('other').scrollTop = 300; }")+ page.wait_for_timeout(400)+ checks.record("scrolling an unrelated list leaves the menu open", menus_open(page) >= 1)+ close_all(page)++ open_row(page, 5)+ page.get_by_test_id("export-5").click()+ page.wait_for_timeout(400)+ with_sub = menus_open(page)+ page.evaluate(+ "() => { const vs = document.querySelectorAll('[data-slot=dropdown-menu-viewport]');"+ " vs[vs.length - 1].scrollTop = 100; }"+ )+ page.wait_for_timeout(400)+ checks.record(+ "scrolling an open submenu leaves both menus open",+ with_sub >= 2 and menus_open(page) == with_sub,+ f"{with_sub} -> {menus_open(page)}",+ )+ close_all(page)+++def check_dismiss_guard(page, checks: Checks) -> None:+ # Reset the counter AFTER opening: the click that opens a menu reaches document too.+ open_row(page, 7)+ page.evaluate("() => window.probe.resetClicks()")+ raw_click(page, "#outside-button")+ page.wait_for_timeout(300)+ swallowed = page.evaluate("() => window.probe.documentClicks()")+ checks.record(+ "the click that dismisses a menu does not reach what is under it",+ menus_open(page) == 0 and swallowed == 0,+ f"clicks={swallowed}",+ )+ page.evaluate("() => window.probe.resetClicks()")+ raw_click(page, "#outside-button")+ page.wait_for_timeout(200)+ delivered = page.evaluate("() => window.probe.documentClicks()")+ checks.record("the click after that one is delivered", delivered == 1, delivered)++ for label, opener in (+ ("a converted menu", lambda: open_row(page, 8)),+ ("the unconverted control", lambda: open_control(page)),+ ):+ for delay in EXIT_WINDOW_MS:+ opener()+ page.keyboard.press("Escape")+ page.wait_for_timeout(delay)+ page.evaluate("() => window.probe.resetClicks()")+ raw_click(page, "#outside-button")+ page.wait_for_timeout(250)+ landed = page.evaluate("() => window.probe.documentClicks()")+ checks.record(+ f"a click {delay}ms after closing {label} is delivered", landed == 1, landed+ )+ close_all(page)++ # A non-modal menu lets the press reach the field before Radix restores the trigger, so+ # Firefox and WebKit keep the caret and Chromium does not. Either is usable; <body> is not.+ focus_after = {}+ for label, opener in (+ ("converted", lambda: open_row(page, 9)),+ ("control", lambda: open_control(page)),+ ):+ opener()+ raw_click(page, "#outside-input")+ page.wait_for_timeout(700)+ focus_after[label] = page.evaluate(+ "() => document.activeElement?.getAttribute('data-slot')"+ " ?? document.activeElement?.id ?? null"+ )+ close_all(page)+ checks.record(+ "dismissing into an input never drops focus onto the document",+ focus_after["converted"] in {"outside-input", "dropdown-menu-trigger"},+ focus_after,+ )+++def check_focus_return(page, checks: Checks) -> None:+ active = "() => document.activeElement?.getAttribute('aria-label')"+ close_all(page)+ reset_list(page)+ open_row(page, 10)+ page.keyboard.press("Escape")+ page.wait_for_timeout(300)+ checks.record(+ "Escape returns focus to the trigger that opened the menu",+ page.evaluate(active) == "Row options 10",+ page.evaluate(active),+ )++ # A scroll-close takes a different focus path. The flag that selects it must not survive+ # into the next close, or an ordinary Escape stops restoring focus.+ reset_list(page)+ open_row(page, 11)+ page.evaluate("() => { document.getElementById('list').scrollTop = 300; }")+ page.wait_for_timeout(400)+ reset_list(page)+ open_row(page, 12)+ page.keyboard.press("Escape")+ page.wait_for_timeout(300)+ checks.record(+ "a scroll-close does not change how the next Escape restores focus",+ page.evaluate(active) == "Row options 12",+ page.evaluate(active),+ )++ # The content stays mounted for the exit animation, so the user can click into something+ # else before the close-autofocus runs. Radix's own restore checks for that; the+ # scroll-close path prevents its default, so it has to make the same check itself or it+ # takes the caret back out of whatever was clicked.+ reset_list(page)+ open_row(page, 14)+ page.evaluate("() => { document.getElementById('list').scrollTop = 40; }")+ page.wait_for_timeout(20)+ raw_click(page, "#outside-input")+ page.wait_for_timeout(900)+ landed = page.evaluate(+ "() => document.activeElement?.getAttribute('data-slot')"+ " ?? document.activeElement?.id ?? null"+ )+ checks.record(+ "an input clicked while a scroll-closed menu animates out keeps the caret",+ landed == "outside-input",+ landed,+ )++ reset_list(page)+ open_row(page, 13)+ page.evaluate("() => { document.getElementById('list').scrollTop = 600; }")+ page.wait_for_timeout(500)+ checks.record(+ "a scroll-close keeps the scroll it was closed by",+ page.evaluate("() => document.getElementById('list').scrollTop") == 600,+ page.evaluate("() => document.getElementById('list').scrollTop"),+ )+++def check_keyboard(page, checks: Checks) -> None:+ # An on-screen trigger, focus settled: focusing an off-screen one scrolls it into view a+ # frame or two later, which races the open rather than testing it.+ reset_list(page)+ page.get_by_label("Row options 2", exact = True).focus()+ page.wait_for_timeout(250)+ page.keyboard.press("Enter")+ page.wait_for_timeout(300)+ checks.record("Enter opens the menu", menus_open(page) >= 1)+ page.keyboard.press("ArrowDown")+ page.keyboard.press("ArrowRight")+ page.wait_for_timeout(400)+ checks.record("ArrowRight opens the submenu", menus_open(page) >= 2, menus_open(page))+ page.keyboard.press("ArrowLeft")+ page.wait_for_timeout(400)+ checks.record("ArrowLeft closes only the submenu", menus_open(page) == 1, menus_open(page))+ close_all(page)++ page.get_by_label("Row options 3", exact = True).focus()+ page.wait_for_timeout(250)+ page.keyboard.press("Space")+ page.wait_for_timeout(300)+ checks.record("Space opens the menu", menus_open(page) >= 1)+ close_all(page)+++def check_lifetime(page, checks: Checks) -> None:+ reset_list(page)+ open_row(page, 16)+ page.evaluate("() => window.probe.removeRow(16)")+ page.wait_for_timeout(500)+ checks.record(+ "deleting the row while its menu is open strands no menu",+ menus_open(page) == 0,+ menus_open(page),+ )+ page.evaluate("() => window.probe.reset()")+ page.wait_for_timeout(300)++ reopened: dict[str, int] = {}+ reset_list(page)+ for label, opener, name in (+ ("a converted menu", lambda: open_row(page, 17), "Row options 17"),+ ("the unconverted control", lambda: open_control(page), "Control options"),+ ):+ opener()+ page.keyboard.press("Escape")+ page.wait_for_timeout(30)+ page.get_by_label(name, exact = True).click()+ page.wait_for_timeout(500)+ reopened[label] = menus_open(page)+ close_all(page)+ # Whether the reopening click lands is a race both arms lose about as often as they win.+ # The invariant that is not a race: neither may end up with two menus open at once.+ checks.record(+ "reopening during the exit animation never leaves two menus open",+ all(count <= 1 for count in reopened.values()),+ reopened,+ )++ # The scroll watcher is per-open. If a close ever failed to retire one, this climbs.+ before = page.evaluate("() => window.probe.scrollListeners()")+ for _ in range(30):+ page.get_by_label("Row options 18", exact = True).click()+ page.wait_for_timeout(60)+ page.keyboard.press("Escape")+ page.wait_for_timeout(60)+ close_all(page)+ page.wait_for_timeout(400)+ after = page.evaluate("() => window.probe.scrollListeners()")+ checks.record(+ "30 open and close cycles leak no scroll listener", after == before, f"{before} -> {after}"+ )++ page.evaluate(+ "() => { const l = document.getElementById('list');"+ " l.scrollTop = 8 * 40 - l.clientHeight + 20; }"+ )+ page.wait_for_timeout(300)+ # Press the sliver the scroller leaves visible. Not click_forced: that scrolls the+ # trigger into view first, which is the one thing this case must not do.+ trigger = page.get_by_label("Row options 8", exact = True).bounding_box()+ clip = page.locator("#list").bounding_box()+ top = max(trigger["y"], clip["y"])+ bottom = min(trigger["y"] + trigger["height"], clip["y"] + clip["height"])+ page.mouse.click(trigger["x"] + trigger["width"] / 2, (top + bottom) / 2)+ page.wait_for_timeout(500)+ checks.record(+ "a partly visible trigger opens a menu that stays open",+ menus_open(page) >= 1,+ menus_open(page),+ )+ close_all(page)++ reset_list(page)+ open_row(page, 19)+ page.get_by_label("Row options 20", exact = True).click()+ page.wait_for_timeout(400)+ checks.record(+ "clicking another row's trigger does not leave two menus open",+ menus_open(page) <= 1,+ menus_open(page),+ )+ close_all(page)+++def main() -> int:+ vite = start_vite(PORT)+ checks = Checks()+ try:+ url = f"http://127.0.0.1:{PORT}{PAGE}"+ wait_for_smoke_page(url, ENTRY, proc = vite, info = lambda m: print(m, flush = True))+ with sync_playwright() as pw:+ kwargs: dict = {"headless": True}+ if ENGINE == "chromium":+ kwargs["args"] = chromium_launch_args()+ browser = getattr(pw, ENGINE).launch(**kwargs)+ page = browser.new_context(viewport = {"width": 1280, "height": 800}).new_page()+ page.goto(url, wait_until = "domcontentloaded")+ page.wait_for_function("() => Boolean(window.probe)")+ checks.record(+ "the engine honours focus({preventScroll})",+ page.evaluate("() => window.probe.supportsPreventScroll()"),+ ENGINE,+ )+ check_document_is_untouched(page, checks)+ check_scroll_closes(page, checks)+ check_scrolls_that_must_not_close(page, checks)+ check_dismiss_guard(page, checks)+ check_focus_return(page, checks)+ check_keyboard(page, checks)+ check_lifetime(page, checks)+ browser.close()+ finally:+ stop_process(vite)++ passed = len(checks.results) - len(checks.failed)+ print(f"\n{ENGINE}: {passed}/{len(checks.results)} passed", flush = True)+ OUT.parent.mkdir(parents = True, exist_ok = True)+ OUT.write_text(+ json.dumps({"engine": ENGINE, "results": checks.results}, indent = 2), encoding = "utf8"+ )+ return 1 if checks.failed else 0+++if __name__ == "__main__":+ sys.exit(main())