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: keep browser panel tooltips, toasts and menus visible over desktop web pages (#12895)
oobaboogad17af334e4e4
diff --git a/studio/frontend/src/features/browser/browser-panel.tsx b/studio/frontend/src/features/browser/browser-panel.tsxindex 8bd5e717f95..9a36c4de0f1 100644--- a/studio/frontend/src/features/browser/browser-panel.tsx+++ b/studio/frontend/src/features/browser/browser-panel.tsx@@ -256,7 +256,7 @@ function IconButton({)}</button></TooltipTrigger>- <TooltipContent side="bottom" className="tooltip-compact">+ <TooltipContent side="top" className="tooltip-compact">{shortcut ? (<span className="flex items-center gap-1.5">{label}@@ -884,7 +884,7 @@ function SiteIdentity({ address, tab }: { address: string; tab: BrowserTab | und</button></PopoverTrigger></TooltipTrigger>- <TooltipContent side="bottom" className="tooltip-compact">+ <TooltipContent side="top" className="tooltip-compact">{label}</TooltipContent></Tooltip>@@ -1019,7 +1019,7 @@ function ZoomBadge({ tab }: { tab: BrowserTab | undefined }) {{new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 0 }).format(zoom)}</button></TooltipTrigger>- <TooltipContent side="bottom" className="tooltip-compact">+ <TooltipContent side="top" className="tooltip-compact">{label}</TooltipContent></Tooltip>@@ -1212,7 +1212,7 @@ function PanelMenu({ tab, children }: { tab: BrowserTab | undefined; children?:</button></DropdownMenuTrigger></TooltipTrigger>- <TooltipContent side="bottom" className="tooltip-compact">+ <TooltipContent side="top" className="tooltip-compact">{t("browser.more")}</TooltipContent></Tooltip>@@ -1632,7 +1632,7 @@ function BrowserFileToolbar({{errorBadge}</button></TooltipTrigger>- <TooltipContent side="bottom" className="tooltip-compact">+ <TooltipContent side="top" className="tooltip-compact">{consoleLabel}</TooltipContent></Tooltip>diff --git a/studio/frontend/src/features/browser/native-view.ts b/studio/frontend/src/features/browser/native-view.tsindex 39e916be6f6..c1425a0ac2c 100644--- a/studio/frontend/src/features/browser/native-view.ts+++ b/studio/frontend/src/features/browser/native-view.ts@@ -1,30 +1,32 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-/**- * Desktop app web pages: a native view per tab (src-tauri/src/browser_webview.rs) over its placeholder,- * so bot checks work. It sits above the DOM, so it hides while a menu or dialog covers it.- */+/** desktop web pages use per-tab native views for bot checks; native views cover the DOM, so overlays use snapshots. */import { getLocale, translate } from "@/i18n";import type { TranslationKey } from "@/i18n";import type { InterpolationValues } from "@/i18n";import { openExternalLink } from "@/lib/open-link";import { toast } from "@/lib/toast";+import { BROWSER_PAGE_INSET_VAR, CHAT_SETTINGS_INSET_VAR } from "@/lib/toast-offset";import { hostOf } from "./address";import { proxiedFavicon } from "./favicon";import { useBrowserHistoryStore } from "./history-store";import { callNative as call, nativeClearing, onNativeViewsClosed } from "./native-support";-import { type BrowserTab, currentEntry, entryKey, useBrowserStore } from "./store";+import { type BrowserEntry, type BrowserTab, currentEntry, entryKey, useBrowserStore } from "./store";export { clearNativeBrowsingData, useNativeBrowser } from "./native-support";const EVENT = "unsloth-browser";const MAX_VIEWS = 4;const DOCK_GAP = 8;-// Catches moves that resize nothing.+// keep the page visible during capture, but hide it without a snapshot after this timeout.+const SNAPSHOT_WAIT_MS = 250;+// Sonner toast width plus edge offsets, reserving a column beside the page.+const TOAST_COLUMN = 380;+// catch layout shifts that do not trigger resize observers.const RECHECK_MS = 300;-// Pages can open tabs without a click here: a few a minute across all pages, then the user decides.+// cap clickless tab creation across all pages, then require user confirmation.const NEW_TABS_PER_WINDOW = 3;const NEW_TAB_WINDOW_MS = 60_000;@@ -244,10 +246,9 @@ export async function nativeFind(tabId: string, query: string, backwards: booleareturn call<boolean>("browser_view_find", { tabId, query, backwards }).catch(() => false);}-// Studio UI that covers the panel. Not tooltips, or every hover would blank the page; toasts only-// when they carry an action (a mailto: or popup prompt), which would be unclickable under the page.+// exclude upward-opening tooltips to avoid hiding the native page on every hover; overlapping toasts still cover it.const OVERLAY_SELECTOR =- '[data-radix-popper-content-wrapper], [role="dialog"], [role="alertdialog"], [data-slot$="-overlay"], [data-sonner-toast]:has([data-action])';+ '[data-radix-popper-content-wrapper], [role="dialog"], [role="alertdialog"], [data-slot$="-overlay"], [data-sonner-toast]';function intersects(a: DOMRect, b: DOMRect): boolean {return a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom;@@ -281,19 +282,36 @@ function visibleRect(element: HTMLElement): DOMRect | null {return new DOMRect(rect.left, rect.top, rect.width, bottom - rect.top);}-type Desired = { tabId: string; url: string; entry: number; zoom: number; bounds: Bounds } | null;+type Desired =+ | { tabId: string; url: string; entry: number; zoom: number; bounds: Bounds }+ | { tabId: string; covered: true }+ | null;++function placeholder(tabId: string): HTMLElement | null {+ return document.querySelector<HTMLElement>(`[data-native-page="${CSS.escape(tabId)}"]`);+}++let toastInset: string | null = null;++// native views cover DOM toasts, so reserve a left column when the page reaches the right edge or Run settings.+function insetToasts(rect: DOMRect | null): void {+ const style = document.documentElement.style;+ // read the inline value set by watchChatSettingsInset; it is absent when the panel is closed or the row is narrow.+ const settings = Number.parseFloat(style.getPropertyValue(CHAT_SETTINGS_INSET_VAR)) || 0;+ const room = rect && rect.right >= window.innerWidth - settings - 2 && rect.left >= TOAST_COLUMN;+ const next = room ? `${Math.round(window.innerWidth - rect.left)}px` : null;+ if (next === toastInset) return;+ toastInset = next;+ if (next) style.setProperty(BROWSER_PAGE_INSET_VAR, next);+ else style.removeProperty(BROWSER_PAGE_INSET_VAR);+}function desiredView(): Desired {- const state = useBrowserStore.getState();- if (!state.open) return null;- const tab = state.tabs.find((candidate) => candidate.id === state.activeTabId);- if (!tab || tab.nativeError) return null;- const entry = currentEntry(tab);- if (entry.kind !== "web") return null;- const element = document.querySelector<HTMLElement>(`[data-native-page="${CSS.escape(tab.id)}"]`);- if (!element || element.offsetParent === null) return null;- const rect = visibleRect(element);- if (!rect || covered(rect)) return null;+ const page = pageRect();+ insetToasts(page?.rect ?? null);+ if (!page) return null;+ const { tab, entry, rect } = page;+ if (covered(rect)) return { tabId: tab.id, covered: true };return {tabId: tab.id,url: entry.url,@@ -309,6 +327,19 @@ function desiredView(): Desired {};}+function pageRect(): { tab: BrowserTab; entry: Extract<BrowserEntry, { kind: "web" }>; rect: DOMRect } | null {+ const state = useBrowserStore.getState();+ if (!state.open) return null;+ const tab = state.tabs.find((candidate) => candidate.id === state.activeTabId);+ if (!tab || tab.nativeError) return null;+ const entry = currentEntry(tab);+ if (entry.kind !== "web") return null;+ const element = placeholder(tab.id);+ if (!element || element.offsetParent === null) return null;+ const rect = visibleRect(element);+ return rect ? { tab, entry, rect } : null;+}+function pruneViews(shown: string | null): void {const tabs = new Map(useBrowserStore.getState().tabs.map((tab) => [tab.id, tab]));for (const tabId of [...views.keys()]) {@@ -345,8 +376,45 @@ export function whenNativeViewShown(tabId: string, timeoutMs = 1500): Promise<bo});}+// keep the last frame on the placeholder so overlays do not leave the panel blank.+let snapshot: { tabId: string; element: HTMLElement; url: string } | null = null;+let shownBounds: Bounds | null = null;++function clearSnapshot(): void {+ if (!snapshot) return;+ const { style } = snapshot.element;+ for (const property of ["background-image", "background-position", "background-size", "background-repeat"]) {+ style.removeProperty(property);+ }+ URL.revokeObjectURL(snapshot.url);+ snapshot = null;+}++async function paintSnapshot(tabId: string): Promise<void> {+ const bounds = shownBounds;+ const element = placeholder(tabId);+ if (shownView !== tabId || !bounds || !element) return;+ const started = generation;+ const png = await Promise.race([+ call<ArrayBuffer>("browser_capture", { tabId }).catch(() => null),+ new Promise<null>((resolve) => setTimeout(() => resolve(null), SNAPSHOT_WAIT_MS)),+ ]);+ if (!png?.byteLength || !element.isConnected || started !== generation) return;+ const url = URL.createObjectURL(new Blob([png], { type: "image/png" }));+ // align snapshots to the visible native bounds because the chat dock can shorten the view.+ const box = element.getBoundingClientRect();+ element.style.backgroundImage = `url(${url})`;+ element.style.backgroundPosition = `${bounds.x - box.left}px ${bounds.y - box.top}px`;+ element.style.backgroundSize = `${bounds.width}px ${bounds.height}px`;+ element.style.backgroundRepeat = "no-repeat";+ snapshot = { tabId, element, url };+}+async function applyView(desired: Desired): Promise<void> {- if (!desired) {+ if (!desired || "covered" in desired) {+ // keep the snapshot if an overlay reopens during capture.+ if (snapshot?.tabId !== desired?.tabId) clearSnapshot();+ if (desired) await paintSnapshot(desired.tabId);setShownView(null);await call("browser_view_show", { tabId: null });return;@@ -364,8 +432,10 @@ async function applyView(desired: Desired): Promise<void> {try {await call("browser_view_show", { tabId, url: resumed?.entry === entry ? resumed.url : url, bounds });if (stale()) return;+ clearSnapshot();+ shownBounds = bounds;setShownView(tabId);- // A new address for an existing view. Recorded once it went through, so Retry tries again.+ // record the entry after navigation succeeds so failures remain retryable.if (existed && loaded !== entry) {await call("browser_view_navigate", { tabId, url });if (stale()) return;@@ -435,9 +505,7 @@ export function startNativeViews(): () => void {frame = 0;const desired = desiredView();pruneViews(desired?.tabId ?? null);- const element = desired- ? document.querySelector<HTMLElement>(`[data-native-page="${CSS.escape(desired.tabId)}"]`)- : null;+ const element = desired ? placeholder(desired.tabId) : null;if (element !== resized) {if (resized) resizeObserver.unobserve(resized);if (element) resizeObserver.observe(element);@@ -466,10 +534,12 @@ export function startNativeViews(): () => void {resizeObserver.disconnect();window.removeEventListener("resize", schedule);window.clearInterval(interval);- // Closed, not just hidden: a hidden page would keep running scripts and playing media.+ // close pages because hidden native views keep scripts and media running.generation += 1;pending = null;setShownView(null);+ clearSnapshot();+ insetToasts(null);for (const tabId of [...views.keys()]) closeView(tabId);};}diff --git a/studio/frontend/src/lib/toast-offset.ts b/studio/frontend/src/lib/toast-offset.tsindex 65f2a9d6419..a2b94675a9c 100644--- a/studio/frontend/src/lib/toast-offset.ts+++ b/studio/frontend/src/lib/toast-offset.ts@@ -7,7 +7,9 @@ const HEADER_TOP_OFFSET = 52;const DESKTOP_TITLEBAR_HEIGHT = 34;export const CHAT_SETTINGS_INSET_VAR = "--studio-chat-settings-inset";-// Only the widest card scales with --ui-space-scale; the download panel and rail gutters do not.+// the desktop browser panel sets this while its native page spans the toast area and adjacent settings+export const BROWSER_PAGE_INSET_VAR = "--studio-browser-page-inset";+// only the widest card scales with --ui-space-scale; the download panel and rail gutters stay fixedconst CORNER_CARD_MAX_WIDTH = 448;const DOWNLOAD_PANEL_WIDTH = 400;const CORNER_CARD_GUTTERS = 44;@@ -66,7 +68,7 @@ export function insetPastChatSettings(offset: ToastOffset): {} {return {top: offset.top,- right: `calc(${offset.right}px + var(${CHAT_SETTINGS_INSET_VAR}, 0px))`,+ right: `calc(${offset.right}px + max(var(${CHAT_SETTINGS_INSET_VAR}, 0px), var(${BROWSER_PAGE_INSET_VAR}, 0px)))`,};}diff --git a/studio/frontend/tests/browser-native-view-snapshot.test.ts b/studio/frontend/tests/browser-native-view-snapshot.test.tsnew file mode 100644index 00000000000..0840471edc6--- /dev/null+++ b/studio/frontend/tests/browser-native-view-snapshot.test.ts@@ -0,0 +1,190 @@+// 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 { register } from "node:module";+import { test } from "node:test";++// minimal DOM for native-view.ts with one page placeholder and test-controlled overlays+const frames: (() => void)[] = [];+const mutations: (() => void)[] = [];+const overlays: {+ getBoundingClientRect: () => DOMRect;+ closest: () => null;+ querySelector: () => null;+}[] = [];+const rect = (x: number, y: number, width: number, height: number) =>+ ({+ left: x,+ top: y,+ right: x + width,+ bottom: y + height,+ width,+ height,+ }) as DOMRect;+let pageBox = rect(500, 100, 500, 600);+const placeholder = {+ style: {} as Record<string, string> & {+ removeProperty: (name: string) => void;+ },+ offsetParent: {},+ isConnected: true,+ getBoundingClientRect: () => pageBox,+ closest: () => null,+};+const rootVars = new Map<string, string>();+const rootStyle = {+ getPropertyValue: (name: string) => rootVars.get(name) ?? "",+ setProperty: (name: string, value: string) => rootVars.set(name, value),+ removeProperty: (name: string) => rootVars.delete(name),+};+placeholder.style.removeProperty = (name) => {+ delete placeholder.style[+ name.replace(/-(\w)/g, (_, letter: string) => letter.toUpperCase())+ ];+};+const noop = () => undefined;+Object.assign(globalThis, {+ window: Object.assign(globalThis, {+ innerWidth: 1000,+ addEventListener: noop,+ removeEventListener: noop,+ }),+ document: {+ documentElement: { style: rootStyle },+ body: {},+ querySelector: (selector: string) =>+ selector.startsWith("[data-native-page") ? placeholder : null,+ querySelectorAll: (selector: string) =>+ selector.startsWith(".chat-full-view-dock") ? [] : overlays,+ },+ CSS: { escape: (value: string) => value },+ DOMRect: class {+ constructor(x: number, y: number, width: number, height: number) {+ // biome-ignore lint/correctness/noConstructorReturn: a plain rect stands in for DOMRect+ return rect(x, y, width, height);+ }+ },+ requestAnimationFrame: (callback: () => void) => frames.push(callback),+ cancelAnimationFrame: noop,+ ResizeObserver: class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ MutationObserver: class {+ constructor(callback: () => void) {+ mutations.push(callback);+ }+ observe() {}+ disconnect() {}+ },+});++type Call = { command: string; args?: Record<string, unknown> };+const calls: Call[] = [];+let captureDone: ((bytes: ArrayBuffer) => void) | null = null;+(globalThis as { nativeViewCall?: unknown }).nativeViewCall = (+ command: string,+ args?: Record<string, unknown>,+) => {+ calls.push({ command, args });+ if (command === "browser_capture")+ return new Promise((resolve) => (captureDone = resolve));+ return Promise.resolve();+};++register("./helpers/browser-store-resolver.mjs", import.meta.url);+register("./helpers/native-view-resolver.mjs", import.meta.url);+const { useBrowserStore } = await import("../src/features/browser/store.ts");+const { startNativeViews } = await import(+ "../src/features/browser/native-view.ts"+);++const settle = () => new Promise((resolve) => setTimeout(resolve, 5));+// apply overlay mutations before their scheduled frame+async function frame(): Promise<void> {+ for (const callback of mutations) callback();+ for (const callback of frames.splice(0)) callback();+ await settle();+}+const menu = {+ getBoundingClientRect: () => rect(900, 100, 100, 200),+ closest: () => null,+ querySelector: () => null,+};++test("a menu that closes and reopens while the page is captured keeps the snapshot", async () => {+ useBrowserStore.getState().openUrl("https://example.com/");+ const stop = startNativeViews();+ try {+ await frame();+ const tabId = useBrowserStore.getState().activeTabId;+ assert.ok(+ calls.some(+ ({ command, args }) =>+ command === "browser_view_show" && args?.tabId === tabId,+ ),+ );++ overlays.push(menu);+ await frame();+ assert.ok(captureDone, "the covered page is captured before it hides");+ // close and reopen the menu before capture resolves+ overlays.length = 0;+ await frame();+ overlays.push(menu);+ await frame();+ captureDone?.(new Uint8Array([137, 80, 78, 71]).buffer);+ await settle();+ await frame();++ assert.match(placeholder.style.backgroundImage ?? "", /^url\(blob:/);+ const shows = calls.filter(+ ({ command }) => command === "browser_view_show",+ );+ assert.equal(+ shows.at(-1)?.args?.tabId,+ null,+ "the page stays hidden under the menu",+ );++ overlays.length = 0;+ await frame();+ assert.equal(+ placeholder.style.backgroundImage,+ undefined,+ "the snapshot goes once the page shows",+ );+ } finally {+ stop();+ }+});++test("toasts move left of a page that sits beside the Run settings panel", async () => {+ const stop = startNativeViews();+ try {+ pageBox = rect(500, 100, 500, 600);+ await frame();+ assert.equal(rootVars.get("--studio-browser-page-inset"), "500px");++ // ignore pages away from the window edge because they do not constrain toasts+ pageBox = rect(400, 100, 300, 600);+ await frame();+ assert.equal(rootVars.has("--studio-browser-page-inset"), false);++ // include the 300px Run settings panel between the page and window edge+ rootVars.set("--studio-chat-settings-inset", "300px");+ await frame();+ assert.equal(rootVars.get("--studio-browser-page-inset"), "600px");++ // omit the inset when no toast column fits; an overlapping toast will hide the page instead+ pageBox = rect(200, 100, 500, 600);+ await frame();+ assert.equal(rootVars.has("--studio-browser-page-inset"), false);+ } finally {+ stop();+ rootVars.clear();+ pageBox = rect(500, 100, 500, 600);+ }+});diff --git a/studio/frontend/tests/helpers/native-view-resolver.mjs b/studio/frontend/tests/helpers/native-view-resolver.mjsnew file mode 100644index 00000000000..8f9ae239f1c--- /dev/null+++ b/studio/frontend/tests/helpers/native-view-resolver.mjs@@ -0,0 +1,32 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// register after browser-store-resolver.mjs and route Tauri calls through globalThis.nativeViewCall+const stub = (source) => `data:text/javascript,${encodeURIComponent(source)}`;++const STUBS = {+ "@tauri-apps/api/event": stub("export const listen = async () => () => {};"),+ "@/i18n": stub(+ "export const getLocale = () => 'en'; export const translate = (key) => key;",+ ),+ "@/lib/open-link": stub("export const openExternalLink = () => {};"),+ "@/lib/toast": stub(+ "export const toast = Object.assign(() => {}, { success() {}, error() {} });",+ ),+ "./native-support": stub(`+ export const useNativeBrowser = { getState: () => ({ enabled: true }) };+ export const callNative = (command, args) => globalThis.nativeViewCall(command, args);+ export const nativeClearing = () => false;+ export const onNativeViewsClosed = () => () => {};+ export const clearNativeBrowsingData = async () => {};+ `),+ "./favicon": stub("export const proxiedFavicon = async () => null;"),+ "./history-store": stub(+ "export const useBrowserHistoryStore = { getState: () => ({ recordVisit() {}, recordDownload() {} }) };",+ ),+};++export function resolve(specifier, context, next) {+ if (STUBS[specifier]) return { url: STUBS[specifier], shortCircuit: true };+ return next(specifier, context);+}diff --git a/studio/frontend/tests/toast-offset.test.ts b/studio/frontend/tests/toast-offset.test.tsindex 198dd01f733..3cada5fcec5 100644--- a/studio/frontend/tests/toast-offset.test.ts+++ b/studio/frontend/tests/toast-offset.test.ts@@ -119,7 +119,6 @@ test("the header offset follows the UI font size, the titlebar does not", () =>default: { top: 103, right: 12 },mobile: { top: 103, right: 16 },});- // A route with no header keeps its corner inset at any size.assert.deepEqual(getToastOffsets("/settings", false, false, 20 / 15), {default: { top: 12, right: 12 },mobile: { top: 16, right: 16 },@@ -129,7 +128,7 @@ test("the header offset follows the UI font size, the titlebar does not", () =>test("desktop toasts shift left by the open Run settings panel", () => {assert.deepEqual(insetPastChatSettings({ top: 52, right: 12 }), {top: 52,- right: "calc(12px + var(--studio-chat-settings-inset, 0px))",+ right: "calc(12px + max(var(--studio-chat-settings-inset, 0px), var(--studio-browser-page-inset, 0px)))",});});