Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: no text selection from the clicks that follow a dropdown dismissal (#16077)

Michael Hane07e636b7f11
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsx
index 0098ede50aa..bd1ef02faea 100644
--- a/studio/frontend/src/app/provider.tsx
+++ b/studio/frontend/src/app/provider.tsx
@@ -54,6 +54,7 @@ import { useTauriUpdate } from "@/hooks/use-tauri-update";
import { useUiSpaceScale } from "@/hooks/use-ui-space-scale";
import { isTauri } from "@/lib/api-base";
import { followDesktopUpdateScreen } from "@/lib/desktop-update-activity";
+import { installDismissClickStreakGuard } from "@/lib/dismiss-click-streak";
import { useDocumentFlag } from "@/lib/document-flag";
import { refreshWindowChromeTop } from "@/lib/window-chrome";
import {
@@ -1179,6 +1180,7 @@ export function AppProvider({ children }: AppProviderProps) {
useEffect(() => {
dismissStartToasts();
}, [pathname]);
+ useEffect(() => installDismissClickStreakGuard(), []);
return (
<MotionConfig reducedMotion={REDUCED_MOTION_MAP[reduceMotion]}>
<TooltipProvider>
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index eb2bc062ecd..6df06a4c17b 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -2130,7 +2130,7 @@ export const Thread: FC<{
return attachWheelHoverSuppression(viewportEl);
}, [viewportEl]);
- // Layout effect: a remounted viewport must be shifted before its first paint.
+ // Layout effect: shift a remounted viewport before its first paint.
useLayoutEffect(() => {
if (!viewportEl) return;
return watchThreadGutter(viewportEl);
@@ -2598,7 +2598,7 @@ const ThreadComposerDock: FC<{
const resizeObserver = new ResizeObserver(() => apply());
let observedFooter: Element | null = null;
const apply = () => {
- // Can fire before the gutter's observer; unshifted, the composer lands a scrollbar off-centre.
+ // May fire before the gutter's observer, which would leave the composer a scrollbar off-centre.
syncThreadGutter(viewport);
// The footer is the real column box: WebKit's both-edges gutter reserves 2x the scrollbar on the right, clientWidth 1x.
const footer = childWithClass(viewport, "aui-thread-viewport-footer");
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 4a9a1258e25..0b16e4d5204 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -6027,7 +6027,7 @@ export function ImagesPage({
</div>
{workflow === "create" && (
- // Top edge on the icon's drawn top: centred in the line, stroke starts 1.25/24 into the glyph.
+ // Top edge on the icon's drawn top (its stroke starts 1.25/24 into the glyph).
<div className="mt-[calc((var(--text-xl)-18px*var(--ui-space-scale,1))/2+18px*var(--ui-space-scale,1)*0.052)]">
<MediaGenerationPresetControl
kind="image"
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index ea1fb32ced5..378f8726d47 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -3925,7 +3925,7 @@ function VideoGenerator({
</p>
</div>
- {/* Top edge on the icon's drawn top: centred in the line, stroke starts 1.25/24 into the glyph. */}
+ {/* Top edge on the icon's drawn top (its stroke starts 1.25/24 into the glyph). */}
<div className="mt-[calc((var(--text-xl)-18px*var(--ui-space-scale,1))/2+18px*var(--ui-space-scale,1)*0.052)]">
<MediaGenerationPresetControl
kind="video"
diff --git a/studio/frontend/src/lib/dismiss-click-streak.ts b/studio/frontend/src/lib/dismiss-click-streak.ts
new file mode 100644
index 00000000000..60224954e4f
--- /dev/null
+++ b/studio/frontend/src/lib/dismiss-click-streak.ts
@@ -0,0 +1,193 @@
+// 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 OS counts a menu-dismissing press as click 1; later presses select as if it had not (caret, word, block).
+
+const OPEN_FLOATING =
+ '[data-radix-popper-content-wrapper] :is([role="menu"],[role="listbox"],[role="dialog"])';
+
+const TEXT_ENTRY =
+ 'input,textarea,select,[contenteditable]:not([contenteditable="false"])';
+
+type Doc = Pick<
+ Document,
+ "addEventListener" | "removeEventListener" | "querySelector"
+>;
+
+export type ShiftedSelection = "caret" | "word" | "paragraph";
+
+export function shiftedSelection(detail: number): ShiftedSelection {
+ if (detail <= 2) return "caret";
+ return detail === 3 ? "word" : "paragraph";
+}
+
+function asElement(target: EventTarget | null): Element | null {
+ return target && typeof (target as Element).closest === "function"
+ ? (target as Element)
+ : null;
+}
+
+type CaretDoc = Document & {
+ caretPositionFromPoint?: (
+ x: number,
+ y: number,
+ ) => { offsetNode: Node; offset: number } | null;
+};
+
+function caretRangeAt(x: number, y: number): Range | null {
+ const doc = document as CaretDoc;
+ if (typeof doc.caretRangeFromPoint === "function") {
+ return doc.caretRangeFromPoint(x, y);
+ }
+ const position = doc.caretPositionFromPoint?.(x, y);
+ if (!position) return null;
+ const range = doc.createRange();
+ range.setStart(position.offsetNode, position.offset);
+ range.collapse(true);
+ return range;
+}
+
+type Extend = (x: number, y: number) => void;
+
+function unitRangeAt(
+ x: number,
+ y: number,
+ detail: number,
+ block: Element,
+): Range | null {
+ const range = caretRangeAt(x, y);
+ if (!range) return null;
+ const unit = shiftedSelection(detail);
+ if (unit === "word") expandToWord(range);
+ if (unit === "paragraph") expandToBlock(range, block);
+ return range;
+}
+
+function selectAt(event: MouseEvent, target: Element | null): Extend | null {
+ const selection = window.getSelection();
+ if (!selection) return null;
+ selection.removeAllRanges();
+ const anchor =
+ target && unitRangeAt(event.clientX, event.clientY, event.detail, target);
+ // Native selection never starts in unselectable text or outside the pressed element.
+ if (
+ !anchor ||
+ !target?.contains(anchor.startContainer) ||
+ getComputedStyle(target).userSelect === "none"
+ ) {
+ return null;
+ }
+ selection.addRange(anchor);
+ return (x, y) => {
+ const focus = unitRangeAt(x, y, event.detail, document.body);
+ if (!focus) return;
+ if (focus.compareBoundaryPoints(Range.START_TO_START, anchor) < 0) {
+ selection.setBaseAndExtent(
+ anchor.endContainer,
+ anchor.endOffset,
+ focus.startContainer,
+ focus.startOffset,
+ );
+ } else if (focus.compareBoundaryPoints(Range.END_TO_END, anchor) > 0) {
+ selection.setBaseAndExtent(
+ anchor.startContainer,
+ anchor.startOffset,
+ focus.endContainer,
+ focus.endOffset,
+ );
+ } else {
+ selection.removeAllRanges();
+ selection.addRange(anchor);
+ }
+ };
+}
+
+/** Segmenter, not `Selection.modify`: its word steps differ by platform. */
+export function wordBounds(text: string, offset: number): [number, number] {
+ if (!text) return [0, 0];
+ const at = Math.min(offset, text.length - 1);
+ const segment = new Intl.Segmenter(undefined, { granularity: "word" })
+ .segment(text)
+ .containing(at);
+ return segment
+ ? [segment.index, segment.index + segment.segment.length]
+ : [at, at];
+}
+
+function expandToWord(range: Range): void {
+ const node = range.startContainer;
+ if (node.nodeType !== Node.TEXT_NODE) return;
+ const [start, end] = wordBounds(node.textContent ?? "", range.startOffset);
+ range.setStart(node, start);
+ range.setEnd(node, end);
+}
+
+function expandToBlock(range: Range, target: Element): void {
+ let block: Element | null =
+ range.startContainer instanceof Element
+ ? range.startContainer
+ : range.startContainer.parentElement;
+ while (
+ block &&
+ block !== target &&
+ getComputedStyle(block).display.startsWith("inline")
+ ) {
+ block = block.parentElement;
+ }
+ range.selectNodeContents(block ?? target);
+}
+
+export function installDismissClickStreakGuard(
+ doc: Doc = document,
+ select: (
+ event: MouseEvent,
+ target: Element | null,
+ ) => Extend | null = selectAt,
+): () => void {
+ let pressDismisses = false;
+ let streakFromDismiss = false;
+ let extend: Extend | null = null;
+
+ const onPointerDown = (event: PointerEvent): void => {
+ // Capture phase: runs before Radix closes the menu.
+ const target = asElement(event.target);
+ pressDismisses =
+ event.button === 0 &&
+ doc.querySelector(OPEN_FLOATING) !== null &&
+ !target?.closest("[data-radix-popper-content-wrapper]");
+ };
+
+ const onMouseDown = (event: MouseEvent): void => {
+ if (event.button !== 0) return;
+ extend = null;
+ const target = asElement(event.target);
+ if (event.detail <= 1) {
+ streakFromDismiss = pressDismisses;
+ } else if (streakFromDismiss && !target?.closest(TEXT_ENTRY)) {
+ event.preventDefault();
+ extend = select(event, target);
+ }
+ pressDismisses = false;
+ };
+
+ const onMouseMove = (event: MouseEvent): void => {
+ if (!extend) return;
+ if (event.buttons & 1) extend(event.clientX, event.clientY);
+ else extend = null;
+ };
+
+ const onMouseUp = (): void => {
+ extend = null;
+ };
+
+ const listeners: [string, EventListener][] = [
+ ["pointerdown", onPointerDown as EventListener],
+ ["mousedown", onMouseDown as EventListener],
+ ["mousemove", onMouseMove as EventListener],
+ ["mouseup", onMouseUp as EventListener],
+ ];
+ for (const [type, fn] of listeners) doc.addEventListener(type, fn, true);
+ return () => {
+ for (const [type, fn] of listeners) doc.removeEventListener(type, fn, true);
+ };
+}
diff --git a/studio/frontend/tests/dismiss-click-streak.test.ts b/studio/frontend/tests/dismiss-click-streak.test.ts
new file mode 100644
index 00000000000..8f48622f4da
--- /dev/null
+++ b/studio/frontend/tests/dismiss-click-streak.test.ts
@@ -0,0 +1,169 @@
+// 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 assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ installDismissClickStreakGuard,
+ shiftedSelection,
+ wordBounds,
+} from "../src/lib/dismiss-click-streak.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+const INSTALL_ONCE =
+ /useEffect\(\(\) => installDismissClickStreakGuard\(\), \[\]\);/;
+
+type Listener = (event: Event) => void;
+
+function fakeDoc() {
+ const listeners = new Map<string, Listener[]>();
+ let menuOpen = false;
+ const doc = {
+ addEventListener: (type: string, fn: Listener) =>
+ listeners.set(type, [...(listeners.get(type) ?? []), fn]),
+ removeEventListener: (type: string, fn: Listener) =>
+ listeners.set(
+ type,
+ (listeners.get(type) ?? []).filter((f) => f !== fn),
+ ),
+ querySelector: () => (menuOpen ? {} : null),
+ } as unknown as Document;
+ const el = (inside: string[] = []) => ({
+ closest: (selector: string) =>
+ inside.some((s) => selector.includes(s)) ? {} : null,
+ });
+ const selected: number[] = [];
+ const extended: [number, number][] = [];
+ const select = (event: MouseEvent) => {
+ selected.push(event.detail);
+ return (x: number, y: number) => {
+ extended.push([x, y]);
+ };
+ };
+ const fire = (type: string, init: Record<string, unknown>) => {
+ for (const fn of listeners.get(type) ?? []) fn(init as unknown as Event);
+ };
+ const press = (detail: number, target = el(), button = 0): boolean => {
+ let prevented = false;
+ const base = {
+ target,
+ button,
+ detail,
+ preventDefault: () => {
+ prevented = true;
+ },
+ };
+ for (const fn of listeners.get("pointerdown") ?? [])
+ fn(base as unknown as Event);
+ menuOpen = false;
+ for (const fn of listeners.get("mousedown") ?? [])
+ fn(base as unknown as Event);
+ return prevented;
+ };
+ return {
+ doc,
+ select,
+ selected,
+ extended,
+ fire,
+ press,
+ el,
+ openMenu: () => {
+ menuOpen = true;
+ },
+ count: () => [...listeners.values()].flat().length,
+ };
+}
+
+test("after a menu-dismissing press, the rest of the run selects one step finer", () => {
+ const f = fakeDoc();
+ installDismissClickStreakGuard(f.doc, f.select);
+ f.openMenu();
+ assert.equal(f.press(1), false, "the dismissing press itself is untouched");
+ for (const detail of [2, 3, 4, 5, 6]) assert.equal(f.press(detail), true);
+ assert.deepEqual(f.selected, [2, 3, 4, 5, 6]);
+});
+
+test("a run that began by dismissing a menu still selects: caret, word, then paragraph", () => {
+ assert.equal(shiftedSelection(2), "caret");
+ assert.equal(shiftedSelection(3), "word");
+ assert.equal(shiftedSelection(4), "paragraph");
+ assert.equal(shiftedSelection(9), "paragraph");
+});
+
+test("the word under the pointer is found the same way on every platform", () => {
+ const text = "Answer 12. Lorem ipsum";
+ assert.deepEqual(wordBounds(text, 2), [0, 6]);
+ assert.deepEqual(wordBounds(text, 0), [0, 6]);
+ assert.deepEqual(wordBounds(text, 13), [11, 16]);
+ assert.deepEqual(wordBounds(text, text.length), [17, 22]);
+ assert.deepEqual(wordBounds("", 0), [0, 0]);
+});
+
+test("a drag on a shifted press extends the selection until the button is released", () => {
+ const f = fakeDoc();
+ installDismissClickStreakGuard(f.doc, f.select);
+ f.openMenu();
+ f.press(1);
+ f.press(2);
+ f.fire("mousemove", { buttons: 1, clientX: 40, clientY: 10 });
+ f.fire("mousemove", { buttons: 1, clientX: 90, clientY: 30 });
+ f.fire("mouseup", { button: 0 });
+ f.fire("mousemove", { buttons: 0, clientX: 120, clientY: 30 });
+ assert.deepEqual(f.extended, [
+ [40, 10],
+ [90, 30],
+ ]);
+});
+
+test("pointer moves without a shifted press extend nothing", () => {
+ const f = fakeDoc();
+ installDismissClickStreakGuard(f.doc, f.select);
+ f.press(1);
+ f.press(2);
+ f.fire("mousemove", { buttons: 1, clientX: 40, clientY: 10 });
+ assert.deepEqual(f.extended, []);
+});
+
+test("double and triple clicks select as usual when no menu was dismissed", () => {
+ const f = fakeDoc();
+ installDismissClickStreakGuard(f.doc, f.select);
+ assert.equal(f.press(1), false);
+ assert.equal(f.press(2), false);
+ assert.equal(f.press(3), false);
+});
+
+test("a new click run after a dismissal selects as usual", () => {
+ const f = fakeDoc();
+ installDismissClickStreakGuard(f.doc, f.select);
+ f.openMenu();
+ f.press(1);
+ assert.equal(f.press(1), false);
+ assert.equal(f.press(2), false);
+});
+
+test("presses inside the menu and in text fields keep native selection", () => {
+ const f = fakeDoc();
+ installDismissClickStreakGuard(f.doc, f.select);
+ f.openMenu();
+ f.press(1, f.el(["data-radix-popper-content-wrapper"]));
+ assert.equal(f.press(2), false, "a press inside the menu dismisses nothing");
+
+ f.openMenu();
+ f.press(1);
+ assert.equal(
+ f.press(2, f.el(["textarea"])),
+ false,
+ "double-click in a field selects a word",
+ );
+});
+
+test("the guard removes its listeners and is installed once for the app", () => {
+ const f = fakeDoc();
+ const stop = installDismissClickStreakGuard(f.doc, f.select);
+ assert.equal(f.count(), 4);
+ stop();
+ assert.equal(f.count(), 0);
+ assert.match(readSrc("app/provider.tsx"), INSTALL_ONCE);
+});