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
Desktop: fit windows within the monitor work area (#8047)
oobabooga48ab41e1444b
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsxindex 44f10c62a5a..623c48ea767 100644--- a/studio/frontend/src/app/provider.tsx+++ b/studio/frontend/src/app/provider.tsx@@ -37,26 +37,34 @@ import {useRef,useState,} from "react";+import {+ type LogicalWindowSize,+ PREFERRED_SETUP_WINDOW_SIZE,+ type WindowSizeBounds,+ calculateCenteredPosition,+ calculateFirstAppWindowSize,+ constrainWindowSize,+ fitWindowSize,+} from "./window-layout";+import {+ type MeasuredWindowLayout,+ type WindowLayoutGuard,+ finalizeAppWindowLayout,+ shouldFinishWindowLayoutWait,+ measureWindowLayout,+} from "./window-layout-lifecycle";interface AppProviderProps {children: ReactNode;}type TauriWindowMode = "setup" | "app";-type WindowLayoutGuard = () => boolean;-type LogicalWindowSize = {- width: number;- height: number;-};+type WindowModule = typeof import("@tauri-apps/api/window");+type TauriWindow = Awaited<ReturnType<WindowModule["getCurrentWindow"]>>;+type TauriMonitor = NonNullable<+ Awaited<ReturnType<WindowModule["currentMonitor"]>>+>;-const MIN_WINDOW_WIDTH = 900;-const MIN_WINDOW_HEIGHT = 600;-const SETUP_WINDOW_WIDTH = 760;-const SETUP_WINDOW_HEIGHT = 560;-const MINIMUM_APP_WINDOW_SIZE: LogicalWindowSize = {- width: MIN_WINDOW_WIDTH,- height: MIN_WINDOW_HEIGHT,-};// Keep in step with MOBILE_BREAKPOINT in hooks/use-mobile.ts.const MIN_DESKTOP_LAYOUT_WIDTH = 768;@@ -77,74 +85,173 @@ function wasLaunchedHidden(): Promise<boolean> {return launchedHidden;}-async function showSetupWindow(isCurrent: WindowLayoutGuard): Promise<void> {- const { getCurrentWindow, LogicalSize } = await import(- "@tauri-apps/api/window"+type WindowLayoutObserver = {+ waitForSettled: () => Promise<void>;+ dispose: () => void;+};++const WINDOW_LAYOUT_POLL_MS = 50;+const WINDOW_LAYOUT_TIMEOUT_MS = 1000;++function delay(milliseconds: number): Promise<void> {+ return new Promise((resolve) => window.setTimeout(resolve, milliseconds));+}++/** Watches native geometry changes that may arrive after a restore call resolves. */+async function observeWindowLayout(+ win: TauriWindow,+ isCurrent: WindowLayoutGuard,+): Promise<WindowLayoutObserver | null> {+ let revision = 0;+ const noteChange = () => {+ revision += 1;+ };+ const unlistenResized = await win.onResized(noteChange);+ let unlistenMoved: (() => void) | undefined;+ try {+ unlistenMoved = await win.onMoved(noteChange);+ } catch (error) {+ unlistenResized();+ throw error;+ }+ if (!isCurrent()) {+ unlistenResized();+ unlistenMoved();+ return null;+ }++ return {+ waitForSettled: async () => {+ let observedRevision = revision;+ let sawPostShowChange = false;+ for (+ let elapsed = 0;+ elapsed < WINDOW_LAYOUT_TIMEOUT_MS && isCurrent();+ elapsed += WINDOW_LAYOUT_POLL_MS+ ) {+ await delay(WINDOW_LAYOUT_POLL_MS);+ if (revision !== observedRevision) {+ observedRevision = revision;+ sawPostShowChange = true;+ continue;+ }+ if (shouldFinishWindowLayoutWait(sawPostShowChange)) {+ return;+ }+ }+ },+ dispose: () => {+ unlistenResized();+ unlistenMoved();+ },+ };+}++function measureTauriWindowLayout(+ windowModule: WindowModule,+ win: TauriWindow,+ isCurrent: WindowLayoutGuard,+): Promise<MeasuredWindowLayout<TauriMonitor> | null> {+ return measureWindowLayout(+ {+ currentMonitor: () => windowModule.currentMonitor(),+ primaryMonitor: () => windowModule.primaryMonitor(),+ innerSize: () => win.innerSize(),+ outerSize: () => win.outerSize(),+ },+ isCurrent,);+}++/** Sizes the window and centers it inside the work area. */+async function placeWindow(+ win: TauriWindow,+ { LogicalSize, PhysicalPosition }: WindowModule,+ { monitor, frameSize }: MeasuredWindowLayout<TauriMonitor>,+ size: LogicalWindowSize,+ isCurrent: WindowLayoutGuard,+): Promise<void> {+ await win.setSize(new LogicalSize(size.width, size.height));+ if (!isCurrent()) return;+ if (!monitor) {+ await win.center();+ return;+ }+ // Center from the requested size because GTK may still report stale geometry.+ const scaleFactor = await win.scaleFactor();+ if (!isCurrent()) return;+ const position = calculateCenteredPosition(monitor.workArea, {+ width: Math.round(size.width * scaleFactor) + frameSize.width,+ height: Math.round(size.height * scaleFactor) + frameSize.height,+ });+ await win.setPosition(new PhysicalPosition(position.x, position.y));+}++async function showSetupWindow(isCurrent: WindowLayoutGuard): Promise<void> {+ const windowModule = await import("@tauri-apps/api/window");const { invoke } = await import("@tauri-apps/api/core");if (!isCurrent()) return;- const win = getCurrentWindow();+ const win = windowModule.getCurrentWindow();await invoke("reset_app_window_layout_initialized");if (!isCurrent()) return;- await win.setResizable(false);+ // Clear app-mode constraints before showing the smaller setup window.+ await win.setSizeConstraints(null);if (!isCurrent()) return;- await win.setSize(new LogicalSize(SETUP_WINDOW_WIDTH, SETUP_WINDOW_HEIGHT));+ await win.setResizable(false);if (!isCurrent()) return;- await win.center();+ const measured = await measureTauriWindowLayout(windowModule, win, isCurrent);+ if (!measured) return;+ // Keep the non-resizable setup window fully visible.+ const setupSize = fitWindowSize(+ PREFERRED_SETUP_WINDOW_SIZE,+ measured.bounds.maximum,+ );+ await placeWindow(win, windowModule, measured, setupSize, isCurrent);if (!isCurrent()) return;if (await wasLaunchedHidden()) return;if (!isCurrent()) return;await win.show();}-async function enforceMinimumWindowSize(- win: Awaited<- ReturnType<typeof import("@tauri-apps/api/window")["getCurrentWindow"]>- >,- LogicalSize: typeof import("@tauri-apps/api/window")["LogicalSize"],+async function enforceWindowSizeBounds(+ win: TauriWindow,+ LogicalSize: WindowModule["LogicalSize"],isCurrent: WindowLayoutGuard,- requestedSize: LogicalWindowSize = MINIMUM_APP_WINDOW_SIZE,+ bounds: WindowSizeBounds,+ requestedSize: LogicalWindowSize = bounds.minimum,): Promise<void> {- const [innerSize, scaleFactor] = await Promise.all([- win.innerSize(),- win.scaleFactor(),- ]);- if (!isCurrent()) return;-- const logicalWidth = Math.round(innerSize.width / scaleFactor);- const logicalHeight = Math.round(innerSize.height / scaleFactor);- // Linux reports innerSize from a cache updated by WebKitGTK configure events.- // That event can arrive after this check, leaving the old setup size in the- // cache even though the first app resize has completed.- const nextWidth = Math.max(- logicalWidth,- MIN_WINDOW_WIDTH,- requestedSize.width,- );- const nextHeight = Math.max(- logicalHeight,- MIN_WINDOW_HEIGHT,- requestedSize.height,+ const [innerSize, scaleFactor, isMaximized, isFullscreen] = await Promise.all(+ [win.innerSize(), win.scaleFactor(), win.isMaximized(), win.isFullscreen()],);- if (nextWidth !== logicalWidth || nextHeight !== logicalHeight) {- await win.setSize(new LogicalSize(nextWidth, nextHeight));+ if (!isCurrent()) return;+ // Let the window manager size maximized and fullscreen windows.+ if (isMaximized || isFullscreen) return;++ const currentSize = {+ width: Math.round(innerSize.width / scaleFactor),+ height: Math.round(innerSize.height / scaleFactor),+ };+ // Linux can briefly report the pre-resize size from its GTK cache.+ const nextSize = constrainWindowSize(currentSize, requestedSize, bounds);+ if (+ nextSize.width !== currentSize.width ||+ nextSize.height !== currentSize.height+ ) {+ await win.setSize(new LogicalSize(nextSize.width, nextSize.height));}}async function applyAppWindowLayout(isCurrent: WindowLayoutGuard,): Promise<void> {- const { getCurrentWindow, currentMonitor, LogicalSize } = await import(- "@tauri-apps/api/window"- );+ 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 = getCurrentWindow();+ const win = windowModule.getCurrentWindow();// Setup-window activity may create plugin state before the full app is ever// shown, so use a dedicated full-app marker to decide whether restoration is// appropriate. Keep checking plugin state so a missing/corrupt state file@@ -157,60 +264,71 @@ async function applyAppWindowLayout(await win.setResizable(true);if (!isCurrent()) return;+ const measured = await measureTauriWindowLayout(windowModule, win, isCurrent);+ if (!measured) return;let requestedSize: LogicalWindowSize | undefined;- if (hasInitializedAppLayout && hasSavedState) {- // Subsequent launch: plugin restores size/position/maximized, with built-in- // off-screen protection for positions saved on a now-disconnected display.- await restoreStateCurrent(- StateFlags.SIZE | StateFlags.POSITION | StateFlags.MAXIMIZED,- );- } else {- // First launch: fit to the current monitor and center.- const monitor = await currentMonitor();- if (!isCurrent()) return;- let finalW = MIN_WINDOW_WIDTH;- let finalH = MIN_WINDOW_HEIGHT;- if (monitor) {- const scale = monitor.scaleFactor;- const screenW = monitor.size.width / scale;- const screenH = monitor.size.height / scale;- finalW = Math.max(- MIN_WINDOW_WIDTH,- Math.round(screenW * 0.75),- // Windows text scaling shrinks CSS px, so the window would open under- // the sidebar's mobile breakpoint. No-op elsewhere; never exceed the- // screen.- Math.min(- Math.round(MIN_DESKTOP_LAYOUT_WIDTH * logicalPerCssPx(scale)),- Math.round(screenW),- ),+ let restored = false;+ let layoutObserver: WindowLayoutObserver | null = null;+ try {+ if (hasInitializedAppLayout && hasSavedState) {+ restored = true;+ // Subscribe before restoring so native events cannot race listener setup.+ layoutObserver = await observeWindowLayout(win, isCurrent);+ if (!layoutObserver) return;+ // Subsequent launch: plugin restores size/position/maximized, with built-in+ // off-screen protection for positions saved on a now-disconnected display.+ await restoreStateCurrent(+ StateFlags.SIZE | StateFlags.POSITION | StateFlags.MAXIMIZED,);- const targetH = Math.max(MIN_WINDOW_HEIGHT, Math.round(finalW / 1.618));- finalH = Math.min(targetH, Math.round(screenH * 0.85));+ if (!isCurrent()) return;+ } else {+ // First launch: fit to the current work area and center.+ const cssSafeLogicalWidth = measured.monitor+ ? Math.round(+ MIN_DESKTOP_LAYOUT_WIDTH *+ logicalPerCssPx(measured.monitor.scaleFactor),+ )+ : undefined;+ requestedSize = calculateFirstAppWindowSize(+ measured.bounds,+ cssSafeLogicalWidth,+ );+ await placeWindow(win, windowModule, measured, requestedSize, isCurrent);}- requestedSize = { width: finalW, height: finalH };- await win.setSize(new LogicalSize(finalW, finalH));- if (!isCurrent()) return;- await win.center();- }- if (!isCurrent()) return;- if (!(await wasLaunchedHidden())) {+ // Apply work-area constraints after restore to preserve the saved size.+ await finalizeAppWindowLayout({+ restored,+ measured,+ show: async () => {+ if (await wasLaunchedHidden()) return false;+ if (!isCurrent()) return false;+ await win.show();+ return true;+ },+ waitForSettled: layoutObserver?.waitForSettled,+ measure: () => measureTauriWindowLayout(windowModule, win, isCurrent),+ setMinimumConstraints: (minimum) =>+ win.setSizeConstraints({+ minWidth: minimum.width,+ minHeight: minimum.height,+ }),+ enforceBounds: (bounds) =>+ enforceWindowSizeBounds(+ win,+ windowModule.LogicalSize,+ isCurrent,+ bounds,+ requestedSize,+ ),+ isCurrent,+ });+if (!isCurrent()) return;- await win.show();+ await invoke("mark_app_window_layout_initialized");+ } finally {+ layoutObserver?.dispose();}- if (!isCurrent()) return;- // Apply constraints after restore/show: doing so before plugin restore can emit- // a Resized event and overwrite the plugin's cached saved size.- await win.setSizeConstraints({- minWidth: MIN_WINDOW_WIDTH,- minHeight: MIN_WINDOW_HEIGHT,- });- if (!isCurrent()) return;- await enforceMinimumWindowSize(win, LogicalSize, isCurrent, requestedSize);-- if (!isCurrent()) return;- await invoke("mark_app_window_layout_initialized");}async function showWindowFallback(): Promise<void> {@@ -407,6 +525,8 @@ function TauriWrapper({ children }: { children: ReactNode }) {const [desktopAuthReady, setDesktopAuthReady] = useState(!isTauri);const [desktopAuthRetry, setDesktopAuthRetry] = useState(0);const [nativeMacControlsHidden, setNativeMacControlsHidden] = useState(false);++ const [windowRevealRevision, setWindowRevealRevision] = useState(0);const usesCustomTitlebar = shouldUseCustomWindowTitlebar();const usesNativeMacTitlebar = shouldUseNativeMacWindowTitlebar();const hidesTitlebarSidebar = HIDDEN_TITLEBAR_SIDEBAR_ROUTES.has(pathname);@@ -419,6 +539,35 @@ function TauriWrapper({ children }: { children: ReactNode }) {};}, []);++ useEffect(() => {+ if (!isTauri) return;+ let disposed = false;+ let stopListening: (() => void) | undefined;++ 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);+ });+ if (disposed) unlisten();+ else stopListening = unlisten;+ });++ return () => {+ disposed = true;+ stopListening?.();+ };+ }, []);+// Keep the Tauri window hidden until setup or app layout is ready.useEffect(() => {if (!isTauri) return;@@ -449,7 +598,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {/* swallow; window may still be functional */}});- }, [status]);+ }, [status, windowRevealRevision]);useEffect(() => {if (!isTauri) {@@ -588,10 +737,10 @@ function TauriWrapper({ children }: { children: ReactNode }) {}style={nativeMacControlsHidden- ? {+ ? ({...MAC_NATIVE_CHROME_STYLE,"--studio-mac-traffic-light-inset": "6px",- } as CSSProperties+ } as CSSProperties): MAC_NATIVE_CHROME_STYLE}>diff --git a/studio/frontend/src/app/window-layout-lifecycle.ts b/studio/frontend/src/app/window-layout-lifecycle.tsnew file mode 100644index 00000000000..08f8da2c463--- /dev/null+++ b/studio/frontend/src/app/window-layout-lifecycle.ts@@ -0,0 +1,132 @@+// 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 {+ DEFAULT_APP_WINDOW_SIZE_BOUNDS,+ type LogicalWindowSize,+ type WindowSizeBounds,+ calculateWindowSizeBounds,+} from "./window-layout.ts";++export type WindowLayoutGuard = () => boolean;++type WorkAreaMonitor = {+ scaleFactor: number;+ workArea: {+ size: {+ toLogical: (scaleFactor: number) => LogicalWindowSize;+ };+ };+};++type PhysicalWindowSize = {+ width: number;+ height: number;+};++export type MeasuredWindowLayout<Monitor extends WorkAreaMonitor> = {+ bounds: WindowSizeBounds;+ monitor: Monitor | null;+ /** Physical pixels outside the webview's inner rectangle. */+ frameSize: PhysicalWindowSize;+};++type WindowMonitorReader<Monitor extends WorkAreaMonitor> = {+ currentMonitor: () => Promise<Monitor | null>;+ primaryMonitor: () => Promise<Monitor | null>;+ innerSize?: () => Promise<PhysicalWindowSize>;+ outerSize?: () => Promise<PhysicalWindowSize>;+};++/** Size bounds the window has to stay within on its current monitor. */+export async function measureWindowLayout<Monitor extends WorkAreaMonitor>(+ reader: WindowMonitorReader<Monitor>,+ isCurrent: WindowLayoutGuard,+): Promise<MeasuredWindowLayout<Monitor> | null> {+ // Some platforms cannot resolve the monitor for a hidden window.+ const monitor =+ (await reader.currentMonitor()) ?? (await reader.primaryMonitor());+ if (!isCurrent()) return null;++ const frameSize = { width: 0, height: 0 };+ let availableInnerSize: LogicalWindowSize | undefined;+ if (monitor) {+ availableInnerSize = monitor.workArea.size.toLogical(monitor.scaleFactor);+ if (reader.innerSize && reader.outerSize) {+ const [innerSize, outerSize] = await Promise.all([+ reader.innerSize(),+ reader.outerSize(),+ ]);+ if (!isCurrent()) return null;+ frameSize.width = Math.max(0, outerSize.width - innerSize.width);+ frameSize.height = Math.max(0, outerSize.height - innerSize.height);+ // Tauri sizes the inner rectangle but positions the outer rectangle.+ availableInnerSize = {+ width: Math.max(+ 1,+ availableInnerSize.width - frameSize.width / monitor.scaleFactor,+ ),+ height: Math.max(+ 1,+ availableInnerSize.height - frameSize.height / monitor.scaleFactor,+ ),+ };+ }+ }++ const bounds = availableInnerSize+ ? calculateWindowSizeBounds(availableInnerSize)+ : DEFAULT_APP_WINDOW_SIZE_BOUNDS;+ return { bounds, monitor, frameSize };+}++export function shouldFinishWindowLayoutWait(+ sawPostShowChange: boolean,+): boolean {+ return sawPostShowChange;+}+type FinalizeAppWindowLayoutOptions<Monitor extends WorkAreaMonitor> = {+ restored: boolean;+ measured: MeasuredWindowLayout<Monitor>;+ show: () => Promise<boolean>;+ waitForSettled?: () => Promise<void>;+ measure: () => Promise<MeasuredWindowLayout<Monitor> | null>;+ setMinimumConstraints: (minimum: LogicalWindowSize) => Promise<void>;+ enforceBounds: (bounds: WindowSizeBounds) => Promise<void>;+ isCurrent: WindowLayoutGuard;+};++/** Shows the app window, then applies bounds from the visible monitor. */+export async function finalizeAppWindowLayout<Monitor extends WorkAreaMonitor>({+ restored,+ measured,+ show,+ waitForSettled,+ measure,+ setMinimumConstraints,+ enforceBounds,+ isCurrent,+}: FinalizeAppWindowLayoutOptions<Monitor>): Promise<void> {+ if (!isCurrent()) return;+ const shown = await show();+ if (!isCurrent()) return;+ // A restored hidden autostart cannot reliably resolve its saved monitor yet.+ // Keep the plugin-restored geometry untouched until native tray reveal.+ if (restored && !shown) return;++ // Native restore calls complete before GTK/Cocoa move and resize events have+ // necessarily updated Tauri's cached geometry.+ if (restored) {+ await waitForSettled?.();+ if (!isCurrent()) return;+ measured = (await measure()) ?? measured;+ if (!isCurrent()) return;+ }++ await setMinimumConstraints(measured.bounds.minimum);+ if (!isCurrent()) return;+ // Do not cap restored sizes against a temporary monitor fallback.+ await enforceBounds(+ restored ? { minimum: measured.bounds.minimum } : measured.bounds,+ );+}diff --git a/studio/frontend/src/app/window-layout.ts b/studio/frontend/src/app/window-layout.tsnew file mode 100644index 00000000000..6a04f163bea--- /dev/null+++ b/studio/frontend/src/app/window-layout.ts@@ -0,0 +1,127 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export type LogicalWindowSize = {+ width: number;+ height: number;+};++export type PhysicalWindowRect = {+ position: { x: number; y: number };+ size: { width: number; height: number };+};++export type WindowSizeBounds = {+ minimum: LogicalWindowSize;+ maximum?: LogicalWindowSize;+};++export const MINIMUM_APP_WINDOW_SIZE: LogicalWindowSize = {+ width: 900,+ height: 600,+};++export const PREFERRED_SETUP_WINDOW_SIZE: LogicalWindowSize = {+ width: 760,+ height: 560,+};++// Preserve the nominal fallback when no monitor can be read.+export const DEFAULT_APP_WINDOW_SIZE_BOUNDS: WindowSizeBounds = {+ minimum: MINIMUM_APP_WINDOW_SIZE,+};++// Leave resize room when the nominal minimum does not fit.+const RELAXED_MINIMUM_RATIO = 0.85;+const FIRST_WINDOW_WIDTH_RATIO = 0.75;+const FIRST_WINDOW_HEIGHT_RATIO = 0.85;+const FIRST_WINDOW_ASPECT_RATIO = 1.618;++function relaxMinimum(preferred: number, maximum: number): number {+ if (preferred <= maximum) return preferred;+ return Math.max(1, Math.floor(maximum * RELAXED_MINIMUM_RATIO));+}++/** Bounds a frameless window to the monitor work area. */+export function calculateWindowSizeBounds(+ workAreaSize: LogicalWindowSize,+): WindowSizeBounds {+ const maximum = {+ width: Math.max(1, Math.floor(workAreaSize.width)),+ height: Math.max(1, Math.floor(workAreaSize.height)),+ };+ return {+ minimum: {+ width: relaxMinimum(MINIMUM_APP_WINDOW_SIZE.width, maximum.width),+ height: relaxMinimum(MINIMUM_APP_WINDOW_SIZE.height, maximum.height),+ },+ maximum,+ };+}++export function fitWindowSize(+ size: LogicalWindowSize,+ maximum?: LogicalWindowSize,+): LogicalWindowSize {+ if (!maximum) return size;+ return {+ width: Math.min(size.width, maximum.width),+ height: Math.min(size.height, maximum.height),+ };+}++export function calculateFirstAppWindowSize(+ { minimum, maximum }: WindowSizeBounds,+ cssSafeLogicalWidth?: number,+): LogicalWindowSize {+ if (!maximum) return minimum;++ const width = Math.max(+ minimum.width,+ Math.round(maximum.width * FIRST_WINDOW_WIDTH_RATIO),+ Math.min(cssSafeLogicalWidth ?? 0, maximum.width),+ );+ // Preserve requested height when the work area is short.+ const heightCap = Math.max(+ MINIMUM_APP_WINDOW_SIZE.height,+ Math.round(maximum.height * FIRST_WINDOW_HEIGHT_RATIO),+ );+ const height = Math.max(+ minimum.height,+ Math.min(Math.round(width / FIRST_WINDOW_ASPECT_RATIO), heightCap),+ );+ return fitWindowSize({ width, height }, maximum);+}++export function constrainWindowSize(+ currentSize: LogicalWindowSize,+ requestedSize: LogicalWindowSize,+ { minimum, maximum }: WindowSizeBounds,+): LogicalWindowSize {+ return fitWindowSize(+ {+ width: Math.max(currentSize.width, minimum.width, requestedSize.width),+ height: Math.max(+ currentSize.height,+ minimum.height,+ requestedSize.height,+ ),+ },+ maximum,+ );+}++/** Centers a physical window size inside the work area. */+export function calculateCenteredPosition(+ workArea: PhysicalWindowRect,+ windowSize: { width: number; height: number },+): { x: number; y: number } {+ return {+ x:+ workArea.position.x ++ Math.max(0, Math.floor((workArea.size.width - windowSize.width) / 2)),+ y:+ workArea.position.y ++ Math.max(0, Math.floor((workArea.size.height - windowSize.height) / 2)),+ };+}diff --git a/studio/frontend/tests/window-layout.test.ts b/studio/frontend/tests/window-layout.test.tsnew file mode 100644index 00000000000..3433e83e0ed--- /dev/null+++ b/studio/frontend/tests/window-layout.test.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 assert from "node:assert/strict";+import test from "node:test";++import {+ DEFAULT_APP_WINDOW_SIZE_BOUNDS,+ PREFERRED_SETUP_WINDOW_SIZE,+ calculateCenteredPosition,+ calculateFirstAppWindowSize,+ calculateWindowSizeBounds,+ constrainWindowSize,+ fitWindowSize,+} from "../src/app/window-layout.ts";+import {+ finalizeAppWindowLayout,+ shouldFinishWindowLayoutWait,+ measureWindowLayout,+} from "../src/app/window-layout-lifecycle.ts";++// A work area is the panel minus the taskbar, in logical pixels.+function workArea(+ width: number,+ height: number,+ taskbar: number,+ scaleFactor: number,+) {+ return {+ width: width / scaleFactor,+ height: (height - taskbar) / scaleFactor,+ };+}++test("waits for the first native restore event before settling", () => {+ assert.equal(shouldFinishWindowLayoutWait(false), false);+ assert.equal(shouldFinishWindowLayoutWait(true), true);+});+test("keeps the nominal minimum and preferred size on a roomy work area", () => {+ const bounds = calculateWindowSizeBounds({ width: 1920, height: 1040 });++ assert.deepEqual(bounds.minimum, { width: 900, height: 600 });+ assert.deepEqual(calculateFirstAppWindowSize(bounds), {+ width: 1440,+ height: 884,+ });+});++test("fits a 1366x768 panel at 125% scaling above the taskbar", () => {+ const bounds = calculateWindowSizeBounds(workArea(1366, 768, 40, 1.25));++ assert.deepEqual(bounds.maximum, { width: 1092, height: 582 });+ const size = calculateFirstAppWindowSize(bounds);+ assert.deepEqual(size, { width: 900, height: 556 });+ // The window clears the taskbar.+ assert.ok(size.height <= (768 - 40) / 1.25);+});++test("fits a 1080p panel at 175% scaling above the taskbar", () => {+ const bounds = calculateWindowSizeBounds(workArea(1920, 1080, 48, 1.75));++ assert.deepEqual(bounds.maximum, { width: 1097, height: 589 });+ const size = calculateFirstAppWindowSize(bounds);+ assert.deepEqual(size, { width: 900, height: 556 });+ assert.ok(size.height <= (1080 - 48) / 1.75);+});++test("fits a 1600x900 panel at 150% scaling above the taskbar", () => {+ const bounds = calculateWindowSizeBounds(workArea(1600, 900, 40, 1.5));++ assert.deepEqual(bounds.maximum, { width: 1066, height: 573 });+ const size = calculateFirstAppWindowSize(bounds);+ assert.deepEqual(size, { width: 900, height: 556 });+ assert.ok(size.height <= (900 - 40) / 1.5);+});++test("preserves the desktop CSS width floor under Windows text scaling", () => {+ const bounds = calculateWindowSizeBounds(workArea(2880, 1800, 0, 2.5));+ const cssSafeLogicalWidth = 768 * 1.25;++ assert.deepEqual(calculateFirstAppWindowSize(bounds, cssSafeLogicalWidth), {+ width: 960,+ height: 600,+ });+ assert.equal(960 / 1.25, 768);++ const compactBounds = calculateWindowSizeBounds({ width: 920, height: 550 });+ assert.deepEqual(+ calculateFirstAppWindowSize(compactBounds, cssSafeLogicalWidth),+ { width: 920, height: 550 },+ );+});++test("relaxes a minimum that does not fit, keeping room to resize", () => {+ for (const [panel, scaleFactor] of [+ [768, 1.25],+ [768, 1.5],+ [1080, 1.75],+ [900, 1.5],+ ] as const) {+ const { minimum, maximum } = calculateWindowSizeBounds(+ workArea(1366, panel, 40, scaleFactor),+ );+ assert.ok(maximum);+ assert.ok(+ minimum.height <= maximum.height,+ `minimum ${minimum.height} exceeds work area ${maximum.height}`,+ );+ // Keep a vertical resize range.+ assert.ok(+ minimum.height < maximum.height,+ `minimum ${minimum.height} leaves no vertical resize range`,+ );+ }+});++test("fits the non-resizable setup window to the available area", () => {+ const bounds = calculateWindowSizeBounds(workArea(1366, 768, 40, 1.5));++ assert.deepEqual(fitWindowSize(PREFERRED_SETUP_WINDOW_SIZE, bounds.maximum), {+ width: 760,+ height: 485,+ });+ // Roomy panels retain the preferred size.+ assert.deepEqual(+ fitWindowSize(+ PREFERRED_SETUP_WINDOW_SIZE,+ calculateWindowSizeBounds({ width: 1920, height: 1040 }).maximum,+ ),+ PREFERRED_SETUP_WINDOW_SIZE,+ );+});++test("reserves the outer window frame inside the work area", async () => {+ const monitor = {+ scaleFactor: 1,+ workArea: {+ position: { x: 0, y: 0 },+ size: {+ width: 700,+ height: 500,+ toLogical: () => ({ width: 700, height: 500 }),+ },+ },+ };+ const measured = await measureWindowLayout(+ {+ currentMonitor: async () => monitor,+ primaryMonitor: async () => monitor,+ innerSize: async () => ({ width: 760, height: 560 }),+ outerSize: async () => ({ width: 776, height: 577 }),+ },+ () => true,+ );++ assert.ok(measured);+ assert.deepEqual(measured.frameSize, { width: 16, height: 17 });+ assert.deepEqual(measured.bounds.maximum, { width: 684, height: 483 });+ const setupSize = fitWindowSize(+ PREFERRED_SETUP_WINDOW_SIZE,+ measured.bounds.maximum,+ );+ assert.deepEqual(setupSize, { width: 684, height: 483 });+ assert.deepEqual(+ calculateCenteredPosition(monitor.workArea, {+ width: setupSize.width + measured.frameSize.width,+ height: setupSize.height + measured.frameSize.height,+ }),+ { x: 0, y: 0 },+ );+});++test("caps an oversized window to a compact work area", () => {+ const bounds = calculateWindowSizeBounds({ width: 1080, height: 550 });++ assert.deepEqual(+ constrainWindowSize({ width: 1400, height: 900 }, bounds.minimum, bounds),+ { width: 1080, height: 550 },+ );+});++test("grows past a stale setup size without exceeding the work area", () => {+ const bounds = calculateWindowSizeBounds(workArea(1366, 768, 40, 1.25));+ const requested = calculateFirstAppWindowSize(bounds);++ assert.deepEqual(+ constrainWindowSize({ width: 760, height: 560 }, requested, bounds),+ { width: 900, height: 560 },+ );+});++test("centers against the work area of the monitor it is on", () => {+ const secondary = {+ position: { x: 1920, y: 40 },+ size: { width: 1366, height: 728 },+ };++ assert.deepEqual(+ calculateCenteredPosition(secondary, { width: 1125, height: 728 }),+ { x: 2040, y: 40 },+ );+ // Oversized windows pin to the work-area origin.+ assert.deepEqual(+ calculateCenteredPosition(secondary, { width: 1500, height: 800 }),+ { x: 1920, y: 40 },+ );+});++test("falls back to the nominal size when no monitor can be read", () => {+ assert.deepEqual(+ calculateFirstAppWindowSize(DEFAULT_APP_WINDOW_SIZE_BOUNDS),+ {+ width: 900,+ height: 600,+ },+ );+ assert.deepEqual(+ fitWindowSize(PREFERRED_SETUP_WINDOW_SIZE, undefined),+ PREFERRED_SETUP_WINDOW_SIZE,+ );+});++test("remeasures a restored window after show on its compact secondary", async () => {+ const events: string[] = [];+ let visible = false;+ let savedSize = { width: 900, height: 556 };+ const monitor = (+ name: string,+ width: number,+ height: number,+ scale: number,+ ) => ({+ name,+ scaleFactor: scale,+ workArea: {+ size: {+ toLogical: () => ({ width: width / scale, height: height / scale }),+ },+ },+ });+ const primary = monitor("roomy primary", 1920, 1040, 1);+ const secondary = monitor("compact secondary", 1366, 728, 1.25);+ const currentMonitor = async () => {+ events.push(`current:${visible ? "visible" : "hidden"}`);+ return visible ? secondary : null;+ };+ const primaryMonitor = async () => {+ events.push("primary");+ return primary;+ };+ const measure = () =>+ measureWindowLayout({ currentMonitor, primaryMonitor }, () => true);++ let measured = await measure();+ assert.ok(measured);+ events.push("restore");+ measured = (await measure()) ?? measured;++ let constrainedMinimum: { width: number; height: number } | undefined;+ let enforcementBounds: Parameters<typeof constrainWindowSize>[2] | undefined;+ await finalizeAppWindowLayout({+ restored: true,+ measured,+ show: async () => {+ events.push("show");+ visible = true;+ return true;+ },+ measure,+ setMinimumConstraints: async (minimum) => {+ events.push("constraints");+ constrainedMinimum = minimum;+ },+ enforceBounds: async (bounds) => {+ events.push("enforce");+ enforcementBounds = bounds;+ savedSize = constrainWindowSize(savedSize, bounds.minimum, bounds);+ },+ isCurrent: () => true,+ });++ assert.deepEqual(events, [+ "current:hidden",+ "primary",+ "restore",+ "current:hidden",+ "primary",+ "show",+ "current:visible",+ "constraints",+ "enforce",+ ]);+ assert.deepEqual(constrainedMinimum, { width: 900, height: 494 });+ assert.deepEqual(enforcementBounds, {+ minimum: { width: 900, height: 494 },+ });+ assert.deepEqual(savedSize, { width: 900, height: 556 });+});++test("waits for restored geometry before enforcing its minimum", async () => {+ const events: string[] = [];+ let currentSize = { width: 760, height: 560 };+ const measured = {+ bounds: {+ minimum: { width: 900, height: 600 },+ maximum: { width: 1920, height: 1040 },+ },+ monitor: null,+ frameSize: { width: 0, height: 0 },+ };++ await finalizeAppWindowLayout({+ restored: true,+ measured,+ show: async () => {+ events.push("show");+ return true;+ },+ waitForSettled: async () => {+ events.push("settled");+ currentSize = { width: 1200, height: 800 };+ },+ measure: async () => {+ events.push("measure");+ return measured;+ },+ setMinimumConstraints: async () => {+ events.push("constraints");+ },+ enforceBounds: async (bounds) => {+ events.push("enforce");+ currentSize = constrainWindowSize(currentSize, bounds.minimum, bounds);+ },+ isCurrent: () => true,+ });++ assert.deepEqual(events, [+ "show",+ "settled",+ "measure",+ "constraints",+ "enforce",+ ]);+ assert.deepEqual(currentSize, { width: 1200, height: 800 });+});++test("preserves restored geometry while an autostart window stays hidden", async () => {+ const events: string[] = [];+ const measured = {+ bounds: {+ minimum: { width: 900, height: 600 },+ maximum: { width: 1920, height: 1040 },+ },+ monitor: null,+ frameSize: { width: 0, height: 0 },+ };++ await finalizeAppWindowLayout({+ restored: true,+ measured,+ show: async () => {+ events.push("show");+ return false;+ },+ waitForSettled: async () => {+ events.push("settled");+ },+ measure: async () => {+ events.push("measure");+ return measured;+ },+ setMinimumConstraints: async () => {+ events.push("constraints");+ },+ enforceBounds: async () => {+ events.push("enforce");+ },+ isCurrent: () => true,+ });++ assert.deepEqual(events, ["show"]);+});+test("stale layouts do not show the window", async () => {+ let shown = false;++ await finalizeAppWindowLayout({+ restored: false,+ measured: {+ bounds: {+ minimum: { width: 900, height: 600 },+ },+ monitor: null,+ frameSize: { width: 0, height: 0 },+ },+ show: async () => {+ shown = true;+ return true;+ },+ measure: async () => {+ throw new Error("stale layouts must not remeasure");+ },+ setMinimumConstraints: async () => {+ throw new Error("stale layouts must not set constraints");+ },+ enforceBounds: async () => {+ throw new Error("stale layouts must not enforce bounds");+ },+ isCurrent: () => false,+ });++ assert.equal(shown, false);+});diff --git a/studio/src-tauri/capabilities/default.json b/studio/src-tauri/capabilities/default.jsonindex 4dd306cb15b..300cf0690a9 100644--- a/studio/src-tauri/capabilities/default.json+++ b/studio/src-tauri/capabilities/default.json@@ -8,11 +8,13 @@"core:window:allow-show","core:window:allow-hide","core:window:allow-set-focus",+ "core:window:allow-set-position","core:window:allow-set-size","core:window:allow-set-resizable","core:window:allow-set-size-constraints","core:window:allow-center","core:window:allow-current-monitor",+ "core:window:allow-primary-monitor","core:window:allow-start-dragging","core:window:allow-start-resize-dragging","core:window:allow-minimize",diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.pyindex 26768536e78..07c3691703c 100644--- a/tests/studio/test_desktop_reliability_frontend_contract.py+++ b/tests/studio/test_desktop_reliability_frontend_contract.py@@ -368,28 +368,40 @@ def test_full_app_layout_uses_its_own_initialized_marker():assert 'invoke<boolean>("has_initialized_app_window_layout")' in sourcesetup_layout = source.split("async function showSetupWindow", 1)[1].split(- "async function enforceMinimumWindowSize", 1+ "async function enforceWindowSizeBounds", 1)[0]reset_call = 'invoke("reset_app_window_layout_initialized")'assert reset_call in setup_layout- assert setup_layout.index(reset_call) < setup_layout.index("win.setSize")+ assert setup_layout.index(reset_call) < setup_layout.index("placeWindow(")assert 'invoke("mark_app_window_layout_initialized")' in sourceassert "hasInitializedAppLayout && hasSavedState" in sourcedef test_first_app_layout_survives_a_stale_setup_window_size():source = APP_PROVIDER.read_text(encoding = "utf-8")- minimum_helper = source.split("async function enforceMinimumWindowSize", 1)[1].split(+ bounds_helper = source.split("async function enforceWindowSizeBounds", 1)[1].split("async function applyAppWindowLayout", 1)[0]app_layout = source.split("async function applyAppWindowLayout", 1)[1].split("async function showWindowFallback", 1)[0]- assert "requestedSize.width" in minimum_helper- assert "requestedSize.height" in minimum_helper- assert "requestedSize = { width: finalW, height: finalH };" in app_layout- assert "enforceMinimumWindowSize(win, LogicalSize, isCurrent, requestedSize)" in app_layout+ assert "requestedSize: LogicalWindowSize = bounds.minimum" in bounds_helper+ assert "constrainWindowSize(currentSize, requestedSize, bounds)" in bounds_helper+ assert "const cssSafeLogicalWidth = measured.monitor" in app_layout+ first_size_call = app_layout.split("requestedSize = calculateFirstAppWindowSize(", 1)[1].split(+ ");", 1+ )[0]+ assert "measured.bounds," in first_size_call+ assert "cssSafeLogicalWidth," in first_size_call+ assert "finalizeAppWindowLayout({" in app_layout+ assert "enforceWindowSizeBounds(" in app_layout+ finalize_call = app_layout.split("finalizeAppWindowLayout({", 1)[1].split("});", 1)[0]+ assert "measured," in finalize_call+ # Limit the check to this call's arguments.+ bounds_call = app_layout.split("enforceWindowSizeBounds(", 1)[1].split(");", 1)[0]+ assert "bounds," in bounds_call+ assert "requestedSize," in bounds_calldef test_expanded_titlebar_button_and_corner_match_sidebar_edge():