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.

Studio: add File and View menu items to the macOS desktop app (#11902)

Michael Han2f68ec3bee95
diff --git a/studio/frontend/src/app/app-menu-chords.ts b/studio/frontend/src/app/app-menu-chords.ts
new file mode 100644
index 00000000000..82b6934fbfb
--- /dev/null
+++ b/studio/frontend/src/app/app-menu-chords.ts
@@ -0,0 +1,100 @@
+// 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 {
+ formatBindingValue,
+ parseBinding,
+ SHORTCUT_SLOTS,
+ type ShortcutId,
+} from "@/features/settings/lib/keyboard-shortcuts";
+import {
+ resolveBinding,
+ shortcutOwningBinding,
+} from "@/features/settings/stores/keyboard-shortcuts-store";
+
+/** Actions the desktop File and View menus send (src-tauri/src/app_menu.rs). */
+export type AppMenuAction =
+ | "new-chat"
+ | "new-temporary-chat"
+ | "open-folder"
+ | "toggle-sidebar"
+ | "find"
+ | "previous-chat"
+ | "next-chat"
+ | "back"
+ | "forward"
+ | "zoom-in"
+ | "zoom-out"
+ | "actual-size";
+
+/** The chord each item shows (as in src-tauri/src/app_menu.rs). An item for a web shortcut follows
+ * that shortcut's binding; the others keep theirs unless a web shortcut has taken it. */
+export const MENU_CHORDS: Record<AppMenuAction, { shortcut?: ShortcutId; chord: string }> = {
+ "new-chat": { shortcut: "newChat", chord: "Mod+KeyN" },
+ "new-temporary-chat": { shortcut: "newTemporaryChat", chord: "Mod+Shift+KeyN" },
+ "open-folder": { chord: "Mod+KeyO" },
+ "toggle-sidebar": { shortcut: "toggleSidebar", chord: "Mod+KeyB" },
+ "find": { shortcut: "findInPage", chord: "Mod+KeyF" },
+ "previous-chat": { shortcut: "previousChat", chord: "Mod+Shift+BracketLeft" },
+ "next-chat": { shortcut: "nextChat", chord: "Mod+Shift+BracketRight" },
+ "back": { chord: "Mod+BracketLeft" },
+ "forward": { chord: "Mod+BracketRight" },
+ "zoom-in": { chord: "Mod+Equal" },
+ "zoom-out": { chord: "Mod+Minus" },
+ "actual-size": { chord: "Mod+Digit0" },
+};
+
+/** Chords the native macOS menu keeps (Quit, Close, Minimize, Hide, Hide Others, Edit, Enter
+ * Full Screen). Two items on one key equivalent means one silently loses, so ours skip them. */
+export const NATIVE_MENU_CHORDS: ReadonlySet<string> = new Set([
+ "Mod+KeyQ",
+ "Mod+KeyW",
+ "Mod+KeyM",
+ "Mod+KeyH",
+ "Mod+Alt+KeyH",
+ "Mod+KeyZ",
+ "Mod+Shift+KeyZ",
+ "Mod+KeyX",
+ "Mod+KeyC",
+ "Mod+KeyV",
+ "Mod+KeyA",
+ "Mod+Ctrl+KeyF",
+]);
+
+/** A binding as a native accelerator. Only Cmd or Ctrl chords, since a bare key there would take
+ * typing away from text fields, and none a native item already has. */
+function toAccelerator(value: string | null): string | null {
+ const binding = parseBinding(value);
+ if (!binding || !(binding.mod || binding.ctrl)) return null;
+ if (NATIVE_MENU_CHORDS.has(formatBindingValue(binding))) return null;
+ return [
+ binding.mod && "CmdOrCtrl",
+ binding.ctrl && "Ctrl",
+ binding.alt && "Alt",
+ binding.shift && "Shift",
+ binding.code,
+ ]
+ .filter(Boolean)
+ .join("+");
+}
+
+/** What each menu item should show for these shortcut overrides. */
+export function menuAccelerators(
+ overrides: Parameters<typeof resolveBinding>[0],
+): Record<AppMenuAction, string | null> {
+ const out = {} as Record<AppMenuAction, string | null>;
+ for (const action of Object.keys(MENU_CHORDS) as AppMenuAction[]) {
+ const { shortcut, chord } = MENU_CHORDS[action];
+ if (!shortcut) {
+ out[action] = shortcutOwningBinding(overrides, chord) ? null : toAccelerator(chord);
+ continue;
+ }
+ const owned = SHORTCUT_SLOTS.map((slot) => resolveBinding(overrides, shortcut, slot)).filter(
+ (value): value is string =>
+ Boolean(value) && shortcutOwningBinding(overrides, value) === shortcut,
+ );
+ const shown = owned.includes(chord) ? chord : owned.find((value) => toAccelerator(value));
+ out[action] = toAccelerator(shown ?? null);
+ }
+ return out;
+}
diff --git a/studio/frontend/src/app/desktop-shell-ready.ts b/studio/frontend/src/app/desktop-shell-ready.ts
new file mode 100644
index 00000000000..e9fe467d142
--- /dev/null
+++ b/studio/frontend/src/app/desktop-shell-ready.ts
@@ -0,0 +1,26 @@
+// 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 { useSyncExternalStore } from "react";
+
+// Whether the desktop app shows the app rather than its install, startup or recovery screen.
+// Always true on the web. Read by the root, which sits above the wrapper that knows.
+let ready = !isTauri;
+const listeners = new Set<() => void>();
+
+export function setDesktopShellReady(value: boolean): void {
+ if (ready === value) return;
+ ready = value;
+ listeners.forEach((listener) => listener());
+}
+
+export function useDesktopShellReady(): boolean {
+ return useSyncExternalStore(
+ (listener) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ () => ready,
+ );
+}
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsx
index 546b8586059..94d76803e14 100644
--- a/studio/frontend/src/app/provider.tsx
+++ b/studio/frontend/src/app/provider.tsx
@@ -49,6 +49,7 @@ import { useUiSpaceScale } from "@/hooks/use-ui-space-scale";
import { getToastOffsets } from "@/lib/toast-offset";
import { Z_LAYER } from "@/lib/z-layers";
import { useRouterState } from "@tanstack/react-router";
+import { setDesktopShellReady } from "./desktop-shell-ready";
import { MotionConfig } from "motion/react";
import {
type CSSProperties,
@@ -638,6 +639,12 @@ function TauriWrapper({ children }: { children: ReactNode }) {
const [nativeMacControlsHidden, setNativeMacControlsHidden] = useState(false);
const [appShellReady, setAppShellReady] = useState(false);
const canMountApp = status === "running" && desktopAuthReady;
+ // Same as showApp below: until the shell is ready the app sits hidden behind the startup screen.
+ useEffect(() => {
+ if (!isTauri) return;
+ setDesktopShellReady(canMountApp && appShellReady);
+ return () => setDesktopShellReady(false);
+ }, [canMountApp, appShellReady]);
// Readiness is delivered by the mounted AppReadinessBoundary, not the
// global reload-snapshot event: an obsolete async load cannot reveal us.
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index 1b71daefab0..92a3c2db5aa 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -19,7 +19,9 @@ import {
type ChatSearch,
clearNewChatDraft,
hydrateModelDisclaimerPreference,
+ openFolderAsProject,
StopRunningChatsDialog,
+ useOpeningFolder,
useChatRuntimeStore,
} from "@/features/chat";
import { useExportRuntimeLifecycle } from "@/features/export";
@@ -31,15 +33,22 @@ import { usePersonalizationSync } from "@/features/profile";
import { RemoteCodeConsentDialog } from "@/features/security";
import {
SettingsDialogMount,
+ stepInterfaceScale,
+ triggerShortcut,
+ useInterfaceScaleStore,
useSettingsDialogStore,
useShortcut,
+ useShortcutAvailable,
} from "@/features/settings";
import { useLowDiskNotice } from "@/features/settings/hooks/use-low-disk-notice";
import { useTrainingUnloadGuard } from "@/features/training";
import { TransformersUpgradeDialog } from "@/features/transformers-upgrade";
+import { useNativePathLeasesSupported } from "@/features/native-intents";
+import { useRagAvailabilityStore } from "@/features/rag";
import { useIsMobileShell } from "@/hooks/use-mobile";
import { useSidebarPin } from "@/hooks/use-sidebar-pin";
import { type TranslationKey, useT } from "@/i18n";
+import { isTauri } from "@/lib/api-base";
import {
Outlet,
createRootRoute,
@@ -62,6 +71,8 @@ import {
useState,
} from "react";
import { AppProvider } from "../provider";
+import { useDesktopShellReady } from "../desktop-shell-ready";
+import { useAppMenuActions } from "../use-app-menu-actions";
declare module "@tanstack/react-router" {
interface StaticDataRouteOption {
@@ -498,6 +509,49 @@ function RootLayout() {
enabled: routeShortcutEnabled,
});
+ // The desktop File and View menus. Open Folder links the folder, so it needs path leases and RAG.
+ const pathLeasesSupported = useNativePathLeasesSupported();
+ const ragUnavailable = useRagAvailabilityStore((s) => s.isUnavailable());
+ const openingFolder = useOpeningFolder();
+ const desktopShellReady = useDesktopShellReady();
+ // Menu items for web shortcuts are live exactly while a mounted handler would take them.
+ const sidebarMounted = useShortcutAvailable("toggleSidebar", isTauri);
+ const findMounted = useShortcutAvailable("findInPage", isTauri);
+ const previousChatMounted = useShortcutAvailable("previousChat", isTauri);
+ const nextChatMounted = useShortcutAvailable("nextChat", isTauri);
+ const viaShortcut = (id: Parameters<typeof triggerShortcut>[0], mounted: boolean) =>
+ mounted ? () => void triggerShortcut(id) : null;
+ const zoomBy = (direction: 1 | -1) => () => {
+ const scale = useInterfaceScaleStore.getState();
+ scale.setScale(stepInterfaceScale(scale.scale, direction));
+ };
+ useAppMenuActions({
+ "new-chat": routeShortcutEnabled ? () => startNewChat() : null,
+ "new-temporary-chat": routeShortcutEnabled
+ ? () => startNewChat({ incognito: true, standalone: true })
+ : null,
+ "open-folder":
+ routeShortcutEnabled && pathLeasesSupported && !ragUnavailable && !openingFolder
+ ? () =>
+ void openFolderAsProject().then((project) => {
+ if (!project) return;
+ const chatRuntime = useChatRuntimeStore.getState();
+ chatRuntime.setActiveThreadId(null);
+ chatRuntime.setActiveProjectId(project.id);
+ void navigate({ to: "/chat", search: { project: project.id } });
+ })
+ : null,
+ "toggle-sidebar": viaShortcut("toggleSidebar", sidebarMounted),
+ "find": viaShortcut("findInPage", findMounted),
+ "previous-chat": viaShortcut("previousChat", previousChatMounted),
+ "next-chat": viaShortcut("nextChat", nextChatMounted),
+ "back": routeShortcutEnabled ? () => window.history.back() : null,
+ "forward": routeShortcutEnabled ? () => window.history.forward() : null,
+ "zoom-in": zoomBy(1),
+ "zoom-out": zoomBy(-1),
+ "actual-size": () => useInterfaceScaleStore.getState().reset(),
+ }, desktopShellReady);
+
// Workspaces. The shell is mounted on every route, so the chords live here.
const goTo = (to: string) => () => void navigate({ to });
// Carry the frozen search back: a bare /chat is a fresh chat, so switching
diff --git a/studio/frontend/src/app/use-app-menu-actions.ts b/studio/frontend/src/app/use-app-menu-actions.ts
new file mode 100644
index 00000000000..45ecde91f8c
--- /dev/null
+++ b/studio/frontend/src/app/use-app-menu-actions.ts
@@ -0,0 +1,79 @@
+// 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 { useKeyboardShortcutsStore } from "@/features/settings";
+import { isMacPlatform } from "@/features/settings/lib/keyboard-shortcuts";
+import { isTauri } from "@/lib/api-base";
+import { useEffect, useMemo, useRef } from "react";
+import { type AppMenuAction, menuAccelerators } from "./app-menu-chords";
+
+export type { AppMenuAction } from "./app-menu-chords";
+
+// Only the macOS desktop app has these menus.
+const hasAppMenus = isTauri && isMacPlatform();
+
+// Serialized, so the unmount disable never lands before the sync it follows.
+let syncQueue: Promise<unknown> = Promise.resolve();
+function sync(
+ enabled: string[],
+ accelerators: Partial<Record<AppMenuAction, string | null>> = {},
+): void {
+ syncQueue = syncQueue
+ .then(() => import("@tauri-apps/api/core"))
+ .then(({ invoke }) => invoke("set_app_menu_actions", { enabled, accelerators }))
+ .catch(() => undefined);
+}
+
+/** Run app menu actions, and enable in the menu only those with a handler.
+ * A null handler leaves its item disabled, and so does every item while `ready` is false (the
+ * desktop app's install, startup or recovery screen). */
+export function useAppMenuActions(
+ handlers: Record<AppMenuAction, (() => void) | null>,
+ ready: boolean,
+): void {
+ const latest = useRef<Partial<typeof handlers>>(handlers);
+ useEffect(() => {
+ latest.current = ready ? handlers : {};
+ });
+ const enabled = ready
+ ? (Object.keys(handlers) as AppMenuAction[]).filter((action) => handlers[action]).join(",")
+ : "";
+ // Recomputed only when a binding changes. Joined so the effect re-runs only on a real change.
+ const overrides = useKeyboardShortcutsStore((s) => s.overrides);
+ const accelerators = useMemo(
+ () => (hasAppMenus ? JSON.stringify(menuAccelerators(overrides)) : "{}"),
+ [overrides],
+ );
+
+ useEffect(() => {
+ if (!hasAppMenus) return;
+ sync(enabled ? enabled.split(",") : [], JSON.parse(accelerators));
+ }, [enabled, accelerators]);
+
+ // Disable on unmount only. No chords sent, so the menu keeps its own.
+ useEffect(() => {
+ if (!hasAppMenus) return;
+ return () => sync([]);
+ }, []);
+
+ useEffect(() => {
+ if (!hasAppMenus) return;
+ let disposed = false;
+ let unlisten: (() => void) | undefined;
+ void import("@tauri-apps/api/event")
+ .then(({ listen }) =>
+ listen<AppMenuAction>("app-menu-action", ({ payload }) =>
+ latest.current[payload]?.(),
+ ),
+ )
+ .then((cleanup) => {
+ if (disposed) cleanup();
+ else unlisten = cleanup;
+ })
+ .catch(() => undefined);
+ return () => {
+ disposed = true;
+ unlisten?.();
+ };
+ }, []);
+}
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 4df7b3c664d..132b6d40db4 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -257,6 +257,7 @@ import { isAssistantLocalThreadId } from "./utils/thread-ids";
import {
consumeProjectSourcesPending,
hasProjectSourcesPending,
+ noteProjectLandingMounted,
} from "@/features/rag/components/project-source-dropzone";
import {
exportConversationCsv,
@@ -1369,6 +1370,7 @@ function ProjectLanding({
// Drop the marker once committed: React may replay the initializer above.
useEffect(() => {
consumeProjectSourcesPending(projectId);
+ return noteProjectLandingMounted(projectId);
}, [projectId]);
const [pendingNewThreadId, setPendingNewThreadId] = useState<string | null>(
null,
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 01a3c736b04..8351afc646f 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -56,6 +56,7 @@ export {
type Preset,
} from "./chat-settings-sheet";
export { useChatRuntimeStore } from "./stores/chat-runtime-store";
+export { openFolderAsProject, useOpeningFolder } from "./utils/open-folder-as-project";
export {
hydrateModelDisclaimerPreference,
refreshModelDisclaimerPreference,
diff --git a/studio/frontend/src/features/chat/utils/open-folder-as-project.ts b/studio/frontend/src/features/chat/utils/open-folder-as-project.ts
new file mode 100644
index 00000000000..25a884e8361
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/open-folder-as-project.ts
@@ -0,0 +1,81 @@
+// 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 { pickNativeDocumentFolder } from "@/features/native-intents";
+import {
+ announceProjectSourcesUpdated,
+ createLinkedFolder,
+ noteProjectWork,
+ watchProjectFolderJob,
+} from "@/features/rag/api/rag-api";
+import {
+ isProjectLandingMounted,
+ markProjectSourcesPending,
+} from "@/features/rag/components/project-source-dropzone";
+import { toast } from "@/lib/toast";
+import { useSyncExternalStore } from "react";
+import { createChatProject } from "../hooks/use-chat-projects";
+import type { ProjectRecord } from "../types";
+
+let opening = false;
+const openingListeners = new Set<() => void>();
+
+function setOpening(value: boolean): void {
+ opening = value;
+ openingListeners.forEach((listener) => listener());
+}
+
+/** True from the picker until the folder is linked, so the menu item can stay disabled. */
+export function useOpeningFolder(): boolean {
+ return useSyncExternalStore(
+ (listener) => {
+ openingListeners.add(listener);
+ return () => openingListeners.delete(listener);
+ },
+ () => opening,
+ );
+}
+
+/** File > Open Folder: pick a folder, make a project named after it with the folder linked, and
+ * land on its Sources. Resolves to the project, even when only the link failed, or null when
+ * cancelled or no project was made. */
+export async function openFolderAsProject(): Promise<ProjectRecord | null> {
+ if (opening) return null;
+ setOpening(true);
+ try {
+ const selected = await pickNativeDocumentFolder();
+ if (!selected) return null;
+ const project = await createChatProject(selected.displayName);
+ // Before the link: the sidebar can already open the project, and should open it on Sources.
+ markProjectSourcesPending(project.id);
+ noteProjectWork(project.id, 1);
+ try {
+ const { job } = await createLinkedFolder(
+ { type: "project", id: project.id },
+ selected.token,
+ selected.displayName,
+ );
+ watchProjectFolderJob(project.id, job.id);
+ announceProjectSourcesUpdated(project.id);
+ } catch (error) {
+ // Kept, not deleted: chats may have joined it meanwhile, and deleting a project deletes
+ // them. Its Sources has Link folder to retry.
+ toast.error("Could not link folder", {
+ description: error instanceof Error ? error.message : String(error),
+ });
+ } finally {
+ noteProjectWork(project.id, -1);
+ }
+ // Opened and left during the link, the first visit spent the marker, so renew it for the
+ // navigation that follows. Not while it is on screen: nothing would read it until next time.
+ if (!isProjectLandingMounted(project.id)) markProjectSourcesPending(project.id);
+ return project;
+ } catch (error) {
+ toast.error("Could not open folder", {
+ description: error instanceof Error ? error.message : String(error),
+ });
+ return null;
+ } finally {
+ setOpening(false);
+ }
+}
diff --git a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx b/studio/frontend/src/features/rag/components/project-source-dropzone.tsx
index 694fdd8631e..e571e6f3118 100644
--- a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx
+++ b/studio/frontend/src/features/rag/components/project-source-dropzone.tsx
@@ -53,7 +53,7 @@ function formatSize(bytes: number): string {
// Projects created with staged files, so the landing can open on Sources.
const projectsWithPendingSources = new Set<string>();
-function markProjectSourcesPending(projectId: string): void {
+export function markProjectSourcesPending(projectId: string): void {
projectsWithPendingSources.add(projectId);
}
@@ -68,6 +68,23 @@ export function consumeProjectSourcesPending(projectId: string): void {
projectsWithPendingSources.delete(projectId);
}
+// Landings mounted now, counted, so a caller can tell whether a marker would still be read.
+const mountedProjectLandings = new Map<string, number>();
+
+/** Call from the landing's mount effect; returns the cleanup. */
+export function noteProjectLandingMounted(projectId: string): () => void {
+ mountedProjectLandings.set(projectId, (mountedProjectLandings.get(projectId) ?? 0) + 1);
+ return () => {
+ const count = (mountedProjectLandings.get(projectId) ?? 1) - 1;
+ if (count > 0) mountedProjectLandings.set(projectId, count);
+ else mountedProjectLandings.delete(projectId);
+ };
+}
+
+export function isProjectLandingMounted(projectId: string): boolean {
+ return mountedProjectLandings.has(projectId);
+}
+
/** Upload staged files to a new project. Indexing runs in the background; a
* per-file failure toasts and never blocks project creation. */
export async function uploadStagedSources(
diff --git a/studio/frontend/src/features/settings/hooks/use-shortcut.ts b/studio/frontend/src/features/settings/hooks/use-shortcut.ts
index 4bef4be4054..e455e62284a 100644
--- a/studio/frontend/src/features/settings/hooks/use-shortcut.ts
+++ b/studio/frontend/src/features/settings/hooks/use-shortcut.ts
@@ -1,7 +1,7 @@
// 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 { useEffect, useMemo, useRef } from "react";
+import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
import {
SHORTCUT_SLOTS,
type ShortcutBinding,
@@ -115,6 +115,71 @@ export interface UseShortcutOptions {
claims?: () => boolean;
}
+/** A mounted handler, for running an action without its chord (the desktop menu). */
+export interface ShortcutTrigger {
+ /** The handler's `claims`, asked the same way a key press asks it. */
+ claims: () => boolean;
+ run: () => void;
+}
+
+/** Newest last. */
+const triggers = new Map<ShortcutId, ShortcutTrigger[]>();
+const triggerListeners = new Set<() => void>();
+const notifyTriggerListeners = () => triggerListeners.forEach((listener) => listener());
+
+/** Exported for the test. Returns the unregister. */
+export function registerShortcutTrigger(
+ id: ShortcutId,
+ trigger: ShortcutTrigger,
+): () => void {
+ triggers.set(id, [...(triggers.get(id) ?? []), trigger]);
+ notifyTriggerListeners();
+ return () => {
+ triggers.set(id, (triggers.get(id) ?? []).filter((t) => t !== trigger));
+ notifyTriggerListeners();
+ };
+}
+
+/** Run `id` as if its chord were pressed, minus the key checks. False when nothing took it. */
+export function triggerShortcut(id: ShortcutId): boolean {
+ const trigger = [...(triggers.get(id) ?? [])].reverse().find((t) => t.claims());
+ trigger?.run();
+ return trigger !== undefined;
+}
+
+// Claims mostly ask whether a modal covers the surface, which shows as aria-hidden or inert.
+let modalObserver: MutationObserver | null = null;
+function subscribeTriggers(listener: () => void, watchModals: boolean): () => void {
+ triggerListeners.add(listener);
+ if (watchModals && !modalObserver && typeof MutationObserver !== "undefined") {
+ modalObserver = new MutationObserver(notifyTriggerListeners);
+ modalObserver.observe(document.documentElement, {
+ subtree: true,
+ attributes: true,
+ attributeFilter: ["aria-hidden", "inert"],
+ });
+ }
+ return () => {
+ triggerListeners.delete(listener);
+ if (triggerListeners.size === 0) {
+ modalObserver?.disconnect();
+ modalObserver = null;
+ }
+ };
+}
+
+/** Whether a mounted handler would take `id` right now, claims included. `watchModals` also
+ * re-asks when a modal opens or closes; the desktop menu passes it, the web has no use for it. */
+export function useShortcutAvailable(id: ShortcutId, watchModals: boolean): boolean {
+ const subscribe = useCallback(
+ (listener: () => void) => subscribeTriggers(listener, watchModals),
+ [watchModals],
+ );
+ return useSyncExternalStore(subscribe, () =>
+ (triggers.get(id) ?? []).some((t) => t.claims()),
+ );
+}
+
/** The chords `id` answers to now, joined so the effect re-runs only on a real change. */
function useBindingValues(id: ShortcutId): string {
return useKeyboardShortcutsStore((s) =>
@@ -167,6 +232,15 @@ export function useShortcut(
const latestRef = useRef({ handler, claims });
latestRef.current = { handler, claims };
+ // Registered even with no chord bound: the menu still reaches the action.
+ useEffect(() => {
+ if (!enabled) return;
+ return registerShortcutTrigger(id, {
+ claims: () => latestRef.current.claims?.() !== false,
+ run: () => latestRef.current.handler(new KeyboardEvent("keydown")),
+ });
+ }, [id, enabled]);
+
useEffect(() => {
if (bindings.length === 0 || !enabled) return;
const onKeyDown = (event: KeyboardEvent) => {
diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.ts
index 0b52a045a21..ca1b14d0562 100644
--- a/studio/frontend/src/features/settings/index.ts
+++ b/studio/frontend/src/features/settings/index.ts
@@ -55,6 +55,7 @@ export type {
export { useMonitorOverlayStore } from "./stores/monitor-overlay-store";
export {
applyInterfaceScale,
+ stepInterfaceScale,
useInterfaceScaleStore,
} from "./stores/interface-scale-store";
// The runtime module, not the store, so consumers outside this feature do not have to pull
@@ -79,9 +80,11 @@ export {
isImeComposing,
isSurfaceBackgrounded,
isSurfaceInForeground,
+ triggerShortcut,
useShortcut,
useShortcutLabel,
useShortcutLabels,
+ useShortcutAvailable,
} from "./hooks/use-shortcut";
export { Shortcut } from "./components/shortcut";
export {
diff --git a/studio/frontend/src/features/settings/stores/interface-scale-store.ts b/studio/frontend/src/features/settings/stores/interface-scale-store.ts
index 59e97210267..1e176d72466 100644
--- a/studio/frontend/src/features/settings/stores/interface-scale-store.ts
+++ b/studio/frontend/src/features/settings/stores/interface-scale-store.ts
@@ -65,6 +65,18 @@ export function interfaceScaleToZoom(scale: number): number {
return sanitizeInterfaceScale(scale) / 100;
}
+/** Zoom In and Zoom Out stops, the ones browsers use. */
+export const INTERFACE_ZOOM_STEPS = [50, 67, 75, 80, 90, 100, 110, 125, 150, 175, 200] as const;
+
+/** The next stop past `scale` in `direction`, or `scale` itself at either end. */
+export function stepInterfaceScale(scale: number, direction: 1 | -1): number {
+ const next =
+ direction > 0
+ ? INTERFACE_ZOOM_STEPS.find((step) => step > scale)
+ : [...INTERFACE_ZOOM_STEPS].reverse().find((step) => step < scale);
+ return next ?? scale;
+}
+
interface InterfaceScaleState {
scale: number;
setScale: (scale: number) => void;
diff --git a/studio/frontend/tests/desktop-app-menus.test.ts b/studio/frontend/tests/desktop-app-menus.test.ts
new file mode 100644
index 00000000000..7c1ec5c5f08
--- /dev/null
+++ b/studio/frontend/tests/desktop-app-menus.test.ts
@@ -0,0 +1,265 @@
+// 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 { readSrc, readText, registerBundlerResolver } from "./helpers/kit.ts";
+
+// The menu is native and the hook is React, so the contract between them is asserted on source.
+const APP_MENU = readText("../../src-tauri/src/app_menu.rs");
+const MAIN_RS = readText("../../src-tauri/src/main.rs");
+const HOOK = readSrc("app/use-app-menu-actions.ts");
+const CHORDS = readSrc("app/app-menu-chords.ts");
+const ROOT = readSrc("app/routes/__root.tsx");
+
+const rowsOf = (table: string) =>
+ [...APP_MENU.match(new RegExp(`const ${table}: &\\[Row\\] = &\\[([\\s\\S]*?)\\];`))![1].matchAll(
+ /Row::Action\(\s*"([a-z-]+)"/g,
+ )].map((m) => m[1]);
+const fileActions = rowsOf("FILE_ROWS");
+const viewActions = rowsOf("VIEW_ROWS");
+const rustActions = [...fileActions, ...viewActions];
+const hookActions = [...CHORDS.match(/export type AppMenuAction =([^;]+);/)![1].matchAll(/"([a-z-]+)"/g)].map(
+ (m) => m[1],
+);
+
+test("the menus and the renderer name the same actions", () => {
+ assert.deepEqual(fileActions, ["new-chat", "new-temporary-chat", "open-folder"]);
+ assert.deepEqual(viewActions, [
+ "toggle-sidebar",
+ "find",
+ "previous-chat",
+ "next-chat",
+ "back",
+ "forward",
+ "zoom-in",
+ "zoom-out",
+ "actual-size",
+ ]);
+ assert.deepEqual([...hookActions].sort(), [...rustActions].sort());
+});
+
+test("every action is handled in the app shell", () => {
+ for (const action of rustActions) {
+ assert.ok(ROOT.includes(`"${action}":`), `__root.tsx handles ${action}`);
+ }
+});
+
+test("both sides use the same event and command names", () => {
+ assert.match(APP_MENU, /APP_MENU_ACTION_EVENT: &str = "app-menu-action"/);
+ assert.match(HOOK, /listen<AppMenuAction>\("app-menu-action"/);
+ assert.match(HOOK, /invoke\("set_app_menu_actions"/);
+ assert.match(MAIN_RS, /app_menu::set_app_menu_actions,/);
+});
+
+test("items start disabled and the renderer disables them when it goes away", () => {
+ assert.match(APP_MENU, /\.enabled\(false\)/);
+ assert.match(HOOK, /return \(\) => sync\(\[\]\)/);
+});
+
+test("the shortcuts shown match the web shortcuts they stand for", () => {
+ const shortcuts = readSrc("features/settings/lib/keyboard-shortcuts.ts");
+ assert.match(APP_MENU, /"New Chat", "CmdOrCtrl\+N"/);
+ assert.match(shortcuts, /def\("newChat", "Mod\+Shift\+KeyO", \{ defaultAlternateBinding: "Mod\+KeyN" \}\)/);
+ assert.match(APP_MENU, /"New Temporary Chat",\s*"CmdOrCtrl\+Shift\+N"/);
+ assert.match(shortcuts, /def\("newTemporaryChat", "Mod\+Shift\+KeyN"\)/);
+ // No web shortcut owns Cmd+O, so the menu's is free.
+ assert.doesNotMatch(shortcuts, /"Mod\+KeyO"/);
+});
+
+test("View items for web shortcuts show the chord the web shortcut uses", () => {
+ const shortcuts = readSrc("features/settings/lib/keyboard-shortcuts.ts");
+ const pairs: [string, string, string, string][] = [
+ ["toggle-sidebar", "CmdOrCtrl+B", "toggleSidebar", "Mod+KeyB"],
+ ["find", "CmdOrCtrl+F", "findInPage", "Mod+KeyF"],
+ ["previous-chat", "CmdOrCtrl+Shift+[", "previousChat", "Mod+Shift+BracketLeft"],
+ ["next-chat", "CmdOrCtrl+Shift+]", "nextChat", "Mod+Shift+BracketRight"],
+ ];
+ for (const [action, accelerator, id, binding] of pairs) {
+ const row = new RegExp(`Row::Action\\(\\s*"${action}",\\s*"[^"]+",\\s*"([^"]+)"`);
+ assert.equal(APP_MENU.match(row)?.[1], accelerator, action);
+ assert.match(shortcuts, new RegExp(`def\\("${id}", "${binding.replace(/\+/g, "\\+")}"`));
+ assert.ok(ROOT.includes(`viaShortcut("${id}"`), `${action} runs ${id}`);
+ }
+ // The rest have no web shortcut, so the menu's chords take no key from one.
+ for (const binding of ["Mod+BracketLeft", "Mod+BracketRight", "Mod+Equal", "Mod+Minus", "Mod+Digit0"]) {
+ assert.doesNotMatch(shortcuts, new RegExp(`"${binding.replace(/\+/g, "\\+")}"`));
+ }
+});
+
+test("View keeps the native Enter Full Screen below the Unsloth items", () => {
+ assert.match(APP_MENU, /for item in &native \{\s*submenu\.append\(item\)\?;/);
+});
+
+test("Close keeps the native close so Cmd+W still reaches the window's close handling", () => {
+ assert.match(APP_MENU, /PredefinedMenuItem::close_window\(app, Some\("Close"\)\)/);
+});
+
+test("Open Folder lands on the new project's Sources, not its chats", () => {
+ const openFolder = readSrc("features/chat/utils/open-folder-as-project.ts");
+ const landing = readSrc("features/chat/chat-page.tsx");
+ // Marked as soon as the project exists, before the link: the sidebar can open it meanwhile.
+ const marked = openFolder.indexOf("markProjectSourcesPending(project.id)");
+ assert.ok(marked > openFolder.indexOf("await createChatProject("));
+ assert.ok(marked < openFolder.indexOf("await createLinkedFolder("));
+ assert.match(landing, /hasProjectSourcesPending\(projectId\) \? "sources" : "chats"/);
+ // A failed link keeps the project: deleting it would delete chats that joined it meanwhile.
+ assert.doesNotMatch(openFolder, /deleteChatProject/);
+ // Keyed by project, so a new project mounts fresh and reads the marker.
+ assert.match(landing, /<ProjectLanding\s+key=\{baseView\.projectId\}/);
+});
+
+test("Open Folder still lands on Sources after a visit during the link", () => {
+ const dropzone = readSrc("features/rag/components/project-source-dropzone.tsx");
+ const openFolder = readSrc("features/chat/utils/open-folder-as-project.ts");
+ const landing = readSrc("features/chat/chat-page.tsx");
+ const m = new Function(
+ `${stripTypeScriptTypes(dropzone.slice(dropzone.indexOf("const projectsWithPendingSources"), dropzone.indexOf("/** Upload staged files"))).replace(/^export /gm, "")}
+ return { markProjectSourcesPending, hasProjectSourcesPending, consumeProjectSourcesPending, noteProjectLandingMounted, isProjectLandingMounted };`,
+ )();
+ // The landing's mount effect, and the rule Open Folder applies once the link settles.
+ const mount = (id: string) => (m.consumeProjectSourcesPending(id), m.noteProjectLandingMounted(id));
+ const settle = (id: string) => {
+ if (!m.isProjectLandingMounted(id)) m.markProjectSourcesPending(id);
+ };
+ assert.match(landing, /consumeProjectSourcesPending\(projectId\);\s*return noteProjectLandingMounted\(projectId\);/);
+ assert.match(openFolder, /if \(!isProjectLandingMounted\(project\.id\)\) markProjectSourcesPending\(project\.id\);/);
+
+ // Opened during the link, then left: the completion navigation still lands on Sources.
+ m.markProjectSourcesPending("a");
+ const leave = mount("a");
+ leave();
+ settle("a");
+ assert.equal(m.hasProjectSourcesPending("a"), true);
+
+ // Still on it when the link settles: no marker left over for a later visit.
+ m.markProjectSourcesPending("b");
+ mount("b");
+ settle("b");
+ assert.equal(m.hasProjectSourcesPending("b"), false);
+
+ // Never opened: the first marker is simply still there.
+ m.markProjectSourcesPending("c");
+ settle("c");
+ assert.equal(m.hasProjectSourcesPending("c"), true);
+});
+
+test("every menu item stays disabled while the desktop app is not showing the app", () => {
+ const hook = readSrc("app/use-app-menu-actions.ts");
+ const provider = readSrc("app/provider.tsx");
+ // The root sits above TauriWrapper, so the wrapper publishes whether the app is mounted.
+ // Published as the same predicate that reveals the app, not just "backend up".
+ assert.match(provider, /setDesktopShellReady\(canMountApp && appShellReady\);\s*return \(\) => setDesktopShellReady\(false\);/);
+ assert.match(provider, /const showApp = canMountApp && appShellReady;/);
+ assert.match(ROOT, /\}, desktopShellReady\);/);
+ assert.match(hook, /const enabled = ready\s*\?/);
+ assert.match(hook, /latest\.current = ready \? handlers : \{\};/);
+});
+
+test("Open Folder is disabled until the open in progress finishes", () => {
+ const openFolder = readSrc("features/chat/utils/open-folder-as-project.ts");
+ assert.match(openFolder, /if \(opening\) return null;\s*setOpening\(true\);/);
+ assert.match(openFolder, /\} finally \{\s*setOpening\(false\);/);
+ assert.match(ROOT, /pathLeasesSupported && !ragUnavailable && !openingFolder/);
+});
+
+test("menu triggers reach the newest mounted handler that claims the action", async () => {
+ registerBundlerResolver();
+ const { registerShortcutTrigger, triggerShortcut } = await import(
+ "../src/features/settings/hooks/use-shortcut.ts"
+ );
+ const calls: string[] = [];
+ assert.equal(triggerShortcut("toggleSidebar"), false, "nothing mounted");
+ const offOld = registerShortcutTrigger("toggleSidebar", {
+ claims: () => true,
+ run: () => calls.push("old"),
+ });
+ const offNew = registerShortcutTrigger("toggleSidebar", {
+ claims: () => false,
+ run: () => calls.push("declined"),
+ });
+ // The newest declines (its claims() said no), so the older one runs, and only once.
+ assert.equal(triggerShortcut("toggleSidebar"), true);
+ assert.deepEqual(calls, ["old"]);
+ offOld();
+ assert.equal(triggerShortcut("toggleSidebar"), false, "only a declining handler left");
+ offNew();
+ assert.equal(triggerShortcut("toggleSidebar"), false, "unregistered");
+});
+
+test("menu chords follow the user's bindings and never steal a web shortcut's chord", async () => {
+ registerBundlerResolver();
+ const { menuAccelerators } = await import("../src/app/app-menu-chords.ts");
+ const defaults = menuAccelerators({});
+ // The defaults match what the native menu is built with.
+ const rustAccel = (action: string) =>
+ APP_MENU.match(new RegExp(`Row::Action\\(\\s*"${action}",\\s*"[^"]+",\\s*"([^"]+)"`))?.[1];
+ const native = (accel: string) =>
+ accel
+ .replace(/\+([A-Z])$/, "+Key$1")
+ .replace(/\+(\d)$/, "+Digit$1")
+ .replace("+[", "+BracketLeft")
+ .replace("+]", "+BracketRight")
+ .replace("+=", "+Equal")
+ .replace(/\+-$/, "+Minus");
+ for (const action of rustActions) {
+ assert.equal(defaults[action as keyof typeof defaults], native(rustAccel(action)!), action);
+ }
+ // Rebound: the item shows the new chord.
+ assert.equal(
+ menuAccelerators({ toggleSidebar: { primary: "Mod+KeyJ" } } as never)["toggle-sidebar"],
+ "CmdOrCtrl+KeyJ",
+ );
+ // Cleared: no chord, so the menu does not keep answering the old one.
+ assert.equal(
+ menuAccelerators({ findInPage: { primary: null } } as never)["find"],
+ null,
+ );
+ // A fixed item whose chord a web shortcut now owns gives it up.
+ assert.equal(
+ menuAccelerators({ findInPage: { primary: "Mod+KeyO" } } as never)["open-folder"],
+ null,
+ );
+ // A chord a native item keeps is never doubled, and a usable second binding is shown instead.
+ assert.equal(
+ menuAccelerators({ toggleSidebar: { primary: "Mod+KeyW" } } as never)["toggle-sidebar"],
+ null,
+ );
+ assert.equal(
+ menuAccelerators({ findInPage: { primary: "Mod+KeyM", alternate: "Mod+KeyJ" } } as never)["find"],
+ "CmdOrCtrl+KeyJ",
+ );
+ // The list matches what the native menu actually holds: Tauri's default items plus our Quit.
+ assert.match(MAIN_RS, /MenuItemBuilder::with_id\(APP_QUIT_MENU_ID, "Quit Unsloth"\)\s*\.accelerator\("CmdOrCtrl\+Q"\)/);
+ const { MENU_CHORDS, NATIVE_MENU_CHORDS } = await import("../src/app/app-menu-chords.ts");
+ for (const { chord } of Object.values(MENU_CHORDS)) {
+ assert.ok(!NATIVE_MENU_CHORDS.has(chord), `${chord} is not a native chord`);
+ }
+ // A chord without Cmd or Ctrl never reaches the menu, which would take it from text fields.
+ assert.equal(
+ menuAccelerators({ toggleSidebar: { primary: "Alt+KeyB" } } as never)["toggle-sidebar"],
+ null,
+ );
+});
+
+test("menu items for web shortcuts follow a mounted handler, and honour claims", () => {
+ const hook = readSrc("features/settings/hooks/use-shortcut.ts");
+ // Registered on `enabled` alone, so a cleared chord still leaves the menu item working.
+ assert.match(hook, /if \(!enabled\) return;\s*return registerShortcutTrigger\(id, \{\s*claims: \(\) => latestRef\.current\.claims\?\.\(\) !== false,/);
+ // Availability asks claims(), and the root has it re-ask when a modal opens or closes.
+ assert.match(hook, /\(triggers\.get\(id\) \?\? \[\]\)\.some\(\(t\) => t\.claims\(\)\)/);
+ assert.match(hook, /attributeFilter: \["aria-hidden", "inert"\]/);
+ for (const id of ["toggleSidebar", "findInPage", "previousChat", "nextChat"]) {
+ assert.ok(ROOT.includes(`useShortcutAvailable("${id}", isTauri)`), `${id} enables its item`);
+ }
+});
+
+test("Back and Forward follow page history, and zoom steps the interface scale", () => {
+ assert.match(ROOT, /"back": routeShortcutEnabled \? \(\) => window\.history\.back\(\) : null/);
+ assert.match(ROOT, /"forward": routeShortcutEnabled \? \(\) => window\.history\.forward\(\) : null/);
+ assert.match(ROOT, /"zoom-in": zoomBy\(1\)/);
+ assert.match(ROOT, /"zoom-out": zoomBy\(-1\)/);
+ assert.match(ROOT, /"actual-size": \(\) => useInterfaceScaleStore\.getState\(\)\.reset\(\)/);
+});
diff --git a/studio/frontend/tests/interface-zoom-steps.test.ts b/studio/frontend/tests/interface-zoom-steps.test.ts
new file mode 100644
index 00000000000..ea194d3eea5
--- /dev/null
+++ b/studio/frontend/tests/interface-zoom-steps.test.ts
@@ -0,0 +1,41 @@
+// 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 { readSrc } from "./helpers/kit.ts";
+
+// The store pulls in zustand persist and Tauri, so the stepping is lifted out and run on its own.
+const STORE = readSrc("features/settings/stores/interface-scale-store.ts");
+const steps = JSON.parse(STORE.match(/INTERFACE_ZOOM_STEPS = (\[[^\]]+\])/)![1]) as number[];
+const range = STORE.match(/min: (\d+),\s*max: (\d+),\s*default: (\d+)/)!.slice(1).map(Number);
+const stepInterfaceScale = (scale: number, direction: 1 | -1): number =>
+ (direction > 0
+ ? steps.find((step) => step > scale)
+ : [...steps].reverse().find((step) => step < scale)) ?? scale;
+
+test("the stops cover the whole range and include the default", () => {
+ const [min, max, def] = range;
+ assert.equal(steps[0], min);
+ assert.equal(steps.at(-1), max);
+ assert.ok(steps.includes(def));
+ assert.deepEqual([...steps].sort((a, b) => a - b), steps);
+});
+
+test("zoom walks the stops and stops at the ends", () => {
+ assert.equal(stepInterfaceScale(100, 1), 110);
+ assert.equal(stepInterfaceScale(100, -1), 90);
+ assert.equal(stepInterfaceScale(200, 1), 200);
+ assert.equal(stepInterfaceScale(50, -1), 50);
+});
+
+test("a scale typed in Settings between stops moves to the nearest stop that way", () => {
+ assert.equal(stepInterfaceScale(105, 1), 110);
+ assert.equal(stepInterfaceScale(105, -1), 100);
+});
+
+test("the function the menu runs matches the one tested here", () => {
+ assert.match(STORE, /INTERFACE_ZOOM_STEPS\.find\(\(step\) => step > scale\)/);
+ assert.match(STORE, /\[\.\.\.INTERFACE_ZOOM_STEPS\]\.reverse\(\)\.find\(\(step\) => step < scale\)/);
+});
diff --git a/studio/src-tauri/src/app_menu.rs b/studio/src-tauri/src/app_menu.rs
new file mode 100644
index 00000000000..38264767d04
--- /dev/null
+++ b/studio/src-tauri/src/app_menu.rs
@@ -0,0 +1,196 @@
+//! The macOS File and View menus. Their actions run in the renderer, which enables only the ones
+//! it can handle right now, so they stay disabled through install, login and startup.
+
+#[cfg(target_os = "macos")]
+use tauri::{menu::MenuItem, Manager};
+
+/// Event the renderer listens for; the payload is the action name.
+#[cfg(target_os = "macos")]
+pub const APP_MENU_ACTION_EVENT: &str = "app-menu-action";
+
+/// A menu row: an action or a separator.
+#[cfg(target_os = "macos")]
+enum Row {
+ /// (action sent to the renderer, label, accelerator)
+ Action(&'static str, &'static str, &'static str),
+ Separator,
+}
+
+#[cfg(target_os = "macos")]
+const FILE_ROWS: &[Row] = &[
+ Row::Action("new-chat", "New Chat", "CmdOrCtrl+N"),
+ Row::Action(
+ "new-temporary-chat",
+ "New Temporary Chat",
+ "CmdOrCtrl+Shift+N",
+ ),
+ Row::Separator,
+ Row::Action("open-folder", "Open Folder\u{2026}", "CmdOrCtrl+O"),
+ Row::Separator,
+];
+
+#[cfg(target_os = "macos")]
+const VIEW_ROWS: &[Row] = &[
+ Row::Action("toggle-sidebar", "Toggle Sidebar", "CmdOrCtrl+B"),
+ Row::Separator,
+ Row::Action("find", "Find", "CmdOrCtrl+F"),
+ Row::Separator,
+ Row::Action("previous-chat", "Previous Chat", "CmdOrCtrl+Shift+["),
+ Row::Action("next-chat", "Next Chat", "CmdOrCtrl+Shift+]"),
+ Row::Action("back", "Back", "CmdOrCtrl+["),
+ Row::Action("forward", "Forward", "CmdOrCtrl+]"),
+ Row::Separator,
+ Row::Action("zoom-in", "Zoom In", "CmdOrCtrl+="),
+ Row::Action("zoom-out", "Zoom Out", "CmdOrCtrl+-"),
+ Row::Action("actual-size", "Actual Size", "CmdOrCtrl+0"),
+ Row::Separator,
+];
+
+/// Menu ids are the action names, prefixed so they cannot collide with other menu ids.
+#[cfg(target_os = "macos")]
+const ID_PREFIX: &str = "app-menu:";
+
+#[cfg(target_os = "macos")]
+struct ActionItem {
+ action: &'static str,
+ item: MenuItem<tauri::Wry>,
+ submenu: tauri::menu::Submenu<tauri::Wry>,
+ /// The chord it shows, which muda cannot report back.
+ accelerator: Option<String>,
+}
+
+/// The action items, replaced in place when a chord is cleared.
+#[cfg(target_os = "macos")]
+pub struct AppMenuActions(std::sync::Mutex<Vec<ActionItem>>);
+
+/// Put the Unsloth rows at the top of the File and View menus, keeping each menu's native items
+/// (Close, Enter Full Screen) below them.
+#[cfg(target_os = "macos")]
+pub fn setup_app_menus(
+ app: &tauri::App,
+ menu: &tauri::menu::Menu<tauri::Wry>,
+) -> Result<(), Box<dyn std::error::Error>> {
+ use tauri::menu::{MenuItemBuilder, PredefinedMenuItem};
+
+ let mut actions = Vec::new();
+ for (title, rows) in [("File", FILE_ROWS), ("View", VIEW_ROWS)] {
+ let Some(submenu) = menu.items()?.into_iter().find_map(|item| {
+ let submenu = item.as_submenu()?.clone();
+ (submenu.text().ok()? == title).then_some(submenu)
+ }) else {
+ continue;
+ };
+ let native = submenu.items()?;
+ for item in &native {
+ submenu.remove(item)?;
+ }
+ for row in rows {
+ match row {
+ Row::Action(action, label, accelerator) => {
+ let item = MenuItemBuilder::with_id(format!("{ID_PREFIX}{action}"), *label)
+ .accelerator(*accelerator)
+ .enabled(false)
+ .build(app)?;
+ submenu.append(&item)?;
+ actions.push(ActionItem {
+ action,
+ item,
+ submenu: submenu.clone(),
+ accelerator: Some(accelerator.to_string()),
+ });
+ }
+ Row::Separator => submenu.append(&PredefinedMenuItem::separator(app)?)?,
+ }
+ }
+ if title == "File" {
+ // The native close, so Cmd+W still goes through the window's close handling.
+ submenu.append(&PredefinedMenuItem::close_window(app, Some("Close"))?)?;
+ } else {
+ for item in &native {
+ submenu.append(item)?;
+ }
+ }
+ }
+ app.manage(AppMenuActions(std::sync::Mutex::new(actions)));
+ Ok(())
+}
+
+/// Forward a menu click to the renderer. Ignores ids this module does not own.
+#[cfg(target_os = "macos")]
+pub fn handle_menu_event(app: &tauri::AppHandle, id: &str) {
+ use tauri::Emitter;
+
+ let Some(action) = id.strip_prefix(ID_PREFIX) else {
+ return;
+ };
+ // The window may be hidden after Close; bring it back for the action to show.
+ crate::show_main_window(app);
+ if let Err(error) = app.emit_to("main", APP_MENU_ACTION_EVENT, action) {
+ log::warn!("Could not send menu action {action}: {error}");
+ }
+}
+
+/// Enable exactly the listed actions, and show the chord each is bound to now (None for none).
+/// A no-op where there are no app menus.
+#[tauri::command]
+pub fn set_app_menu_actions(
+ app: tauri::AppHandle,
+ enabled: Vec<String>,
+ accelerators: std::collections::HashMap<String, Option<String>>,
+) {
+ #[cfg(target_os = "macos")]
+ if let Some(actions) = app.try_state::<AppMenuActions>() {
+ let Ok(mut actions) = actions.0.lock() else {
+ return;
+ };
+ for entry in actions.iter_mut() {
+ if let Some(wanted) = accelerators.get(entry.action) {
+ if *wanted != entry.accelerator {
+ if let Err(error) = set_item_accelerator(&app, entry, wanted.as_deref()) {
+ log::warn!("Could not update the {} shortcut: {error}", entry.action);
+ }
+ }
+ }
+ let _ = entry
+ .item
+ .set_enabled(enabled.iter().any(|name| name == entry.action));
+ }
+ }
+ #[cfg(not(target_os = "macos"))]
+ let _ = (app, enabled, accelerators);
+}
+
+/// muda's `set_accelerator(None)` leaves the native key equivalent in place, so clearing one
+/// swaps in a fresh item without it. A chord muda cannot parse is cleared too.
+#[cfg(target_os = "macos")]
+fn set_item_accelerator(
+ app: &tauri::AppHandle,
+ entry: &mut ActionItem,
+ accelerator: Option<&str>,
+) -> tauri::Result<()> {
+ use tauri::menu::MenuItemBuilder;
+
+ if let Some(accelerator) = accelerator {
+ if entry.item.set_accelerator(Some(accelerator)).is_ok() {
+ entry.accelerator = Some(accelerator.to_string());
+ return Ok(());
+ }
+ }
+ if entry.accelerator.is_none() {
+ return Ok(());
+ }
+ let position = entry
+ .submenu
+ .items()?
+ .iter()
+ .position(|item| item.id() == entry.item.id())
+ .unwrap_or(0);
+ let fresh = MenuItemBuilder::with_id(entry.item.id().clone(), entry.item.text()?)
+ .enabled(entry.item.is_enabled()?)
+ .build(app)?;
+ entry.submenu.remove(&entry.item)?;
+ entry.submenu.insert(&fresh, position)?;
+ entry.item = fresh;
+ entry.accelerator = None;
+ Ok(())
+}
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index 5fe58264c69..7e8f06086ad 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -1,6 +1,7 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod app_layout;
+mod app_menu;
mod commands;
#[cfg(target_os = "linux")]
mod debian_update;
@@ -1610,10 +1611,13 @@ fn setup_quit_menu(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
.accelerator("CmdOrCtrl+Q")
.build(app)?;
app_menu.append(&quit)?;
+ app_menu::setup_app_menus(app, &menu)?;
app.set_menu(menu)?;
app.on_menu_event(|app, event| {
if event.id() == APP_QUIT_MENU_ID {
request_quit(app);
+ } else {
+ app_menu::handle_menu_event(app, event.id().as_ref());
}
});
Ok(())
@@ -2126,6 +2130,7 @@ fn main() {
.manage(new_close_to_tray_state())
.manage(native_file_dialogs::ChatImportRegistry::default())
.invoke_handler(tauri::generate_handler![
+ app_menu::set_app_menu_actions,
set_training_active,
set_renderer_activity,
app_layout::has_initialized_app_window_layout,