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): reuse hardware monitor drag and resize handling for API monitor (#12204)
Lee Jackson51411259562f
diff --git a/studio/frontend/src/components/floating-monitor.tsx b/studio/frontend/src/components/floating-monitor.tsxindex c6bf540d0d6..ad93a5fbaeb 100644--- a/studio/frontend/src/components/floating-monitor.tsx+++ b/studio/frontend/src/components/floating-monitor.tsx@@ -1,15 +1,13 @@// 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 { useFloatingPanelLayout } from "@/hooks/use-floating-panel-layout";import { Button } from "@/components/ui/button";import { Progress } from "@/components/ui/progress";import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";import { FIND_PORTAL_ATTRIBUTE } from "@/features/find-in-page/lib/find-attributes";-import {- useMonitorFrameStore,- useMonitorOverlayStore,-} from "@/features/settings";+import { useMonitorOverlayStore } from "@/features/settings";import { gpuMemoryDisplay } from "@/hooks/gpu-memory-display";import { gpuMemoryTotalsGb, resolveGpuVramUsedGb } from "@/hooks/gpu-vram";import { useChatSettingsWidth } from "@/hooks/use-chat-settings-width";@@ -26,15 +24,7 @@ import { cn } from "@/lib/utils";import { useRouterState } from "@tanstack/react-router";import { CpuIcon, GripVerticalIcon, XIcon } from "lucide-react";import { AnimatePresence, motion } from "motion/react";-import {- type PointerEvent,- useEffect,- useLayoutEffect,- useMemo,- useRef,- useState,- useSyncExternalStore,-} from "react";+import { useEffect, useRef, useState, useSyncExternalStore } from "react";import {FLOATING_MONITOR_WIDTH,@@ -43,429 +33,8 @@ import {} from "./floating-monitor-layout";import { useUiSpaceScale } from "@/hooks/use-ui-space-scale";-interface MonitorLayout {- left: number;- top: number;- minWidth: number;- minHeight: number;- maxWidth: number;- maxHeight: number;-}--interface DragSession {- pointerId: number;- startX: number;- startY: number;- left: number;- top: number;- maxLeft: number;- maxTop: number;- constraintsWidth: number;- constraintsHeight: number;- /** The committed left/top the drag's transform offsets from. */- baseLeft: number;- baseTop: number;-}--function clamp(value: number, min: number, max: number): number {- return Math.max(min, Math.min(max, value));-}--// Anchored to the far edge until the user drags, then clamped where they left it.-function place(dragged: boolean, current: number, max: number): number {- return dragged ? clamp(current, 0, max) : max;-}--function sameLayout(a: MonitorLayout, b: MonitorLayout): boolean {- return (- a.left === b.left &&- a.top === b.top &&- a.minWidth === b.minWidth &&- a.minHeight === b.minHeight &&- a.maxWidth === b.maxWidth &&- a.maxHeight === b.maxHeight- );-}--// Height the panel wants. Reading the rendered box instead hides growth once-// maxHeight caps it, so the observer never fires and the cap is never lifted.-function desiredPanelHeight(- renderedHeight: number,- scroll: HTMLDivElement | null,- content: HTMLDivElement | null,-): number {- if (!(scroll && content)) {- return renderedHeight;- }- // The scroll region is the only flexible child, so the rest is fixed chrome.- const chrome = renderedHeight - scroll.getBoundingClientRect().height;- return chrome + content.getBoundingClientRect().height;-}--// Width the panel wants. While anchored, maxWidth equals the current width, so-// the cap is also a floor: a monitor opened in a narrow window never widens-// again. Lift the cap for one measurement to break that.-function naturalWidth(monitor: HTMLDivElement): number {- const capped = monitor.style.maxWidth;- // "none", not "", so the class-level max-w-full lifts too.- monitor.style.maxWidth = "none";- const width = monitor.getBoundingClientRect().width;- monitor.style.maxWidth = capped;- return width;-}--function useMonitorLayout(- constraintsElement: HTMLDivElement | null,- narrowed: boolean,- hidden: boolean,-) {- // This panel's claim on the shared frame. Reopening the monitor mid-exit- // mounts the replacement while the old panel is still animating out, and the- // old one unmounts last, so its cleanup must only clear its own frame.- const publisher = useMemo(() => ({}), []);- const monitorRef = useRef<HTMLDivElement>(null);- const scrollRef = useRef<HTMLDivElement>(null);- const contentRef = useRef<HTMLDivElement>(null);- const dragSessionRef = useRef<DragSession | null>(null);- const dragFrameRef = useRef(0);- const hasDraggedLeftRef = useRef(false);- const hasDraggedTopRef = useRef(false);- const preferredWidthRef = useRef<number | null>(null);- const preferredHeightRef = useRef<number | null>(null);- const surfaceWidthRef = useRef(0);- const narrowedRef = useRef(narrowed);- const hiddenRef = useRef(hidden);- // The user's own placement while the container is at full width. Cleared when- // they drag while it is narrowed, which is a newer choice, not a clamp.- const chosenLeftRef = useRef<number | null>(null);- const restoreLeftRef = useRef<number | null>(null);- const remeasureRef = useRef(0);- const [layout, setLayout] = useState<MonitorLayout | null>(null);- // Reconcile normally arrives from the observers. A transition that leaves the- // constraint geometry untouched -- suppressed to undocked -- fires none.- const reconcileRef = useRef<(() => void) | null>(null);-- useLayoutEffect(() => {- const monitor = monitorRef.current;- const constraints = constraintsElement;- if (!(monitor && constraints)) {- return;- }- // Deferred to the next frame: writing a style while ResizeObserver entries- // are delivered makes Firefox report an observer loop. A hand-resized panel- // keeps the user's width instead of re-measuring.- const scheduleWidthRemeasure = (surfaceWidth: number) => {- if (surfaceWidth === surfaceWidthRef.current) {- return;- }- surfaceWidthRef.current = surfaceWidth;- if (monitor.style.width || remeasureRef.current) {- return;- }- remeasureRef.current = requestAnimationFrame(() => {- remeasureRef.current = 0;- preferredWidthRef.current = naturalWidth(monitor);- reconcileGeometry();- });- };-- const reconcileGeometry = () => {- const constraintsBox = constraints.getBoundingClientRect();- const monitorBox = monitor.getBoundingClientRect();- const desiredHeight = desiredPanelHeight(- monitorBox.height,- scrollRef.current,- contentRef.current,- );-- scheduleWidthRemeasure(constraintsBox.width);- const desiredWidth = Math.max(- monitorBox.width,- preferredWidthRef.current ?? monitorBox.width,- );-- // Content height is the floor, as a resolved number: intrinsic- // min-content outranks max-height, a number clamped to it cannot.- if (!monitor.style.height) {- preferredHeightRef.current = desiredHeight;- }-- const width = Math.min(desiredWidth, constraintsBox.width);- // Clamp position against the height actually rendered. A hand-resized panel keeps its own- // height and scrolls, so growing content must not drag it upwards and leave a gap below.- const height = Math.min(- monitor.style.height ? monitorBox.height : desiredHeight,- constraintsBox.height,- );- const maxLeft = Math.max(0, constraintsBox.width - width);- const maxTop = Math.max(0, constraintsBox.height - height);- const currentLeft = monitorBox.left - constraintsBox.left;- const currentTop = monitorBox.top - constraintsBox.top;- // A restored position is a deliberate left the constraint had clamped- // away, so it replaces `place()` for exactly one pass.- const restoreTo = restoreLeftRef.current;- const left =- restoreTo === null- ? place(hasDraggedLeftRef.current, currentLeft, maxLeft)- : clamp(restoreTo, 0, maxLeft);- restoreLeftRef.current = null;- if (!narrowedRef.current && hasDraggedLeftRef.current) {- chosenLeftRef.current = left;- }- const top = place(hasDraggedTopRef.current, currentTop, maxTop);-- const session = dragSessionRef.current;- if (session) {- session.left = left;- session.top = top;- session.maxLeft = maxLeft;- session.maxTop = maxTop;- session.constraintsWidth = constraintsBox.width;- session.constraintsHeight = constraintsBox.height;- }-- // Publish the real box so the overlay stack can keep clear of it.- if (!hiddenRef.current) {- useMonitorFrameStore.getState().setFrame(publisher, {- left: monitorBox.left,- top: monitorBox.top,- right: monitorBox.right,- bottom: monitorBox.bottom,- });- }-- setLayout((current) => {- // Mid-drag the offset lives in a transform, and the measured box already includes it, so- // committing left/top here would apply it twice. finishDrag lands the position instead.- const held = session && current ? current : null;- const restLeft = held?.left ?? left;- const restTop = held?.top ?? top;- const next = {- left: restLeft,- top: restTop,- minWidth: preferredWidthRef.current ?? monitorBox.width,- minHeight: preferredHeightRef.current ?? monitorBox.height,- maxWidth: constraintsBox.width - restLeft,- maxHeight: constraintsBox.height - restTop,- };- return current && sameLayout(current, next) ? current : next;- });- };-- reconcileRef.current = reconcileGeometry;- reconcileGeometry();- const observer = new ResizeObserver(reconcileGeometry);- observer.observe(constraints);- observer.observe(monitor);- // The unclamped content wrapper is what makes late GPU rows reposition the- // panel instead of being cut off.- if (contentRef.current) {- observer.observe(contentRef.current);- }- return () => {- observer.disconnect();- reconcileRef.current = null;- useMonitorFrameStore.getState().clearFrame(publisher);- if (remeasureRef.current) {- cancelAnimationFrame(remeasureRef.current);- remeasureRef.current = 0;- }- if (dragFrameRef.current) {- cancelAnimationFrame(dragFrameRef.current);- dragFrameRef.current = 0;- }- };- }, [constraintsElement, publisher]);-- // Narrowing clamps the monitor left, and `place()` keeps the clamped spot.- // The position the user did drag to is put back when the container widens.- // Settled in a layout effect, before the next observation can reconcile.- // The API monitor treats any published frame as a live obstacle, so an- // invisible resource monitor must not keep publishing its box. Visibility and- // aria-hidden fire no ResizeObserver, so `hidden` also feeds the republish- // below: it is what restores the box once the monitor is on screen again.- useLayoutEffect(() => {- hiddenRef.current = hidden;- if (hidden) {- useMonitorFrameStore.getState().clearFrame(publisher);- }- }, [hidden, publisher]);-- useLayoutEffect(() => {- if (narrowedRef.current === narrowed) {- return;- }- narrowedRef.current = narrowed;- if (!narrowed) {- restoreLeftRef.current = chosenLeftRef.current;- reconcileRef.current?.();- }- }, [narrowed]);-- // ResizeObserver never fires for a position-only change, so dragging alone would leave the- // published frame at the monitor's old corner and the overlay stack dodging where it used to be.- // Re-publish once each layout is committed, which after a drag is on release: the frames in- // between are a transform, and republishing through them would re-render every overlay in the- // stack for each one, which is most of what made dragging feel heavy.- useLayoutEffect(() => {- void layout;- const monitor = monitorRef.current;- if (!(monitor && constraintsElement) || hiddenRef.current) {- return;- }- const box = monitor.getBoundingClientRect();- useMonitorFrameStore.getState().setFrame(publisher, {- left: box.left,- top: box.top,- right: box.right,- bottom: box.bottom,- });- }, [layout, constraintsElement, publisher, hidden]);-- function startDrag(event: PointerEvent<HTMLDivElement>) {- const monitor = monitorRef.current;- if (event.button !== 0 || !(monitor && constraintsElement)) {- return;- }-- event.preventDefault();- const constraintsBox = constraintsElement.getBoundingClientRect();- const monitorBox = monitor.getBoundingClientRect();- const left = monitorBox.left - constraintsBox.left;- const top = monitorBox.top - constraintsBox.top;-- // Native resize records attempted inline dimensions even when max-width- // or max-height hides them. Normalize only hidden dimensions so an- // auto-sized monitor can still grow when system rows arrive later.- const inlineWidth = Number.parseFloat(monitor.style.width);- const inlineHeight = Number.parseFloat(monitor.style.height);- if (- Number.isFinite(inlineWidth) &&- Math.abs(inlineWidth - monitorBox.width) > 0.5- ) {- monitor.style.width = `${monitorBox.width}px`;- }- if (- Number.isFinite(inlineHeight) &&- Math.abs(inlineHeight - monitorBox.height) > 0.5- ) {- monitor.style.height = `${monitorBox.height}px`;- }-- dragSessionRef.current = {- pointerId: event.pointerId,- startX: event.clientX,- startY: event.clientY,- left,- top,- maxLeft: Math.max(0, constraintsBox.width - monitorBox.width),- maxTop: Math.max(0, constraintsBox.height - monitorBox.height),- constraintsWidth: constraintsBox.width,- constraintsHeight: constraintsBox.height,- baseLeft: left,- baseTop: top,- };- event.currentTarget.setPointerCapture(event.pointerId);- }-- // One paint per frame, and through a transform rather than left/top. The panel is- // backdrop-blurred, so every layout-driven move re-sampled what is behind it; a trackpad also- // reports moves faster than the display refreshes, so most of those renders were never shown.- function paintDrag() {- dragFrameRef.current = 0;- const session = dragSessionRef.current;- const monitor = monitorRef.current;- if (!(session && monitor)) {- return;- }- monitor.style.transform = `translate3d(${session.left - session.baseLeft}px, ${- session.top - session.baseTop- }px, 0)`;- }-- function updateDrag(event: PointerEvent<HTMLDivElement>) {- const session = dragSessionRef.current;- if (!session || session.pointerId !== event.pointerId) {- return;- }-- // Horizontal placement is chosen on release. An intermediate move that- // returns to its starting X must leave an anchored monitor anchored.- const previousTop = session.top;- const left = clamp(- session.left + event.clientX - session.startX,- 0,- session.maxLeft,- );- const top = clamp(- session.top + event.clientY - session.startY,- 0,- session.maxTop,- );- if (top !== previousTop) {- hasDraggedTopRef.current = true;- }- session.startX = event.clientX;- session.startY = event.clientY;- session.left = left;- session.top = top;- if (!dragFrameRef.current) {- dragFrameRef.current = requestAnimationFrame(paintDrag);- }- }-- function finishDrag(event: PointerEvent<HTMLDivElement>) {- const session = dragSessionRef.current;- if (session?.pointerId !== event.pointerId) {- return;- }- if (dragFrameRef.current) {- cancelAnimationFrame(dragFrameRef.current);- dragFrameRef.current = 0;- }- const { left, top, baseLeft, constraintsWidth, constraintsHeight } =- session;- dragSessionRef.current = null;- // Only the released horizontal position is a new choice. Returning to the- // starting X keeps the saved full-width position even after intermediate moves.- if (left !== baseLeft) {- hasDraggedLeftRef.current = true;- chosenLeftRef.current = narrowedRef.current ? null : left;- }- // Written to the node as well as to state, in this order, so handing the- // offset back to left/top cannot show a frame at the spot it started from.- const monitor = monitorRef.current;- if (monitor) {- monitor.style.left = `${left}px`;- monitor.style.top = `${top}px`;- monitor.style.transform = "";- }- setLayout((current) =>- !current || (current.left === left && current.top === top)- ? current- : {- ...current,- left,- top,- maxWidth: constraintsWidth - left,- maxHeight: constraintsHeight - top,- },- );- }-- return {- monitorRef,- scrollRef,- contentRef,- layout,- startDrag,- updateDrag,- finishDrag,- };-}-function clampPercent(value: number): number {- return clamp(value, 0, 100);+ return Math.max(0, Math.min(100, value));}function usageIndicatorClass(percent: number): string {@@ -525,7 +94,7 @@ function FloatingMonitorPanel({startDrag,updateDrag,finishDrag,- } = useMonitorLayout(+ } = useFloatingPanelLayout(constraintsElement,dockedBesideRunSettings || suppressed,suppressed,diff --git a/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx b/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsxindex 070859a1f25..7fe1746ffb9 100644--- a/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx+++ b/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx@@ -7,7 +7,8 @@import { getApiMonitor } from "@/features/chat/api/chat-api";import type { ApiMonitorEntry } from "@/features/chat/types/api";import { FIND_PORTAL_ATTRIBUTE } from "@/features/find-in-page/lib/find-attributes";-import { useShortcut } from "@/features/settings";+import { useMonitorFrameStore, useShortcut } from "@/features/settings";+import { useFloatingPanelLayout } from "@/hooks/use-floating-panel-layout";import {useFloatingPanelOrderStore,useFloatingPanelZIndex,@@ -21,20 +22,8 @@ import {import { HugeiconsIcon } from "@hugeicons/react";import { useNavigate, useRouterState } from "@tanstack/react-router";import { XIcon } from "lucide-react";-import {- AnimatePresence,- motion,- useDragControls,- useMotionValue,-} from "motion/react";-import {- type PointerEvent,- type ReactElement,- useEffect,- useMemo,- useRef,- useState,-} from "react";+import { AnimatePresence, motion, useIsPresent } from "motion/react";+import { type ReactElement, useEffect, useRef, useState } from "react";import { isLifecycleEntry, lifecycleLabel } from "./lifecycle";import {type ApiMonitorWatch,@@ -45,11 +34,19 @@ import {startWatching,} from "./new-traffic";import { useApiMonitorOverlayStore } from "./overlay-store";+import {+ isFullyCovered,+ PANEL_MARGIN,+ PANEL_TOP_MARGIN,+ placeFloatingPanel,+} from "./panel-placement";import { computeStats } from "./use-api-monitor";-import { usePanelAnchor } from "./use-panel-anchor";// Live cadence while the panel is on screen.const OPEN_POLL_MS = 1500;+// The body scrolls, so the grip may shrink below content size (the hardware monitor's floor).+const MIN_PANEL_WIDTH = 280;+const MIN_PANEL_HEIGHT = 200;// Closed, the poll only has to notice traffic started, so it backs off.const IDLE_POLL_MS = 5000;// Requests shown in the panel; the rest are one click away on the full page.@@ -121,7 +118,6 @@ function StatCell({export function ApiMonitorOverlay(): ReactElement | null {const { isOpen, suppressed, autoOpen, open, close, setAutoOpen } =useApiMonitorOverlayStore();- const navigate = useNavigate();const pathname = useRouterState({ select: (s) => s.location.pathname });const onFullPage = pathname === "/api-monitor";@@ -196,9 +192,6 @@ export function ApiMonitorOverlay(): ReactElement | null {};}, [isOpen, onFullPage, autoOpen]);- const entries = useMemo(() => data?.entries ?? [], [data]);- const stats = useMemo(() => computeStats(entries), [entries]);-useEffect(() => {if (data == null) {return;@@ -232,154 +225,186 @@ export function ApiMonitorOverlay(): ReactElement | null {}}, [onFullPage]);- const [constraintsElement, setConstraintsElement] =- useState<HTMLDivElement | null>(null);- const constraintsRef = useMemo(- () => ({ current: constraintsElement }),- [constraintsElement],+ const visible = isOpen && !onFullPage;+ const [panelKey, setPanelKey] = useState(0);+ const wasVisibleRef = useRef(visible);+ // Remount on reopen: fresh native size and frame owner.+ useEffect(() => {+ if (wasVisibleRef.current && !visible) {+ setPanelKey((current) => current + 1);+ }+ wasVisibleRef.current = visible;+ }, [visible]);+ return (+ <AnimatePresence>+ {visible && (+ <ApiMonitorPanel+ key={panelKey}+ data={data}+ close={close}+ setAutoOpen={setAutoOpen}+ />+ )}+ </AnimatePresence>);- const dragControls = useDragControls();+}- // Where the panel sits, and whether it is still allowed to move itself. The- // panel keeps clear of the resource monitor until the user drags it; after- // that it stays where it was put, even if that is on top of the monitor.- const [panelElement, setPanelElement] = useState<HTMLDivElement | null>(null);- const [placedByUser, setPlacedByUser] = useState(false);- // Bumped when the panel has moved without its anchor changing: the entry animation is a- // transform, and the box the stack keeps clear of has to be the one on screen.- const [settledAt, setSettledAt] = useState(0);- const { anchor, covered, place } = usePanelAnchor(- panelElement,- placedByUser,- settledAt,+function ApiMonitorPanel({+ data,+ close,+ setAutoOpen,+}: {+ data: Awaited<ReturnType<typeof getApiMonitor>> | null;+ close: () => void;+ setAutoOpen: (value: boolean) => void;+}): ReactElement {+ const navigate = useNavigate();+ const entries = data?.entries ?? [];+ const stats = computeStats(entries);+ const serverStatus = data?.status ?? "idle";+ const isPresent = useIsPresent();+ const [constraintsElement, setConstraintsElement] =+ useState<HTMLDivElement | null>(null);+ const {+ monitorRef,+ scrollRef,+ contentRef,+ layout,+ publisher,+ startDrag,+ updateDrag,+ finishDrag,+ } = useFloatingPanelLayout(+ constraintsElement,+ false,+ // An exiting panel must not stay an obstacle for the one reopening.+ !isPresent,+ (size, bounds) => {+ const initial = placeFloatingPanel(+ size,+ [...useMonitorFrameStore.getState().frames.values()],+ {+ width: window.innerWidth,+ height: window.innerHeight,+ },+ );+ return {+ left: initial.left - bounds.left,+ top: initial.top - bounds.top,+ };+ },);- // The drag offset, owned here rather than left to motion, so it can be folded back into the- // anchor on release. Left as a transform it would be applied on top of every later clamp, and the- // published box would stay at the corner the panel was dragged away from.- const dragX = useMotionValue(0);- const dragY = useMotionValue(0);-+ const frames = useMonitorFrameStore((state) => state.frames);+ const ownFrame = frames.get(publisher);+ const covered =+ ownFrame !== undefined &&+ isFullyCovered(+ ownFrame,+ {+ width: ownFrame.right - ownFrame.left,+ height: ownFrame.bottom - ownFrame.top,+ },+ [...frames]+ .filter(([owner]) => owner !== publisher)+ .map(([, frame]) => frame),+ );const zIndex = useFloatingPanelZIndex("api-monitor", covered);const raisePanel = useFloatingPanelOrderStore((state) => state.raise);-- function startDrag(event: PointerEvent<HTMLDivElement>): void {- event.preventDefault();- setPlacedByUser(true);- dragControls.start(event);- }-- // Written to the node before the offset is zeroed, in that order, so handing- // the drag back to left/top cannot show a frame at the corner it started from.- function finishDrag(): void {- if (!anchor) {- // Dragged before the first measurement landed: nothing to fold into, so- // leave motion holding the offset rather than snapping the panel back.- return;- }- const landed = place({- left: anchor.left + dragX.get(),- top: anchor.top + dragY.get(),- });- panelElement?.style.setProperty("left", `${landed.left}px`);- panelElement?.style.setProperty("top", `${landed.top}px`);- dragX.set(0);- dragY.set(0);- setSettledAt(Date.now());- }-- const visible = isOpen && !onFullPage;- const serverStatus = data?.status ?? "idle";-- // A panel that has just opened is the one the user is being shown, so it comes to the front.- // Touching either panel afterwards brings that one forward instead, which is the only way out of- // a resource monitor resized over the whole viewport.useEffect(() => {- if (visible) {- raisePanel("api-monitor");- }- }, [visible, raisePanel]);-+ raisePanel("api-monitor");+ }, [raisePanel]);return (- <AnimatePresence>- {visible && (- <div- ref={setConstraintsElement}- className="pointer-events-none fixed inset-0"- style={{ zIndex }}- >- <motion.div- {...{ [FIND_PORTAL_ATTRIBUTE]: "" }}- ref={setPanelElement}- onPointerDownCapture={() => raisePanel("api-monitor")}- drag={true}- onDragEnd={finishDrag}- onAnimationComplete={() => setSettledAt(Date.now())}- dragControls={dragControls}- dragListener={false}- dragConstraints={constraintsRef}- dragElastic={0}- dragMomentum={false}- initial={{ opacity: 0, scale: 0.94 }}- animate={{ opacity: 1, scale: 1 }}- exit={{ opacity: 0, scale: 0.94 }}- /* Panel language from the sidebar menu: soft surface, 20px corner, heading font. */- className={cn(- "menu-soft-surface pointer-events-auto fixed flex w-[calc(400px*var(--ui-space-scale,1))] max-w-[calc(100vw-2rem)] cursor-default select-none resize flex-col overflow-hidden rounded-[20px] border-0 p-2.5 font-heading ring-0",- // The CSS corner until it has been measured, so the first paint- // is the corner it has always opened in rather than the top left.- anchor ? "top-0 left-0" : "bottom-4 right-4",- )}- style={- anchor- ? { left: anchor.left, top: anchor.top, x: dragX, y: dragY }- : { x: dragX, y: dragY }- }- >- <div className="flex items-center justify-between gap-2 px-1.5 pb-2 pt-0.5">- <div className="flex min-w-0 flex-1 items-center gap-2">- <HugeiconsIcon- icon={Globe02Icon}- strokeWidth={1.75}- className="size-icon shrink-0 text-nav-fg"- />- <span className="truncate text-ui-13p5 font-semibold tracking-[0.025em] text-nav-fg dark:tracking-[0.04em]">- API monitor- </span>- <span- className={cn(- "size-1.5 shrink-0 rounded-full",- serverStatus === "generating"- ? "animate-pulse bg-blue-500"- : serverStatus === "ready"- ? "bg-emerald-500"- : "bg-muted-foreground",- )}- aria-hidden={true}- />- </div>- <div className="flex shrink-0 items-center gap-0.5">- <div- onPointerDown={startDrag}- className="flex size-7 touch-none cursor-grab items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-nav-surface-hover hover:text-foreground active:cursor-grabbing"- >- <HugeiconsIcon- icon={DragDropVerticalIcon}- strokeWidth={1.75}- className="size-4"- />- </div>- <button- type="button"- onClick={close}- title="Close"- aria-label="Close API monitor"- className="flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-nav-surface-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"- >- <XIcon className="size-3.5" strokeWidth={1.75} />- </button>- </div>+ <div+ ref={setConstraintsElement}+ className="pointer-events-none fixed"+ style={{+ zIndex,+ left: PANEL_MARGIN,+ right: PANEL_MARGIN,+ top: PANEL_TOP_MARGIN,+ bottom: PANEL_MARGIN,+ }}+ >+ <motion.div+ {...{ [FIND_PORTAL_ATTRIBUTE]: "" }}+ ref={monitorRef}+ data-testid="api-monitor-panel"+ onPointerDownCapture={() => raisePanel("api-monitor")}+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ exit={{ opacity: 0 }}+ /* Panel language from the sidebar menu: soft surface, 20px corner, heading font. */+ className={cn(+ "menu-soft-surface pointer-events-auto absolute flex max-h-full w-[calc(400px*var(--ui-space-scale,1))] max-w-full cursor-default select-none flex-col overflow-hidden rounded-[20px] border-0 p-2.5 font-heading ring-0",+ // The CSS corner until it has been measured, so the first paint+ // is the corner it has always opened in rather than the top left.+ layout ? "top-0 left-0 resize" : "bottom-0 right-0",+ )}+ style={+ layout+ ? {+ left: layout.left,+ top: layout.top,+ minWidth: Math.min(MIN_PANEL_WIDTH, layout.maxWidth),+ minHeight: Math.min(MIN_PANEL_HEIGHT, layout.maxHeight),+ maxWidth: layout.maxWidth,+ maxHeight: layout.maxHeight,+ }+ : undefined+ }+ >+ <div className="flex shrink-0 items-center justify-between gap-2 px-1.5 pb-2 pt-0.5">+ <div className="flex min-w-0 flex-1 items-center gap-2">+ <HugeiconsIcon+ icon={Globe02Icon}+ strokeWidth={1.75}+ className="size-icon shrink-0 text-nav-fg"+ />+ <span className="truncate text-ui-13p5 font-semibold tracking-[0.025em] text-nav-fg dark:tracking-[0.04em]">+ API monitor+ </span>+ <span+ className={cn(+ "size-1.5 shrink-0 rounded-full",+ serverStatus === "generating"+ ? "animate-pulse bg-blue-500"+ : serverStatus === "ready"+ ? "bg-emerald-500"+ : "bg-muted-foreground",+ )}+ aria-hidden={true}+ />+ </div>+ <div className="flex shrink-0 items-center gap-0.5">+ <div+ onPointerDown={startDrag}+ onPointerMove={updateDrag}+ onPointerUp={finishDrag}+ onPointerCancel={finishDrag}+ onLostPointerCapture={finishDrag}+ data-testid="api-monitor-drag-handle"+ className="flex size-7 touch-none cursor-grab items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-nav-surface-hover hover:text-foreground active:cursor-grabbing"+ >+ <HugeiconsIcon+ icon={DragDropVerticalIcon}+ strokeWidth={1.75}+ className="size-4"+ /></div>+ <button+ type="button"+ onClick={close}+ title="Close"+ aria-label="Close API monitor"+ className="flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-nav-surface-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"+ >+ <XIcon className="size-3.5" strokeWidth={1.75} />+ </button>+ </div>+ </div>+ <div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto">+ <div ref={contentRef}><p className="truncate px-1.5 pb-2.5 text-ui-11p5 tracking-nav text-muted-foreground">{data?.active_model ?? "No model loaded"}</p>@@ -448,38 +473,37 @@ export function ApiMonitorOverlay(): ReactElement | null {)))}</div>-- {/* Through to payloads, filters and per request tokens. */}- <button- type="button"- onClick={() => {- close();- void navigate({ to: "/api-monitor" });- }}- className="mt-1 flex h-[calc(33px*var(--ui-space-scale,1))] w-full items-center justify-center gap-[calc(8.5px*var(--ui-space-scale,1))] rounded-full bg-muted/60 text-ui-13p5 font-medium tracking-nav text-nav-fg transition-colors hover:bg-nav-surface-hover focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring dark:bg-background/50"- >- <HugeiconsIcon- icon={ExpandIcon}- strokeWidth={1.75}- className="size-icon shrink-0"- />- Expand to full monitor- </button>-- {/* Closing silences this burst; this is the permanent off. */}- <button- type="button"- onClick={() => {- setAutoOpen(false);- close();- }}- className="mt-1.5 w-full rounded-[12px] py-1 text-ui-11 tracking-nav text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"- >- Stop opening this automatically- </button>- </motion.div>+ </div></div>- )}- </AnimatePresence>+ {/* Through to payloads, filters and per request tokens. */}+ <button+ type="button"+ onClick={() => {+ close();+ void navigate({ to: "/api-monitor" });+ }}+ className="mt-1 flex shrink-0 h-[calc(33px*var(--ui-space-scale,1))] w-full items-center justify-center gap-[calc(8.5px*var(--ui-space-scale,1))] rounded-full bg-muted/60 text-ui-13p5 font-medium tracking-nav text-nav-fg transition-colors hover:bg-nav-surface-hover focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring dark:bg-background/50"+ >+ <HugeiconsIcon+ icon={ExpandIcon}+ strokeWidth={1.75}+ className="size-icon shrink-0"+ />+ Expand to full monitor+ </button>++ {/* Closing silences this burst; this is the permanent off. */}+ <button+ type="button"+ onClick={() => {+ setAutoOpen(false);+ close();+ }}+ className="mt-1.5 shrink-0 w-full rounded-[12px] py-1 text-ui-11 tracking-nav text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"+ >+ Stop opening this automatically+ </button>+ </motion.div>+ </div>);}diff --git a/studio/frontend/src/features/api-monitor/use-panel-anchor.ts b/studio/frontend/src/features/api-monitor/use-panel-anchor.tsdeleted file mode 100644index 43d4b7176f0..00000000000--- a/studio/frontend/src/features/api-monitor/use-panel-anchor.ts+++ /dev/null@@ -1,177 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0--// Keeps the API monitor panel clear of the other floating panels, and publishes-// its own box so the notification stack keeps clear of it in turn. The geometry-// is in panel-placement.ts; this is the wiring.--import { useMonitorFrameStore } from "@/features/settings";-import { useCallback, useLayoutEffect, useMemo, useState } from "react";-import {- clampPanelToViewport,- isFullyCovered,- type PanelAnchor,- type PanelRect,- type PanelSize,- placeFloatingPanel,-} from "./panel-placement";--function sameAnchor(a: PanelAnchor | null, b: PanelAnchor): boolean {- return a !== null && a.left === b.left && a.top === b.top;-}--export interface PanelPlacement {- /** Where the panel should sit, or null until it has been measured. */- anchor: PanelAnchor | null;- /** Nothing of the panel is showing, so the layer has to give instead. */- covered: boolean;- /** Commit a position the user dragged the panel to, and report where it- * actually landed once clamped to the viewport. */- place: (anchor: PanelAnchor) => PanelAnchor;-}--/**- * Place the panel, and say whether it ended up hidden anyway.- *- * `frozen` is the user's placement winning. Once the panel has been dragged it- * is where the user put it, overlapping or not: motion holds a drag as a- * transform on top of this anchor, so moving the anchor afterwards would both- * fight the user and shift the panel by the drag distance a second time.- */-export function usePanelAnchor(- element: HTMLElement | null,- frozen: boolean,- republishToken: unknown,-): PanelPlacement {- // This panel's claim on the frame store, stable for the life of the component.- const publisher = useMemo(() => ({}), []);- const frames = useMonitorFrameStore((state) => state.frames);- const [size, setSize] = useState<PanelSize | null>(null);- const [viewport, setViewport] = useState(() => ({- width: typeof window === "undefined" ? 0 : window.innerWidth,- height: typeof window === "undefined" ? 0 : window.innerHeight,- }));- const [anchor, setAnchor] = useState<PanelAnchor | null>(null);-- // Everything published except this panel. Reading its own box back would make- // it dodge itself, one step per frame, off the edge of the screen.- const obstacles = useMemo<PanelRect[]>(() => {- const others: PanelRect[] = [];- for (const [owner, frame] of frames) {- if (owner !== publisher) {- others.push(frame);- }- }- return others;- }, [frames, publisher]);-- useLayoutEffect(() => {- const onResize = () =>- setViewport({ width: window.innerWidth, height: window.innerHeight });- onResize();- window.addEventListener("resize", onResize);- return () => window.removeEventListener("resize", onResize);- }, []);-- // The panel is content-sized and natively resizable, so its box is not known- // ahead of time and does not stay put.- useLayoutEffect(() => {- if (!element) {- setSize(null);- return;- }- // offsetWidth/offsetHeight, not the bounding rect: the panel animates in from scale 0.94, and a- // rect measured through that transform is 6% short. Placed against it, the panel then overhangs- // the right edge of the screen once the animation lands.- const measure = () => {- const width = element.offsetWidth;- const height = element.offsetHeight;- setSize((current) =>- current && current.width === width && current.height === height- ? current- : { width, height },- );- };- measure();- const observer =- typeof ResizeObserver === "undefined"- ? null- : new ResizeObserver(measure);- observer?.observe(element);- return () => observer?.disconnect();- }, [element]);-- const commit = useCallback((next: PanelAnchor) => {- setAnchor((current) => (sameAnchor(current, next) ? current : next));- }, []);-- useLayoutEffect(() => {- if (!size || viewport.width === 0) {- return;- }- // Placed by hand: keep it there, but keep it on screen. Shrinking the- // window is the case -- the panel remembers nothing across reloads, so one- // pushed off the edge is gone until the panel is closed and reopened.- if (frozen) {- setAnchor((current) =>- current === null- ? current- : clampPanelToViewport(current, size, viewport),- );- return;- }- commit(placeFloatingPanel(size, obstacles, viewport));- }, [frozen, size, obstacles, viewport, commit]);-- const place = useCallback(- (next: PanelAnchor) => {- const landed =- !size || viewport.width === 0- ? next- : clampPanelToViewport(next, size, viewport);- commit(landed);- return landed;- },- [commit, size, viewport],- );-- // Publish where it actually landed, so the notification stack steps over this panel the same way- // it steps over the resource monitor. Measured rather than derived from the anchor, because- // before the first anchor is committed the panel is still sitting on its CSS corner.- useLayoutEffect(() => {- const { setFrame, clearFrame } = useMonitorFrameStore.getState();- if (!element) {- clearFrame(publisher);- return;- }- const box = element.getBoundingClientRect();- if (box.width === 0 && box.height === 0) {- clearFrame(publisher);- return;- }- setFrame(publisher, {- left: box.left,- top: box.top,- right: box.right,- bottom: box.bottom,- });- }, [element, anchor, size, publisher, republishToken]);-- // The panel unmounts on close and on every route change to the full page, so- // a frame left behind would hold the stack up over an empty corner forever.- useLayoutEffect(- () => () => useMonitorFrameStore.getState().clearFrame(publisher),- [publisher],- );-- return {- anchor,- // Asked of the placed box rather than the measured one, so the answer does- // not flicker while the panel animates in.- covered:- anchor !== null &&- size !== null &&- isFullyCovered(anchor, size, obstacles),- place,- };-}diff --git a/studio/frontend/src/hooks/use-floating-panel-layout.ts b/studio/frontend/src/hooks/use-floating-panel-layout.tsnew file mode 100644index 00000000000..03f496f586d--- /dev/null+++ b/studio/frontend/src/hooks/use-floating-panel-layout.ts@@ -0,0 +1,412 @@+// 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 { useMonitorFrameStore } from "@/features/settings";+import {+ type PointerEvent,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from "react";++interface MonitorLayout {+ left: number;+ top: number;+ minWidth: number;+ minHeight: number;+ maxWidth: number;+ maxHeight: number;+}++interface DragSession {+ pointerId: number;+ startX: number;+ startY: number;+ left: number;+ top: number;+ maxLeft: number;+ maxTop: number;+ constraintsWidth: number;+ constraintsHeight: number;+ // Committed left/top the drag transform offsets from.+ baseLeft: number;+ baseTop: number;+}++function clamp(value: number, min: number, max: number): number {+ return Math.max(min, Math.min(max, value));+}++// Anchored to the far edge until the user drags, then clamped where they left it.+function place(dragged: boolean, current: number, max: number): number {+ return dragged ? clamp(current, 0, max) : max;+}++function sameLayout(a: MonitorLayout, b: MonitorLayout): boolean {+ return (+ a.left === b.left &&+ a.top === b.top &&+ a.minWidth === b.minWidth &&+ a.minHeight === b.minHeight &&+ a.maxWidth === b.maxWidth &&+ a.maxHeight === b.maxHeight+ );+}++// Content height, not the rendered box: maxHeight would hide growth.+function desiredPanelHeight(+ renderedHeight: number,+ scroll: HTMLDivElement | null,+ content: HTMLDivElement | null,+): number {+ if (!(scroll && content)) {+ return renderedHeight;+ }+ const chrome = renderedHeight - scroll.getBoundingClientRect().height;+ return chrome + content.getBoundingClientRect().height;+}++// Lift the maxWidth cap for one measurement so an anchored panel can widen again.+function naturalWidth(monitor: HTMLDivElement): number {+ const capped = monitor.style.maxWidth;+ monitor.style.maxWidth = "none";+ const width = monitor.getBoundingClientRect().width;+ monitor.style.maxWidth = capped;+ return width;+}++export function useFloatingPanelLayout(+ constraintsElement: HTMLDivElement | null,+ narrowed: boolean,+ hidden: boolean,+ initialPlacement?: (+ size: { width: number; height: number },+ bounds: DOMRect,+ ) => { left: number; top: number },+) {+ // Per-instance frame owner: a panel unmounting mid-exit clears only its own frame.+ const publisher = useMemo(() => ({}), []);+ const monitorRef = useRef<HTMLDivElement>(null);+ const scrollRef = useRef<HTMLDivElement>(null);+ const contentRef = useRef<HTMLDivElement>(null);+ const dragSessionRef = useRef<DragSession | null>(null);+ const dragFrameRef = useRef(0);+ const hasDraggedLeftRef = useRef(false);+ const hasDraggedTopRef = useRef(false);+ const preferredWidthRef = useRef<number | null>(null);+ const preferredHeightRef = useRef<number | null>(null);+ const surfaceWidthRef = useRef(0);+ const narrowedRef = useRef(narrowed);+ const hiddenRef = useRef(hidden);+ // User's full-width placement; cleared by a drag while narrowed.+ const chosenLeftRef = useRef<number | null>(null);+ const restoreLeftRef = useRef<number | null>(null);+ const remeasureRef = useRef(0);+ const [layout, setLayout] = useState<MonitorLayout | null>(null);+ // For transitions that fire no observer (suppressed to undocked).+ const reconcileRef = useRef<(() => void) | null>(null);+ const initialPlacementRef = useRef(initialPlacement);+ const initializedRef = useRef(false);++ useLayoutEffect(() => {+ const monitor = monitorRef.current;+ const constraints = constraintsElement;+ if (!(monitor && constraints)) {+ return;+ }+ // Next frame: a style write during ResizeObserver delivery trips Firefox's loop check.+ const scheduleWidthRemeasure = (surfaceWidth: number) => {+ if (surfaceWidth === surfaceWidthRef.current) {+ return;+ }+ surfaceWidthRef.current = surfaceWidth;+ if (monitor.style.width || remeasureRef.current) {+ return;+ }+ remeasureRef.current = requestAnimationFrame(() => {+ remeasureRef.current = 0;+ preferredWidthRef.current = naturalWidth(monitor);+ reconcileGeometry();+ });+ };++ const reconcileGeometry = () => {+ const constraintsBox = constraints.getBoundingClientRect();+ const monitorBox = monitor.getBoundingClientRect();+ const desiredHeight = desiredPanelHeight(+ monitorBox.height,+ scrollRef.current,+ contentRef.current,+ );++ scheduleWidthRemeasure(constraintsBox.width);+ const desiredWidth = Math.max(+ monitorBox.width,+ preferredWidthRef.current ?? monitorBox.width,+ );++ if (!monitor.style.height) {+ preferredHeightRef.current = desiredHeight;+ }++ const width = Math.min(desiredWidth, constraintsBox.width);+ // A hand-resized panel keeps its height and scrolls instead of moving up.+ const height = Math.min(+ monitor.style.height ? monitorBox.height : desiredHeight,+ constraintsBox.height,+ );+ const maxLeft = Math.max(0, constraintsBox.width - width);+ const maxTop = Math.max(0, constraintsBox.height - height);+ const currentLeft = monitorBox.left - constraintsBox.left;+ const currentTop = monitorBox.top - constraintsBox.top;+ const restoreTo = restoreLeftRef.current;+ let left =+ restoreTo === null+ ? place(hasDraggedLeftRef.current, currentLeft, maxLeft)+ : clamp(restoreTo, 0, maxLeft);+ restoreLeftRef.current = null;+ if (!narrowedRef.current && hasDraggedLeftRef.current) {+ chosenLeftRef.current = left;+ }+ let top = place(hasDraggedTopRef.current, currentTop, maxTop);+ // Obstacle avoidance applies to the first placement only.+ if (!initializedRef.current && initialPlacementRef.current) {+ const initial = initialPlacementRef.current(+ { width, height },+ constraintsBox,+ );+ left = clamp(initial.left, 0, maxLeft);+ top = clamp(initial.top, 0, maxTop);+ hasDraggedLeftRef.current = true;+ hasDraggedTopRef.current = true;+ }+ initializedRef.current = true;++ const session = dragSessionRef.current;+ if (session) {+ session.left = left;+ session.top = top;+ session.maxLeft = maxLeft;+ session.maxTop = maxTop;+ session.constraintsWidth = constraintsBox.width;+ session.constraintsHeight = constraintsBox.height;+ }++ if (!hiddenRef.current) {+ useMonitorFrameStore.getState().setFrame(publisher, {+ left: monitorBox.left,+ top: monitorBox.top,+ right: monitorBox.right,+ bottom: monitorBox.bottom,+ });+ }++ setLayout((current) => {+ // Mid-drag the measured box includes the transform; finishDrag commits instead.+ const held = session && current ? current : null;+ const restLeft = held?.left ?? left;+ const restTop = held?.top ?? top;+ const next = {+ left: restLeft,+ top: restTop,+ minWidth: preferredWidthRef.current ?? monitorBox.width,+ minHeight: preferredHeightRef.current ?? monitorBox.height,+ maxWidth: constraintsBox.width - restLeft,+ maxHeight: constraintsBox.height - restTop,+ };+ return current && sameLayout(current, next) ? current : next;+ });+ };++ reconcileRef.current = reconcileGeometry;+ reconcileGeometry();+ const observer = new ResizeObserver(reconcileGeometry);+ observer.observe(constraints);+ observer.observe(monitor);+ if (contentRef.current) {+ observer.observe(contentRef.current);+ }+ return () => {+ observer.disconnect();+ reconcileRef.current = null;+ useMonitorFrameStore.getState().clearFrame(publisher);+ if (remeasureRef.current) {+ cancelAnimationFrame(remeasureRef.current);+ remeasureRef.current = 0;+ }+ if (dragFrameRef.current) {+ cancelAnimationFrame(dragFrameRef.current);+ dragFrameRef.current = 0;+ }+ };+ }, [constraintsElement, publisher]);++ // A hidden panel must not publish a frame others dodge.+ useLayoutEffect(() => {+ hiddenRef.current = hidden;+ if (hidden) {+ useMonitorFrameStore.getState().clearFrame(publisher);+ }+ }, [hidden, publisher]);++ useLayoutEffect(() => {+ if (narrowedRef.current === narrowed) {+ return;+ }+ narrowedRef.current = narrowed;+ if (!narrowed) {+ restoreLeftRef.current = chosenLeftRef.current;+ reconcileRef.current?.();+ }+ }, [narrowed]);++ // Position-only changes fire no ResizeObserver, so republish per committed layout (not per drag frame).+ useLayoutEffect(() => {+ void layout;+ const monitor = monitorRef.current;+ if (!(monitor && constraintsElement) || hiddenRef.current) {+ return;+ }+ const box = monitor.getBoundingClientRect();+ useMonitorFrameStore.getState().setFrame(publisher, {+ left: box.left,+ top: box.top,+ right: box.right,+ bottom: box.bottom,+ });+ }, [layout, constraintsElement, publisher, hidden]);++ function startDrag(event: PointerEvent<HTMLDivElement>) {+ const monitor = monitorRef.current;+ if (event.button !== 0 || !(monitor && constraintsElement)) {+ return;+ }++ event.preventDefault();+ const constraintsBox = constraintsElement.getBoundingClientRect();+ const monitorBox = monitor.getBoundingClientRect();+ const left = monitorBox.left - constraintsBox.left;+ const top = monitorBox.top - constraintsBox.top;++ // Sync inline size to the rendered box where max-width/height clipped a native resize.+ const inlineWidth = Number.parseFloat(monitor.style.width);+ const inlineHeight = Number.parseFloat(monitor.style.height);+ if (+ Number.isFinite(inlineWidth) &&+ Math.abs(inlineWidth - monitorBox.width) > 0.5+ ) {+ monitor.style.width = `${monitorBox.width}px`;+ }+ if (+ Number.isFinite(inlineHeight) &&+ Math.abs(inlineHeight - monitorBox.height) > 0.5+ ) {+ monitor.style.height = `${monitorBox.height}px`;+ }++ dragSessionRef.current = {+ pointerId: event.pointerId,+ startX: event.clientX,+ startY: event.clientY,+ left,+ top,+ maxLeft: Math.max(0, constraintsBox.width - monitorBox.width),+ maxTop: Math.max(0, constraintsBox.height - monitorBox.height),+ constraintsWidth: constraintsBox.width,+ constraintsHeight: constraintsBox.height,+ baseLeft: left,+ baseTop: top,+ };+ event.currentTarget.setPointerCapture(event.pointerId);+ }++ // One transform per frame: left/top moves re-sample the backdrop blur.+ function paintDrag() {+ dragFrameRef.current = 0;+ const session = dragSessionRef.current;+ const monitor = monitorRef.current;+ if (!(session && monitor)) {+ return;+ }+ monitor.style.transform = `translate3d(${session.left - session.baseLeft}px, ${+ session.top - session.baseTop+ }px, 0)`;+ }++ function updateDrag(event: PointerEvent<HTMLDivElement>) {+ const session = dragSessionRef.current;+ if (!session || session.pointerId !== event.pointerId) {+ return;+ }++ const previousTop = session.top;+ const left = clamp(+ session.left + event.clientX - session.startX,+ 0,+ session.maxLeft,+ );+ const top = clamp(+ session.top + event.clientY - session.startY,+ 0,+ session.maxTop,+ );+ if (top !== previousTop) {+ hasDraggedTopRef.current = true;+ }+ session.startX = event.clientX;+ session.startY = event.clientY;+ session.left = left;+ session.top = top;+ if (!dragFrameRef.current) {+ dragFrameRef.current = requestAnimationFrame(paintDrag);+ }+ }++ function finishDrag(event: PointerEvent<HTMLDivElement>) {+ const session = dragSessionRef.current;+ if (session?.pointerId !== event.pointerId) {+ return;+ }+ if (dragFrameRef.current) {+ cancelAnimationFrame(dragFrameRef.current);+ dragFrameRef.current = 0;+ }+ const { left, top, baseLeft, constraintsWidth, constraintsHeight } =+ session;+ dragSessionRef.current = null;+ if (left !== baseLeft) {+ hasDraggedLeftRef.current = true;+ chosenLeftRef.current = narrowedRef.current ? null : left;+ }+ // Write the node before state so the handoff never flashes the start position.+ const monitor = monitorRef.current;+ if (monitor) {+ monitor.style.left = `${left}px`;+ monitor.style.top = `${top}px`;+ monitor.style.transform = "";+ }+ setLayout((current) =>+ !current || (current.left === left && current.top === top)+ ? current+ : {+ ...current,+ left,+ top,+ maxWidth: constraintsWidth - left,+ maxHeight: constraintsHeight - top,+ },+ );+ }++ return {+ publisher,+ monitorRef,+ scrollRef,+ contentRef,+ layout,+ startDrag,+ updateDrag,+ finishDrag,+ };+}diff --git a/studio/frontend/tests/drag-costs-no-render.test.ts b/studio/frontend/tests/drag-costs-no-render.test.tsindex fde55d53754..f490de75237 100644--- a/studio/frontend/tests/drag-costs-no-render.test.ts+++ b/studio/frontend/tests/drag-costs-no-render.test.ts@@ -13,6 +13,25 @@ import test from "node:test";import { readSrc } from "./helpers/kit.ts";+test("both monitors use the hardware monitor's shared interaction hook", () => {+ for (const path of ["components/floating-monitor.tsx", "features/api-monitor/api-monitor-overlay.tsx"]) {+ const panel = readSrc(path);+ assert.match(panel, /useFloatingPanelLayout\(/);+ assert.match(panel, /onPointerMove=\{updateDrag\}/);+ assert.match(panel, /onLostPointerCapture=\{finishDrag\}/);+ assert.match(panel, /ref=\{scrollRef\}/);+ assert.doesNotMatch(panel, /useDragControls|usePanelAnchor|useMotionValue/);+ }+});++test("the API monitor can shrink at its opening corner and never dodges its own exiting panel", () => {+ const panel = readSrc("features/api-monitor/api-monitor-overlay.tsx");+ assert.match(panel, /minWidth: Math\.min\(MIN_PANEL_WIDTH, layout\.maxWidth\)/);+ assert.match(panel, /minHeight: Math\.min\(MIN_PANEL_HEIGHT, layout\.maxHeight\)/);+ assert.match(panel, /const isPresent = useIsPresent\(\);/);+ assert.match(panel, /useFloatingPanelLayout\(\s*constraintsElement,\s*false,[^,]*!isPresent,/);+});+test("the card paints a drag frame through a transform", () => {const hook = readSrc("features/loaded-models/use-drag-position.ts");assert.match(hook, /panel\.style\.transform = `translate3d\(/);@@ -42,7 +61,7 @@ test("the card hands the offset back to left/top on release", () => {});test("the monitor paints a drag frame through a transform", () => {- const panel = readSrc("components/floating-monitor.tsx");+ const panel = readSrc("hooks/use-floating-panel-layout.ts");assert.match(panel, /monitor\.style\.transform = `translate3d\(/);assert.match(panel,@@ -51,7 +70,7 @@ test("the monitor paints a drag frame through a transform", () => {});test("the monitor commits its position once, on release", () => {- const panel = readSrc("components/floating-monitor.tsx");+ const panel = readSrc("hooks/use-floating-panel-layout.ts");const finish = panel.slice(panel.indexOf("function finishDrag"));assert.match(finish, /monitor\.style\.transform = ""/);assert.match(finish, /setLayout\(\(current\) =>/);@@ -60,7 +79,7 @@ test("the monitor commits its position once, on release", () => {// The measured box carries the drag's transform, so committing it mid-drag// would move the panel twice as far as the pointer went.test("a resize mid-drag does not commit the transformed box", () => {- const panel = readSrc("components/floating-monitor.tsx");+ const panel = readSrc("hooks/use-floating-panel-layout.ts");assert.match(panel, /const held = session && current \? current : null;/);assert.match(panel, /left: restLeft,/);assert.match(panel, /maxWidth: constraintsBox\.width - restLeft,/);@@ -69,7 +88,7 @@ test("a resize mid-drag does not commit the transformed box", () => {// Every frame published the monitor's box to a shared store, and each write// re-rendered every overlay subscribed to it, the loaded models card included.test("dragging the monitor does not republish its frame per frame", () => {- const panel = readSrc("components/floating-monitor.tsx");+ const panel = readSrc("hooks/use-floating-panel-layout.ts");const update = panel.slice(panel.indexOf("function updateDrag"),panel.indexOf("function finishDrag"),diff --git a/studio/frontend/tests/floating-monitor-dock.test.ts b/studio/frontend/tests/floating-monitor-dock.test.tsindex 75f983e8792..d76639612e9 100644--- a/studio/frontend/tests/floating-monitor-dock.test.ts+++ b/studio/frontend/tests/floating-monitor-dock.test.ts@@ -19,6 +19,10 @@ const source = readFileSync(new URL("../src/components/floating-monitor.tsx", import.meta.url),"utf8",);+const layoutSource = readFileSync(+ new URL("../src/hooks/use-floating-panel-layout.ts", import.meta.url),+ "utf8",+);const desktop = {isOpen: true,isMobile: false,@@ -148,21 +152,21 @@ test("responsive changes reattach geometry observers and recalculate capacity",test("suppression retains layout but does not publish a phantom frame", () => {assert.match(source, /\(visible \|\| suppressed\) &&/);assert.match(source, /suppressed && "invisible"/);- assert.match(source, /if \(hidden\) \{\s*useMonitorFrameStore\.getState\(\)\.clearFrame\(publisher\);/);- assert.match(source, /if \(!hiddenRef\.current\) \{\s*useMonitorFrameStore\.getState\(\)\.setFrame/);- assert.match(source, /\}, \[layout, constraintsElement, publisher, hidden\]\);/);+ assert.match(layoutSource, /if \(hidden\) \{\s*useMonitorFrameStore\.getState\(\)\.clearFrame\(publisher\);/);+ assert.match(layoutSource, /if \(!hiddenRef\.current\) \{\s*useMonitorFrameStore\.getState\(\)\.setFrame/);+ assert.match(layoutSource, /\}, \[layout, constraintsElement, publisher, hidden\]\);/);});test("a net-zero docked drag must not discard the saved full-width X", () => {- const update = source.slice(source.indexOf("function updateDrag"), source.indexOf("function finishDrag"));- const finish = source.slice(source.indexOf("function finishDrag"));+ const update = layoutSource.slice(layoutSource.indexOf("function updateDrag"), layoutSource.indexOf("function finishDrag"));+ const finish = layoutSource.slice(layoutSource.indexOf("function finishDrag"));// Intermediate pointer moves are provisional. Only a released horizontal// displacement replaces the user's earlier full-width placement.assert.doesNotMatch(update, /chosenLeftRef\.current = null/);assert.match(finish, /if \(left !== baseLeft\) \{\s*hasDraggedLeftRef\.current = true;\s*chosenLeftRef\.current = narrowedRef\.current \? null : left;/);- assert.match(source, /restoreLeftRef\.current = chosenLeftRef\.current/);- assert.match(source, /if \(!narrowed\) \{\s*restoreLeftRef\.current = chosenLeftRef\.current;\s*reconcileRef\.current\?\.\(\);/);- assert.match(source, /place\(hasDraggedTopRef\.current, currentTop, maxTop\)/);+ assert.match(layoutSource, /restoreLeftRef\.current = chosenLeftRef\.current/);+ assert.match(layoutSource, /if \(!narrowed\) \{\s*restoreLeftRef\.current = chosenLeftRef\.current;\s*reconcileRef\.current\?\.\(\);/);+ assert.match(layoutSource, /place\(hasDraggedTopRef\.current, currentTop, maxTop\)/);});test("the panel width clamps to the same bounds used by docking", async () => {@@ -197,8 +201,8 @@ test("spacing and the resize handle use the same live UI scale", () => {test("docking never remounts the monitor or loses its drag geometry", () => {assert.doesNotMatch(source, /key=\{`\$\{panelKey\}-/);- assert.match(source, /useLayoutEffect\(\(\) => \{\s*if \(narrowedRef\.current === narrowed\)/);- assert.match(source, /const restoreTo = restoreLeftRef\.current;/);- assert.match(source, /place\(hasDraggedLeftRef\.current, currentLeft, maxLeft\)/);+ assert.match(layoutSource, /useLayoutEffect\(\(\) => \{\s*if \(narrowedRef\.current === narrowed\)/);+ assert.match(layoutSource, /const restoreTo = restoreLeftRef\.current;/);+ assert.match(layoutSource, /place\(hasDraggedLeftRef\.current, currentLeft, maxLeft\)/);assert.match(source, /const unpinnedSidebarWidth = sidebarHoldsRail \? paintedSidebarWidth : 0/);});diff --git a/studio/frontend/tests/monitor-frame-ownership.test.ts b/studio/frontend/tests/monitor-frame-ownership.test.tsindex 5ef5e839923..b614bfc0c2a 100644--- a/studio/frontend/tests/monitor-frame-ownership.test.ts+++ b/studio/frontend/tests/monitor-frame-ownership.test.ts@@ -21,7 +21,7 @@ import {import { readSrc } from "./helpers/kit.ts";-const PANEL_SOURCE = readSrc("components/floating-monitor.tsx");+const PANEL_SOURCE = readSrc("hooks/use-floating-panel-layout.ts");const ROOT_SOURCE = readSrc("app/routes/__root.tsx");const SETTINGS_MOUNT_SOURCE = readSrc(diff --git a/tests/studio/test_overlay_layering.py b/tests/studio/test_overlay_layering.pyindex e013547ea7d..b2a48e5a9f1 100644--- a/tests/studio/test_overlay_layering.py+++ b/tests/studio/test_overlay_layering.py@@ -88,7 +88,7 @@ def test_both_floating_panels_stack_on_the_shared_layer(path: Path):Sharing the layer is what lets the one the user touched last come forward,which is the only way out of a monitor resized over the whole viewport."""container = _container(path, "setConstraintsElement")- style_applies_shared_layer = "style={{ zIndex }}" in container or re.search(+ style_applies_shared_layer = re.search(r"style=\{\{\s*zIndex\s*[,}]", container) or re.search(r"style=\{floatingMonitorConstraintStyle\(\{\s*zIndex,", container)assert style_applies_shared_layer, (