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.

desktop: add interface scaling setting (#9666)

Maheswar Kumar8bc55304a2e3
diff --git a/studio/frontend/smoke-composer-icons.html b/studio/frontend/smoke-composer-icons.html
index 407b3b0b987..3ee8d6f3f6a 100644
--- a/studio/frontend/smoke-composer-icons.html
+++ b/studio/frontend/smoke-composer-icons.html
@@ -7,6 +7,7 @@
</head>
<body>
<div id="root"></div>
+ <script src="/crypto-boot.js"></script>
<script type="module" src="/smoke-composer-icons-main.tsx"></script>
</body>
</html>
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsx
index a8add8a0beb..36a86a2c1c5 100644
--- a/studio/frontend/src/app/provider.tsx
+++ b/studio/frontend/src/app/provider.tsx
@@ -27,8 +27,14 @@ import {
import { LoadedModelsIndicator } from "@/features/loaded-models";
import { NativeIntentDrain } from "@/features/native-intents/native-intent-drain";
import {
+ NATIVE_MAC_TITLEBAR_HEIGHT_VAR,
+ NATIVE_MAC_TRAFFIC_LIGHT_INSET_VAR,
applyCustomizationToDocument,
+ applyInterfaceScale,
+ getAppliedInterfaceZoom,
+ subscribeAppliedInterfaceZoom,
useAppearanceCustomStore,
+ useInterfaceScaleStore,
useTheme,
} from "@/features/settings";
import { SttDownloadPrompt } from "@/features/settings/components/stt-download-prompt";
@@ -86,11 +92,12 @@ const MIN_DESKTOP_LAYOUT_WIDTH = 768;
const STACK_SHADOW_GUTTER_BOTTOM = 16;
const STACK_SHADOW_GUTTER_TOP = 8;
-// Logical px per CSS px: webview zoom above the display scale; 1 if none.
+// macos page zoom does not change dpr; windows already includes zoom in its dpr.
function logicalPerCssPx(monitorScale: number): number {
- if (typeof window === "undefined" || !(monitorScale > 0)) return 1;
+ const zoom = Math.max(1, getAppliedInterfaceZoom());
+ if (typeof window === "undefined" || !(monitorScale > 0)) return zoom;
const ratio = window.devicePixelRatio / monitorScale;
- return Number.isFinite(ratio) && ratio > 1 ? ratio : 1;
+ return Math.max(zoom, Number.isFinite(ratio) ? ratio : 1);
}
// Autostart passes --hidden: layout still applies, but the window stays in the tray.
@@ -490,16 +497,16 @@ const WEB_UPDATE_HIDDEN_ROUTES = new Set([
const MAC_NATIVE_CHROME_STYLE = {
"--studio-titlebar-height": "0px",
- "--studio-mac-titlebar-height": "34px",
- "--studio-desktop-titlebar-height": "34px",
+ "--studio-mac-titlebar-height": NATIVE_MAC_TITLEBAR_HEIGHT_VAR,
+ "--studio-desktop-titlebar-height": NATIVE_MAC_TITLEBAR_HEIGHT_VAR,
"--studio-titlebar-navigation-margin-top": "4px",
"--studio-titlebar-navigation-offset-y": "4px",
- "--studio-mac-traffic-light-inset": "78px",
- "--studio-collapsed-chat-controls-inset": "188px",
- "--studio-startup-top-inset": "58px",
+ "--studio-mac-traffic-light-inset": NATIVE_MAC_TRAFFIC_LIGHT_INSET_VAR,
+ "--studio-collapsed-chat-controls-inset": `calc(110px + ${NATIVE_MAC_TRAFFIC_LIGHT_INSET_VAR})`,
+ "--studio-startup-top-inset": `calc(24px + ${NATIVE_MAC_TITLEBAR_HEIGHT_VAR})`,
"--studio-content-top-inset": "0px",
- "--studio-non-chat-content-top-inset": "34px",
- "--studio-hidden-route-top-inset": "34px",
+ "--studio-non-chat-content-top-inset": NATIVE_MAC_TITLEBAR_HEIGHT_VAR,
+ "--studio-hidden-route-top-inset": NATIVE_MAC_TITLEBAR_HEIGHT_VAR,
"--studio-chat-header-height": "44px",
"--studio-chat-header-padding-top": "9px",
"--studio-media-header-left-inset": "0.5rem",
@@ -540,12 +547,19 @@ function DesktopChromeVarsEffect({
? el.style.removeProperty(name)
: el.style.setProperty(name, value);
set("--studio-custom-titlebar-height", usesCustomTitlebar ? "34px" : null);
- set("--studio-mac-titlebar-height", usesNativeMacTitlebar ? "34px" : null);
+ set(
+ "--studio-mac-titlebar-height",
+ usesNativeMacTitlebar ? NATIVE_MAC_TITLEBAR_HEIGHT_VAR : null,
+ );
set("--studio-window-control-inset", usesCustomTitlebar ? "112px" : null);
// How far body-portaled surfaces must stay clear of the top: either titlebar paints over them.
set(
"--studio-window-chrome-top",
- usesCustomTitlebar || usesNativeMacTitlebar ? "34px" : null,
+ usesCustomTitlebar
+ ? "34px"
+ : usesNativeMacTitlebar
+ ? NATIVE_MAC_TITLEBAR_HEIGHT_VAR
+ : null,
);
return () => {
set("--studio-custom-titlebar-height", null);
@@ -695,7 +709,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {
if (!ratioSource) return;
let disposed = false;
- const stop = observeDevicePixelRatio(ratioSource, () => {
+ const refresh = () => {
// The setup window has no constraints to keep current.
if (disposed || appliedWindowModeRef.current !== "app") return;
// Read on the change, not on mount: a layout pass that starts after this
@@ -706,10 +720,13 @@ function TauriWrapper({ children }: { children: ReactNode }) {
).catch(() => {
/* swallow; the floor in force stands */
});
- });
+ };
+ const stop = observeDevicePixelRatio(ratioSource, refresh);
+ const stopZoom = subscribeAppliedInterfaceZoom(refresh);
return () => {
disposed = true;
stop();
+ stopZoom();
};
}, []);
@@ -932,6 +949,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {
function AppearanceCustomizationEffect() {
const { theme, resolved } = useTheme();
const customization = useAppearanceCustomStore((s) => s.customization);
+ const interfaceScale = useInterfaceScaleStore((s) => s.scale);
useEffect(() => {
applyCustomizationToDocument(customization, resolved);
}, [customization, resolved]);
@@ -943,6 +961,9 @@ function AppearanceCustomizationEffect() {
)
.catch(() => undefined);
}, [theme]);
+ useEffect(() => {
+ void applyInterfaceScale(interfaceScale).catch(() => undefined);
+ }, [interfaceScale]);
return null;
}
diff --git a/studio/frontend/src/components/navbar.tsx b/studio/frontend/src/components/navbar.tsx
index 706fb8c06dd..253244ae4fa 100644
--- a/studio/frontend/src/components/navbar.tsx
+++ b/studio/frontend/src/components/navbar.tsx
@@ -56,7 +56,9 @@ export function Navbar() {
"flex h-full",
usesCustomTitlebar
? "items-center pl-3"
- : "items-start pt-[11px] pl-2",
+ : usesNativeMacTitlebar
+ ? "items-start pt-[11px] pl-[calc(var(--studio-mac-traffic-light-inset,78px)+6px)]"
+ : "items-start pt-[11px] pl-2",
)}
>
<SidebarTrigger className="pointer-events-auto !size-[34px]" />
diff --git a/studio/frontend/src/features/native-intents/native-drop-position.ts b/studio/frontend/src/features/native-intents/native-drop-position.ts
index 14999367f91..0d93de7d178 100644
--- a/studio/frontend/src/features/native-intents/native-drop-position.ts
+++ b/studio/frontend/src/features/native-intents/native-drop-position.ts
@@ -1,9 +1,12 @@
// 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 { getAppliedInterfaceZoom } from "../settings/lib/interface-scale-runtime.ts";
+
// Tauri types every drop position as physical, but wry only produces one on
// WebView2 (ScreenToClient device pixels). macOS reports NSView points and GTK
-// reports widget coordinates, both of which are already CSS pixels.
+// reports widget coordinates, and neither of those moves with page zoom, so they
+// are CSS pixels only at 100%.
function isPhysicalDropPosition(): boolean {
return (
typeof navigator !== "undefined" && navigator.userAgent.includes("Windows")
@@ -21,12 +24,25 @@ function physicalPerCssPx(windowScaleFactor: number): number {
: 1;
}
-/** A drop position in the CSS pixels the DOM is measured in. */
+/**
+ * A drop position in the CSS pixels the DOM is measured in.
+ *
+ * The two branches read zoom from different places and that asymmetry is forced, not an
+ * oversight. **Do not collapse them onto `devicePixelRatio`.** Page zoom is not readable
+ * from JS, so macOS and GTK have only the value we last handed the webview; and on macOS
+ * `devicePixelRatio` carries a backing-scale factor that NSView points do not have, so
+ * using it there would divide by the Retina factor twice.
+ */
export function nativeDropPointToCss(
position: { x: number; y: number },
windowScaleFactor: number,
+ webviewZoom = getAppliedInterfaceZoom(),
): { x: number; y: number } {
- if (!isPhysicalDropPosition()) return position;
+ if (!isPhysicalDropPosition()) {
+ const scale =
+ Number.isFinite(webviewZoom) && webviewZoom > 0 ? webviewZoom : 1;
+ return { x: position.x / scale, y: position.y / scale };
+ }
const scale = physicalPerCssPx(windowScaleFactor);
return { x: position.x / scale, y: position.y / scale };
}
diff --git a/studio/frontend/src/features/settings/components/appearance-custom-controls.tsx b/studio/frontend/src/features/settings/components/appearance-custom-controls.tsx
index 0e77ab9280a..bb41b9b9a24 100644
--- a/studio/frontend/src/features/settings/components/appearance-custom-controls.tsx
+++ b/studio/frontend/src/features/settings/components/appearance-custom-controls.tsx
@@ -46,6 +46,10 @@ import {
isDefaultCustomization,
useAppearanceCustomStore,
} from "../stores/appearance-custom-store";
+import {
+ INTERFACE_SCALE_RANGE,
+ useInterfaceScaleStore,
+} from "../stores/interface-scale-store";
import {
type Palette,
type ResolvedTheme,
@@ -53,6 +57,7 @@ import {
useTheme,
} from "../stores/theme-store";
import { ColorPickerSwatch } from "./color-picker";
+import { normalizeSizeInputDraft } from "./size-input-value";
/* ------------------------------- Colors -------------------------------- */
@@ -761,33 +766,31 @@ function useFontImport(onImported: (name: string) => void) {
return { inputs, requestUpload, requestFolder, importFile };
}
-function FontSizeInput({
+function SizeInput({
value,
range,
onCommit,
ariaLabel,
+ unit,
}: {
value: number | null;
range: { min: number; max: number; default: number };
onCommit: (next: number | null) => void;
ariaLabel: string;
+ unit: string;
}) {
const [draft, setDraft] = useState(value === null ? "" : String(value));
useEffect(() => {
setDraft(value === null ? "" : String(value));
}, [value]);
const commit = () => {
- const trimmed = draft.trim();
- if (trimmed === "") {
- onCommit(null);
- return;
- }
- const parsed = Number.parseInt(trimmed, 10);
- if (Number.isNaN(parsed)) {
+ const normalized = normalizeSizeInputDraft(draft, range);
+ if (!normalized) {
setDraft(value === null ? "" : String(value));
return;
}
- onCommit(Math.min(range.max, Math.max(range.min, parsed)));
+ setDraft(normalized.draft);
+ onCommit(normalized.value);
};
return (
<div className="flex items-center gap-1.5">
@@ -809,11 +812,26 @@ function FontSizeInput({
aria-label={ariaLabel}
className="h-8 w-20 text-xs"
/>
- <span className="text-xs text-muted-foreground">px</span>
+ <span className="text-xs text-muted-foreground">{unit}</span>
</div>
);
}
+export function InterfaceScaleRow() {
+ const t = useT();
+ const interfaceScale = useInterfaceScaleStore((s) => s.scale);
+ const setScale = useInterfaceScaleStore((s) => s.setScale);
+ return (
+ <SizeInput
+ value={interfaceScale}
+ range={INTERFACE_SCALE_RANGE}
+ onCommit={(next) => setScale(next ?? INTERFACE_SCALE_RANGE.default)}
+ ariaLabel={t("settings.appearance.custom.interfaceScale.label")}
+ unit="%"
+ />
+ );
+}
+
export function UiFontSizeRow() {
const t = useT();
const uiFontSize = useAppearanceCustomStore(
@@ -821,11 +839,12 @@ export function UiFontSizeRow() {
);
const patch = useAppearanceCustomStore((s) => s.patch);
return (
- <FontSizeInput
+ <SizeInput
value={uiFontSize}
range={UI_FONT_SIZE_RANGE}
onCommit={(next) => patch({ uiFontSize: next })}
ariaLabel={t("settings.appearance.custom.uiFontSize.label")}
+ unit="px"
/>
);
}
@@ -837,11 +856,12 @@ export function CodeFontSizeRow() {
);
const patch = useAppearanceCustomStore((s) => s.patch);
return (
- <FontSizeInput
+ <SizeInput
value={codeFontSize}
range={CODE_FONT_SIZE_RANGE}
onCommit={(next) => patch({ codeFontSize: next })}
ariaLabel={t("settings.appearance.custom.codeFontSize.label")}
+ unit="px"
/>
);
}
@@ -956,14 +976,21 @@ export function ResetCustomizationButton() {
const t = useT();
const customization = useAppearanceCustomStore((s) => s.customization);
const resetAll = useAppearanceCustomStore((s) => s.resetAll);
- const pristine = isDefaultCustomization(customization);
+ const interfaceScale = useInterfaceScaleStore((s) => s.scale);
+ const resetInterfaceScale = useInterfaceScaleStore((s) => s.reset);
+ const pristine =
+ isDefaultCustomization(customization) &&
+ interfaceScale === INTERFACE_SCALE_RANGE.default;
return (
<Button
type="button"
variant="outline"
size="sm"
disabled={pristine}
- onClick={resetAll}
+ onClick={() => {
+ resetAll();
+ resetInterfaceScale();
+ }}
>
{t("settings.appearance.custom.resetAll")}
</Button>
diff --git a/studio/frontend/src/features/settings/components/size-input-value.ts b/studio/frontend/src/features/settings/components/size-input-value.ts
new file mode 100644
index 00000000000..df6bcfdebfd
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/size-input-value.ts
@@ -0,0 +1,18 @@
+// 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 function normalizeSizeInputDraft(
+ draft: string,
+ range: { min: number; max: number },
+): { draft: string; value: number | null } | null {
+ const trimmed = draft.trim();
+ if (trimmed === "") {
+ return { draft: "", value: null };
+ }
+ const parsed = Number(trimmed);
+ if (!Number.isFinite(parsed)) {
+ return null;
+ }
+ const value = Math.min(range.max, Math.max(range.min, Math.round(parsed)));
+ return { draft: String(value), value };
+}
diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.ts
index 72be54f65cd..80015c6f96f 100644
--- a/studio/frontend/src/features/settings/index.ts
+++ b/studio/frontend/src/features/settings/index.ts
@@ -51,6 +51,18 @@ export type {
SidebarNavItemPref,
} from "./stores/appearance-custom-store";
export { useMonitorOverlayStore } from "./stores/monitor-overlay-store";
+export {
+ applyInterfaceScale,
+ useInterfaceScaleStore,
+} from "./stores/interface-scale-store";
+// The runtime module, not the store, so consumers outside this feature do not have to pull
+// zustand in with them. native-drop-position.ts imports it directly for that reason.
+export {
+ NATIVE_MAC_TITLEBAR_HEIGHT_VAR,
+ NATIVE_MAC_TRAFFIC_LIGHT_INSET_VAR,
+ getAppliedInterfaceZoom,
+ subscribeAppliedInterfaceZoom,
+} from "./lib/interface-scale-runtime";
export {
type MonitorFrame,
useMonitorFrameStore,
diff --git a/studio/frontend/src/features/settings/lib/interface-scale-runtime.ts b/studio/frontend/src/features/settings/lib/interface-scale-runtime.ts
new file mode 100644
index 00000000000..1d7089908cf
--- /dev/null
+++ b/studio/frontend/src/features/settings/lib/interface-scale-runtime.ts
@@ -0,0 +1,48 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * macOS draws the titlebar and traffic lights itself, at a size webview zoom does not
+ * touch. Every CSS inset that has to clear them is therefore divided by the zoom, so the
+ * gap stays the same number of screen points at any interface scale.
+ *
+ * These two numbers are the single source for that. `provider.tsx` builds its `var(...)`
+ * fallbacks from them and the tests assert against them, so changing the titlebar height
+ * here cannot leave a stale divisor behind at any scale but 100%.
+ */
+export const NATIVE_MAC_TITLEBAR_HEIGHT_PX = 34;
+export const NATIVE_MAC_TRAFFIC_LIGHT_INSET_PX = 78;
+
+export const NATIVE_MAC_TITLEBAR_HEIGHT_VAR = `var(--studio-native-titlebar-height, ${NATIVE_MAC_TITLEBAR_HEIGHT_PX}px)`;
+export const NATIVE_MAC_TRAFFIC_LIGHT_INSET_VAR = `var(--studio-native-traffic-light-inset, ${NATIVE_MAC_TRAFFIC_LIGHT_INSET_PX}px)`;
+
+let appliedInterfaceZoom = 1;
+const appliedInterfaceZoomListeners = new Set<() => void>();
+
+/**
+ * The zoom last handed to the webview, not a reading off it. Page zoom is not observable
+ * from JS, so this is the only value the non-Windows drop path has.
+ */
+export function getAppliedInterfaceZoom(): number {
+ return appliedInterfaceZoom;
+}
+
+export function subscribeAppliedInterfaceZoom(listener: () => void): () => void {
+ appliedInterfaceZoomListeners.add(listener);
+ return () => {
+ appliedInterfaceZoomListeners.delete(listener);
+ };
+}
+
+export function setAppliedInterfaceZoom(zoom: number): void {
+ appliedInterfaceZoom = zoom;
+ document.documentElement.style.setProperty(
+ "--studio-native-titlebar-height",
+ `${NATIVE_MAC_TITLEBAR_HEIGHT_PX / zoom}px`,
+ );
+ document.documentElement.style.setProperty(
+ "--studio-native-traffic-light-inset",
+ `${NATIVE_MAC_TRAFFIC_LIGHT_INSET_PX / zoom}px`,
+ );
+ for (const listener of appliedInterfaceZoomListeners) listener();
+}
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index f4a70c43e64..998b6c8c2e2 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -268,6 +268,10 @@ export function createSettingsSearchIndex({
// and searching Settings for "repair" answered "No settings found."
"settings.general.repairInstall.label",
],
+ appearance: [
+ ...SETTINGS_SEARCH_INDEX.appearance,
+ "settings.appearance.custom.interfaceScale.label",
+ ],
about: SETTINGS_SEARCH_INDEX.about.filter(
(key) => key !== "settings.about.updates",
),
diff --git a/studio/frontend/src/features/settings/stores/interface-scale-store.ts b/studio/frontend/src/features/settings/stores/interface-scale-store.ts
new file mode 100644
index 00000000000..80d3b146bfa
--- /dev/null
+++ b/studio/frontend/src/features/settings/stores/interface-scale-store.ts
@@ -0,0 +1,152 @@
+// 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 { isTauri } from "@/lib/api-base";
+import { create } from "zustand";
+import {
+ type StateStorage,
+ createJSONStorage,
+ persist,
+} from "zustand/middleware";
+import {
+ getAppliedInterfaceZoom,
+ setAppliedInterfaceZoom,
+} from "../lib/interface-scale-runtime.ts";
+
+export { getAppliedInterfaceZoom };
+
+export const INTERFACE_SCALE_STORAGE_KEY = "unsloth_interface_scale";
+// The floor is 50, not the 25 Chrome and VS Code allow, because both of those ship
+// Cmd/Ctrl+0 and this does not yet. At 25% the Settings row you would use to undo it
+// renders around 3.5px, and the value is device-local in localStorage, so recovery means
+// clearing app data. Drop it back to 25 once a reset accelerator exists.
+export const INTERFACE_SCALE_RANGE = {
+ min: 50,
+ max: 200,
+ default: 100,
+} as const;
+
+const guardedLocalStorage: StateStorage = {
+ getItem: (name) => {
+ try {
+ return window.localStorage.getItem(name);
+ } catch {
+ return null;
+ }
+ },
+ setItem: (name, value) => {
+ try {
+ window.localStorage.setItem(name, value);
+ } catch {
+ // ignore: the scale stays in memory for this session
+ }
+ },
+ removeItem: (name) => {
+ try {
+ window.localStorage.removeItem(name);
+ } catch {
+ // ignore
+ }
+ },
+};
+
+export function sanitizeInterfaceScale(value: unknown): number {
+ if (typeof value !== "number" || !Number.isFinite(value)) {
+ return INTERFACE_SCALE_RANGE.default;
+ }
+ return Math.min(
+ INTERFACE_SCALE_RANGE.max,
+ Math.max(INTERFACE_SCALE_RANGE.min, Math.round(value)),
+ );
+}
+
+export function interfaceScaleToZoom(scale: number): number {
+ return sanitizeInterfaceScale(scale) / 100;
+}
+
+interface InterfaceScaleState {
+ scale: number;
+ setScale: (scale: number) => void;
+ reset: () => void;
+}
+
+export const useInterfaceScaleStore = create<InterfaceScaleState>()(
+ persist(
+ (set) => ({
+ scale: INTERFACE_SCALE_RANGE.default,
+ setScale: (scale) => set({ scale: sanitizeInterfaceScale(scale) }),
+ reset: () => set({ scale: INTERFACE_SCALE_RANGE.default }),
+ }),
+ {
+ name: INTERFACE_SCALE_STORAGE_KEY,
+ storage: createJSONStorage(() => guardedLocalStorage),
+ merge: (persisted, current) => ({
+ ...current,
+ scale: sanitizeInterfaceScale(
+ (persisted as Partial<InterfaceScaleState> | undefined)?.scale,
+ ),
+ }),
+ },
+ ),
+);
+
+let appliedInterfaceScale: number | null = null;
+let requestedInterfaceScale: number = INTERFACE_SCALE_RANGE.default;
+let interfaceScaleApplicationQueue = Promise.resolve();
+
+export function applyInterfaceScale(scale: number): Promise<void> {
+ if (!isTauri) {
+ return Promise.resolve();
+ }
+ requestedInterfaceScale = sanitizeInterfaceScale(scale);
+ const application = interfaceScaleApplicationQueue.then(async () => {
+ const nextScale = requestedInterfaceScale;
+ if (nextScale === appliedInterfaceScale) {
+ return;
+ }
+ const { getCurrentWebview } = await import("@tauri-apps/api/webview");
+ const zoom = interfaceScaleToZoom(nextScale);
+ await getCurrentWebview().setZoom(zoom);
+ if (nextScale !== requestedInterfaceScale) {
+ // a timed-out command can overwrite a newer native zoom when it finishes.
+ appliedInterfaceScale = null;
+ void applyInterfaceScale(requestedInterfaceScale).catch(() => undefined);
+ return;
+ }
+ appliedInterfaceScale = nextScale;
+ setAppliedInterfaceZoom(zoom);
+ });
+ interfaceScaleApplicationQueue = application.catch(() => undefined);
+ return application;
+}
+
+/**
+ * Applying the scale before the first render is what stops a 100% frame painting and
+ * then relaying out. Worth waiting for, not worth waiting forever: this is the only
+ * thing gating first paint on the Tauri IPC bridge, and a rejection is caught while a
+ * hang is not, so without a deadline a wedged bridge is a permanently blank window.
+ *
+ * Past the deadline the app renders at 100% and the effect in `provider.tsx` applies the
+ * real scale whenever the bridge does answer.
+ */
+export const INTERFACE_SCALE_FIRST_PAINT_TIMEOUT_MS = 1000;
+
+export function applyInterfaceScaleBeforeFirstPaint(
+ scale: number,
+ timeoutMs: number = INTERFACE_SCALE_FIRST_PAINT_TIMEOUT_MS,
+): Promise<void> {
+ const applied = applyInterfaceScale(scale).catch(() => undefined);
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => {
+ // Rendering is unblocked, but the queue is still chained to a call that may never
+ // settle, and everything after it waits behind that. Cut it loose or the retry in
+ // `provider.tsx` and every later scale change are dead until restart.
+ interfaceScaleApplicationQueue = Promise.resolve();
+ resolve();
+ }, timeoutMs);
+ void applied.finally(() => {
+ clearTimeout(timer);
+ resolve();
+ });
+ });
+}
diff --git a/studio/frontend/src/features/settings/tabs/appearance-tab.tsx b/studio/frontend/src/features/settings/tabs/appearance-tab.tsx
index ce74de7d492..c8fc01b382e 100644
--- a/studio/frontend/src/features/settings/tabs/appearance-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/appearance-tab.tsx
@@ -5,6 +5,7 @@ import { useEffect, useRef } from "react";
import { Switch } from "@/components/ui/switch";
import { useSidebarPin } from "@/hooks/use-sidebar-pin";
import { useT } from "@/i18n";
+import { isTauri } from "@/lib/api-base";
import {
ActiveColorControl,
ChatFontRow,
@@ -13,6 +14,7 @@ import {
ContrastSliderRow,
FontSmoothingSwitch,
HeadingFontRow,
+ InterfaceScaleRow,
PointerCursorsSwitch,
ReduceMotionSegmented,
ResetCustomizationButton,
@@ -63,6 +65,67 @@ export function AppearanceTab() {
</p>
</header>
+ <SettingsSection title={t("settings.appearance.custom.preferencesTitle")}>
+ <SettingsRow label={t("settings.appearance.custom.uiFont.label")}>
+ <UiFontRow />
+ </SettingsRow>
+ <SettingsRow label={t("settings.appearance.custom.codeFont.label")}>
+ <CodeFontRow />
+ </SettingsRow>
+ {isTauri && (
+ <SettingsRow
+ label={t("settings.appearance.custom.interfaceScale.label")}
+ description={t(
+ "settings.appearance.custom.interfaceScale.description",
+ )}
+ >
+ <InterfaceScaleRow />
+ </SettingsRow>
+ )}
+ <SettingsRow
+ label={t("settings.appearance.custom.pointerCursors.label")}
+ description={t(
+ "settings.appearance.custom.pointerCursors.description",
+ )}
+ >
+ <PointerCursorsSwitch />
+ </SettingsRow>
+ <SettingsRow
+ label={t("settings.appearance.custom.reduceMotion.label")}
+ description={t("settings.appearance.custom.reduceMotion.description")}
+ >
+ <ReduceMotionSegmented />
+ </SettingsRow>
+ <SettingsRow
+ label={t("settings.appearance.custom.uiFontSize.label")}
+ description={t("settings.appearance.custom.uiFontSize.description")}
+ >
+ <UiFontSizeRow />
+ </SettingsRow>
+ <SettingsRow
+ label={t("settings.appearance.custom.codeFontSize.label")}
+ description={t("settings.appearance.custom.codeFontSize.description")}
+ >
+ <CodeFontSizeRow />
+ </SettingsRow>
+ <SettingsRow
+ label={t("settings.appearance.custom.fontSmoothing.label")}
+ description={t(
+ "settings.appearance.custom.fontSmoothing.description",
+ )}
+ >
+ <FontSmoothingSwitch />
+ </SettingsRow>
+ <SettingsRow
+ label={t("settings.appearance.layout.compactSidebar")}
+ description={t(
+ "settings.appearance.layout.compactSidebarDescription",
+ )}
+ >
+ <Switch checked={pinned} onCheckedChange={setPinned} />
+ </SettingsRow>
+ </SettingsSection>
+
<SettingsSection title={t("settings.appearance.theme.title")}>
<SettingsRow
label={t("settings.appearance.theme.label")}
@@ -105,18 +168,12 @@ export function AppearanceTab() {
/>
</SettingsRow>
<SettingsGroupDivider />
- <SettingsRow label={t("settings.appearance.custom.uiFont.label")}>
- <UiFontRow />
- </SettingsRow>
<SettingsRow label={t("settings.appearance.custom.headingFont.label")}>
<HeadingFontRow />
</SettingsRow>
<SettingsRow label={t("settings.appearance.custom.chatFont.label")}>
<ChatFontRow />
</SettingsRow>
- <SettingsRow label={t("settings.appearance.custom.codeFont.label")}>
- <CodeFontRow />
- </SettingsRow>
<SettingsGroupDivider />
<SettingsRow
label={t("settings.appearance.custom.contrast.label")}
@@ -126,51 +183,6 @@ export function AppearanceTab() {
</SettingsRow>
</SettingsSection>
- <SettingsSection title={t("settings.appearance.custom.preferencesTitle")}>
- <SettingsRow
- label={t("settings.appearance.custom.pointerCursors.label")}
- description={t(
- "settings.appearance.custom.pointerCursors.description",
- )}
- >
- <PointerCursorsSwitch />
- </SettingsRow>
- <SettingsRow
- label={t("settings.appearance.custom.reduceMotion.label")}
- description={t("settings.appearance.custom.reduceMotion.description")}
- >
- <ReduceMotionSegmented />
- </SettingsRow>
- <SettingsRow
- label={t("settings.appearance.custom.uiFontSize.label")}
- description={t("settings.appearance.custom.uiFontSize.description")}
- >
- <UiFontSizeRow />
- </SettingsRow>
- <SettingsRow
- label={t("settings.appearance.custom.codeFontSize.label")}
- description={t("settings.appearance.custom.codeFontSize.description")}
- >
- <CodeFontSizeRow />
- </SettingsRow>
- <SettingsRow
- label={t("settings.appearance.custom.fontSmoothing.label")}
- description={t(
- "settings.appearance.custom.fontSmoothing.description",
- )}
- >
- <FontSmoothingSwitch />
- </SettingsRow>
- <SettingsRow
- label={t("settings.appearance.layout.compactSidebar")}
- description={t(
- "settings.appearance.layout.compactSidebarDescription",
- )}
- >
- <Switch checked={pinned} onCheckedChange={setPinned} />
- </SettingsRow>
- </SettingsSection>
-
{/* Nav shape first, then the profile menu inside it. */}
<div ref={sidebarNavSectionRef} className="scroll-mt-4">
<SettingsSection
diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsx
index f5aaf7b5008..95e6849df7f 100644
--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx
@@ -74,6 +74,7 @@ import { SettingsSection } from "../components/settings-section";
import { StudioVersionSection } from "../components/studio-version-section";
import { useDesktopBooleanSetting } from "../hooks/use-desktop-boolean-setting";
import { KEYBOARD_SHORTCUTS_STORAGE_KEY } from "../stores/keyboard-shortcuts-store";
+import { INTERFACE_SCALE_STORAGE_KEY } from "../stores/interface-scale-store";
import { SETTINGS_PANEL_PREFS_STORAGE_KEY } from "../stores/settings-panel-prefs-store";
import { CHAT_PROJECT_ATTACHMENT_TARGET_KEY } from "@/features/chat/utils/project-attachment-target";
@@ -85,6 +86,7 @@ const PREFS_KEYS: string[] = [
"theme",
"palette",
"unsloth_appearance_customization",
+ INTERFACE_SCALE_STORAGE_KEY,
LOCALE_STORAGE_KEY,
// UI state
"sidebar_pinned",
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 0cc21fc2b30..13b2d8cb1aa 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1079,6 +1079,10 @@ export const ar = {
"لا توجد مساحة تخزين محلية كافية لهذا الخط. أزل خطًا مستوردًا أولًا.",
errorFailed: "تعذّر تحميل ملف الخط هذا.",
},
+ interfaceScale: {
+ label: "مقياس الواجهة",
+ description: "غيّر حجم جميع عناصر الواجهة.",
+ },
uiFontSize: {
label: "حجم خط الواجهة",
description: "اضبط الحجم الأساسي المستخدم في واجهة Unsloth.",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 0830cab27ab..65967021625 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1103,6 +1103,10 @@ export const de = {
"Nicht genug lokaler Speicher für diese Schrift. Entfernen Sie zuerst eine importierte Schrift.",
errorFailed: "Diese Schriftdatei konnte nicht geladen werden.",
},
+ interfaceScale: {
+ label: "Oberflächenskalierung",
+ description: "Passen Sie die Größe aller Oberflächenelemente an.",
+ },
uiFontSize: {
label: "Schriftgröße der Oberfläche",
description: "Passen Sie die Grundgröße der Unsloth-Oberfläche an.",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 7da35f076d2..1599432da02 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1073,6 +1073,10 @@ export const en = {
"Not enough local storage for this font. Remove an imported font first.",
errorFailed: "Could not load this font file.",
},
+ interfaceScale: {
+ label: "Interface scale",
+ description: "Resize all interface elements.",
+ },
uiFontSize: {
label: "UI font size",
description: "Adjust the base size used for the Unsloth UI.",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 45cb06835d7..40396f23d1c 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1098,6 +1098,10 @@ export const es = {
"No hay suficiente almacenamiento local para esta fuente. Quita antes una fuente importada.",
errorFailed: "No se pudo cargar este archivo de fuente.",
},
+ interfaceScale: {
+ label: "Escala de la interfaz",
+ description: "Cambia el tamaño de todos los elementos de la interfaz.",
+ },
uiFontSize: {
label: "Tamaño de fuente de la interfaz",
description: "Ajusta el tamaño base usado en la interfaz de Unsloth.",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index c60412dd8a0..ed517ab13a3 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1102,6 +1102,10 @@ export const fr = {
"Stockage local insuffisant pour cette police. Retirez d'abord une police importée.",
errorFailed: "Impossible de charger ce fichier de police.",
},
+ interfaceScale: {
+ label: "Échelle de l'interface",
+ description: "Redimensionnez tous les éléments de l'interface.",
+ },
uiFontSize: {
label: "Taille de police de l'interface",
description: "Ajustez la taille de base utilisée pour l'interface Unsloth.",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index e75463a1a05..78217f8b98c 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1082,6 +1082,10 @@ export const hi = {
"इस फ़ॉन्ट के लिए पर्याप्त लोकल स्टोरेज नहीं है। पहले कोई आयातित फ़ॉन्ट हटाएं।",
errorFailed: "यह फ़ॉन्ट फ़ाइल लोड नहीं हो सकी।",
},
+ interfaceScale: {
+ label: "इंटरफ़ेस स्केल",
+ description: "सभी इंटरफ़ेस तत्वों का आकार बदलें।",
+ },
uiFontSize: {
label: "UI फ़ॉन्ट का आकार",
description: "Unsloth UI के लिए उपयोग होने वाला आधार आकार समायोजित करें।",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index d27ca1dcec0..37d88a9b17f 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1067,6 +1067,10 @@ export const it = {
"Spazio di archiviazione locale insufficiente per questo font. Rimuovi prima un font importato.",
errorFailed: "Impossibile caricare questo file di font.",
},
+ interfaceScale: {
+ label: "Scala dell'interfaccia",
+ description: "Ridimensiona tutti gli elementi dell'interfaccia.",
+ },
uiFontSize: {
label: "Dimensione del font dell'interfaccia",
description:
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index d85de906fde..36bf59aaa9c 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1060,6 +1060,10 @@ export const ja = {
errorStorageFull: "ローカルストレージの空き容量が足りません。先にインポート済みフォントを削除してください。",
errorFailed: "このフォントファイルを読み込めませんでした。",
},
+ interfaceScale: {
+ label: "インターフェースの表示倍率",
+ description: "すべてのインターフェース要素のサイズを変更します。",
+ },
uiFontSize: {
label: "UI フォントサイズ",
description: "Unsloth UI の基本サイズを調整します。",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index c988d168da2..c526982a7dd 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1075,6 +1075,10 @@ export const ko = {
"이 글꼴을 저장할 로컬 저장 공간이 부족합니다. 가져온 글꼴을 먼저 제거하세요.",
errorFailed: "이 글꼴 파일을 불러올 수 없습니다.",
},
+ interfaceScale: {
+ label: "인터페이스 배율",
+ description: "모든 인터페이스 요소의 크기를 조정합니다.",
+ },
uiFontSize: {
label: "UI 글꼴 크기",
description: "Unsloth UI에 쓰이는 기본 크기를 조정합니다.",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index de863512535..8235addae7c 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1088,6 +1088,10 @@ export const ptBR = {
errorStorageFull: "Sem espaço de armazenamento local para esta fonte. Remova uma fonte importada primeiro.",
errorFailed: "Não foi possível carregar este arquivo de fonte.",
},
+ interfaceScale: {
+ label: "Escala da interface",
+ description: "Redimensione todos os elementos da interface.",
+ },
uiFontSize: {
label: "Tamanho da fonte da interface",
description: "Ajuste o tamanho base da interface do Unsloth.",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 281e4caf801..8ad738db99c 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1083,6 +1083,10 @@ export const ru = {
"Недостаточно локального хранилища для этого шрифта. Сначала удалите один из импортированных.",
errorFailed: "Не удалось загрузить этот файл шрифта.",
},
+ interfaceScale: {
+ label: "Масштаб интерфейса",
+ description: "Измените размер всех элементов интерфейса.",
+ },
uiFontSize: {
label: "Размер шрифта интерфейса",
description: "Настройте базовый размер шрифта интерфейса Unsloth.",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 5008cd67692..6814f78c929 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1061,6 +1061,10 @@ export const zhCN = {
errorStorageFull: "本地存储空间不足。请先删除一个已导入的字体。",
errorFailed: "无法加载此字体文件。",
},
+ interfaceScale: {
+ label: "界面缩放",
+ description: "调整所有界面元素的大小。",
+ },
uiFontSize: {
label: "界面字号",
description: "调整 Unsloth 界面的基准字号。",
diff --git a/studio/frontend/src/main.tsx b/studio/frontend/src/main.tsx
index 1b7935239f6..db8fefcc5c6 100644
--- a/studio/frontend/src/main.tsx
+++ b/studio/frontend/src/main.tsx
@@ -11,6 +11,10 @@ import {
watchMathBlockContainmentOverride,
} from "./components/assistant-ui/math-block-containment";
import { fetchDeviceType } from "./config/env";
+import {
+ applyInterfaceScaleBeforeFirstPaint,
+ useInterfaceScaleStore,
+} from "./features/settings/stores/interface-scale-store";
import { initializeLocale } from "./i18n";
import { isTauri } from "./lib/api-base";
import { watchOverlayScrollbarGutter } from "./lib/overlay-scrollbar";
@@ -59,8 +63,13 @@ function renderApp(): void {
}
const localeInitialization = initializeLocale();
-if (typeof localeInitialization !== "string") {
- localeInitialization.then(renderApp);
+const interfaceScaleInitialization = applyInterfaceScaleBeforeFirstPaint(
+ useInterfaceScaleStore.getState().scale,
+);
+if (typeof localeInitialization !== "string" || isTauri) {
+ Promise.all([localeInitialization, interfaceScaleInitialization]).then(
+ renderApp,
+ );
} else {
renderApp();
}
diff --git a/studio/frontend/tests/helpers/tauri-webview-resolver.mjs b/studio/frontend/tests/helpers/tauri-webview-resolver.mjs
new file mode 100644
index 00000000000..82c26f4e200
--- /dev/null
+++ b/studio/frontend/tests/helpers/tauri-webview-resolver.mjs
@@ -0,0 +1,45 @@
+// 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 { existsSync } from "node:fs";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const SRC = fileURLToPath(new URL("../../src/", import.meta.url));
+const WEBVIEW_STUB = new URL("./tauri-webview-stub.mjs", import.meta.url).href;
+
+function firstExisting(base) {
+ for (const candidate of [`${base}.ts`, `${base}/index.ts`, base]) {
+ if (existsSync(candidate)) {
+ return pathToFileURL(candidate).href;
+ }
+ }
+ return null;
+}
+
+function bustOf(parentURL) {
+ if (!parentURL) {
+ return "";
+ }
+ const bust = new URL(parentURL).searchParams.get("bust");
+ return bust ? `?bust=${bust}` : "";
+}
+
+export function resolve(specifier, context, next) {
+ const suffix = bustOf(context.parentURL);
+ if (specifier === "@tauri-apps/api/webview") {
+ return next(WEBVIEW_STUB + suffix, context);
+ }
+ if (specifier.startsWith("@/")) {
+ const resolved = firstExisting(SRC + specifier.slice(2));
+ return next(resolved ? resolved + suffix : specifier, context);
+ }
+ if (specifier.startsWith(".") && context.parentURL?.startsWith("file:")) {
+ const parent = new URL(context.parentURL);
+ parent.search = "";
+ const resolved = firstExisting(fileURLToPath(new URL(specifier, parent)));
+ if (resolved) {
+ return next(resolved + suffix, context);
+ }
+ }
+ return next(specifier, context);
+}
diff --git a/studio/frontend/tests/helpers/tauri-webview-stub.mjs b/studio/frontend/tests/helpers/tauri-webview-stub.mjs
new file mode 100644
index 00000000000..7096dfd86f1
--- /dev/null
+++ b/studio/frontend/tests/helpers/tauri-webview-stub.mjs
@@ -0,0 +1,15 @@
+// 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 function getCurrentWebview() {
+ return {
+ setZoom: (scaleFactor) => {
+ const control = globalThis.__TAURI_WEBVIEW_STUB__;
+ if (control.setZoom) {
+ return control.setZoom(scaleFactor);
+ }
+ control.zooms.push(scaleFactor);
+ return Promise.resolve();
+ },
+ };
+}
diff --git a/studio/frontend/tests/interface-scale-window-layout.test.ts b/studio/frontend/tests/interface-scale-window-layout.test.ts
new file mode 100644
index 00000000000..6e478bbe381
--- /dev/null
+++ b/studio/frontend/tests/interface-scale-window-layout.test.ts
@@ -0,0 +1,102 @@
+// 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 { stripTypeScriptTypes } from "node:module";
+import test from "node:test";
+
+import { calculateWindowSizeBounds } from "../src/app/window-layout.ts";
+import { observeDevicePixelRatio } from "../src/app/window-layout-lifecycle.ts";
+import {
+ getAppliedInterfaceZoom,
+ setAppliedInterfaceZoom,
+ subscribeAppliedInterfaceZoom,
+} from "../src/features/settings/lib/interface-scale-runtime.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+const provider = readSrc("app/provider.tsx");
+const ratioFunction = provider.match(
+ /function logicalPerCssPx\([\s\S]*?\n\}/,
+)?.[0];
+assert.ok(ratioFunction);
+const windowStub = { devicePixelRatio: 2 };
+const logicalPerCssPx = new Function(
+ "window",
+ "getAppliedInterfaceZoom",
+ `${stripTypeScriptTypes(ratioFunction)}\nreturn logicalPerCssPx;`,
+)(windowStub, getAppliedInterfaceZoom) as (monitorScale: number) => number;
+
+Object.defineProperty(globalThis, "document", {
+ configurable: true,
+ value: { documentElement: { style: { setProperty: () => undefined } } },
+});
+
+const bounds = () =>
+ calculateWindowSizeBounds({ width: 1920, height: 1080 }, logicalPerCssPx(2))
+ .minimum;
+
+test("startup constraints account for page zoom without counting Windows zoom twice", () => {
+ try {
+ setAppliedInterfaceZoom(2);
+ assert.deepEqual(bounds(), { width: 920, height: 960 });
+ windowStub.devicePixelRatio = 4;
+ assert.deepEqual(bounds(), { width: 920, height: 960 });
+ windowStub.devicePixelRatio = 6;
+ assert.equal(logicalPerCssPx(2), 3);
+ } finally {
+ windowStub.devicePixelRatio = 2;
+ setAppliedInterfaceZoom(1);
+ }
+});
+
+test("applied zoom refreshes live constraints with unchanged DPR and stops on unmount", () => {
+ const observerIndex = provider.indexOf(
+ "observeDevicePixelRatio(ratioSource,",
+ );
+ assert.ok(observerIndex >= 0);
+ const start = provider.lastIndexOf(" useEffect(() => {", observerIndex);
+ const end = provider.indexOf("\n }, []);", observerIndex);
+ assert.ok(start >= 0 && end > start);
+ const effect = provider.slice(start, end + "\n }, []);".length);
+ const minimums: Array<{ width: number; height: number }> = [];
+ const mode = { current: "app" };
+ let dispose = () => {};
+ const scope = {
+ isTauri: true,
+ useEffect: (setup: () => () => void) => {
+ dispose = setup();
+ },
+ windowPixelRatioSource: () => ({
+ devicePixelRatio: () => windowStub.devicePixelRatio,
+ matchResolution: () => null,
+ }),
+ observeDevicePixelRatio,
+ subscribeAppliedInterfaceZoom,
+ appliedWindowModeRef: mode,
+ windowLayoutGenerationRef: { current: 1 },
+ reapplyWindowSizeConstraints: async (isCurrent: () => boolean) => {
+ if (isCurrent()) minimums.push(bounds());
+ },
+ };
+ new Function(...Object.keys(scope), stripTypeScriptTypes(effect))(
+ ...Object.values(scope),
+ );
+ try {
+ setAppliedInterfaceZoom(2);
+ setAppliedInterfaceZoom(1);
+ assert.deepEqual(minimums, [
+ { width: 920, height: 960 },
+ { width: 460, height: 480 },
+ ]);
+ mode.current = "setup";
+ setAppliedInterfaceZoom(1.5);
+ assert.equal(minimums.length, 2);
+ mode.current = "app";
+ dispose();
+ setAppliedInterfaceZoom(2);
+ assert.equal(minimums.length, 2);
+ } finally {
+ dispose();
+ setAppliedInterfaceZoom(1);
+ }
+});
diff --git a/studio/frontend/tests/interface-scale.test.ts b/studio/frontend/tests/interface-scale.test.ts
new file mode 100644
index 00000000000..8d42926f168
--- /dev/null
+++ b/studio/frontend/tests/interface-scale.test.ts
@@ -0,0 +1,277 @@
+// 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 { readFile } from "node:fs/promises";
+import { register } from "node:module";
+import test from "node:test";
+
+register("./helpers/tauri-webview-resolver.mjs", import.meta.url);
+
+const MODULE = new URL(
+ "../src/features/settings/stores/interface-scale-store.ts",
+ import.meta.url,
+).href;
+const CAPABILITIES = new URL(
+ "../../src-tauri/capabilities/default.json",
+ import.meta.url,
+);
+const MAIN = new URL("../src/main.tsx", import.meta.url);
+const PROVIDER = new URL("../src/app/provider.tsx", import.meta.url);
+const APPEARANCE_TAB = new URL(
+ "../src/features/settings/tabs/appearance-tab.tsx",
+ import.meta.url,
+);
+const APPEARANCE_CONTROLS = new URL(
+ "../src/features/settings/components/appearance-custom-controls.tsx",
+ import.meta.url,
+);
+const GENERAL_TAB = new URL(
+ "../src/features/settings/tabs/general-tab.tsx",
+ import.meta.url,
+);
+
+const { NATIVE_MAC_TITLEBAR_HEIGHT_PX, NATIVE_MAC_TRAFFIC_LIGHT_INSET_PX } =
+ await import("../src/features/settings/lib/interface-scale-runtime.ts");
+
+type InterfaceScaleModule = {
+ sanitizeInterfaceScale: (value: unknown) => number;
+ interfaceScaleToZoom: (scale: number) => number;
+ getAppliedInterfaceZoom: () => number;
+ applyInterfaceScale: (scale: number) => Promise<void>;
+ applyInterfaceScaleBeforeFirstPaint: (
+ scale: number,
+ timeoutMs?: number,
+ ) => Promise<void>;
+};
+
+let generation = 0;
+
+function define(name: string, value: unknown) {
+ Object.defineProperty(globalThis, name, {
+ value,
+ configurable: true,
+ writable: true,
+ });
+}
+
+async function load(tauri: boolean) {
+ const styles = new Map<string, string>();
+ const windowStub: Record<string, unknown> = {
+ location: { protocol: tauri ? "tauri:" : "https:" },
+ localStorage: {
+ getItem: () => null,
+ setItem: () => undefined,
+ removeItem: () => undefined,
+ },
+ };
+ if (tauri) {
+ windowStub["__TAURI_INTERNALS__"] = {};
+ }
+ define("window", windowStub);
+ define("document", {
+ documentElement: {
+ style: {
+ setProperty: (name: string, value: string) => styles.set(name, value),
+ },
+ },
+ });
+ const control: {
+ zooms: number[];
+ setZoom?: (zoom: number) => Promise<void>;
+ } = { zooms: [] };
+ define("__TAURI_WEBVIEW_STUB__", control);
+ generation += 1;
+ const mod = (await import(
+ `${MODULE}?bust=${generation}`
+ )) as InterfaceScaleModule;
+ return { mod, control, styles };
+}
+
+test("interface scale is rounded and clamped to a usable range", async () => {
+ const { mod } = await load(false);
+ assert.equal(mod.sanitizeInterfaceScale(undefined), 100);
+ assert.equal(mod.sanitizeInterfaceScale(10), 50);
+ assert.equal(mod.sanitizeInterfaceScale(66.6), 67);
+ assert.equal(mod.sanitizeInterfaceScale(500), 200);
+ assert.equal(mod.interfaceScaleToZoom(55), 0.55);
+ // Below the floor the zoom clamps too, rather than reaching the webview raw.
+ assert.equal(mod.interfaceScaleToZoom(25), 0.5);
+});
+
+test("desktop scale sets native webview zoom", async () => {
+ const { mod, control, styles } = await load(true);
+ await mod.applyInterfaceScale(55);
+ await mod.applyInterfaceScale(55);
+ assert.deepEqual(control.zooms, [0.55]);
+ assert.equal(mod.getAppliedInterfaceZoom(), 0.55);
+ assert.equal(
+ styles.get("--studio-native-titlebar-height"),
+ `${NATIVE_MAC_TITLEBAR_HEIGHT_PX / 0.55}px`,
+ );
+ assert.equal(
+ styles.get("--studio-native-traffic-light-inset"),
+ `${NATIVE_MAC_TRAFFIC_LIGHT_INSET_PX / 0.55}px`,
+ );
+});
+
+test("the latest scale wins while an older native update is pending", async () => {
+ const { mod, control, styles } = await load(true);
+ let markFirstStarted: () => void = () => undefined;
+ let releaseFirst: () => void = () => undefined;
+ const firstStarted = new Promise<void>((resolve) => {
+ markFirstStarted = resolve;
+ });
+ control.setZoom = (zoom) => {
+ control.zooms.push(zoom);
+ if (zoom !== 0.55) {
+ return Promise.resolve();
+ }
+ markFirstStarted();
+ return new Promise<void>((resolve) => {
+ releaseFirst = resolve;
+ });
+ };
+
+ const first = mod.applyInterfaceScale(55);
+ await firstStarted;
+ const latest = mod.applyInterfaceScale(75);
+ releaseFirst();
+ await Promise.all([first, latest]);
+
+ assert.deepEqual(control.zooms, [0.55, 0.75]);
+ assert.equal(mod.getAppliedInterfaceZoom(), 0.75);
+ assert.equal(
+ styles.get("--studio-native-titlebar-height"),
+ `${NATIVE_MAC_TITLEBAR_HEIGHT_PX / 0.75}px`,
+ );
+});
+
+test("first paint is not held hostage by a wedged native bridge", async () => {
+ const { mod, control } = await load(true);
+ // Never resolves: the failure a plain catch() does not cover.
+ control.setZoom = () => new Promise<void>(() => undefined);
+ await mod.applyInterfaceScaleBeforeFirstPaint(75, 10);
+});
+
+// Timed, because the regression these two cover is a queue that never drains: without the
+// release the awaits below hang rather than fail, and an unbounded hang wedges the runner
+// instead of reporting.
+test(
+ "a scale change after a wedged first paint still applies",
+ { timeout: 5_000 },
+ async () => {
+ const { mod, control, styles } = await load(true);
+ let wedged = true;
+ control.setZoom = (zoom) => {
+ if (wedged) {
+ return new Promise<void>(() => undefined);
+ }
+ control.zooms.push(zoom);
+ return Promise.resolve();
+ };
+
+ await mod.applyInterfaceScaleBeforeFirstPaint(75, 10);
+ // The bridge comes back. Nothing about the abandoned call may keep the queue closed.
+ wedged = false;
+ await mod.applyInterfaceScale(125);
+
+ assert.deepEqual(control.zooms, [1.25]);
+ assert.equal(mod.getAppliedInterfaceZoom(), 1.25);
+ assert.equal(
+ styles.get("--studio-native-titlebar-height"),
+ `${NATIVE_MAC_TITLEBAR_HEIGHT_PX / 1.25}px`,
+ );
+ },
+);
+
+test(
+ "a late wedged call restores the requested native zoom",
+ { timeout: 5_000 },
+ async () => {
+ const { mod, control, styles } = await load(true);
+ let nativeZoom = 1;
+ let releaseWedged: () => void = () => undefined;
+ let markRestored: () => void = () => undefined;
+ const restored = new Promise<void>((resolve) => {
+ markRestored = resolve;
+ });
+ control.setZoom = (zoom) => {
+ control.zooms.push(zoom);
+ if (zoom === 0.75) {
+ return new Promise<void>((resolve) => {
+ releaseWedged = () => {
+ nativeZoom = zoom;
+ resolve();
+ };
+ });
+ }
+ nativeZoom = zoom;
+ if (control.zooms.length === 3) {
+ markRestored();
+ }
+ return Promise.resolve();
+ };
+
+ await mod.applyInterfaceScaleBeforeFirstPaint(75, 10);
+ await mod.applyInterfaceScale(125);
+ releaseWedged();
+ await restored;
+ await mod.applyInterfaceScale(125);
+
+ assert.equal(nativeZoom, 1.25);
+ assert.deepEqual(control.zooms, [0.75, 1.25, 1.25]);
+ assert.equal(mod.getAppliedInterfaceZoom(), 1.25);
+ assert.equal(
+ styles.get("--studio-native-titlebar-height"),
+ `${NATIVE_MAC_TITLEBAR_HEIGHT_PX / 1.25}px`,
+ );
+ },
+);
+
+test("first paint waits for the scale when the bridge answers", async () => {
+ const { mod, control, styles } = await load(true);
+ await mod.applyInterfaceScaleBeforeFirstPaint(75, 5_000);
+ assert.deepEqual(control.zooms, [0.75]);
+ assert.equal(
+ styles.get("--studio-native-titlebar-height"),
+ `${NATIVE_MAC_TITLEBAR_HEIGHT_PX / 0.75}px`,
+ );
+});
+
+test("browser scale never calls the native webview", async () => {
+ const { mod, control } = await load(false);
+ await mod.applyInterfaceScale(75);
+ assert.deepEqual(control.zooms, []);
+});
+
+test("desktop capability allows webview zoom", async () => {
+ const capabilities = JSON.parse(await readFile(CAPABILITIES, "utf8")) as {
+ permissions: unknown[];
+ };
+ assert.ok(
+ capabilities.permissions.includes("core:webview:allow-set-webview-zoom"),
+ );
+});
+
+test("startup, live changes, and both resets use the local scale", async () => {
+ const [main, provider, tab, controls, general] = await Promise.all(
+ [MAIN, PROVIDER, APPEARANCE_TAB, APPEARANCE_CONTROLS, GENERAL_TAB].map(
+ (path) => readFile(path, "utf8"),
+ ),
+ );
+ assert.match(
+ main,
+ /applyInterfaceScaleBeforeFirstPaint\(\s*useInterfaceScaleStore\.getState\(\)\.scale/,
+ );
+ assert.match(
+ provider,
+ /useInterfaceScaleStore\(\(s\) => s\.scale\)[\s\S]*applyInterfaceScale\(interfaceScale\)/,
+ );
+ assert.match(
+ tab,
+ /isTauri && \([\s\S]*settings\.appearance\.custom\.interfaceScale\.label/,
+ );
+ assert.match(controls, /resetAll\(\);\s*resetInterfaceScale\(\);/);
+ assert.match(general, /INTERFACE_SCALE_STORAGE_KEY/);
+});
diff --git a/studio/frontend/tests/mac-titlebar-optical-alignment.test.ts b/studio/frontend/tests/mac-titlebar-optical-alignment.test.ts
index 06cfd4062b7..5dea7511204 100644
--- a/studio/frontend/tests/mac-titlebar-optical-alignment.test.ts
+++ b/studio/frontend/tests/mac-titlebar-optical-alignment.test.ts
@@ -3,6 +3,9 @@ import test from "node:test";
import { readSrc } from "./helpers/kit.ts";
+const PORTALLED_NATIVE_TITLEBAR_PATTERN =
+ /"--studio-window-chrome-top",[\s\S]*?NATIVE_MAC_TITLEBAR_HEIGHT_VAR/;
+
test("mac titlebar navigation shifts buttons with centered glyphs", async () => {
const [titlebar, provider] = await Promise.all([
readSrc("components/tauri/window-titlebar.tsx"),
@@ -41,3 +44,33 @@ test("mac chat and media headers share the lowered control row", async () => {
assert.match(page, /var\(--studio-chat-header-padding-top,/);
}
});
+
+// The runtime divides these by the zoom and provider.tsx uses them as CSS fallbacks. Two
+// copies of 34 would agree at 100% and silently disagree everywhere else, so assert the
+// fallback string is built from the same constant rather than retyped.
+test("mac native chrome clearance stays fixed across interface scales", async () => {
+ const [provider, runtime] = await Promise.all([
+ readSrc("app/provider.tsx"),
+ readSrc("features/settings/lib/interface-scale-runtime.ts"),
+ ]);
+ assert.match(
+ runtime,
+ /NATIVE_MAC_TITLEBAR_HEIGHT_VAR = `var\(--studio-native-titlebar-height, \$\{NATIVE_MAC_TITLEBAR_HEIGHT_PX\}px\)`/,
+ );
+ assert.match(
+ runtime,
+ /NATIVE_MAC_TRAFFIC_LIGHT_INSET_VAR = `var\(--studio-native-traffic-light-inset, \$\{NATIVE_MAC_TRAFFIC_LIGHT_INSET_PX\}px\)`/,
+ );
+ assert.match(
+ runtime,
+ /NATIVE_MAC_TITLEBAR_HEIGHT_PX \/ zoom/,
+ );
+ assert.match(
+ runtime,
+ /NATIVE_MAC_TRAFFIC_LIGHT_INSET_PX \/ zoom/,
+ );
+ // No literal 34px or 78px left in provider.tsx to drift out from under the runtime.
+ assert.doesNotMatch(provider, /--studio-native-titlebar-height, 34px/);
+ assert.doesNotMatch(provider, /--studio-native-traffic-light-inset, 78px/);
+ assert.match(provider, PORTALLED_NATIVE_TITLEBAR_PATTERN);
+});
diff --git a/studio/frontend/tests/native-drop-targets.test.ts b/studio/frontend/tests/native-drop-targets.test.ts
index 7b8b4b7ed6e..e1dba24f557 100644
--- a/studio/frontend/tests/native-drop-targets.test.ts
+++ b/studio/frontend/tests/native-drop-targets.test.ts
@@ -19,12 +19,22 @@ Object.assign(globalThis, {
// devicePixelRatio 2: a physical drop position is twice the CSS position the
// DOM is hit-tested in, which is the conversion this module owns.
window: { devicePixelRatio: 2, location: { protocol: "http:" } },
- document: { elementFromPoint: () => hit },
+ document: {
+ elementFromPoint: () => hit,
+ // setAppliedInterfaceZoom writes the mac chrome vars here on its way through.
+ documentElement: { style: { setProperty: () => undefined } },
+ },
});
const { nativeDropTargetAt, registerNativeDropTarget } = await import(
"../src/features/native-intents/native-drop-targets.ts"
);
+const { nativeDropPointToCss } = await import(
+ "../src/features/native-intents/native-drop-position.ts"
+);
+const { setAppliedInterfaceZoom } = await import(
+ "../src/features/settings/lib/interface-scale-runtime.ts"
+);
const IMAGE_DROPZONE = readSrc("components/image-dropzone.tsx");
const USE_NATIVE_DROP = readSrc("features/native-intents/use-native-drop.ts");
@@ -119,6 +129,45 @@ test("a Linux drop position is hit-tested as-is", () => {
});
});
+for (const userAgent of [
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X)",
+ "Mozilla/5.0 (X11; Linux x86_64)",
+]) {
+ test(`${userAgent} drop positions follow webview zoom`, () => {
+ Object.defineProperty(globalThis, "navigator", {
+ value: { userAgent },
+ configurable: true,
+ });
+ assert.deepEqual(nativeDropPointToCss({ x: 120, y: 80 }, 2, 0.5), {
+ x: 240,
+ y: 160,
+ });
+ });
+}
+
+// Every other case passes the zoom explicitly, which leaves the default argument
+// unexercised. That default is the seam between the scale store and the drop path, and
+// wiring it to the wrong getter would keep every one of those cases green.
+test("the default zoom comes from the applied interface scale", () => {
+ Object.defineProperty(globalThis, "navigator", {
+ value: { userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X)" },
+ configurable: true,
+ });
+ assert.deepEqual(nativeDropPointToCss({ x: 120, y: 80 }, 2), {
+ x: 120,
+ y: 80,
+ });
+ setAppliedInterfaceZoom(0.5);
+ try {
+ assert.deepEqual(nativeDropPointToCss({ x: 120, y: 80 }, 2), {
+ x: 240,
+ y: 160,
+ });
+ } finally {
+ setAppliedInterfaceZoom(1);
+ }
+});
+
test("a Windows drop position is divided by the scale factor", () => {
assert.deepEqual(pointSeenFor("Mozilla/5.0 (Windows NT 10.0; Win64)"), {
x: 60,
diff --git a/studio/frontend/tests/native-training-dataset-drop.test.ts b/studio/frontend/tests/native-training-dataset-drop.test.ts
index 337fea79e6c..3e41bec2990 100644
--- a/studio/frontend/tests/native-training-dataset-drop.test.ts
+++ b/studio/frontend/tests/native-training-dataset-drop.test.ts
@@ -113,8 +113,8 @@ test("classifies native drops before truncating long display filenames", () => {
});
// Only WebView2 reports a device-pixel drop position; macOS and GTK already
-// report CSS pixels, so scaling those halved every hit test on a HiDPI display
-// and the zone never matched.
+// report CSS pixels at 100% zoom, so scaling those by the monitor factor halved
+// every hit test on a HiDPI display and the zone never matched.
test("hit testing scales a Windows drop position to CSS pixels", () => {
Object.defineProperty(globalThis, "navigator", {
value: { userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64)" },
diff --git a/studio/frontend/tests/settings-search.test.ts b/studio/frontend/tests/settings-search.test.ts
index 2f22d276a25..c413e4b01c4 100644
--- a/studio/frontend/tests/settings-search.test.ts
+++ b/studio/frontend/tests/settings-search.test.ts
@@ -11,6 +11,7 @@ import {
import { en } from "../src/i18n/locales/en.ts";
const UPDATE_ENTRY = "settings.about.updates";
+const INTERFACE_SCALE_ENTRY = "settings.appearance.custom.interfaceScale.label";
test("desktop update searches route to General", () => {
const index = createSettingsSearchIndex({ desktop: true, closeToTray: true });
@@ -26,6 +27,14 @@ test("browser update searches keep routing to About", () => {
assert.ok(index.about.includes(UPDATE_ENTRY));
});
+test("interface scale is searchable only on desktop", () => {
+ const desktop = createSettingsSearchIndex({ desktop: true, closeToTray: true });
+ const browser = createSettingsSearchIndex({ desktop: false, closeToTray: false });
+
+ assert.ok(desktop.appearance.includes(INTERFACE_SCALE_ENTRY));
+ assert.ok(!browser.appearance.includes(INTERFACE_SCALE_ENTRY));
+});
+
// The words a user types for this feature are not substrings of any of its
// labels, so without keywords the rows it is named after were unfindable.
test("model memory rows are reachable by the terms the feature is about", () => {
diff --git a/studio/frontend/tests/size-input-value.test.ts b/studio/frontend/tests/size-input-value.test.ts
new file mode 100644
index 00000000000..add3b2ee88a
--- /dev/null
+++ b/studio/frontend/tests/size-input-value.test.ts
@@ -0,0 +1,27 @@
+// 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 { normalizeSizeInputDraft } from "../src/features/settings/components/size-input-value.ts";
+
+test("an out-of-range draft is reconciled to the active boundary", () => {
+ assert.deepEqual(normalizeSizeInputDraft("250", { min: 25, max: 200 }), {
+ draft: "200",
+ value: 200,
+ });
+});
+
+test("size drafts parse the complete number before rounding", () => {
+ const range = { min: 50, max: 200 };
+ assert.deepEqual(normalizeSizeInputDraft("66.6", range), {
+ draft: "67",
+ value: 67,
+ });
+ assert.deepEqual(normalizeSizeInputDraft("1e2", range), {
+ draft: "100",
+ value: 100,
+ });
+ assert.equal(normalizeSizeInputDraft("1e999", range), null);
+});
diff --git a/studio/src-tauri/capabilities/default.json b/studio/src-tauri/capabilities/default.json
index 300cf0690a9..aa93e2091ed 100644
--- a/studio/src-tauri/capabilities/default.json
+++ b/studio/src-tauri/capabilities/default.json
@@ -22,6 +22,7 @@
"core:window:allow-toggle-maximize",
"core:window:allow-close",
"core:window:allow-set-theme",
+ "core:webview:allow-set-webview-zoom",
"core:tray:default",
"process:default",
"deep-link:default",
diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.py
index 7ae9cb8f62a..a5762363503 100644
--- a/tests/studio/test_desktop_reliability_frontend_contract.py
+++ b/tests/studio/test_desktop_reliability_frontend_contract.py
@@ -33,6 +33,7 @@ SHEET = FRONTEND / "components/ui/sheet.tsx"
RESEARCH_ACTIVITY_PANEL = FRONTEND / "features/chat/components/research-activity-panel.tsx"
RESPONSE_DETAILS_SHEET = FRONTEND / "components/assistant-ui/message-response-details-sheet.tsx"
DOCUMENT_PREVIEW_SHEET = FRONTEND / "features/rag/components/document-preview-sheet.tsx"
+INTERFACE_SCALE_RUNTIME = FRONTEND / "features/settings/lib/interface-scale-runtime.ts"
NATIVE_DIALOGS = REPO / "studio/src-tauri/src/native_file_dialogs.rs"
NATIVE_CLIPBOARD = REPO / "studio/src-tauri/src/native_clipboard.rs"
TAURI_MAIN = REPO / "studio/src-tauri/src/main.rs"
@@ -72,13 +73,46 @@ IMAGE = FRONTEND / "components/assistant-ui/image.tsx"
AUDIO_PLAYER = FRONTEND / "components/assistant-ui/audio-player.tsx"
+def _scale_constants() -> dict[str, str]:
+ """The mac chrome constants, resolved to the strings provider.tsx puts in a style block.
+
+ ``NATIVE_MAC_TITLEBAR_HEIGHT_VAR`` is ``var(--studio-native-titlebar-height, 34px)``
+ built from ``NATIVE_MAC_TITLEBAR_HEIGHT_PX``. The runtime divides by the interface zoom
+ and provider.tsx uses the same constant as the CSS fallback, which is what keeps a
+ single 34 in the codebase, so read it from there rather than repeating it here.
+ """
+ source = INTERFACE_SCALE_RUNTIME.read_text(encoding = "utf-8")
+ numbers = dict(re.findall(r"export const (\w+_PX) = (\d+);", source))
+ return {
+ name: re.sub(r"\$\{(\w+)\}", lambda m: numbers.get(m.group(1), m.group(0)), body)
+ for name, body in re.findall(r"export const (\w+_VAR) = `([^`]+)`;", source)
+ }
+
+
def _chrome_style_blocks(source: str) -> dict[str, dict[str, str]]:
"""Each ``const <NAME>_STYLE = { ... } as CSSProperties`` block as a var -> value map.
Per block, so a value is only ever compared against the others that ship with it.
+
+ A value may be a string, a template, or one of the imported constants above. Before the
+ interface-scale setting they were all plain px strings; resolving the other two is what
+ keeps these contracts checking the same arithmetic instead of silently reading absent.
"""
+ constants = _scale_constants()
+
+ def resolve(raw: str) -> str:
+ raw = raw.strip()
+ if raw[:1] in ('"', "`"):
+ raw = raw[1:-1]
+ return re.sub(
+ r"\$\{(\w+)\}", lambda m: constants.get(m.group(1), m.group(0)), constants.get(raw, raw)
+ )
+
return {
- name: dict(re.findall(r'"(--[\w-]+)":\s*"([^"]+)"', body))
+ name: {
+ var: resolve(value)
+ for var, value in re.findall(r'"(--[\w-]+)":\s*(`[^`]*`|"[^"]*"|\w+)', body)
+ }
for name, body in re.findall(
r"const (\w+_STYLE) = \{(.*?)\} as CSSProperties;", source, re.S
)
@@ -92,9 +126,24 @@ def _titlebar_nav_button_px(source: str) -> int | None:
def _px(value: str | None) -> int | None:
- """*value* as whole pixels, or None if it is not a px literal (rem, calc, absent)."""
- match = re.fullmatch(r"(\d+)px", (value or "").strip())
- return int(match.group(1)) if match else None
+ """*value* as whole pixels at 100% interface scale, or None if it is not pixel-valued.
+
+ **At 100%, and only there.** The mac chrome vars carry their own px fallback and the
+ runtime divides that number by the webview zoom, because macOS draws the titlebar and
+ traffic lights at a size zoom does not touch. So every sum below is the arithmetic as
+ it ships at 100%, which is the scale these contracts were written against and the only
+ one a static read of the source can see.
+ """
+ text = (value or "").strip()
+ for pattern in (
+ r"(\d+)px",
+ r"var\(--[\w-]+,\s*(\d+)px\)",
+ ):
+ match = re.fullmatch(pattern, text)
+ if match:
+ return int(match.group(1))
+ match = re.fullmatch(r"calc\((\d+)px\s*\+\s*var\(--[\w-]+,\s*(\d+)px\)\)", text)
+ return int(match.group(1)) + int(match.group(2)) if match else None
def test_desktop_update_offer_remains_actionable_from_settings():
@@ -630,9 +679,17 @@ def test_collapsed_tauri_keeps_history_arrows_and_adds_new_chat_by_model_picker(
assert 'isTauri && !isMobile && !pinned && view.mode !== "compare"' in chat_page
assert "pl-[var(--studio-collapsed-chat-controls-inset,0.75rem)]" in chat_page
- assert '"--studio-collapsed-chat-controls-inset": "188px"' in APP_PROVIDER.read_text(
- encoding = "utf-8"
- )
+ # 188 is the number, not the spelling. It ships as `calc(110px + var(...78px))` so the
+ # traffic-light half can be divided by the interface zoom while the content half is
+ # not, and asserting the literal string is what broke when that landed. The custom
+ # titlebar sets the same var to its own much smaller inset, hence the mac-only filter.
+ insets = {
+ name: _px(values["--studio-collapsed-chat-controls-inset"])
+ for name, values in _chrome_style_blocks(APP_PROVIDER.read_text(encoding = "utf-8")).items()
+ if "--studio-mac-traffic-light-inset" in values
+ }
+ assert insets, "no style block sets both the traffic-light and collapsed-controls insets"
+ assert set(insets.values()) == {188}, insets
assert 'className="!size-[30px] rounded-[10px] text-muted-foreground"' in chat_page
assert 'aria-label="New chat"' in chat_page
new_chat_click = chat_page.index("onClick={handleDesktopNewChat}")