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 desktop: steady floating browser window on drag, resize and float (#17027)
Michael Hanca5e22e6294a
diff --git a/studio/frontend/src/features/browser/browser-panel.tsx b/studio/frontend/src/features/browser/browser-panel.tsxindex 55af6bbedf9..4f612f4b8a2 100644--- a/studio/frontend/src/features/browser/browser-panel.tsx+++ b/studio/frontend/src/features/browser/browser-panel.tsx@@ -140,7 +140,7 @@ import { browserTabType, fileBarKind, mediaKind } from "./file-kind";import { canCopyVideoFrame, copyVideoFrame, tabVideo } from "./video-registry";import { CONTEXT_MENU } from "./link-context-menu";import { FLOATING_SCALE_VAR } from "./floating-events";-import { nudgeFloating, startFloatingGesture } from "./floating-preview";+import { announceGrab, nudgeFloating, startFloatingGesture } from "./floating-preview";import { closeOrFloatBrowser } from "./close-browser";import { CONTEXT_TAB_MENU, TabMenuItems, focusRenameField, renameTabTo, setTabMuted } from "./tab-menu";import {@@ -262,6 +262,7 @@ type ButtonProps = {disabled?: boolean;className?: string;children?: ReactNode;+ tooltip?: boolean;};function IconButton({@@ -272,31 +273,34 @@ function IconButton({disabled,className,children,+ tooltip = true,}: ButtonProps) {+ const button = (+ <button+ type="button"+ aria-label={label}+ onClick={onClick}+ disabled={disabled}+ className={cn(+ TOOLBAR_ICON_BUTTON,+ className,+ )}+ >+ {icon ? (+ <HugeiconsIcon+ icon={icon}+ strokeWidth={1.75}+ className="size-4.5"+ />+ ) : (+ children+ )}+ </button>+ );+ if (!tooltip) return button;return (<Tooltip>- <TooltipTrigger asChild={true}>- <button- type="button"- aria-label={label}- onClick={onClick}- disabled={disabled}- className={cn(- TOOLBAR_ICON_BUTTON,- className,- )}- >- {icon ? (- <HugeiconsIcon- icon={icon}- strokeWidth={1.75}- className="size-4.5"- />- ) : (- children- )}- </button>- </TooltipTrigger>+ <TooltipTrigger asChild={true}>{button}</TooltipTrigger><TooltipContent side="top" className="tooltip-compact">{shortcut ? (<span className="flex items-center gap-1.5">@@ -1514,19 +1518,19 @@ function FloatingBar({ tab, active }: { tab: BrowserTab | undefined; active: booreturn (<divonPointerDown={(event) => startFloatingGesture(event, "move")}+ onPointerEnter={announceGrab}onDoubleClick={(event) => {if (!(event.target as Element).closest("button:not([data-floating-handle])")) setFloating(false);}}className="browser-chrome flex h-[calc(30px*var(--ui-space-scale,1))] shrink-0 cursor-grab touch-none select-none items-center gap-px border-b border-border/70 px-1">- <IconButton label={t("browser.back")} disabled={!canGoBackIn(tab)} onClick={() => goBackIn(tab)} className={FLOATING_BUTTON}>+ <IconButton label={t("browser.back")} tooltip={false} disabled={!canGoBackIn(tab)} onClick={() => goBackIn(tab)} className={FLOATING_BUTTON}><ArrowLeft strokeWidth={NAV_STROKE} className={FLOATING_GLYPH} /></IconButton><buttontype="button"data-floating-handle=""aria-label={t("browser.floating.handle")}- title={title}onKeyDown={nudgeFloating}className="flex h-6 min-w-0 flex-1 cursor-grab items-center gap-1.5 rounded-[7px] px-1 text-start text-ui-11 text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring [&_img]:size-3.5 [&_svg]:size-3">@@ -1534,25 +1538,25 @@ function FloatingBar({ tab, active }: { tab: BrowserTab | undefined; active: boo<span className="min-w-0 flex-1 truncate">{title}</span></button><IconButton- label={t("browser.floating.dock")}+ label={t("browser.fullView.enter")}+ shortcut={fullViewShortcut}onClick={() => {- setFloating(false);+ setFullView(true);focusAfterLayout(SHOWN_TAB);}}className={FLOATING_BUTTON}>- {glyph(chatOnRight ? PanelLeftIcon : PanelRightIcon)}+ {glyph(EnterFullViewIcon)}</IconButton><IconButton- label={t("browser.fullView.enter")}- shortcut={fullViewShortcut}+ label={t("browser.floating.dock")}onClick={() => {- setFullView(true);+ setFloating(false);focusAfterLayout(SHOWN_TAB);}}className={FLOATING_BUTTON}>- {glyph(EnterFullViewIcon)}+ {glyph(chatOnRight ? PanelLeftIcon : PanelRightIcon)}</IconButton><IconButton label={t("browser.floating.close")} onClick={closePanel} className={FLOATING_BUTTON}>{glyph(Cancel01Icon)}@@ -1598,11 +1602,12 @@ function WebToolbar({ tab, visible }: { tab: BrowserTab | undefined; visible: boreturn (<><div className="flex shrink-0 items-center gap-0.5">- <IconButton label={t("browser.back")} disabled={!canGoBack} onClick={back} className={NAV_BUTTON}>+ <IconButton label={t("browser.back")} tooltip={false} disabled={!canGoBack} onClick={back} className={NAV_BUTTON}><ArrowLeft strokeWidth={NAV_STROKE} className={NAV_ICON} /></IconButton><IconButtonlabel={t("browser.forward")}+ tooltip={false}disabled={!canGoForward}onClick={forward}className={NAV_BUTTON}@@ -1611,6 +1616,7 @@ function WebToolbar({ tab, visible }: { tab: BrowserTab | undefined; visible: bo</IconButton><IconButtonlabel={t("browser.reload")}+ tooltip={false}disabled={!tab || currentEntry(tab).kind !== "web"}onClick={() => {if (!tab) return;@@ -1716,6 +1722,7 @@ function BrowserFileToolbar({<div className="flex shrink-0 items-center gap-0.5"><IconButtonlabel={t("browser.back")}+ tooltip={false}disabled={tab.index === 0}onClick={() => goBack(tab.id)}className={NAV_BUTTON}@@ -1724,6 +1731,7 @@ function BrowserFileToolbar({</IconButton><IconButtonlabel={t("browser.forward")}+ tooltip={false}disabled={tab.index >= tab.history.length - 1}onClick={() => goForward(tab.id)}className={NAV_BUTTON}@@ -1732,6 +1740,7 @@ function BrowserFileToolbar({</IconButton><IconButtonlabel={t(kind === "html" ? "browser.file.runAgain" : "browser.reload")}+ tooltip={kind === "html"}onClick={runAgain}className={NAV_BUTTON}>diff --git a/studio/frontend/src/features/browser/floating-events.ts b/studio/frontend/src/features/browser/floating-events.tsindex 12f0cff1003..070e9b134a9 100644--- a/studio/frontend/src/features/browser/floating-events.ts+++ b/studio/frontend/src/features/browser/floating-events.ts@@ -4,6 +4,8 @@export const FLOATING_ATTRIBUTE = "data-browser-floating";/** Per frame of a move, so a native page follows (native-view.ts). */export const FLOATING_MOVE_EVENT = "unsloth-browser-floating-move";+/** Pointer at or pressing the window's header: the page is captured for a drag. */+export const FLOATING_PRESS_EVENT = "unsloth-browser-floating-press";export const FLOATING_SCALE_VAR = "--browser-floating-scale";/** `browser_view_zoom`'s floor (browser_webview.rs): below it the call fails and the tab shows an error. */export const NATIVE_MIN_ZOOM = 0.25;diff --git a/studio/frontend/src/features/browser/floating-preview.ts b/studio/frontend/src/features/browser/floating-preview.tsindex 83ff6c0c45c..7247f0ae57e 100644--- a/studio/frontend/src/features/browser/floating-preview.ts+++ b/studio/frontend/src/features/browser/floating-preview.ts@@ -14,6 +14,7 @@ import type {import {FLOATING_ATTRIBUTE,FLOATING_MOVE_EVENT,+ FLOATING_PRESS_EVENT,FLOATING_SCALE_VAR,} from "./floating-events";@@ -278,6 +279,7 @@ const CURSORS: Record<FloatingEdge, string> = {};const announceMove = () => window.dispatchEvent(new Event(FLOATING_MOVE_EVENT));+export const announceGrab = () => window.dispatchEvent(new Event(FLOATING_PRESS_EVENT));/** A move rides a transform and a resize only rescales, once per frame; a sheet keeps the page's frame off the pointer. */export function startFloatingGesture(@@ -298,6 +300,7 @@ export function startFloatingGesture(const room = surface ? roomFor(surface) : null;if (!surface || !room) return;event.preventDefault();+ announceGrab();const start = currentBox(room);const startX = event.clientX;const startY = event.clientY;diff --git a/studio/frontend/src/features/browser/native-view.ts b/studio/frontend/src/features/browser/native-view.tsindex db6593a3600..9cd996971e6 100644--- a/studio/frontend/src/features/browser/native-view.ts+++ b/studio/frontend/src/features/browser/native-view.ts@@ -19,7 +19,13 @@ import { abandonDownload, beginDownload, finishDownload, useDownloadActivity } fimport { proxiedFavicon } from "./favicon";import { useBrowserHistoryStore } from "./history-store";import { decideNativeDownload } from "./native-downloads";-import { FLOATING_ATTRIBUTE, FLOATING_MOVE_EVENT, FLOATING_SCALE_VAR, floatingNativeZoom } from "./floating-events";+import {+ FLOATING_ATTRIBUTE,+ FLOATING_MOVE_EVENT,+ FLOATING_PRESS_EVENT,+ FLOATING_SCALE_VAR,+ floatingNativeZoom,+} from "./floating-events";import { outsideThread } from "./outside-thread";import { callNative as call, localOriginGranted, nativeClearing, onNativeViewsClosed, setLocalViewCloser } from "./native-support";import { useBrowserPrefsStore } from "./prefs-store";@@ -555,6 +561,9 @@ function lendKeys(blocked: boolean): void {const HOLE_ATTRIBUTE = "data-native-hole";const HOLE_VARS = ["--native-hole-x", "--native-hole-y", "--native-hole-w", "--native-hole-h"] as const;let holed: HTMLElement[] = [];+// In the floating window a fixed background misses the page: cut in the node's own box, backgrounds only.+const LOCAL_ATTRIBUTE = "data-native-hole-local";+let local: HTMLElement[] = [];// The wallpaper is no ancestor of the page, so it is masked instead.const MASK_ATTRIBUTE = "data-native-hole-mask";let masked: HTMLElement[] = [];@@ -567,6 +576,10 @@ let holeBounds: Bounds | null = null;// by cutting the hole no wider than the panel.let holeClip: DOMRect | null = null;+function paints(computed: CSSStyleDeclaration): boolean {+ return computed.backgroundImage !== "none" || opaque(computed.backgroundColor);+}+function opaque(color: string): boolean {if (color === "transparent") return false;const alpha = /\/\s*([\d.]+)%?\s*\)$/.exec(color) ?? /^rgba\([^)]*,\s*([\d.]+)\s*\)$/.exec(color);@@ -591,12 +604,43 @@ function placeHole(): void {const right = holeClip ? Math.min(holeBounds.x + holeBounds.width, holeClip.right) : holeBounds.x + holeBounds.width;const rect = [left, holeBounds.y, Math.max(0, right - left), holeBounds.height];const values = rect.map((value) => value / zoom);- for (const node of holed) HOLE_VARS.forEach((name, index) => node.style.setProperty(name, `${values[index]}px`));- // No zoom correction: a mask is no fixed background.- for (const node of masked) {+ for (const node of holed) {+ if (local.includes(node)) continue;+ HOLE_VARS.forEach((name, index) => node.style.setProperty(name, `${values[index]}px`));+ cutAt(node, "background", values[0], values[1], values[2], values[3]);+ }+ // No zoom correction: neither a mask nor a box-local cut is a fixed background.+ for (const node of [...local, ...masked]) {const box = node.getBoundingClientRect();- const local = [rect[0] - box.left, rect[1] - box.top, rect[2], rect[3]];- HOLE_VARS.forEach((name, index) => node.style.setProperty(name, `${local[index]}px`));+ // Untrimmed: a node that grows later (the chat as its panel floats) kept the old edge.+ const x = rect[0] - box.left;+ const y = rect[1] - box.top;+ const [width, height] = [rect[2], rect[3]];+ const cut = [x, y, width, height];+ HOLE_VARS.forEach((name, index) => node.style.setProperty(name, `${cut[index]}px`));+ cutAt(node, local.includes(node) ? "background" : "mask", x, y, width, height);+ }+}++const CUT_PROPERTIES = [+ "background-position",+ "background-size",+ "mask-position",+ "mask-size",+ "-webkit-mask-position",+ "-webkit-mask-size",+] as const;++/** Also as lengths: WebKit doesn't repaint a background or mask when only registered vars change. */+function cutAt(node: HTMLElement, kind: "background" | "mask", x: number, y: number, width: number, height: number): void {+ const right = x + width;+ const bottom = y + height;+ const position = `0 0, 0 ${bottom}px, 0 ${y}px, ${right}px ${y}px`;+ const size = `100% ${Math.max(0, y)}px, 100% max(0px, calc(100% - ${bottom}px)), ${Math.max(0, x)}px ${height}px, max(0px, calc(100% - ${right}px)) ${height}px`;+ const prefixes = kind === "background" ? ["background"] : ["mask", "-webkit-mask"];+ for (const prefix of prefixes) {+ node.style.setProperty(`${prefix}-position`, position, "important");+ node.style.setProperty(`${prefix}-size`, size, "important");}}@@ -615,19 +659,24 @@ function markHole(): boolean {.flatMap((node) => [...(node.children ?? [])].filter((child): child is HTMLElement => child.classList.contains("chat-wallpaper")));layers.push(...floatingUnderlay(chain));const signature = `${root.dataset.palette}|${theme}|${chain.map((node) => node.className).join("|")}|${layers.length}`;- if (signature === holeSignature && [...holed, ...masked].every((node) => node.isConnected)) return false;+ // A node can start painting later with no class change (just floated): uncut, the page stayed white.+ const missed = chain.some((node) => !node.hasAttribute?.(HOLE_ATTRIBUTE) && paints(getComputedStyle(node)));+ if (signature === holeSignature && !missed && [...holed, ...masked].every((node) => node.isConnected)) return false;unmarkHole();holeSignature = signature;+ const floating = chain.findIndex((node) => node.hasAttribute?.(FLOATING_ATTRIBUTE));const colors = chain.map((node) => getComputedStyle(node));chain.forEach((node, index) => {const computed = colors[index];- if (computed.backgroundImage === "none" && !opaque(computed.backgroundColor)) return;+ if (!paints(computed)) return;node.style.setProperty("--native-hole-bg", computed.backgroundColor);holed.push(node);+ if (index <= floating) local.push(node);});masked = layers;placeHole();for (const node of holed) node.setAttribute(HOLE_ATTRIBUTE, "");+ for (const node of local) node.setAttribute(LOCAL_ATTRIBUTE, "");for (const node of masked) node.setAttribute(MASK_ATTRIBUTE, "");// Mid theme switch everything can read transparent: retry next sync.if (holed.length === 0) holeSignature = "";@@ -651,12 +700,14 @@ function floatingUnderlay(chain: HTMLElement[]): HTMLElement[] {function unmarkHole(): void {for (const node of holed) {node.removeAttribute(HOLE_ATTRIBUTE);- for (const name of ["--native-hole-bg", ...HOLE_VARS]) node.style.removeProperty(name);+ for (const name of ["--native-hole-bg", ...HOLE_VARS, ...CUT_PROPERTIES]) node.style.removeProperty(name);}holed = [];+ for (const node of local) node.removeAttribute(LOCAL_ATTRIBUTE);+ local = [];for (const node of masked) {node.removeAttribute(MASK_ATTRIBUTE);- for (const name of HOLE_VARS) node.style.removeProperty(name);+ for (const name of [...HOLE_VARS, ...CUT_PROPERTIES]) node.style.removeProperty(name);}masked = [];holeSignature = "";@@ -679,7 +730,9 @@ function panelArea(element: HTMLElement): HTMLElement | null {/** Re-cuts the hole when the panel's edges move; cheap, so it runs every frame of a drag. */function clipHole(element: HTMLElement | null): void {- const area = element && layered ? panelArea(element)?.getBoundingClientRect() ?? null : null;+ // Docked only: in a floating window this chopped the cut at a stale panel edge.+ const docked = element && layered && !element.closest?.(`[${FLOATING_ATTRIBUTE}]`);+ const area = docked ? panelArea(element)?.getBoundingClientRect() ?? null : null;const same = area && holeClip ? area.left === holeClip.left && area.right === holeClip.right : area === holeClip;if (same) return;holeClip = area;@@ -758,7 +811,12 @@ function desiredView(): Desired {viewportWidth: window.innerWidth,},};- return !layered && coveredNow(rect) ? { ...shown, covered: true } : shown;+ const covered = movingWindow() || (!layered && coveredNow(rect));+ return covered ? { ...shown, covered: true } : shown;+}++function movingWindow(): boolean {+ return document.querySelector?.("[data-floating-gesture]") != null;}function pageRect(): { tab: BrowserTab; entry: Extract<BrowserEntry, { kind: "web" }>; rect: DOMRect } | null {@@ -1020,7 +1078,138 @@ export function refreshCoveredPage(tabId: string): void {});}+// The page's picture while its floating window moves: a child, as the placeholder's background is the cut's fill.+let dragShot: {+ tabId: string;+ url: string;+ image: HTMLImageElement;+ size: Bounds | null;+ layoutWidth: number;+ shown: boolean;+} | null = null;+let dragShotTicket = 0;++async function captureForDrag(tabId: string): Promise<void> {+ const ticket = ++dragShotTicket;+ const size = shownBounds;+ const layoutWidth = placeholder(tabId)?.clientWidth ?? 0;+ const png = await call<ArrayBuffer>("browser_capture", { tabId }).catch(() => null);+ if (!png?.byteLength) return;+ const url = URL.createObjectURL(new Blob([png], { type: "image/png" }));+ const image = new Image();+ image.src = url;+ if (!(await image.decode().then(() => true, () => false)) || ticket !== dragShotTicket) {+ URL.revokeObjectURL(url);+ return;+ }+ // Swapped in place: removing the old one first left the window empty.+ const wasShown = dragShot?.tabId === tabId && dragShot.shown;+ clearDragShot();+ dragShot = { tabId, url, image, size, layoutWidth, shown: false };+ if (wasShown || parkedView === tabId) showDragShot();+}++// The box is fractional, so its rounded size moves by a pixel with the window.+function sameSize(a: Bounds | null, b: Bounds | null): boolean {+ return !!a && !!b && Math.abs(a.width - b.width) <= 2 && Math.abs(a.height - b.height) <= 2;+}++function showDragShot(): void {+ const page = dragShot ? placeholder(dragShot.tabId) : null;+ // Taken at another size (before it floated): stretched, it flickered.+ if (!dragShot || !page || dragShot.shown || !sameSize(dragShot.size, shownBounds)) return;+ // The decoded image, not a CSS background: WebKit re-decoded that while the window moved.+ Object.assign(dragShot.image.style, {+ position: "absolute",+ left: "0",+ top: "0",+ // Its own proportions: scales with the window like the page, cropped, never stretched.+ width: dragShot.layoutWidth ? `${dragShot.layoutWidth}px` : "100%",+ height: "auto",+ pointerEvents: "none",+ });+ page.style.position = "relative";+ page.style.overflow = "hidden";+ page.appendChild(dragShot.image);+ dragShot.shown = true;+}++function hideDragShot(): void {+ if (!dragShot?.shown) return;+ const page = dragShot.image.parentElement;+ dragShot.image.remove();+ page?.style.removeProperty("position");+ page?.style.removeProperty("overflow");+ dragShot.shown = false;+}++function clearDragShot(): void {+ if (!dragShot) return;+ hideDragShot();+ URL.revokeObjectURL(dragShot.url);+ dragShot = null;+}++function floats(element: HTMLElement): boolean {+ return element.closest?.(`[${FLOATING_ATTRIBUTE}]`) != null;+}++/** Kept marked, so the app isn't restyled (a flash). */+function shutHole(): void {+ if (holeBounds && (holeBounds.width > 0 || holeBounds.height > 0)) {+ holeBounds = { ...holeBounds, width: 0, height: 0 };+ placeHole();+ }+}++function coverForDrag(tabId: string): void {+ shutHole();+ if (dragShot?.tabId === tabId) showDragShot();+}++// A dropped page redraws a moment after it lands (its off-window tiles may be gone): the picture stays till then.+const DROP_HOLD_MS = 400;+let dropTimer = 0;++function clearDragShotAfterDrop(): void {+ window.clearTimeout(dropTimer);+ dropTimer = window.setTimeout(() => {+ if (parkedView !== null || movingWindow()) return;+ hideDragShot();+ // No hover capture comes before the next drag, and a page that just floated has none at its size.+ const page = shownView ? placeholder(shownView) : null;+ if (shownView && page && floats(page)) void captureForDrag(shownView);+ }, DROP_HOLD_MS);+}++// Started outside the apply pump: applyView waits for it, or it could undo a quick drop's restore.+let parking: { tabId: string; done: Promise<void> } | null = null;++function parkForDrag(tabId: string): Promise<void> {+ if (parkedView === tabId) return Promise.resolve();+ if (parking?.tabId === tabId) return parking.done;+ coverForDrag(tabId);+ const done = call("browser_view_show", { tabId, bounds: shownBounds, parked: true }).then(+ () => {+ parkedView = tabId;+ setShownView(null);+ if (dragShot?.tabId === tabId) showDragShot();+ else void captureForDrag(tabId);+ },+ () => undefined,+ ).finally(() => {+ if (parking?.done === done) parking = null;+ });+ parking = { tabId, done };+ return done;+}+async function applyView(desired: Desired): Promise<void> {+ if (parking) await parking.done;+ if (desired && "covered" in desired && movingWindow() && parkable(desired.tabId)) {+ await parkForDrag(desired.tabId);+ return;+ }if (!desired || "covered" in desired) {closeHole();// keep the snapshot if an overlay reopens during capture.@@ -1051,12 +1240,31 @@ async function applyView(desired: Desired): Promise<void> {};try {openedTabs.add(tabId);+ // Zoomed while hidden, so the page isn't seen at the old scale (on top: parked here; layered: cut shut).+ const rezoom = existed && loaded === entry && (zooms.get(tabId) ?? 1) !== zoom;+ const resized = JSON.stringify(bounds) !== JSON.stringify(shownBounds);+ if (rezoom && !layered && shownView === tabId && resized) {+ await call("browser_view_show", { tabId, bounds: shownBounds, parked: true });+ if (stale()) return;+ parkedView = tabId;+ }+ if (rezoom && parkedView === tabId) {+ zooms.set(tabId, zoom);+ await call("browser_view_zoom", { tabId, zoom });+ if (stale()) return;+ }await call("browser_view_show", { tabId, url: resumed?.entry === entry ? resumed.url : url, bounds });if (stale()) return;parkedView = null;staleSnapshot = null;coverFails = 0;clearSnapshot();+ clearDragShotAfterDrop();+ if (layered && existed && loaded === entry && (zooms.get(tabId) ?? 1) !== zoom) {+ zooms.set(tabId, zoom);+ await call("browser_view_zoom", { tabId, zoom });+ if (stale()) return;+ }// After the move, so hole and page update together.if (layered) openHole(tabId, bounds);shownBounds = bounds;@@ -1145,12 +1353,18 @@ export function startNativeViews(): () => void {const sync = () => {frame = 0;if (layered === null) return;- // A page on top waits out a floating drag under its snapshot, not a capture per frame.- if (!layered && parkedView !== null && document.querySelector?.("[data-floating-gesture]")) return;+ if (parkedView !== null && document.querySelector?.("[data-floating-gesture]")) return;markHole();const desired = desiredView();+ if (desired && movingWindow() && desired.tabId === shownView) coverForDrag(desired.tabId);pruneViews(desired?.tabId ?? null);const element = desired ? placeholder(desired.tabId) : null;+ // Docked <-> floating: the old cut showed the page through the chat until it moved.+ if (layered !== null && element && resized && element !== resized && desired?.tabId === shownView && floats(element) !== floats(resized)) {+ if (layered) shutHole();+ // The chat's panels animate and the window's backgrounds paint late: re-cut every frame.+ motionUntil = performance.now() + MOTION_MS;+ }if (element !== resized) {if (resized) resizeObserver.unobserve(resized);if (resizedArea) areaObserver.unobserve(resizedArea);@@ -1160,6 +1374,8 @@ export function startNativeViews(): () => void {resized = element;}clipHole(element);+ // Boxes under the cut resize on their own (the chat as its panel floats).+ placeHole();if (performance.now() < motionUntil) schedule();const key = JSON.stringify([epoch, coverRetry, desired]);if (key === sent) return;@@ -1198,9 +1414,21 @@ export function startNativeViews(): () => void {document.addEventListener("pointerup", schedule, true);// A layered page follows the floating window; one on top waits for the drop (see sync).const floatingMoved = () => {+ // In the move's own frame (a sync is a frame late); on top of the app nothing syncs mid-gesture.+ if (shownView && movingWindow()) {+ const tabId = shownView;+ coverForDrag(tabId);+ // Outside apply: forgotten, or a gesture ending where it started never shows the page again.+ sent = "";+ if (!layered && parkable(tabId)) void parkForDrag(tabId);+ }if (layered || !document.querySelector("[data-floating-gesture]")) schedule();};window.addEventListener(FLOATING_MOVE_EVENT, floatingMoved);+ const floatingPressed = () => {+ if (layered !== null && shownView) void captureForDrag(shownView);+ };+ window.addEventListener(FLOATING_PRESS_EVENT, floatingPressed);const interval = window.setInterval(schedule, RECHECK_MS);void askLayered().then(schedule);schedule();@@ -1217,6 +1445,7 @@ export function startNativeViews(): () => void {document.removeEventListener("pointerover", reachedPage, true);document.removeEventListener("pointerup", schedule, true);window.removeEventListener(FLOATING_MOVE_EVENT, floatingMoved);+ window.removeEventListener(FLOATING_PRESS_EVENT, floatingPressed);window.clearInterval(interval);panelUp = false;tooltipHold = 0;@@ -1227,6 +1456,7 @@ export function startNativeViews(): () => void {parkedView = null;setShownView(null);clearSnapshot();+ clearDragShot();closeHole();sendInput(NO_INPUT);insetToasts(null);diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.cssindex 33a6a13eea7..3cd2e2281dc 100644--- a/studio/frontend/src/index.css+++ b/studio/frontend/src/index.css@@ -6160,6 +6160,12 @@ html[data-find-bar-open] [data-sonner-toaster][data-y-position="top"] {max(0px, calc(100% - var(--native-hole-x) - var(--native-hole-w))) var(--native-hole-h) !important;}+/* Floating window: cut in the node's own box (native-view.ts). */+[data-native-hole][data-native-hole-local] {+ background-attachment: scroll !important;+ background-origin: border-box !important;+}+/* A backdrop-filter would paint over the hole. */[data-native-hole] {-webkit-backdrop-filter: none !important;diff --git a/studio/frontend/tests/browser-native-floating-hole.test.ts b/studio/frontend/tests/browser-native-floating-hole.test.tsnew file mode 100644index 00000000000..52cc2372bfe--- /dev/null+++ b/studio/frontend/tests/browser-native-floating-hole.test.ts@@ -0,0 +1,95 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Floating window paths, read from source (no DOM here).++import assert from "node:assert/strict";+import test from "node:test";++import { readSrc } from "./helpers/kit.ts";++const NATIVE = readSrc("features/browser/native-view.ts");+const CSS = readSrc("index.css");++function body(name: string): string {+ const at = NATIVE.indexOf(`function ${name}(`);+ assert.notEqual(at, -1, `${name} not found`);+ return NATIVE.slice(at, NATIVE.indexOf("\n}\n", at));+}++test("backgrounds inside the floating window are cut in their own box, and the window is not masked", () => {+ const mark = body("markHole");+ assert.match(mark, /const floating = chain\.findIndex\(\(node\) => node\.hasAttribute\?\.\(FLOATING_ATTRIBUTE\)\)/);+ assert.match(mark, /if \(index <= floating\) local\.push\(node\);/);+ // A mask would hide UI drawn over the page too, e.g. the annotation comment form.+ assert.match(mark, /masked = layers;/);+ assert.match(CSS, /\[data-native-hole\]\[data-native-hole-local\] \{\s*background-attachment: scroll !important;\s*background-origin: border-box !important;/);+});++test("a box-local or mask cut is not trimmed to the box, and its lengths stay non-negative", () => {+ const place = body("placeHole");+ assert.match(place, /const x = rect\[0\] - box\.left;/);+ assert.match(place, /const \[width, height\] = \[rect\[2\], rect\[3\]\];/);+ const cut = body("cutAt");+ assert.match(cut, /100% \$\{Math\.max\(0, y\)\}px/);+ assert.match(cut, /\$\{Math\.max\(0, x\)\}px \$\{height\}px/);+});++test("every cut is also written as lengths, which WebKit repaints, and removed when unmarked", () => {+ const place = body("placeHole");+ assert.match(place, /cutAt\(node, "background", values\[0\], values\[1\], values\[2\], values\[3\]\);/);+ assert.match(place, /cutAt\(node, local\.includes\(node\) \? "background" : "mask", x, y, width, height\);/);+ const cut = body("cutAt");+ assert.match(cut, /const prefixes = kind === "background" \? \["background"\] : \["mask", "-webkit-mask"\];/);+ assert.match(cut, /setProperty\(`\$\{prefix\}-position`, position, "important"\)/);+ assert.match(body("unmarkHole"), /\.\.\.CUT_PROPERTIES\]\) node\.style\.removeProperty\(name\)/);+});++test("the panel-edge clip, for a docked split drag, is not applied in the floating window", () => {+ const clip = body("clipHole");+ assert.match(clip, /const docked = element && layered && !element\.closest\?\.\(`\[\$\{FLOATING_ATTRIBUTE\}\]`\);/);+ assert.match(clip, /const area = docked \? panelArea\(element\)\?\.getBoundingClientRect\(\) \?\? null : null;/);+});++test("switching between docked and floating shuts the cut until the page is moved and zoomed there", () => {+ const start = NATIVE.indexOf(" const sync = () => {");+ const sync = NATIVE.slice(start, NATIVE.indexOf("\n };\n", start));+ assert.match(sync, /layered !== null && element && resized[^\n]*floats\(element\) !== floats\(resized\)\) \{\s*if \(layered\) shutHole\(\);/);+ assert.match(sync, /shutHole\(\);[\s\S]*?motionUntil = performance\.now\(\) \+ MOTION_MS;\s*\}/);+ const apply = body("applyView");+ const call = 'await call("browser_view_zoom", { tabId, zoom });';+ const show = apply.indexOf('await call("browser_view_show", { tabId, url:');+ const zoom = apply.indexOf(call, show);+ assert.ok(zoom > show, "zoomed after the move");+ assert.ok(zoom < apply.indexOf("if (layered) openHole(tabId, bounds);"), "and before the cut opens");+ const parked = apply.indexOf("if (rezoom && parkedView === tabId) {");+ assert.match(apply, /if \(rezoom && !layered && shownView === tabId && resized\) \{\s*await call\("browser_view_show", \{ tabId, bounds: shownBounds, parked: true \}\);/);+ assert.ok(parked >= 0 && apply.indexOf(call, parked) < show);+});++test("a moved or resized floating window parks its page under the picture on every platform", () => {+ assert.match(NATIVE, /function movingWindow\(\): boolean \{\s*return document\.querySelector\?\.\("\[data-floating-gesture\]"\) != null;/);+ assert.match(NATIVE, /const covered = movingWindow\(\) \|\| \(!layered && coveredNow\(rect\)\);/);+ assert.match(body("applyView"), /if \(desired && "covered" in desired && movingWindow\(\) && parkable\(desired\.tabId\)\) \{\s*await parkForDrag/);+ assert.match(NATIVE, /coverForDrag\(tabId\);\s*(\/\/[^\n]*\n\s*)*sent = "";\s*if \(!layered && parkable\(tabId\)\) void parkForDrag\(tabId\);/);+ assert.match(readSrc("features/browser/floating-preview.ts"), /event\.preventDefault\(\);\s*announceGrab\(\);/);+});++test("a drag picture taken at another size (before the page floated) is never shown", () => {+ assert.match(body("showDragShot"), /!sameSize\(dragShot\.size, shownBounds\)\) return;/);+ assert.match(body("captureForDrag"), /const size = shownBounds;/);+ assert.match(body("sameSize"), /Math\.abs\(a\.width - b\.width\) <= 2 && Math\.abs\(a\.height - b\.height\) <= 2/);+});++test("a resize crops the drag picture instead of stretching it", () => {+ const show = body("showDragShot");+ assert.match(show, /width: dragShot\.layoutWidth \? `\$\{dragShot\.layoutWidth\}px` : "100%",\s*height: "auto",/);+ assert.match(body("captureForDrag"), /const layoutWidth = placeholder\(tabId\)\?\.clientWidth \?\? 0;/);+ assert.match(show, /page\.style\.overflow = "hidden";/);+ assert.match(body("hideDragShot"), /removeProperty\("overflow"\)/);+});++test("a park started on a gesture's first frame finishes before the drop's restore", () => {+ assert.match(body("applyView"), /function applyView\(desired: Desired\): Promise<void> \{\s*if \(parking\) await parking\.done;/);+ assert.match(body("parkForDrag"), /if \(parking\?\.tabId === tabId\) return parking\.done;/);+});diff --git a/studio/frontend/tests/browser-native-view-layered.test.ts b/studio/frontend/tests/browser-native-view-layered.test.tsindex 2621efd2cfc..230c537fc9f 100644--- a/studio/frontend/tests/browser-native-view-layered.test.ts+++ b/studio/frontend/tests/browser-native-view-layered.test.ts@@ -183,7 +183,7 @@ test("a menu over a layered page neither captures nor hides it, and owns its inp};const innerPage = { parentElement: outerPage, closest: () => innerPage };const unpinned = placeholder.closest;- Object.assign(placeholder, { closest: () => innerPage });+ Object.assign(placeholder, { closest: (selector: string) => (selector === "[data-browser-page]" ? innerPage : null) });const showsBeforeDrag = calls.filter(({ command }) => command === "browser_view_show").length;for (const left of [650, 700, 750]) {panelLeft = left;@@ -457,3 +457,105 @@ test("a page whose protections fail shows an error, and Try again opens a new vistop();}});++test("a dragged floating window shows its layered page as a snapshot, and the live page again on the drop", async () => {+ const doc = (globalThis as unknown as { document: { querySelector: (selector: string) => unknown } }).document;+ const globals = globalThis as unknown as Record<string, unknown>;+ const { querySelector } = doc;+ const { Image, nativeViewCall } = globals;+ globals.Image = class {+ src = "";+ style = {};+ parentElement: unknown = null;+ decode = () => Promise.resolve();+ remove = () => shown.splice(shown.indexOf(this as unknown as (typeof shown)[number]), 1);+ };+ globals.nativeViewCall = (command: string, args?: Record<string, unknown>) => {+ calls.push({ command, args });+ if (command === "browser_capture") return Promise.resolve(new Uint8Array([137, 80, 78, 71]).buffer);+ return Promise.resolve(command === "browser_view_layered" ? true : undefined);+ };+ const unpinned = placeholder.closest;+ Object.assign(placeholder, { closest: (selector: string) => (selector === "[data-browser-floating]" ? {} : null) });+ const shown: { style: Record<string, string>; parentElement: unknown; remove: () => void }[] = [];+ Object.assign(placeholder, {+ appendChild: (child: (typeof shown)[number]) => {+ child.parentElement = placeholder;+ shown.push(child);+ },+ });+ let moving = false;+ doc.querySelector = (selector: string) =>+ selector.startsWith("[data-floating-gesture") ? (moving ? {} : null) : querySelector(selector);+ // an earlier test left only the section opaque+ const cut = () => section.attributes.has("data-native-hole") && section.vars.get("--native-hole-w") !== "0px";+ useBrowserStore.getState().openUrl("https://drag.example/");+ const stop = startNativeViews();+ try {+ await frame();+ await frame();+ const tabId = useBrowserStore.getState().activeTabId;+ assert.ok(cut(), "cut open while still");++ const from = calls.length;+ moving = true;+ await frame();+ await frame();+ const during = calls.slice(from);+ assert.ok(during.some(({ command, args }) => command === "browser_capture" && args?.tabId === tabId));+ assert.ok(during.some(({ command, args }) => command === "browser_view_show" && args?.parked === true));+ assert.ok(!cut(), "the picture shows, uncut, while the window moves");+ assert.ok(section.attributes.has("data-native-hole"), "cuts stay marked, so the app is not restyled");+ await settle();+ assert.equal(shown.length, 1, "the picture is laid over the page");+ const parked = calls.length;+ await frame();+ assert.equal(calls.length, parked, "nothing is sent per frame of the drag");++ moving = false;+ await frame();+ await frame();+ const dropped = calls.slice(parked);+ assert.ok(dropped.some(({ command, args }) => command === "browser_view_show" && args?.tabId === tabId && !args?.parked));+ assert.ok(cut(), "cut open again on the drop");+ assert.equal(shown.length, 1, "the picture stays a moment, while the page draws");+ const held = calls.length;+ await new Promise((resolve) => setTimeout(resolve, 450));+ assert.equal(shown.length, 0, "and is taken away");+ assert.ok(+ calls.slice(held).some(({ command, args }) => command === "browser_capture" && args?.tabId === tabId),+ "a fresh picture is taken for the next drag, with the pointer still on the bar",+ );+ await settle();+ moving = true;+ await frame();+ assert.equal(shown.length, 1, "so the next drag shows it from its first frame");+ moving = false;+ await frame();+ await frame();+ } finally {+ stop();+ Object.assign(placeholder, { closest: unpinned });+ doc.querySelector = querySelector;+ globals.Image = Image;+ globals.nativeViewCall = nativeViewCall;+ }+});++test("a node around a layered page that starts painting later, with no class change, is cut too", async () => {+ useBrowserStore.getState().openUrl("https://late.example/");+ const stop = startNativeViews();+ const before = wrapper.background;+ try {+ await frame();+ await frame();+ assert.ok(!wrapper.attributes.has("data-native-hole"), "transparent when marked");+ // e.g. switching to the floating window: the panel's background lands a frame later+ wrapper.background = "rgb(254, 254, 253)";+ await frame();+ assert.ok(wrapper.attributes.has("data-native-hole"), "cut once it paints");+ } finally {+ stop();+ wrapper.background = before;+ }+});diff --git a/studio/src-tauri/src/browser_webview.rs b/studio/src-tauri/src/browser_webview.rsindex c15d627a904..a6e5d9c2c6b 100644--- a/studio/src-tauri/src/browser_webview.rs+++ b/studio/src-tauri/src/browser_webview.rs@@ -123,6 +123,23 @@ const PAGE_GUARD_SCRIPT: &str = r#"(() => {const PAGE_RESTORE_SCRIPT: &str = "window.__unslothPageGuard?.();";+/// Studio's scrollbar in pages; first in the document, so a page's own scrollbar styles win.+const PAGE_SCROLLBAR_SCRIPT: &str = r#"(() => {+ const css = "::-webkit-scrollbar{width:8px;height:8px;background:transparent}"+ + "::-webkit-scrollbar-track,::-webkit-scrollbar-track-piece,::-webkit-scrollbar-corner{background:transparent;border:none;box-shadow:none}"+ + "::-webkit-scrollbar-thumb{background:rgb(99 99 99 / 0.54);border-radius:9999px;border:none;box-shadow:none}"+ + "::-webkit-scrollbar-button{display:none;width:0;height:0}";+ const add = () => {+ const root = document.documentElement;+ if (!root) return false;+ const style = document.createElement("style");+ style.textContent = css;+ root.prepend(style);+ return true;+ };+ if (!add()) new MutationObserver((_, seen) => add() && seen.disconnect()).observe(document, { childList: true });+})();"#;+/// Registered before the opener, dialog and notification plugins (`PAGE_GUARD_SCRIPT`).pub fn page_guard_plugin<R: Runtime>() -> tauri::plugin::TauriPlugin<R> {tauri::plugin::Builder::new("unsloth-page-guard")@@ -1469,6 +1486,7 @@ async fn create_view<R: Runtime>(_ => false,}).initialization_script(PAGE_RESTORE_SCRIPT)+ .initialization_script(PAGE_SCROLLBAR_SCRIPT).zoom_hotkeys_enabled(false).devtools(cfg!(debug_assertions)).focused(false);@@ -2775,6 +2793,17 @@ mod tests {);}+ #[test]+ fn pages_get_the_studio_scrollbar_first_in_the_document() {+ let source = include_str!("browser_webview.rs").replace("\r\n", "\n");+ let code = &source[..source.find("#[cfg(test)]\nmod tests").unwrap()];+ assert!(code.contains(".initialization_script(PAGE_SCROLLBAR_SCRIPT)"));+ assert!(PAGE_SCROLLBAR_SCRIPT.contains("root.prepend(style)"));+ assert!(PAGE_SCROLLBAR_SCRIPT.contains("border-radius:9999px"));+ let studio = include_str!("../../frontend/src/index.css");+ assert!(studio.contains("::-webkit-scrollbar {\n\twidth: 8px;"));+ }+#[test]fn the_internet_mark_keeps_where_not_secrets() {let source = |url: &str| sanitized_source(&Url::parse(url).unwrap());