Skip to content

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

Keep the two floating panels out of each other's corner (#8249)

Daniel Hanb6c3229a9e50
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsx
index 398ccb5aaf9..dfc3ce05449 100644
--- a/studio/frontend/src/app/provider.tsx
+++ b/studio/frontend/src/app/provider.tsx
@@ -34,6 +34,7 @@ import { type BackendStatus, useTauriBackend } from "@/hooks/use-tauri-backend";
import { useTauriUpdate } from "@/hooks/use-tauri-update";
import { isTauri } from "@/lib/api-base";
import { cn } from "@/lib/utils";
+import { Z_LAYER } from "@/lib/z-layers";
import { useRouterState } from "@tanstack/react-router";
import { MotionConfig } from "motion/react";
import {
@@ -56,8 +57,8 @@ import {
type MeasuredWindowLayout,
type WindowLayoutGuard,
finalizeAppWindowLayout,
- shouldFinishWindowLayoutWait,
measureWindowLayout,
+ shouldFinishWindowLayoutWait,
} from "./window-layout-lifecycle";
interface AppProviderProps {
@@ -253,8 +254,9 @@ async function applyAppWindowLayout(
): Promise<void> {
const windowModule = await import("@tauri-apps/api/window");
const { invoke } = await import("@tauri-apps/api/core");
- const { restoreStateCurrent, StateFlags } =
- await import("@tauri-apps/plugin-window-state");
+ const { restoreStateCurrent, StateFlags } = await import(
+ "@tauri-apps/plugin-window-state"
+ );
if (!isCurrent()) return;
const win = windowModule.getCurrentWindow();
@@ -407,10 +409,14 @@ function TauriUpdateLayer({
// costs it its scrollbar, and only the cards opt back in, so nothing
// would drag the ones below the fold into view.
className={cn(
- "fixed right-4 z-[9998] -mx-3 flex flex-col items-end gap-2 overflow-y-auto overflow-x-hidden overscroll-contain px-3",
+ "fixed right-4 -mx-3 flex flex-col items-end gap-2 overflow-y-auto overflow-x-hidden overscroll-contain px-3",
stack.overflowing ? "pointer-events-auto" : "pointer-events-none",
)}
- style={{ bottom: stack.bottom, maxHeight: stack.maxHeight }}
+ style={{
+ bottom: stack.bottom,
+ maxHeight: stack.maxHeight,
+ zIndex: Z_LAYER.OVERLAY_STACK,
+ }}
>
<UpdateBanner
status={update.status}
@@ -562,7 +568,6 @@ function TauriWrapper({ children }: { children: ReactNode }) {
};
}, []);
-
useEffect(() => {
if (!isTauri) return;
let disposed = false;
@@ -571,16 +576,18 @@ function TauriWrapper({ children }: { children: ReactNode }) {
void wasLaunchedHidden().then(async (hiddenAtLaunch) => {
if (!hiddenAtLaunch || disposed) return;
const { getCurrentWindow } = await import("@tauri-apps/api/window");
- const unlisten = await getCurrentWindow().onFocusChanged(({ payload }) => {
- if (!payload || disposed) return;
- stopListening?.();
- stopListening = undefined;
- // Native tray reveal focuses the window. Re-run the deferred layout now
- // that currentMonitor() can resolve the restored display.
- launchedHidden = Promise.resolve(false);
- appliedWindowModeRef.current = null;
- setWindowRevealRevision((revision) => revision + 1);
- });
+ const unlisten = await getCurrentWindow().onFocusChanged(
+ ({ payload }) => {
+ if (!payload || disposed) return;
+ stopListening?.();
+ stopListening = undefined;
+ // Native tray reveal focuses the window. Re-run the deferred layout now
+ // that currentMonitor() can resolve the restored display.
+ launchedHidden = Promise.resolve(false);
+ appliedWindowModeRef.current = null;
+ setWindowRevealRevision((revision) => revision + 1);
+ },
+ );
if (disposed) unlisten();
else stopListening = unlisten;
});
@@ -701,10 +708,14 @@ function TauriWrapper({ children }: { children: ReactNode }) {
// costs it its scrollbar, and only the cards opt back in, so nothing
// would drag the ones below the fold into view.
className={cn(
- "fixed right-4 z-[9998] -mx-3 flex flex-col items-end gap-2 overflow-y-auto overflow-x-hidden overscroll-contain px-3",
+ "fixed right-4 -mx-3 flex flex-col items-end gap-2 overflow-y-auto overflow-x-hidden overscroll-contain px-3",
stack.overflowing ? "pointer-events-auto" : "pointer-events-none",
)}
- style={{ bottom: stack.bottom, maxHeight: stack.maxHeight }}
+ style={{
+ bottom: stack.bottom,
+ maxHeight: stack.maxHeight,
+ zIndex: Z_LAYER.OVERLAY_STACK,
+ }}
>
<WebUpdateBanner
positioned={false}
diff --git a/studio/frontend/src/components/floating-monitor.tsx b/studio/frontend/src/components/floating-monitor.tsx
index 3c8f98a5650..74b3696f610 100644
--- a/studio/frontend/src/components/floating-monitor.tsx
+++ b/studio/frontend/src/components/floating-monitor.tsx
@@ -9,6 +9,10 @@ import {
} from "@/features/settings";
import { aggregateGpuMemoryTotalGb, useSystemInfo } from "@/hooks/use-system";
import { useT } from "@/i18n";
+import {
+ useFloatingPanelOrderStore,
+ useFloatingPanelZIndex,
+} from "@/lib/floating-panel-order";
import { cn } from "@/lib/utils";
import { CpuIcon, GripVerticalIcon, XIcon } from "lucide-react";
import { AnimatePresence, motion } from "motion/react";
@@ -433,6 +437,15 @@ function FloatingMonitorPanel({
finishDrag,
} = useMonitorLayout(constraintsElement);
+ const zIndex = useFloatingPanelZIndex("resource-monitor");
+ const raisePanel = useFloatingPanelOrderStore((state) => state.raise);
+
+ // Opening the monitor puts it in front of the API monitor panel; touching
+ // either afterwards brings that one forward instead.
+ useEffect(() => {
+ raisePanel("resource-monitor");
+ }, [raisePanel]);
+
const ramTotal = systemInfo.memory?.total_gb ?? 0;
const ramAvailable = systemInfo.memory?.available_gb ?? 0;
const ramUsed = Math.max(0, ramTotal - ramAvailable);
@@ -467,20 +480,26 @@ function FloatingMonitorPanel({
const hasGpu = (displayedGpu?.available ?? false) && devices.length > 0;
- // The container's z sits above the bottom-right overlay stack (z-[9998]). That
- // stack normally dodges this monitor, but the dodge has a floor: drag the monitor
- // to the corner and resize it to fill the viewport and there is nowhere left to
- // dodge to, so stackBottomInset clamps at MIN_STACK_ROOM and parks the stack at
- // the top of the screen, directly over this monitor's title bar and Close button.
- // The stack is passive status; this is a window the user is dragging, resizing and
- // closing, so it wins. Still below the startup screen and tooltips.
+ // The container sits on the floating panel layer, above the bottom-right
+ // overlay stack. That stack normally dodges this monitor, but the dodge has a
+ // floor: drag the monitor to the corner and resize it to fill the viewport and
+ // there is nowhere left to dodge to, so stackBottomInset clamps at
+ // MIN_STACK_ROOM and parks the stack at the top of the screen, directly over
+ // this monitor's title bar and Close button. The stack is passive status; this
+ // is a window the user is dragging, resizing and closing, so it wins. Still
+ // below the startup screen and tooltips. See lib/z-layers.
+ //
+ // The API monitor panel shares this layer rather than sitting under it, and
+ // whichever of the two the user touched last is the one in front.
return (
<div
ref={setConstraintsElement}
- className="pointer-events-none fixed inset-4 z-[9999]"
+ className="pointer-events-none fixed inset-4"
+ style={{ zIndex }}
>
<motion.div
ref={monitorRef}
+ onPointerDownCapture={() => raisePanel("resource-monitor")}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
diff --git a/studio/frontend/src/components/tauri/startup-screen.tsx b/studio/frontend/src/components/tauri/startup-screen.tsx
index b017a88d708..1df427a4e0d 100644
--- a/studio/frontend/src/components/tauri/startup-screen.tsx
+++ b/studio/frontend/src/components/tauri/startup-screen.tsx
@@ -548,7 +548,8 @@ function StartupSurface({ children }: { children: ReactNode }) {
*
* A layer over the app rather than a replacement for it: a declined quit has to hand the
* user back the tree they had, in-flight generations and unsaved drafts included. The
- * z-index clears the titlebar and the download stack, the last of which is 9998.
+ * z-index clears the titlebar, the download stack and the floating panels above it:
+ * it is Z_LAYER.STARTUP_SCREEN, which lib/z-layers puts over both.
*/
export function ClosingScreen() {
return (
diff --git a/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx b/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx
index d14fb2127a1..a9aef3b90c1 100644
--- a/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx
+++ b/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx
@@ -6,6 +6,10 @@
import { getApiMonitor } from "@/features/chat/api/chat-api";
import type { ApiMonitorEntry } from "@/features/chat/types/api";
+import {
+ useFloatingPanelOrderStore,
+ useFloatingPanelZIndex,
+} from "@/lib/floating-panel-order";
import { cn } from "@/lib/utils";
import {
ArrowExpand01Icon,
@@ -15,7 +19,12 @@ import {
import { HugeiconsIcon } from "@hugeicons/react";
import { useNavigate, useRouterState } from "@tanstack/react-router";
import { XIcon } from "lucide-react";
-import { AnimatePresence, motion, useDragControls } from "motion/react";
+import {
+ AnimatePresence,
+ motion,
+ useDragControls,
+ useMotionValue,
+} from "motion/react";
import {
type PointerEvent,
type ReactElement,
@@ -35,6 +44,7 @@ import {
} from "./new-traffic";
import { useApiMonitorOverlayStore } from "./overlay-store";
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;
@@ -216,23 +226,82 @@ export function ApiMonitorOverlay(): ReactElement | null {
);
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,
+ );
+ // 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 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]);
+
return (
<AnimatePresence>
{visible && (
<div
ref={setConstraintsElement}
- className="pointer-events-none fixed inset-0 z-50"
+ className="pointer-events-none fixed inset-0"
+ style={{ zIndex }}
>
<motion.div
+ ref={setPanelElement}
+ onPointerDownCapture={() => raisePanel("api-monitor")}
drag={true}
+ onDragEnd={finishDrag}
+ onAnimationComplete={() => setSettledAt(Date.now())}
dragControls={dragControls}
dragListener={false}
dragConstraints={constraintsRef}
@@ -242,7 +311,17 @@ export function ApiMonitorOverlay(): ReactElement | null {
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.94 }}
/* Panel language from the sidebar menu: soft surface, 20px corner, heading font. */
- className="menu-soft-surface pointer-events-auto fixed bottom-4 right-4 flex w-[400px] 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"
+ className={cn(
+ "menu-soft-surface pointer-events-auto fixed flex w-[400px] 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">
diff --git a/studio/frontend/src/features/api-monitor/panel-placement.ts b/studio/frontend/src/features/api-monitor/panel-placement.ts
new file mode 100644
index 00000000000..37513e5b873
--- /dev/null
+++ b/studio/frontend/src/features/api-monitor/panel-placement.ts
@@ -0,0 +1,214 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Where the API monitor panel sits so that it does not land on top of another
+ * floating panel.
+ *
+ * The Live resource monitor defaults to the bottom-right corner and so does
+ * this one, which put this panel's header, its Close button and its drag
+ * handle underneath a window the user can resize across the whole viewport.
+ *
+ * Avoidance rather than a z-index, because it is what Studio already does in
+ * this corner: the notification stack does not outrank the monitor, it steps
+ * over it (monitor-frame-store's stackGeometry, whose gap and inset this file
+ * matches so the three surfaces line up on one grid). This panel reads the same
+ * published boxes and does the same thing one rung further in.
+ *
+ * Pure, and separate from the component, because the interesting part is what
+ * happens when there is nowhere clear to go.
+ */
+
+/** A box in viewport coordinates, as published to the monitor frame store. */
+export interface PanelRect {
+ left: number;
+ top: number;
+ right: number;
+ bottom: number;
+}
+
+export interface PanelSize {
+ width: number;
+ height: number;
+}
+
+export interface PanelViewport {
+ width: number;
+ height: number;
+}
+
+/** The panel's top-left corner, in viewport coordinates. */
+export interface PanelAnchor {
+ left: number;
+ top: number;
+}
+
+/** The inset the panel shipped with (`bottom-4 right-4`), and the stack's. */
+export const PANEL_MARGIN = 16;
+/** Clearance left between the panel and a box it has stepped over. */
+export const PANEL_GAP = 8;
+/**
+ * How far down the panel's own top edge may come.
+ *
+ * The app's top chrome -- the navbar at 48px, or the custom Tauri titlebar band
+ * that carries the window's own minimise and close buttons -- publishes no box,
+ * and this layer paints over all of it. Stepping over something tall would
+ * otherwise park a floating panel on the window controls, which is the one
+ * place a user must always be able to reach.
+ */
+export const PANEL_TOP_MARGIN = 64;
+
+/**
+ * A place to sit, and how much this panel wants it.
+ *
+ * Two orders, because they disagree. `clearRank` is which free spot to take:
+ * the corner the panel shipped in, else the smallest step out of the way, else
+ * anywhere. `refugeRank` is which spot to take when none of them are free, and
+ * there the right-hand corners are the worst ones: both floating panels put
+ * their close button and their resize grip on their right edge, so covering a
+ * right-hand corner is what takes a covered window away from the user.
+ */
+interface Candidate {
+ anchor: PanelAnchor;
+ clearRank: number;
+ refugeRank: number;
+}
+
+function overlapArea(
+ anchor: PanelAnchor,
+ size: PanelSize,
+ box: PanelRect,
+): number {
+ const width =
+ Math.min(anchor.left + size.width, box.right) -
+ Math.max(anchor.left, box.left);
+ const height =
+ Math.min(anchor.top + size.height, box.bottom) -
+ Math.max(anchor.top, box.top);
+ return width > 0 && height > 0 ? width * height : 0;
+}
+
+/**
+ * Keep the whole panel on screen. The margin wins a viewport too small to hold
+ * the panel at all, so its top-left corner -- the title, the drag handle --
+ * stays reachable and the overflow goes off the far edge.
+ *
+ * Also applied to a panel the user has placed by hand, which stops being
+ * re-placed but must not be left off the edge by a window the user then
+ * shrinks: the panel keeps no position across reloads, so a panel stranded
+ * outside the viewport has no way back.
+ */
+export function clampPanelToViewport(
+ anchor: PanelAnchor,
+ size: PanelSize,
+ viewport: PanelViewport,
+): PanelAnchor {
+ return {
+ left: Math.max(
+ PANEL_MARGIN,
+ Math.min(anchor.left, viewport.width - PANEL_MARGIN - size.width),
+ ),
+ top: Math.max(
+ PANEL_TOP_MARGIN,
+ Math.min(anchor.top, viewport.height - PANEL_MARGIN - size.height),
+ ),
+ };
+}
+
+function candidates(
+ size: PanelSize,
+ obstacles: readonly PanelRect[],
+ viewport: PanelViewport,
+): Candidate[] {
+ const right = viewport.width - PANEL_MARGIN - size.width;
+ const bottom = viewport.height - PANEL_MARGIN - size.height;
+ // Stepping over the lowest box first: clearing that one may be enough, and
+ // it is the smallest move away from where the user last saw the panel.
+ const steps = [...obstacles]
+ .sort((a, b) => b.top - a.top)
+ .map((box) => ({ left: right, top: box.top - PANEL_GAP - size.height }));
+ // The corner each candidate came from, kept rather than inferred back out of
+ // its coordinates. A 400px panel in a 768px window is anchored right at
+ // left=352, which is left of the midpoint, so reading the side off `left`
+ // ranked the right-hand corner as a left-hand refuge. Being first, it then
+ // won the tie and the panel stayed exactly where it was, over the Close
+ // button and the resize grip this fallback exists to keep reachable.
+ const ordered: Array<PanelAnchor & { rightSide: boolean }> = [
+ { left: right, top: bottom, rightSide: true },
+ ...steps.map((step) => ({ ...step, rightSide: true })),
+ { left: PANEL_MARGIN, top: bottom, rightSide: false },
+ { left: PANEL_MARGIN, top: PANEL_TOP_MARGIN, rightSide: false },
+ { left: right, top: PANEL_TOP_MARGIN, rightSide: true },
+ ];
+ return ordered.map((anchor, index) => {
+ const placed = clampPanelToViewport(anchor, size, viewport);
+ return {
+ anchor: placed,
+ clearRank: index,
+ // Left half first, and within a half the bottom first: this panel and
+ // the stack both live along the bottom edge, so a refuge up top is the
+ // bigger surprise.
+ refugeRank:
+ (anchor.rightSide ? 2 : 0) +
+ (placed.top > viewport.height / 2 ? 0 : 1),
+ };
+ });
+}
+
+/**
+ * The best anchor for a panel of `size` given everything it must keep clear of.
+ *
+ * The first candidate that touches nothing wins, so a free corner keeps the
+ * panel exactly where it has always been. If every candidate is covered -- a
+ * monitor resized over the whole viewport -- the least covered one wins, and
+ * an outright tie goes to the corner that leaves the covered window's own
+ * controls reachable rather than back to the corner both panels want.
+ */
+export function placeFloatingPanel(
+ size: PanelSize,
+ obstacles: readonly PanelRect[],
+ viewport: PanelViewport,
+): PanelAnchor {
+ const options = candidates(size, obstacles, viewport);
+ let best = options[0];
+ let bestOverlap = Number.POSITIVE_INFINITY;
+ for (const option of options) {
+ let overlap = 0;
+ for (const box of obstacles) {
+ overlap += overlapArea(option.anchor, size, box);
+ }
+ if (overlap === 0) {
+ return option.anchor;
+ }
+ if (
+ overlap < bestOverlap ||
+ (overlap === bestOverlap && option.refugeRank < best.refugeRank)
+ ) {
+ best = option;
+ bestOverlap = overlap;
+ }
+ }
+ return best.anchor;
+}
+
+/**
+ * Whether one of these boxes hides the panel completely.
+ *
+ * The panel opens itself, so unlike the resource monitor it can be swallowed
+ * without the user having asked for anything, and a panel with no pixel showing
+ * has no way back to the front. This is the one case where the layer, not the
+ * geometry, has to give.
+ */
+export function isFullyCovered(
+ anchor: PanelAnchor,
+ size: PanelSize,
+ obstacles: readonly PanelRect[],
+): boolean {
+ return obstacles.some(
+ (box) =>
+ box.left <= anchor.left &&
+ box.top <= anchor.top &&
+ box.right >= anchor.left + size.width &&
+ box.bottom >= anchor.top + size.height,
+ );
+}
diff --git a/studio/frontend/src/features/api-monitor/use-panel-anchor.ts b/studio/frontend/src/features/api-monitor/use-panel-anchor.ts
new file mode 100644
index 00000000000..f3cc8fcadde
--- /dev/null
+++ b/studio/frontend/src/features/api-monitor/use-panel-anchor.ts
@@ -0,0 +1,179 @@
+// 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/features/settings/stores/monitor-frame-store.ts b/studio/frontend/src/features/settings/stores/monitor-frame-store.ts
index bef22ee54ed..9a762459974 100644
--- a/studio/frontend/src/features/settings/stores/monitor-frame-store.ts
+++ b/studio/frontend/src/features/settings/stores/monitor-frame-store.ts
@@ -4,7 +4,13 @@
// What the bottom-right overlay stack has to keep clear of, in viewport
// coordinates. The Live monitor is draggable and resizable and defaults to that
// same corner; the chat composer docks to the bottom of the same column once a
-// thread has turns. Each publishes its box here while it is mounted.
+// thread has turns; the API monitor panel opens in that corner on its own. Each
+// publishes its box here while it is mounted.
+//
+// Read as well as written: the API monitor panel places itself against every
+// box but its own (api-monitor/panel-placement), so the three surfaces resolve
+// in one direction -- the monitor is placed by the user, the API panel steps
+// around the monitor, and the stack steps around both.
import { useCallback, useEffect, useMemo, useState } from "react";
import { create } from "zustand";
diff --git a/studio/frontend/src/lib/floating-panel-order.ts b/studio/frontend/src/lib/floating-panel-order.ts
new file mode 100644
index 00000000000..2cabba7e656
--- /dev/null
+++ b/studio/frontend/src/lib/floating-panel-order.ts
@@ -0,0 +1,74 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Which floating panel is in front.
+ *
+ * The Live resource monitor and the API monitor overlay are both windows: they
+ * float over the page, they are dragged, resized and closed, and they both
+ * default to the bottom-right corner. They keep out of each other's way
+ * geometrically (see api-monitor/panel-placement), and that is the whole
+ * answer while there is anywhere to move to. There is not always: a monitor
+ * resized to fill the viewport leaves no clear space at all, and then the only
+ * thing deciding whether the panel underneath can be reached is z-index.
+ *
+ * So they share one layer and the one the user touched last comes forward,
+ * which is what every window manager does and what the rest of Studio's
+ * corner overlays already imply -- the notification stack yields to whichever
+ * panel is published under it rather than fighting for a number.
+ *
+ * Deliberately not a stack of arbitrary depth: there are two panels, so "which
+ * one is on top" is one value, and a list would only invite a third caller to
+ * assume ordering it does not have.
+ */
+
+import { create } from "zustand";
+import { Z_LAYER } from "./z-layers.ts";
+
+export type FloatingPanelId = "resource-monitor" | "api-monitor";
+
+interface FloatingPanelOrderState {
+ /** The panel in front, or null before either has been opened. */
+ top: FloatingPanelId | null;
+ /** Bring `id` forward. A no-op write must not notify: this runs on pointerdown. */
+ raise: (id: FloatingPanelId) => void;
+}
+
+export const useFloatingPanelOrderStore = create<FloatingPanelOrderState>(
+ (set) => ({
+ top: null,
+ raise: (id) => set((state) => (state.top === id ? state : { top: id })),
+ }),
+);
+
+/**
+ * The z-index `id` should paint at.
+ *
+ * Both panels sit on FLOATING_PANEL; the front one takes the single step above
+ * it. Nothing is ever two steps up, so the pair can never straddle the layer
+ * above them.
+ *
+ * `hidden` is the one override: a panel with no pixel left showing cannot be
+ * clicked, so it cannot be brought back to the front by the same rule as
+ * everything else. It comes forward on its own. Only the API monitor panel asks
+ * this, because only it opens and places itself; the resource monitor is where
+ * the user put it, and whatever is over it is there because they dragged it.
+ */
+export function floatingPanelZIndex(
+ id: FloatingPanelId,
+ top: FloatingPanelId | null,
+ hidden = false,
+): number {
+ return hidden || top === id
+ ? Z_LAYER.FLOATING_PANEL_TOP
+ : Z_LAYER.FLOATING_PANEL;
+}
+
+/** `floatingPanelZIndex` for the calling panel, re-read as the front one changes. */
+export function useFloatingPanelZIndex(
+ id: FloatingPanelId,
+ hidden = false,
+): number {
+ const top = useFloatingPanelOrderStore((state) => state.top);
+ return floatingPanelZIndex(id, top, hidden);
+}
diff --git a/studio/frontend/src/lib/z-layers.ts b/studio/frontend/src/lib/z-layers.ts
new file mode 100644
index 00000000000..2880af3574b
--- /dev/null
+++ b/studio/frontend/src/lib/z-layers.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * The stacking order of Studio's full-viewport surfaces, in one place.
+ *
+ * Everything here is a `position: fixed` surface that covers whatever is under
+ * it, so the only thing deciding who wins is the number. Written down together
+ * because these numbers are meaningless apart: raising one file's z-index to
+ * fix one screenshot is what produced the 9998/9999 pair this replaces.
+ *
+ * Ordered bottom to top:
+ *
+ * OVERLAY_STACK passive corner status, nothing to click through to
+ * FLOATING_PANEL windows the user drags, resizes and closes
+ * FLOATING_PANEL_TOP the one of those the user touched last
+ * STARTUP_SCREEN blocks the app while the backend comes up or quits
+ * TOOLTIP transient, must be readable above whatever spawned it
+ *
+ * In-page surfaces -- dropdowns, popovers, dialogs, sheets, the sidebar, the
+ * Tauri titlebar -- all sit in the 1..120 band on Tailwind's own `z-*` scale
+ * and are deliberately not renumbered here: nothing in this file competes with
+ * them for a number, so folding them in would change what paints over what
+ * without fixing anything. See tests/studio/test_overlay_layering.py.
+ */
+export const Z_LAYER = {
+ /**
+ * The bottom-right notification stack: update banners, the download panel,
+ * the loaded models card. Passive; it already keeps clear of the panels
+ * below it geometrically (see monitor-frame-store), and where it cannot, it
+ * loses.
+ */
+ OVERLAY_STACK: 9000,
+ /**
+ * Floating panels: the Live resource monitor and the API monitor overlay.
+ * Above the stack because a window the user is dragging, resizing and
+ * closing outranks a status card that happened to land on top of it.
+ */
+ FLOATING_PANEL: 9100,
+ /**
+ * The floating panel the user touched last. Only ever one panel at a time,
+ * so a single step above FLOATING_PANEL is enough; see floating-panel-order.
+ */
+ FLOATING_PANEL_TOP: 9101,
+ /**
+ * The startup and closing screens, which stand in for the whole app while
+ * the backend comes up or shuts down. Nothing below may show through.
+ */
+ STARTUP_SCREEN: 9999,
+ /** Tooltips, which have to be legible above whatever spawned them. */
+ TOOLTIP: 999999,
+} as const;
+
+export type ZLayer = (typeof Z_LAYER)[keyof typeof Z_LAYER];
diff --git a/studio/frontend/tests/floating-panel-order.test.ts b/studio/frontend/tests/floating-panel-order.test.ts
new file mode 100644
index 00000000000..400d86e914f
--- /dev/null
+++ b/studio/frontend/tests/floating-panel-order.test.ts
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The two floating panels share one layer, and the one the user touched last
+// paints over the other. Geometry keeps them apart while there is anywhere to
+// move to; this is what decides the case where there is not.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ floatingPanelZIndex,
+ useFloatingPanelOrderStore,
+} from "../src/lib/floating-panel-order.ts";
+import { Z_LAYER } from "../src/lib/z-layers.ts";
+
+test("before either panel is touched neither is singled out", () => {
+ assert.equal(
+ floatingPanelZIndex("api-monitor", null),
+ Z_LAYER.FLOATING_PANEL,
+ );
+ assert.equal(
+ floatingPanelZIndex("resource-monitor", null),
+ Z_LAYER.FLOATING_PANEL,
+ );
+});
+
+test("the panel in front outranks the other one", () => {
+ assert.equal(
+ floatingPanelZIndex("api-monitor", "api-monitor"),
+ Z_LAYER.FLOATING_PANEL_TOP,
+ );
+ assert.equal(
+ floatingPanelZIndex("resource-monitor", "api-monitor"),
+ Z_LAYER.FLOATING_PANEL,
+ );
+});
+
+// Nothing is ever two steps up, so the pair cannot straddle the layer above.
+test("the front panel stays under the layer above the floating panels", () => {
+ assert.ok(Z_LAYER.FLOATING_PANEL_TOP < Z_LAYER.STARTUP_SCREEN);
+ assert.ok(Z_LAYER.FLOATING_PANEL_TOP < Z_LAYER.TOOLTIP);
+});
+
+test("raising swaps which panel is in front", () => {
+ const { raise } = useFloatingPanelOrderStore.getState();
+ raise("resource-monitor");
+ assert.equal(useFloatingPanelOrderStore.getState().top, "resource-monitor");
+ raise("api-monitor");
+ assert.equal(useFloatingPanelOrderStore.getState().top, "api-monitor");
+});
+
+// This runs on pointerdown, so a re-raise of the panel already in front must
+// not notify: every subscriber re-renders on it.
+test("raising the panel already in front changes nothing", () => {
+ const { raise } = useFloatingPanelOrderStore.getState();
+ raise("api-monitor");
+ let notified = 0;
+ const unsubscribe = useFloatingPanelOrderStore.subscribe(() => {
+ notified += 1;
+ });
+ raise("api-monitor");
+ unsubscribe();
+ assert.equal(notified, 0);
+});
+
+// A panel with nothing showing cannot be clicked, so it cannot be raised by the
+// same rule as everything else. This is the way out of a resource monitor
+// resized over the whole viewport.
+test("a completely hidden panel comes forward whatever is in front", () => {
+ assert.equal(
+ floatingPanelZIndex("api-monitor", "resource-monitor", true),
+ Z_LAYER.FLOATING_PANEL_TOP,
+ );
+});
+
+test("a panel that is merely behind stays behind", () => {
+ assert.equal(
+ floatingPanelZIndex("api-monitor", "resource-monitor", false),
+ Z_LAYER.FLOATING_PANEL,
+ );
+});
diff --git a/studio/frontend/tests/panel-placement.test.ts b/studio/frontend/tests/panel-placement.test.ts
new file mode 100644
index 00000000000..6b148d619cf
--- /dev/null
+++ b/studio/frontend/tests/panel-placement.test.ts
@@ -0,0 +1,256 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Where the API monitor panel puts itself when the Live resource monitor is
+// already in the corner it wants. The reported bug: both default to bottom
+// right, so the monitor covered this panel's header and Close button, and a
+// monitor resized across the viewport hid it completely.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ clampPanelToViewport,
+ isFullyCovered,
+ PANEL_GAP,
+ PANEL_MARGIN,
+ PANEL_TOP_MARGIN,
+ type PanelRect,
+ type PanelSize,
+ placeFloatingPanel,
+} from "../src/features/api-monitor/panel-placement.ts";
+
+const W = 1440;
+const H = 900;
+const VIEWPORT = { width: W, height: H };
+/** The panel as it ships: w-[400px], four rows and two buttons tall. */
+const PANEL: PanelSize = { width: 400, height: 300 };
+
+/** The Live monitor where it opens by default: bottom-right, w-64, inset-4. */
+function monitorCorner(height = 300): PanelRect {
+ return {
+ left: W - PANEL_MARGIN - 256,
+ top: H - PANEL_MARGIN - height,
+ right: W - PANEL_MARGIN,
+ bottom: H - PANEL_MARGIN,
+ };
+}
+
+function overlaps(
+ anchor: { left: number; top: number },
+ size: PanelSize,
+ box: PanelRect,
+): boolean {
+ return (
+ anchor.left < box.right &&
+ anchor.left + size.width > box.left &&
+ anchor.top < box.bottom &&
+ anchor.top + size.height > box.top
+ );
+}
+
+test("with nothing in the way the panel keeps the corner it shipped in", () => {
+ const anchor = placeFloatingPanel(PANEL, [], VIEWPORT);
+ assert.deepEqual(anchor, {
+ left: W - PANEL_MARGIN - PANEL.width,
+ top: H - PANEL_MARGIN - PANEL.height,
+ });
+});
+
+// The collision itself.
+test("a monitor in the shared corner is stepped over, not sat on", () => {
+ const monitor = monitorCorner();
+ const anchor = placeFloatingPanel(PANEL, [monitor], VIEWPORT);
+ assert.ok(
+ !overlaps(anchor, PANEL, monitor),
+ `the panel still covers the monitor: ${JSON.stringify(anchor)}`,
+ );
+ // Same column, directly above it, which is the move the notification stack
+ // makes: staying put horizontally is the smallest surprise.
+ assert.equal(anchor.left, W - PANEL_MARGIN - PANEL.width);
+ assert.equal(anchor.top + PANEL.height + PANEL_GAP, monitor.top);
+});
+
+test("a monitor dragged out of the corner leaves the panel where it was", () => {
+ const monitor: PanelRect = {
+ left: PANEL_MARGIN,
+ top: PANEL_MARGIN,
+ right: PANEL_MARGIN + 256,
+ bottom: PANEL_MARGIN + 300,
+ };
+ assert.deepEqual(placeFloatingPanel(PANEL, [monitor], VIEWPORT), {
+ left: W - PANEL_MARGIN - PANEL.width,
+ top: H - PANEL_MARGIN - PANEL.height,
+ });
+});
+
+test("a monitor too tall to step over sends the panel to the other side", () => {
+ // Full-height, but only as wide as the monitor gets: the left half is free.
+ const monitor: PanelRect = {
+ left: W - PANEL_MARGIN - 500,
+ top: PANEL_MARGIN,
+ right: W - PANEL_MARGIN,
+ bottom: H - PANEL_MARGIN,
+ };
+ const anchor = placeFloatingPanel(PANEL, [monitor], VIEWPORT);
+ assert.ok(!overlaps(anchor, PANEL, monitor), "the panel must clear it");
+ assert.equal(anchor.left, PANEL_MARGIN);
+});
+
+test("every published box is dodged, not just the first", () => {
+ const monitor = monitorCorner(200);
+ // The docked chat composer publishes too, and it is wide.
+ const composer: PanelRect = {
+ left: 200,
+ top: H - 260,
+ right: W - 200,
+ bottom: H - 24,
+ };
+ const anchor = placeFloatingPanel(PANEL, [monitor, composer], VIEWPORT);
+ assert.ok(!overlaps(anchor, PANEL, monitor), "monitor still covered");
+ assert.ok(!overlaps(anchor, PANEL, composer), "composer still covered");
+});
+
+// The rescue case, and the reason the fallback order is not the same as the
+// preference order: with the monitor over everything, the panel has to land
+// somewhere that leaves the monitor's own close button and resize grip -- both
+// on its right-hand edge -- clickable.
+test("a monitor filling the viewport pushes the panel off the right edge", () => {
+ const monitor: PanelRect = {
+ left: PANEL_MARGIN,
+ top: PANEL_MARGIN,
+ right: W - PANEL_MARGIN,
+ bottom: H - PANEL_MARGIN,
+ };
+ const anchor = placeFloatingPanel(PANEL, [monitor], VIEWPORT);
+ assert.equal(anchor.left, PANEL_MARGIN, "must not stay in the right column");
+ assert.equal(anchor.top, H - PANEL_MARGIN - PANEL.height);
+});
+
+// The same rescue, in a window narrow enough that the right-hand anchor's own
+// left coordinate falls left of the midpoint. Reading the side back out of the
+// coordinates called that a left-hand refuge, so it tied with the real one,
+// won on order, and left the panel over the controls it was moving to clear.
+test("a narrow window still sends the panel off the right edge", () => {
+ for (const width of [768, 800, 832]) {
+ const viewport = { width, height: 700 };
+ const monitor: PanelRect = {
+ left: PANEL_MARGIN,
+ top: PANEL_MARGIN,
+ right: width - PANEL_MARGIN,
+ bottom: 700 - PANEL_MARGIN,
+ };
+ const anchor = placeFloatingPanel(PANEL, [monitor], viewport);
+ assert.equal(
+ anchor.left,
+ PANEL_MARGIN,
+ `at ${width}px the panel stayed in the right column, over Close and the grip`,
+ );
+ }
+});
+
+test("the panel always lands fully on screen", () => {
+ const monitor = monitorCorner(600);
+ for (const viewport of [
+ { width: 1440, height: 900 },
+ { width: 420, height: 700 },
+ ]) {
+ const size = {
+ width: Math.min(PANEL.width, viewport.width - 2 * PANEL_MARGIN),
+ height: PANEL.height,
+ };
+ const anchor = placeFloatingPanel(size, [monitor], viewport);
+ assert.ok(anchor.left >= PANEL_MARGIN, `left off screen: ${anchor.left}`);
+ assert.ok(anchor.top >= PANEL_MARGIN, `top off screen: ${anchor.top}`);
+ assert.ok(
+ anchor.left + size.width <= viewport.width - PANEL_MARGIN,
+ `right off screen: ${anchor.left + size.width}`,
+ );
+ assert.ok(
+ anchor.top + size.height <= viewport.height - PANEL_MARGIN,
+ `bottom off screen: ${anchor.top + size.height}`,
+ );
+ }
+});
+
+// A viewport shorter than the panel has no anchor that fits. The header is the
+// part that has to survive, because it holds the drag handle and Close.
+test("a viewport too small for the panel keeps its header on screen", () => {
+ const anchor = placeFloatingPanel(PANEL, [], { width: 320, height: 200 });
+ assert.deepEqual(anchor, { left: PANEL_MARGIN, top: PANEL_TOP_MARGIN });
+});
+
+// The top chrome -- the navbar, and on desktop the titlebar carrying the
+// window's own close button -- publishes no box and sits under this layer.
+test("stepping over a tall box never reaches the top chrome", () => {
+ const tall: PanelRect = {
+ left: 400,
+ top: 100,
+ right: W - PANEL_MARGIN,
+ bottom: H - PANEL_MARGIN,
+ };
+ const anchor = placeFloatingPanel(PANEL, [tall], VIEWPORT);
+ assert.ok(
+ anchor.top >= PANEL_TOP_MARGIN,
+ `the panel climbed into the top chrome: ${anchor.top}`,
+ );
+});
+
+test("nothing published leaves the panel uncovered", () => {
+ const anchor = { left: 100, top: 100 };
+ assert.equal(isFullyCovered(anchor, PANEL, []), false);
+});
+
+test("a box that swallows the panel whole is reported", () => {
+ const anchor = { left: 100, top: 100 };
+ const whole: PanelRect = { left: 0, top: 0, right: W, bottom: H };
+ assert.equal(isFullyCovered(anchor, PANEL, [whole]), true);
+});
+
+// Partly covered is not covered: a sliver is enough to click, and raising the
+// panel for a sliver would fight a user who dragged the monitor over it. One
+// case per edge, because a containment test that drops one edge still passes
+// every other example.
+test("a box that leaves any edge of the panel showing is not reported", () => {
+ const anchor = { left: 100, top: 100 };
+ const whole: PanelRect = {
+ left: 0,
+ top: 0,
+ right: 100 + PANEL.width,
+ bottom: 100 + PANEL.height,
+ };
+ const shy = {
+ left: { ...whole, left: anchor.left + 1 },
+ top: { ...whole, top: anchor.top + 1 },
+ right: { ...whole, right: whole.right - 1 },
+ bottom: { ...whole, bottom: whole.bottom - 1 },
+ };
+ // The reference box, one pixel bigger on every side, does cover it.
+ assert.equal(isFullyCovered(anchor, PANEL, [whole]), true);
+ for (const [edge, box] of Object.entries(shy)) {
+ assert.equal(
+ isFullyCovered(anchor, PANEL, [box]),
+ false,
+ `a strip showing on the ${edge} still counted as covered`,
+ );
+ }
+});
+
+// A panel the user has placed stops being re-placed, but it still has to be
+// pulled back onto a viewport that has shrunk under it: the panel keeps no
+// position across reloads, so one stranded off the edge is unreachable.
+test("a hand-placed panel is pulled back onto a shrunken viewport", () => {
+ const landed = clampPanelToViewport({ left: 1200, top: 700 }, PANEL, {
+ width: 800,
+ height: 600,
+ });
+ assert.deepEqual(landed, {
+ left: 800 - PANEL_MARGIN - PANEL.width,
+ top: 600 - PANEL_MARGIN - PANEL.height,
+ });
+});
+
+test("a hand-placed panel inside the viewport is left alone", () => {
+ const placed = { left: 300, top: 300 };
+ assert.deepEqual(clampPanelToViewport(placed, PANEL, VIEWPORT), placed);
+});
diff --git a/studio/frontend/tests/update-banner-flex-priority.test.ts b/studio/frontend/tests/update-banner-flex-priority.test.ts
index 557117bdb08..87e76367dce 100644
--- a/studio/frontend/tests/update-banner-flex-priority.test.ts
+++ b/studio/frontend/tests/update-banner-flex-priority.test.ts
@@ -232,7 +232,7 @@ test("the collapsed notes summary scrolls, like the expanded notes", () => {
});
test("the rail scrolls rather than spilling its cards", () => {
- const rails = PROVIDER.split("fixed right-4 z-[9998]");
+ const rails = PROVIDER.split('"fixed right-4 ');
// The desktop rail and the browser rail.
assert.equal(rails.length - 1, 2, "the rail count changed");
for (const rail of rails.slice(1)) {
@@ -260,7 +260,7 @@ test("the rail scrolls rather than spilling its cards", () => {
// opt back in, so a scrolling rail nobody can drag hides the cards under the
// fold. It is click-through only while there is nothing to scroll to.
test("a scrolling rail takes pointer input, a fitting one stays click-through", () => {
- const rails = PROVIDER.split("fixed right-4 z-[9998]");
+ const rails = PROVIDER.split('"fixed right-4 ');
assert.equal(rails.length - 1, 2, "the rail count changed");
for (const rail of rails.slice(1)) {
const branch = rail.slice(0, rail.indexOf("style={{"));
diff --git a/studio/frontend/tests/z-layers.test.ts b/studio/frontend/tests/z-layers.test.ts
new file mode 100644
index 00000000000..75e71b476d5
--- /dev/null
+++ b/studio/frontend/tests/z-layers.test.ts
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The order the named layers are meant to be in. Renumbering is fine; the
+// ordering is the contract, and it is the ordering that decides whether a
+// Close button can be clicked. tests/studio/test_overlay_layering.py checks the
+// components actually use these.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { Z_LAYER } from "../src/lib/z-layers.ts";
+
+// The layers, bottom to top. Adding one belongs in this list.
+const ORDER = [
+ "OVERLAY_STACK",
+ "FLOATING_PANEL",
+ "FLOATING_PANEL_TOP",
+ "STARTUP_SCREEN",
+ "TOOLTIP",
+] as const;
+
+test("the named layers are strictly ordered", () => {
+ for (let i = 1; i < ORDER.length; i += 1) {
+ const below = ORDER[i - 1];
+ const above = ORDER[i];
+ assert.ok(
+ Z_LAYER[below] < Z_LAYER[above],
+ `${below} (${Z_LAYER[below]}) must sit under ${above} (${Z_LAYER[above]})`,
+ );
+ }
+});
+
+test("every layer is listed in the order", () => {
+ assert.deepEqual(Object.keys(Z_LAYER).sort(), [...ORDER].sort());
+});
+
+// What #8199 fixed: a passive status card was covering a window's Close button.
+test("floating panels paint over the notification stack", () => {
+ assert.ok(Z_LAYER.FLOATING_PANEL > Z_LAYER.OVERLAY_STACK);
+});
+
+// Every in-page surface -- dialogs, sheets, dropdowns, the Tauri titlebar --
+// is on Tailwind's own scale and tops out at 120. Nothing named here may drop
+// into that band, or the numbers stop being comparable at a glance.
+test("the named layers stay clear of the in-page scale", () => {
+ for (const name of ORDER) {
+ assert.ok(
+ Z_LAYER[name] > 120,
+ `${name} (${Z_LAYER[name]}) has dropped into the in-page z-index band`,
+ );
+ }
+});
diff --git a/tests/studio/test_overlay_layering.py b/tests/studio/test_overlay_layering.py
index b0bab83d006..afc780a7d91 100644
--- a/tests/studio/test_overlay_layering.py
+++ b/tests/studio/test_overlay_layering.py
@@ -3,16 +3,23 @@
"""Who paints over whom in the bottom-right corner.
-The floating API monitor and the notification stack both live there. The stack
-tries to dodge the monitor (see stackGeometry and monitor-stack-inset.test.ts),
-but the dodge has a floor: a monitor dragged to the corner and resized to fill
-the viewport leaves nowhere to dodge to, and the stack is parked at the top of
-the screen, on top of the monitor's own title bar. At that point z-order is the
-only thing deciding whether the monitor's Close button can be clicked.
+The Live resource monitor, the API monitor panel and the notification stack all
+live there. The first two keep out of each other's way geometrically and the
+stack steps over both (stackGeometry, panel-placement, monitor-stack-inset.test.ts
+and panel-placement.test.ts), but the dodge has a floor: a monitor dragged to the
+corner and resized to fill the viewport leaves nowhere to dodge to, and the stack
+is parked at the top of the screen, on top of the monitor's own title bar. At that
+point z-order is the only thing deciding whether the monitor's Close button can be
+clicked.
The Windows UI smoke does exactly that drag-and-resize and then clicks Close, so
it catches a regression here for real. It takes about twenty minutes and needs a
Windows runner. These read the numbers straight out of the source instead.
+
+The numbers themselves live in one place now, studio/frontend/src/lib/z-layers.ts.
+These tests compare them rather than pinning any one of them, so renumbering a
+layer does not break them -- what breaks them is a surface leaving the named scale
+or two layers swapping places.
"""
from __future__ import annotations
@@ -24,52 +31,102 @@ import pytest
REPO = Path(__file__).resolve().parents[2]
FRONTEND = REPO / "studio/frontend/src"
+Z_LAYERS = FRONTEND / "lib/z-layers.ts"
MONITOR = FRONTEND / "components/floating-monitor.tsx"
+API_PANEL = FRONTEND / "features/api-monitor/api-monitor-overlay.tsx"
PROVIDER = FRONTEND / "app/provider.tsx"
STARTUP = FRONTEND / "components/tauri/startup-screen.tsx"
TOOLTIP = FRONTEND / "components/ui/tooltip.tsx"
_Z = re.compile(r"z-\[(\d+)\]")
+_LAYER = re.compile(r"^\s{2}([A-Z_]+): (\d+),$", re.MULTILINE)
+
+
+def _layers() -> dict[str, int]:
+ """The named scale, straight out of z-layers.ts."""
+ text = Z_LAYERS.read_text(encoding = "utf-8")
+ found = {name: int(value) for name, value in _LAYER.findall(text)}
+ assert found, "no named layers were found in z-layers.ts"
+ return found
def _z_indexes(path: Path) -> list[int]:
return [int(m) for m in _Z.findall(path.read_text(encoding = "utf-8"))]
-def _monitor_root_z() -> int:
- """The z on the monitor's constraints container, which is what stacks it."""
- src = MONITOR.read_text(encoding = "utf-8")
- root = re.search(r"ref=\{setConstraintsElement\}\s*\n\s*className=\"([^\"]+)\"", src)
- assert root, "the monitor's constraints container was not found"
- found = _Z.search(root.group(1))
- assert found, f"the monitor's container carries no z-\\[n\\]: {root.group(1)!r}"
- return int(found.group(1))
+def _container(path: Path, ref: str) -> str:
+ """The JSX attributes of the fixed container that stacks a floating panel."""
+ src = path.read_text(encoding = "utf-8")
+ found = re.search(rf"ref=\{{{ref}\}}\s*\n(?:\s*[^\n]*\n)*?\s*>", src)
+ assert found, f"{path.name}: the container with ref={{{ref}}} was not found"
+ return found.group(0)
-def _stack_z() -> int:
- """The bottom-right overlay stack. Both copies, browser and desktop."""
- src = PROVIDER.read_text(encoding = "utf-8")
- # The click-through class is applied conditionally, so it is not part of
- # the literal the stack's own classes are authored in.
- stacks = re.findall(r'"fixed right-4 z-\[(\d+)\]', src)
- assert stacks, "the bottom-right overlay stack was not found"
- assert len(set(stacks)) == 1, f"the two stacks disagree on z-index: {stacks}"
- return int(stacks[0])
+def test_the_floating_panels_paint_over_the_notification_stack():
+ """A full-viewport monitor parks the stack over its own title bar. The stack is
+ passive status; the panels are windows being dragged, resized and closed."""
+ layers = _layers()
+ assert layers["FLOATING_PANEL"] > layers["OVERLAY_STACK"], (
+ "the notification stack paints over the floating panels, so their Close "
+ "buttons cannot be clicked once a panel fills the viewport"
+ )
-def test_the_monitor_paints_over_the_notification_stack():
- """A full-viewport monitor parks the stack over its own title bar. The stack is
- passive status; the monitor is a window being dragged, resized and closed."""
- assert _monitor_root_z() > _stack_z(), (
- "the notification stack paints over the floating monitor, so its Close "
- "button cannot be clicked once the monitor fills the viewport"
+def test_the_front_panel_does_not_climb_past_the_layer_above_it():
+ """Only one panel is ever raised, by one step, so the pair cannot straddle
+ the startup screen."""
+ layers = _layers()
+ assert layers["FLOATING_PANEL_TOP"] == layers["FLOATING_PANEL"] + 1
+ assert layers["FLOATING_PANEL_TOP"] < layers["STARTUP_SCREEN"]
+
+
[email protected]("path", [MONITOR, API_PANEL])
+def test_both_floating_panels_stack_on_the_shared_layer(path: Path):
+ """Both containers take their z-index from the order store, not from a class.
+ 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")
+ assert "style={{ zIndex }}" in container, (
+ f"{path.name}: the panel container no longer takes its z-index from the "
+ f"floating panel order store: {container!r}"
)
+ assert not _Z.search(container), (
+ f"{path.name}: the panel container still carries a hard-coded z-index, "
+ f"which would win over the shared layer: {container!r}"
+ )
+ src = path.read_text(encoding = "utf-8")
+ assert (
+ "useFloatingPanelZIndex" in src
+ ), f"{path.name}: the panel no longer reads the shared floating panel layer"
[email protected]("path", [STARTUP, TOOLTIP])
-def test_the_monitor_stays_under_the_layers_that_outrank_it(path: Path):
- """Raising the monitor must not put it over the startup screen, which blocks
- the app while the backend comes up, or over tooltips, which are transient and
- have to be readable above whatever spawned them."""
- above = [z for z in _z_indexes(path) if z >= _monitor_root_z()]
- assert above, f"{path.name} no longer outranks the floating monitor"
+def test_the_notification_stack_uses_the_named_layer():
+ """Both copies, browser and desktop. They drifted apart once already."""
+ src = PROVIDER.read_text(encoding = "utf-8")
+ # The click-through class is applied conditionally now, so it is not part
+ # of the literal the rail's own classes are authored in.
+ stacks = re.findall(r'"fixed right-4 ([^"]*)"', src)
+ assert len(stacks) == 2, f"expected the two bottom-right stacks, found {len(stacks)}"
+ for stack in stacks:
+ assert not _Z.search(stack), f"the stack still carries a hard-coded z-index: {stack!r}"
+ assert (
+ src.count("zIndex: Z_LAYER.OVERLAY_STACK") == 2
+ ), "the two bottom-right stacks disagree on their layer"
+
+
+ ("path", "layer"),
+ [(STARTUP, "STARTUP_SCREEN"), (TOOLTIP, "TOOLTIP")],
+)
+def test_the_layers_that_outrank_the_panels_still_do(path: Path, layer: str):
+ """The startup screen blocks the app while the backend comes up, and tooltips
+ are transient and have to be readable above whatever spawned them. Both are
+ still Tailwind classes, so check the literal against the scale as well as the
+ ordering -- otherwise the scale can say one thing and the class another."""
+ layers = _layers()
+ assert (
+ layers[layer] > layers["FLOATING_PANEL_TOP"]
+ ), f"{layer} no longer outranks the floating panels"
+ assert layers[layer] in _z_indexes(
+ path
+ ), f"{path.name} has drifted from Z_LAYER.{layer} ({layers[layer]})"
diff --git a/tests/studio/test_update_release_notes.py b/tests/studio/test_update_release_notes.py
index 134db85efa6..800db843b0f 100644
--- a/tests/studio/test_update_release_notes.py
+++ b/tests/studio/test_update_release_notes.py
@@ -1285,7 +1285,9 @@ def test_the_overlay_stack_fits_the_viewport():
it. The cap is `stackGeometry` now, checked numerically in
studio/frontend/tests/monitor-stack-inset.test.ts; here the stack must read it."""
provider = (FRONTEND / "app/provider.tsx").read_text(encoding = "utf-8")
- stacks = _overlay_stacks(provider)
+ # Counted by the layer they sit on, not by a literal z-index: the
+ # overlay rail reads its depth from Z_LAYER now.
+ stacks = provider.count("zIndex: Z_LAYER.OVERLAY_STACK")
assert stacks, "the bottom-right overlay stack is gone"
# Counted, not merely present: capping only one of the stacks is the bug here.
assert provider.count("maxHeight: stack.maxHeight") == stacks, "every stack is capped"
@@ -1511,7 +1513,9 @@ def test_the_download_panel_can_shrink_inside_the_capped_stack():
)
assert 'positioned ? "fixed bottom-4 right-4 z-50" : "flex min-h-0 justify-end"' in panel
provider = (FRONTEND / "app/provider.tsx").read_text(encoding="utf-8")
- stacks = _overlay_stacks(provider)
+ # Counted by the layer they sit on, not by a literal z-index: the
+ # overlay rail reads its depth from Z_LAYER now.
+ stacks = provider.count("zIndex: Z_LAYER.OVERLAY_STACK")
assert provider.count("maxHeight: stack.maxHeight") == stacks, "the cap this has to absorb"