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
fix(studio): restore menu trigger focus after outside dismiss (#9772)
alkinun3fd9dc0e881a
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 2b61188fbe7..cbaf65f90b6 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -7888,6 +7888,7 @@ async function exportMessageMarkdown(content: string): Promise<void> {}const AssistantActionBar: FC = () => {const aui = useAui();+ const moreMenuTriggerRef = useRef<HTMLButtonElement>(null);const { forkMessage, forkDisabled } = useForkMessageAction();const researchRunId = useResearchMessageRunId();const researchActive = useThreadResearchActive();@@ -7958,6 +7959,7 @@ const AssistantActionBar: FC = () => {<ActionBarMorePrimitive.Root modal={false}><ActionBarMorePrimitive.Trigger asChild={true}><TooltipIconButton+ ref={moreMenuTriggerRef}tooltip="More"className="data-[state=open]:bg-accent">@@ -7971,7 +7973,7 @@ const AssistantActionBar: FC = () => {className="aui-action-bar-more-content z-50 min-w-32 overflow-hidden rounded-[21px] bg-popover px-[9px] py-2 text-popover-foreground shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] dark:shadow-none">{/* Prevent an outside dismissal from triggering Delete. */}- <MenuDismissGuard />+ <MenuDismissGuard triggerRef={moreMenuTriggerRef} /><ActionBarMorePrimitive.Itemdisabled={forkDisabled}onSelect={() => void forkMessage()}diff --git a/studio/frontend/src/lib/menu-dismiss-guard.tsx b/studio/frontend/src/lib/menu-dismiss-guard.tsxindex 9282183dee1..df745d80b61 100644--- a/studio/frontend/src/lib/menu-dismiss-guard.tsx+++ b/studio/frontend/src/lib/menu-dismiss-guard.tsx@@ -1,7 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-import type { FC } from "react";+import type { FC, RefObject } from "react";import { useDismissingClickGuard } from "@/lib/menu-dismiss";@@ -9,7 +9,9 @@ import { useDismissingClickGuard } from "@/lib/menu-dismiss";* Marker mounted inside non-modal menu content. The lifetime is mount-scoped: exit-animated* content can outlive the open state, so animated menus must add explicit open-state gating.*/-export const MenuDismissGuard: FC = () => {- useDismissingClickGuard();+export const MenuDismissGuard: FC<{+ triggerRef: RefObject<HTMLElement | null>;+}> = ({ triggerRef }) => {+ useDismissingClickGuard(triggerRef);return null;};diff --git a/studio/frontend/src/lib/menu-dismiss.ts b/studio/frontend/src/lib/menu-dismiss.tsindex 8d73398b577..5f1f6d6bce3 100644--- a/studio/frontend/src/lib/menu-dismiss.ts+++ b/studio/frontend/src/lib/menu-dismiss.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-import { useEffect } from "react";+import { type RefObject, useEffect } from "react";/*** Swallow the outside click that dismisses a non-modal menu before it activates an adjacent@@ -30,6 +30,7 @@ let keyboardOnly = false;/** Used to undo focus taken by the swallowed press. */let armedPressTarget: Node | undefined;let focusBeforePress: Element | null = null;+let armedTrigger: HTMLElement | null = null;/** Maximum post-release click delay. */const CLICK_GRACE_MS = 500;@@ -68,6 +69,7 @@ const disarm = (): void => {keyboardOnly = false;armedPressTarget = undefined;focusBeforePress = null;+ armedTrigger = null;document.removeEventListener("pointerdown", disarmOnNewPointerDown, true);document.removeEventListener("click", swallowClick, true);document.removeEventListener("pointerup", startGrace, true);@@ -101,14 +103,27 @@ function startGrace(event: PointerEvent): void {const TEXT_ENTRY = "input,textarea,select";function releaseFocusTakenByTheGuardedPress(): void {- // Swallowing the click is not enough: blur only focus acquired by this guarded press, so a- // later Space key cannot activate the dismissed control.+ // Swallowing the click is not enough: move focus away from the control focused by this guarded+ // press, so a later Space key cannot activate it.const active = document.activeElement;if (!(active instanceof HTMLElement)) return;if (active === focusBeforePress) return;if (active.isContentEditable || active.matches(TEXT_ENTRY)) return;if (!(armedPressTarget instanceof Node)) return;if (!active.contains(armedPressTarget)) return;+ const trigger = armedTrigger;+ if (+ trigger?.isConnected &&+ !trigger.matches(":disabled") &&+ !trigger.closest("[inert]")+ ) {+ try {+ trigger.focus({ preventScroll: true });+ if (document.activeElement === trigger) return;+ } catch {+ // Fall through to the existing blur fallback for an unfocusable trigger.+ }+ }active.blur();}@@ -156,7 +171,12 @@ function swallowClick(event: Event): void {document.dispatchEvent(new MouseEvent("click", { bubbles: false }));}-const arm = (touch: boolean, pointerId: number, pressTarget: Node): void => {+const arm = (+ touch: boolean,+ pointerId: number,+ pressTarget: Node,+ trigger: HTMLElement | null,+): void => {if (armed) return;armed = true;armedByTouch = touch;@@ -166,6 +186,7 @@ const arm = (touch: boolean, pointerId: number, pressTarget: Node): void => {keyboardOnly = false;armedPressTarget = pressTarget;focusBeforePress = document.activeElement;+ armedTrigger = trigger;document.addEventListener("pointerdown", disarmOnNewPointerDown, true);document.addEventListener("click", swallowClick, true);document.addEventListener("pointerup", startGrace, true);@@ -176,7 +197,9 @@ const arm = (touch: boolean, pointerId: number, pressTarget: Node): void => {};/** Install the watcher for one open menu. */-export function installDismissingClickGuard(): () => void {+export function installDismissingClickGuard(+ triggerRef?: RefObject<HTMLElement | null>,+): () => void {const onPointerDown = (event: PointerEvent): void => {if (armed && pointerIsDown && event.pointerId !== armedPointerId) return;disarmAndReleaseFocus();@@ -184,7 +207,13 @@ export function installDismissingClickGuard(): () => void {const target = event.target;if (!(target instanceof Element)) return;if (target.closest(MENU_SURFACE)) return;- arm(event.pointerType === "touch", event.pointerId, target);+ const trigger = triggerRef?.current;+ arm(+ event.pointerType === "touch",+ event.pointerId,+ target,+ trigger instanceof HTMLElement ? trigger : null,+ );};document.addEventListener("pointerdown", onPointerDown, true);return () => {@@ -193,6 +222,8 @@ export function installDismissingClickGuard(): () => void {}/** Mount the guard inside an open non-modal menu's content. */-export function useDismissingClickGuard(): void {- useEffect(installDismissingClickGuard, []);+export function useDismissingClickGuard(+ triggerRef: RefObject<HTMLElement | null>,+): void {+ useEffect(() => installDismissingClickGuard(triggerRef), [triggerRef]);}diff --git a/studio/frontend/tests/nonmodal-menu-dismiss-guard.test.ts b/studio/frontend/tests/nonmodal-menu-dismiss-guard.test.tsindex a37cdd1a8f3..f2f47614e9c 100644--- a/studio/frontend/tests/nonmodal-menu-dismiss-guard.test.ts+++ b/studio/frontend/tests/nonmodal-menu-dismiss-guard.test.ts@@ -12,7 +12,7 @@ import { fileURLToPath } from "node:url";const SRC = fileURLToPath(new URL("../src/", import.meta.url));const TAG_NAME = /^<([A-Za-z0-9_.]+)/;-const GUARD = /<MenuDismissGuard\s*\/>/;+const GUARD = /<MenuDismissGuard\b(?=[^>]*\btriggerRef=\{)[^>]*\/>/;/** Explicit non-modal menus that intentionally remain unguarded. */const UNGUARDED = new Map<string, string>([@@ -133,7 +133,7 @@ test("the element scan does not confuse a tag with one that merely starts the sa"<DropdownMenu modal={false}>"," <DropdownMenuTrigger />","</DropdownMenu>",- "<MenuDismissGuard />",+ "<MenuDismissGuard triggerRef={triggerRef} />",].join("\n");const { tag, body } = element(source, source.indexOf("modal={false}"));assert.equal(tag, "DropdownMenu");@@ -157,7 +157,7 @@ test("the guard component is what mounts the watcher", () => {);assert.match(guard,- /useDismissingClickGuard\(\)/,- "MenuDismissGuard must install the document watcher, or every mount above is decoration",+ /useDismissingClickGuard\(triggerRef\)/,+ "MenuDismissGuard must give the document watcher its trigger, or every mount above loses focus restoration",);});diff --git a/studio/frontend/tests/nonmodal-menu-second-pointer.test.ts b/studio/frontend/tests/nonmodal-menu-second-pointer.test.tsindex 26dbd4ae5d0..dd136b7b78a 100644--- a/studio/frontend/tests/nonmodal-menu-second-pointer.test.ts+++ b/studio/frontend/tests/nonmodal-menu-second-pointer.test.ts@@ -27,6 +27,7 @@ class FakeNode {}/** Minimal `closest` implementation for the guard's menu check. */class FakeElement extends FakeNode {inMenu: boolean;+ inert = false;readonly parent?: FakeElement;readonly textEntry: boolean;constructor(inMenu: boolean, parent?: FakeElement, textEntry = false) {@@ -35,7 +36,14 @@ class FakeElement extends FakeNode {this.parent = parent;this.textEntry = textEntry;}- closest(): FakeElement | null {+ closest(selector?: string): FakeElement | null {+ if (selector === "[inert]") {+ if (this.inert) return this;+ for (let node = this.parent; node; node = node.parent) {+ if (node.inert) return node;+ }+ return null;+ }if (this.inMenu) return this;for (let node = this.parent; node; node = node.parent) {if (node.inMenu) return node;@@ -59,10 +67,28 @@ class FakeElement extends FakeNode {class FakeHTMLElement extends FakeElement {isContentEditable = false;+ isConnected = true;+ disabled = false;+ acceptsFocus = true;blurCount = 0;+ focusCount = 0;+ focusOptions: FocusOptions | undefined;blur(): void {this.blurCount += 1;- if (fakeDocument.activeElement === this) fakeDocument.activeElement = null;+ if (fakeDocument.activeElement === this) {+ fakeDocument.activeElement = fakeDocument.body;+ }+ }+ focus(options?: FocusOptions): void {+ this.focusCount += 1;+ this.focusOptions = options;+ if (this.isConnected && !this.disabled && this.acceptsFocus) {+ fakeDocument.activeElement = this;+ }+ }+ matches(selector?: string): boolean {+ if (selector === ":disabled") return this.disabled;+ return super.matches();}}@@ -77,7 +103,8 @@ class FakeMouseEvent implements FakeEvent {class FakeDocument {private readonly capturing = new Map<string, Listener[]>();private readonly bubbling = new Map<string, Listener[]>();- activeElement: unknown = null;+ readonly body = new FakeHTMLElement(false);+ activeElement: unknown = this.body;addEventListener(type: string, fn: Listener, capture?: boolean): void {const bucket = capture ? this.capturing : this.bubbling;@@ -141,7 +168,8 @@ class FakeWindow {if (at >= 0) list.splice(at, 1);}dispatchEvent(event: FakeEvent): void {- for (const fn of [...(this.windowListeners.get(event.type) ?? [])]) fn(event);+ for (const fn of [...(this.windowListeners.get(event.type) ?? [])])+ fn(event);}advance(ms: number): void {this.now += ms;@@ -205,8 +233,14 @@ function clickReachedTheControl(target: unknown): boolean {}/** Install a guard for one isolated test. */-function withOpenMenu(body: () => void): void {- const remove = installDismissingClickGuard();+function withOpenMenu(+ body: () => void,+ triggerRef?: { current: FakeHTMLElement | null },+): void {+ const install = installDismissingClickGuard as (ref?: {+ current: FakeHTMLElement | null;+ }) => () => void;+ const remove = install(triggerRef);try {body();} finally {@@ -288,6 +322,95 @@ test("the armed pointer's own click is still swallowed, once", () => {});});+test("a swallowed outside press restores focus to its captured trigger", () => {+ const trigger = new FakeHTMLElement(false);+ const triggerRef = { current: trigger as FakeHTMLElement | null };+ const outsideButton = new FakeHTMLElement(false);+ let outsideActivations = 0;+ const activateOutside = (event: FakeEvent): void => {+ if (event.target === outsideButton) outsideActivations += 1;+ };+ fakeDocument.addEventListener("click", activateOutside, false);++ try {+ withOpenMenu(() => {+ fakeDocument.activeElement = INSIDE_MENU;+ down(11, "mouse", outsideButton);+ // The menu can unmount and clear its ref before the compatibility click arrives.+ triggerRef.current = null;+ // Pointerdown's default action focuses the button after capture listeners run.+ fakeDocument.activeElement = outsideButton;+ up(11, "mouse");+ fakeDocument.dispatchEvent({+ type: "click",+ detail: 1,+ target: outsideButton,+ });++ assert.equal(+ outsideActivations,+ 0,+ "the dismissing click reached the outside button",+ );+ assert.equal(+ fakeDocument.activeElement,+ trigger,+ "focus fell back to BODY instead of returning to the menu trigger",+ );+ assert.deepEqual(trigger.focusOptions, { preventScroll: true });++ // Space only activates a button that retained focus from the swallowed press.+ if (fakeDocument.activeElement === outsideButton) {+ fakeDocument.dispatchEvent({+ type: "click",+ detail: 0,+ target: outsideButton,+ });+ }+ assert.equal(+ outsideActivations,+ 0,+ "Space activated the outside button after its dismissing click was swallowed",+ );+ }, triggerRef);+ } finally {+ fakeDocument.removeEventListener("click", activateOutside, false);+ }+});++test("an unavailable trigger falls back to blurring the pressed control", () => {+ const scenarios: [string, FakeHTMLElement | null][] = [+ ["absent", null],+ [+ "detached",+ Object.assign(new FakeHTMLElement(false), { isConnected: false }),+ ],+ ["disabled", Object.assign(new FakeHTMLElement(false), { disabled: true })],+ ["inert", Object.assign(new FakeHTMLElement(false), { inert: true })],+ [+ "unfocusable",+ Object.assign(new FakeHTMLElement(false), { acceptsFocus: false }),+ ],+ ];++ for (const [label, trigger] of scenarios) {+ withOpenMenu(+ () => {+ const outsideButton = new FakeHTMLElement(false);+ fakeDocument.activeElement = INSIDE_MENU;+ down(11, "mouse", outsideButton);+ fakeDocument.activeElement = outsideButton;+ up(11, "mouse");+ assert.equal(clickReachedTheControl(outsideButton), false, label);++ assert.equal(outsideButton.blurCount, 1, label);+ assert.equal(fakeDocument.activeElement, fakeDocument.body, label);+ },+ { current: trigger },+ );+ }+});+test("a new gesture supersedes an armed no-click gesture after menu cleanup", () => {const remove = installDismissingClickGuard();try {@@ -351,24 +474,29 @@ test("a drag-retargeted click releases the control focused by the guarded press"});test("focus moved elsewhere during the gesture is preserved", () => {- withOpenMenu(() => {- const clickAncestor = new FakeHTMLElement(false);- const pressedButton = new FakeHTMLElement(false, clickAncestor);- const icon = new FakeElement(false, pressedButton);- const appFocusedControl = new FakeHTMLElement(false);- fakeDocument.activeElement = INSIDE_MENU;-- down(11, "mouse", icon);- fakeDocument.activeElement = appFocusedControl;- up(11, "mouse");- clickReachedTheControl(clickAncestor);-- assert.equal(- appFocusedControl.blurCount,- 0,- "the guard must not blur focus the app moved away from the pressed control",- );- });+ const trigger = new FakeHTMLElement(false);+ withOpenMenu(+ () => {+ const clickAncestor = new FakeHTMLElement(false);+ const pressedButton = new FakeHTMLElement(false, clickAncestor);+ const icon = new FakeElement(false, pressedButton);+ const appFocusedControl = new FakeHTMLElement(false);+ fakeDocument.activeElement = INSIDE_MENU;++ down(11, "mouse", icon);+ fakeDocument.activeElement = appFocusedControl;+ up(11, "mouse");+ clickReachedTheControl(clickAncestor);++ assert.equal(+ appFocusedControl.blurCount,+ 0,+ "the guard must not blur focus the app moved away from the pressed control",+ );+ assert.equal(trigger.focusCount, 0);+ },+ { current: trigger },+ );});test("a control focused before the guarded press is preserved", () => {@@ -380,7 +508,11 @@ test("a control focused before the guarded press is preserved", () => {up(11, "mouse");assert.equal(clickReachedTheControl(button), false);- assert.equal(button.blurCount, 0, "the press did not acquire this existing focus");+ assert.equal(+ button.blurCount,+ 0,+ "the press did not acquire this existing focus",+ );assert.equal(fakeDocument.activeElement, button);});});@@ -419,16 +551,21 @@ test("a no-click grace timeout also releases press-acquired focus", () => {});test("text-entry focus acquired by the guarded press is preserved", () => {- withOpenMenu(() => {- const input = new FakeHTMLElement(false, undefined, true);- fakeDocument.activeElement = INSIDE_MENU;-- down(11, "mouse", input);- fakeDocument.activeElement = input;- up(11, "mouse");- assert.equal(clickReachedTheControl(input), false);-- assert.equal(input.blurCount, 0, "typing focus must keep its caret");- assert.equal(fakeDocument.activeElement, input);- });+ const trigger = new FakeHTMLElement(false);+ withOpenMenu(+ () => {+ const input = new FakeHTMLElement(false, undefined, true);+ fakeDocument.activeElement = INSIDE_MENU;++ down(11, "mouse", input);+ fakeDocument.activeElement = input;+ up(11, "mouse");+ assert.equal(clickReachedTheControl(input), false);++ assert.equal(input.blurCount, 0, "typing focus must keep its caret");+ assert.equal(fakeDocument.activeElement, input);+ assert.equal(trigger.focusCount, 0);+ },+ { current: trigger },+ );});