Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(desktop): open the Windows app menu from a title-bar icon (#20534)

Inneibf242b4337a0
diff --git a/apps/desktop/src/main/controllers/MenuCtr.ts b/apps/desktop/src/main/controllers/MenuCtr.ts
index 7728d8ea8f5..f9bd0151d6a 100644
--- a/apps/desktop/src/main/controllers/MenuCtr.ts
+++ b/apps/desktop/src/main/controllers/MenuCtr.ts
@@ -1,4 +1,8 @@
-import type { PopupContextMenuParams, PopupContextMenuResult } from '@lobechat/electron-client-ipc';
+import type {
+ AppMenuNode,
+ PopupContextMenuParams,
+ PopupContextMenuResult,
+} from '@lobechat/electron-client-ipc';
import { BrowserWindow } from 'electron';
import { getIpcContext } from '@/utils/ipc';
@@ -44,4 +48,16 @@ export default class MenuController extends ControllerModule {
closePopupContextMenu() {
return this.app.menuManager.closePopupContextMenu();
}
+
+ @IpcMethod()
+ getAppMenu(): AppMenuNode[] {
+ return this.app.menuManager.getAppMenu();
+ }
+
+ @IpcMethod()
+ invokeAppMenuItem(params: { id: string }) {
+ const context = getIpcContext();
+ const window = context ? BrowserWindow.fromWebContents(context.sender) : null;
+ return this.app.menuManager.invokeAppMenuItem(params.id, window, context?.sender);
+ }
}
diff --git a/apps/desktop/src/main/controllers/__tests__/MenuCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/MenuCtr.test.ts
index 9c28f17ad0c..0fe773faa5f 100644
--- a/apps/desktop/src/main/controllers/__tests__/MenuCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/MenuCtr.test.ts
@@ -26,10 +26,14 @@ const mockShowContextMenu = vi.fn();
const mockRebuildAppMenu = vi.fn();
const mockPopupContextMenu = vi.fn();
const mockClosePopupContextMenu = vi.fn();
+const mockGetAppMenu = vi.fn();
+const mockInvokeAppMenuItem = vi.fn();
const mockApp = {
menuManager: {
closePopupContextMenu: mockClosePopupContextMenu,
+ getAppMenu: mockGetAppMenu,
+ invokeAppMenuItem: mockInvokeAppMenuItem,
popupContextMenu: mockPopupContextMenu,
refreshMenus: mockRefreshMenus,
rebuildAppMenu: mockRebuildAppMenu,
@@ -140,4 +144,32 @@ describe('MenuController', () => {
expect(result).toEqual({ success: true });
});
});
+
+ describe('getAppMenu', () => {
+ it('returns the live application menu snapshot', () => {
+ const snapshot = [{ enabled: true, id: 'app-0', label: 'File', type: 'submenu' as const }];
+ mockGetAppMenu.mockReturnValueOnce(snapshot);
+
+ expect(menuController.getAppMenu()).toBe(snapshot);
+ expect(mockGetAppMenu).toHaveBeenCalled();
+ });
+ });
+
+ describe('invokeAppMenuItem', () => {
+ it('invokes the item on the window that opened the menu', () => {
+ const sender = {} as any;
+ const context = { event: { sender } as any, sender } as IpcContext;
+ const mockWindow = { id: 'window' };
+ fromWebContentsMock.mockReturnValueOnce(mockWindow);
+ mockInvokeAppMenuItem.mockReturnValueOnce({ success: true });
+
+ const result = runWithIpcContext(context, () =>
+ menuController.invokeAppMenuItem({ id: 'app-0-1' }),
+ );
+
+ expect(fromWebContentsMock).toHaveBeenCalledWith(sender);
+ expect(mockInvokeAppMenuItem).toHaveBeenCalledWith('app-0-1', mockWindow, sender);
+ expect(result).toEqual({ success: true });
+ });
+ });
});
diff --git a/apps/desktop/src/main/core/ui/MenuManager.ts b/apps/desktop/src/main/core/ui/MenuManager.ts
index fa73b0cf115..1c59308fcd5 100644
--- a/apps/desktop/src/main/core/ui/MenuManager.ts
+++ b/apps/desktop/src/main/core/ui/MenuManager.ts
@@ -1,12 +1,14 @@
import type {
+ AppMenuNode,
PopupContextMenuParams,
PopupContextMenuResult,
TrayNavigationSnapshot,
} from '@lobechat/electron-client-ipc';
-import type { BrowserWindow, Menu } from 'electron';
+import { type BrowserWindow, Menu, type WebContents } from 'electron';
import type { IMenuPlatform, MenuOptions } from '@/menus';
import { createMenuImpl } from '@/menus';
+import { serializeAppMenu } from '@/menus/appMenuSnapshot';
import { createLogger } from '@/utils/logger';
import type { App } from '../App';
@@ -57,6 +59,25 @@ export class MenuManager {
return { success: true };
}
+ getAppMenu(): AppMenuNode[] {
+ const menu = Menu.getApplicationMenu();
+ if (!menu) return [];
+
+ return serializeAppMenu(menu.items);
+ }
+
+ invokeAppMenuItem(
+ id: string,
+ window: BrowserWindow | null,
+ webContents?: WebContents,
+ ): { success: boolean } {
+ const item = Menu.getApplicationMenu()?.getMenuItemById(id);
+ if (!item || item.type === 'separator' || item.type === 'submenu') return { success: false };
+
+ item.click(undefined, window ?? undefined, webContents);
+ return { success: true };
+ }
+
/**
* Build tray menu (usually called by tray manager)
*/
diff --git a/apps/desktop/src/main/core/ui/__tests__/MenuManager.test.ts b/apps/desktop/src/main/core/ui/__tests__/MenuManager.test.ts
index 0d61c7a9ddd..ab3e6e096d4 100644
--- a/apps/desktop/src/main/core/ui/__tests__/MenuManager.test.ts
+++ b/apps/desktop/src/main/core/ui/__tests__/MenuManager.test.ts
@@ -1,3 +1,4 @@
+import { Menu } from 'electron';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { App } from '../../App';
@@ -7,6 +8,7 @@ import { MenuManager } from '../MenuManager';
vi.mock('electron', () => ({
Menu: {
buildFromTemplate: vi.fn(),
+ getApplicationMenu: vi.fn(),
setApplicationMenu: vi.fn(),
},
}));
@@ -348,4 +350,56 @@ describe('MenuManager', () => {
expect(trayMenu).toBe(mockMenu);
});
});
+
+ describe('application menu snapshot', () => {
+ it('serializes the live application menu', () => {
+ vi.mocked(Menu.getApplicationMenu).mockReturnValue({
+ items: [
+ {
+ accelerator: null,
+ checked: false,
+ enabled: true,
+ id: 'quit',
+ label: 'Quit',
+ type: 'normal',
+ visible: true,
+ },
+ ],
+ } as never);
+
+ expect(menuManager.getAppMenu()).toEqual([
+ { enabled: true, id: 'quit', label: 'Quit', type: 'normal' },
+ ]);
+ });
+
+ it('returns an empty menu when the application menu is not ready', () => {
+ vi.mocked(Menu.getApplicationMenu).mockReturnValue(null);
+
+ expect(menuManager.getAppMenu()).toEqual([]);
+ });
+
+ it('invokes the item on the window that opened the menu', () => {
+ const click = vi.fn();
+ const window = { id: 1 };
+ const contents = { id: 2 };
+ vi.mocked(Menu.getApplicationMenu).mockReturnValue({
+ getMenuItemById: (id: string) => (id === 'quit' ? { click, type: 'normal' } : null),
+ } as never);
+
+ expect(menuManager.invokeAppMenuItem('quit', window as never, contents as never)).toEqual({
+ success: true,
+ });
+ expect(click).toHaveBeenCalledWith(undefined, window, contents);
+ });
+
+ it('does not activate submenu rows', () => {
+ const click = vi.fn();
+ vi.mocked(Menu.getApplicationMenu).mockReturnValue({
+ getMenuItemById: () => ({ click, type: 'submenu' }),
+ } as never);
+
+ expect(menuManager.invokeAppMenuItem('file', null)).toEqual({ success: false });
+ expect(click).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/apps/desktop/src/main/menus/appMenuSnapshot.test.ts b/apps/desktop/src/main/menus/appMenuSnapshot.test.ts
new file mode 100644
index 00000000000..2baf36f99fa
--- /dev/null
+++ b/apps/desktop/src/main/menus/appMenuSnapshot.test.ts
@@ -0,0 +1,123 @@
+import type { MenuItemConstructorOptions } from 'electron';
+import { describe, expect, it } from 'vitest';
+
+import { type AppMenuItemSource, assignMenuIds, serializeAppMenu } from './appMenuSnapshot';
+
+const source = (overrides: Partial<AppMenuItemSource> = {}): AppMenuItemSource => ({
+ checked: false,
+ enabled: true,
+ id: 'item',
+ label: 'Item',
+ type: 'normal',
+ visible: true,
+ ...overrides,
+});
+
+describe('assignMenuIds', () => {
+ it('assigns path ids and keeps an id that is already set', () => {
+ const template: MenuItemConstructorOptions[] = [
+ {
+ label: 'File',
+ submenu: [
+ { label: 'New Tab' },
+ { type: 'separator' as const },
+ { id: 'prefs', label: 'Settings' },
+ ],
+ },
+ { type: 'separator' as const },
+ { label: 'Edit' },
+ ];
+
+ assignMenuIds(template);
+
+ expect(template[0]?.id).toBe('app-0');
+ expect(template[0]?.submenu?.[0]?.id).toBe('app-0-0');
+ expect(template[0]?.submenu?.[2]?.id).toBe('prefs');
+ expect(template[2]?.id).toBe('app-2');
+ });
+});
+
+describe('serializeAppMenu', () => {
+ it('keeps labelled submenus and skips hidden accelerator aliases', () => {
+ const nodes = serializeAppMenu([
+ source({
+ id: 'app-0',
+ label: 'File',
+ submenu: {
+ items: [
+ source({ accelerator: 'Ctrl+T', id: 'app-0-1', label: 'New Tab' }),
+ source({ id: '', label: '', type: 'separator' }),
+ source({ enabled: false, id: 'app-0-3', label: 'Checking for updates...' }),
+ ],
+ },
+ type: 'submenu',
+ }),
+ source({
+ id: 'app-2',
+ label: 'View',
+ submenu: {
+ items: [
+ source({ accelerator: 'CmdOrCtrl+=', id: 'zoom-in', label: 'Zoom In' }),
+ source({
+ accelerator: 'CmdOrCtrl+Plus',
+ id: 'zoom-in-alias',
+ label: 'Zoom In',
+ visible: false,
+ }),
+ ],
+ },
+ type: 'submenu',
+ }),
+ source({ checked: true, id: 'trace', label: 'Trace', type: 'checkbox' }),
+ source({ id: 'paste', label: 'Paste', role: 'paste' }),
+ ]);
+
+ expect(nodes).toEqual([
+ {
+ children: [
+ { accelerator: 'Ctrl+T', enabled: true, id: 'app-0-1', label: 'New Tab', type: 'normal' },
+ { type: 'separator', enabled: false, id: '', label: '' },
+ { enabled: false, id: 'app-0-3', label: 'Checking for updates...', type: 'normal' },
+ ],
+ enabled: true,
+ id: 'app-0',
+ label: 'File',
+ type: 'submenu',
+ },
+ {
+ children: [
+ {
+ accelerator: 'CmdOrCtrl+=',
+ enabled: true,
+ id: 'zoom-in',
+ label: 'Zoom In',
+ type: 'normal',
+ },
+ ],
+ enabled: true,
+ id: 'app-2',
+ label: 'View',
+ type: 'submenu',
+ },
+ { checked: true, enabled: true, id: 'trace', label: 'Trace', type: 'checkbox' },
+ { enabled: true, id: 'paste', label: 'Paste', role: 'paste', type: 'normal' },
+ ]);
+ });
+
+ it('drops separators that only surrounded hidden items', () => {
+ expect(
+ serializeAppMenu([
+ source({ id: 'a', label: 'A' }),
+ source({ id: '', label: '', type: 'separator' }),
+ source({ id: 'hidden', label: 'Hidden', visible: false }),
+ source({ id: '', label: '', type: 'separator' }),
+ source({ id: 'b', label: 'B' }),
+ source({ id: '', label: '', type: 'separator' }),
+ ]),
+ ).toEqual([
+ { enabled: true, id: 'a', label: 'A', type: 'normal' },
+ { enabled: false, id: '', label: '', type: 'separator' },
+ { enabled: true, id: 'b', label: 'B', type: 'normal' },
+ ]);
+ });
+});
diff --git a/apps/desktop/src/main/menus/appMenuSnapshot.ts b/apps/desktop/src/main/menus/appMenuSnapshot.ts
new file mode 100644
index 00000000000..88406ec17a4
--- /dev/null
+++ b/apps/desktop/src/main/menus/appMenuSnapshot.ts
@@ -0,0 +1,83 @@
+import type { AppMenuNode } from '@lobechat/electron-client-ipc';
+import type { MenuItemConstructorOptions } from 'electron';
+
+export interface AppMenuItemSource {
+ accelerator?: string | null;
+ checked: boolean;
+ enabled: boolean;
+ id: string;
+ label: string;
+ role?: string | null;
+ submenu?: { items: AppMenuItemSource[] };
+ type: AppMenuNode['type'] | 'header' | 'palette';
+ visible: boolean;
+}
+
+export const assignMenuIds = (template: MenuItemConstructorOptions[], prefix = 'app'): void => {
+ for (const [index, item] of template.entries()) {
+ if (item.type === 'separator') continue;
+
+ item.id ??= `${prefix}-${index}`;
+ if (Array.isArray(item.submenu)) assignMenuIds(item.submenu, item.id);
+ }
+};
+
+const collapseSeparators = (nodes: AppMenuNode[]): AppMenuNode[] => {
+ const collapsed: AppMenuNode[] = [];
+
+ for (const node of nodes) {
+ if (node.type !== 'separator') {
+ collapsed.push(node);
+ continue;
+ }
+
+ if (collapsed.length === 0 || collapsed.at(-1)?.type === 'separator') continue;
+ collapsed.push(node);
+ }
+
+ while (collapsed.at(-1)?.type === 'separator') collapsed.pop();
+
+ return collapsed;
+};
+
+export const serializeAppMenu = (items: AppMenuItemSource[]): AppMenuNode[] => {
+ const nodes: AppMenuNode[] = [];
+
+ for (const item of items) {
+ if (item.visible === false || item.type === 'header' || item.type === 'palette') continue;
+
+ if (item.type === 'separator') {
+ nodes.push({ enabled: false, id: '', label: '', type: 'separator' });
+ continue;
+ }
+
+ if (item.type === 'submenu') {
+ const children = serializeAppMenu(item.submenu?.items ?? []);
+ if (children.length === 0) continue;
+
+ nodes.push({
+ children,
+ enabled: item.enabled,
+ id: item.id,
+ label: item.label,
+ type: 'submenu',
+ });
+ continue;
+ }
+
+ const node: AppMenuNode = {
+ enabled: item.enabled,
+ id: item.id,
+ label: item.label,
+ type: item.type,
+ };
+
+ if (item.accelerator) node.accelerator = item.accelerator;
+ if (item.role) node.role = item.role;
+ if (item.type === 'checkbox' || item.type === 'radio') node.checked = item.checked;
+
+ nodes.push(node);
+ }
+
+ return collapseSeparators(nodes);
+};
diff --git a/apps/desktop/src/main/menus/impls/windows.test.ts b/apps/desktop/src/main/menus/impls/windows.test.ts
index a3df845ef5c..92ac8a398d0 100644
--- a/apps/desktop/src/main/menus/impls/windows.test.ts
+++ b/apps/desktop/src/main/menus/impls/windows.test.ts
@@ -139,6 +139,17 @@ describe('WindowsMenu', () => {
expect(menuLabels).toContain('Window');
expect(menuLabels).toContain('Help');
});
+
+ it('assigns ids the title bar menu can invoke', () => {
+ windowsMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const fileMenu = template.find((item: any) => item.label === 'File');
+ const newTab = fileMenu.submenu.find((item: any) => item.accelerator === 'Ctrl+T');
+
+ expect(fileMenu.id).toBe('app-0');
+ expect(newTab.id).toBe('app-0-1');
+ });
});
describe('buildContextMenu', () => {
diff --git a/apps/desktop/src/main/menus/impls/windows.ts b/apps/desktop/src/main/menus/impls/windows.ts
index ca5e36c7f0f..8ac0c26ce4e 100644
--- a/apps/desktop/src/main/menus/impls/windows.ts
+++ b/apps/desktop/src/main/menus/impls/windows.ts
@@ -8,6 +8,7 @@ import { app, clipboard, Menu, shell } from 'electron';
import { isDev } from '@/const/env';
import { HETERO_AGENT_DIR } from '@/const/heteroAgent';
+import { assignMenuIds } from '../appMenuSnapshot';
import { buildTrayMenuTemplate } from '../trayMenu';
import type { ContextMenuData, IMenuPlatform, MenuOptions } from '../types';
import { BaseMenuPlatform } from './BaseMenuPlatform';
@@ -18,6 +19,7 @@ export class WindowsMenu extends BaseMenuPlatform implements IMenuPlatform {
buildAndSetAppMenu(options?: MenuOptions): Menu {
const template = this.getAppMenuTemplate(options);
+ assignMenuIds(template);
this.appMenu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(this.appMenu);
return this.appMenu;
diff --git a/locales/en-US/electron.json b/locales/en-US/electron.json
index 7bafd88e0a7..c131cf6cfe1 100644
--- a/locales/en-US/electron.json
+++ b/locales/en-US/electron.json
@@ -13,6 +13,7 @@
"gateway.workspaceStatusUnavailable": "Workspace device status is temporarily unavailable",
"navigation.agentShare": "Share",
"navigation.agents": "Agents",
+ "navigation.appMenu": "App menu",
"navigation.apps": "Apps",
"navigation.channels": "Channels",
"navigation.chat": "Chat",
diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.json
index 34adc1e7e19..bf911b0964e 100644
--- a/locales/zh-CN/electron.json
+++ b/locales/zh-CN/electron.json
@@ -13,6 +13,7 @@
"gateway.workspaceStatusUnavailable": "暂时无法获取工作空间设备状态",
"navigation.agentShare": "分享",
"navigation.agents": "助手",
+ "navigation.appMenu": "应用菜单",
"navigation.apps": "应用",
"navigation.channels": "消息频道",
"navigation.chat": "对话",
diff --git a/packages/electron-client-ipc/src/types/appMenu.ts b/packages/electron-client-ipc/src/types/appMenu.ts
new file mode 100644
index 00000000000..18d9e1cafc5
--- /dev/null
+++ b/packages/electron-client-ipc/src/types/appMenu.ts
@@ -0,0 +1,14 @@
+export interface AppMenuNode {
+ accelerator?: string;
+ checked?: boolean;
+ children?: AppMenuNode[];
+ enabled: boolean;
+ id: string;
+ label: string;
+ /**
+ * Electron menu role, when the item has one. Edit roles act on the focused
+ * page element, so the renderer must restore that element before invoking.
+ */
+ role?: string;
+ type: 'checkbox' | 'normal' | 'radio' | 'separator' | 'submenu';
+}
diff --git a/packages/electron-client-ipc/src/types/index.ts b/packages/electron-client-ipc/src/types/index.ts
index d38510997e1..28396a75332 100644
--- a/packages/electron-client-ipc/src/types/index.ts
+++ b/packages/electron-client-ipc/src/types/index.ts
@@ -1,3 +1,4 @@
+export * from './appMenu';
export * from './binary';
export * from './bootstrap';
export * from './browserControl';
diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.ts
index 161991a5975..b5ab39a11a5 100644
--- a/packages/locales/src/default/electron.ts
+++ b/packages/locales/src/default/electron.ts
@@ -8,6 +8,7 @@ export default {
'navigation.discoverMcp': 'Discover MCP',
'navigation.discoverModels': 'Discover Models',
'navigation.discoverProviders': 'Discover Providers',
+ 'navigation.appMenu': 'App menu',
'navigation.apps': 'Apps',
'navigation.group': 'Group',
'navigation.groupChat': 'Group Chat',
diff --git a/src/features/Electron/titlebar/NavigationBar.test.tsx b/src/features/Electron/titlebar/NavigationBar.test.tsx
index f1f0115c6a2..cb79d94e413 100644
--- a/src/features/Electron/titlebar/NavigationBar.test.tsx
+++ b/src/features/Electron/titlebar/NavigationBar.test.tsx
@@ -43,7 +43,11 @@ vi.mock('@/store/electron', () => ({
selector({ activeRecentScope: { slug: 'acme', type: 'workspace' } }),
}));
vi.mock('@/styles/electron', () => ({ electronStylish: { nodrag: 'nodrag' } }));
-vi.mock('@/utils/platform', () => ({ isMacOS: () => mocks.isMac }));
+vi.mock('@/utils/platform', () => ({
+ getPlatform: () => 'Linux',
+ isMacOS: () => mocks.isMac,
+}));
+vi.mock('./WindowsAppMenu', () => ({ default: () => null }));
vi.mock('../navigation/useNavigationHistory', () => ({
useNavigationHistory: () => ({
canGoBack: false,
diff --git a/src/features/Electron/titlebar/NavigationBar.tsx b/src/features/Electron/titlebar/NavigationBar.tsx
index 413aa82e5b0..14fececcfa7 100644
--- a/src/features/Electron/titlebar/NavigationBar.tsx
+++ b/src/features/Electron/titlebar/NavigationBar.tsx
@@ -17,14 +17,16 @@ import type { GlobalState } from '@/store/global/initialState';
import { systemStatusSelectors } from '@/store/global/selectors';
import { getHomeStoreState } from '@/store/home';
import { electronStylish } from '@/styles/electron';
-import { isMacOS } from '@/utils/platform';
+import { getPlatform, isMacOS } from '@/utils/platform';
import { useNavigationHistory } from '../navigation/useNavigationHistory';
import { getMacTrafficLightPadding } from './layout';
import RecentlyViewed from './RecentlyViewed';
import { useTrayMenuSync } from './TrayMenu/useTrayMenuSync';
+import WindowsAppMenu from './WindowsAppMenu';
const isMac = isMacOS();
+const isWindows = getPlatform() === 'Windows';
const COLLAPSED_NAVIGATION_BAR_WIDTH = 150;
const MAC_COLLAPSED_NAVIGATION_BAR_WIDTH = 116;
@@ -142,7 +144,7 @@ const NavigationBar = memo(() => {
className={styles.root}
data-width={leftPanelWidth}
gap={8}
- justify={isMac ? 'space-between' : 'end'}
+ justify={isMac || isWindows ? 'space-between' : 'end'}
style={{
paddingLeft: macTrafficLightPadding,
paddingRight: 8,
@@ -151,13 +153,13 @@ const NavigationBar = memo(() => {
width: navigationWidth,
}}
>
- {/* The persistent panel toggle is macOS-only; other platforms keep the
- in-page toggles, so the titlebar shows just the navigation controls. */}
+ {/* macOS keeps the sidebar toggle here. Windows uses the app icon as the menu. */}
{isMac && (
<Flexbox horizontal align="center" className={electronStylish.nodrag}>
<ToggleLeftPanelButton forceVisible id={NAV_TOGGLE_ID} size="small" />
</Flexbox>
)}
+ {isWindows && <WindowsAppMenu />}
<Flexbox horizontal align="center" className={electronStylish.nodrag} gap={2}>
<ActionIcon disabled={!canGoBack} icon={ArrowLeft} size="small" onClick={goBack} />
<ActionIcon disabled={!canGoForward} icon={ArrowRight} size="small" onClick={goForward} />
diff --git a/src/features/Electron/titlebar/WindowsAppMenu.tsx b/src/features/Electron/titlebar/WindowsAppMenu.tsx
new file mode 100644
index 00000000000..8f7b29edfce
--- /dev/null
+++ b/src/features/Electron/titlebar/WindowsAppMenu.tsx
@@ -0,0 +1,149 @@
+'use client';
+
+import type { AppMenuNode } from '@lobechat/electron-client-ipc';
+import { DropdownMenu, Tooltip } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cx } from 'antd-style';
+import { ChevronDown } from 'lucide-react';
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { ProductLogo } from '@/components/Branding';
+import { electronSystemService } from '@/services/electron/system';
+import { electronStylish } from '@/styles/electron';
+
+import { toAppMenuDropdownItems } from './appMenuItems';
+import {
+ captureEditingTarget,
+ type EditingTarget,
+ isEditingMenuRole,
+ restoreEditingTarget,
+ runWhenMenuFocusSettles,
+} from './editingFocus';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ chevron: css`
+ flex-shrink: 0;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ logo: css`
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 4px;
+ width: 100%;
+ height: 100%;
+ `,
+ menu: css`
+ width: 176px;
+ min-width: 176px;
+ `,
+ trigger: css`
+ cursor: pointer;
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ width: 44px;
+ height: 28px;
+ /* Align the mark with the sidebar navigation icons below. */
+ margin-inline-start: -4px;
+ padding: 0;
+ border: none;
+ border-radius: 8px;
+
+ background: transparent;
+
+ &:hover,
+ &[data-popup-open] {
+ background: ${cssVar.colorFillTertiary};
+ }
+
+ &:focus-visible {
+ outline: 2px solid ${cssVar.colorPrimary};
+ outline-offset: 2px;
+ }
+ `,
+}));
+
+const WindowsAppMenu = memo(() => {
+ const { t } = useTranslation('electron');
+ const [nodes, setNodes] = useState<AppMenuNode[]>([]);
+ const editingTargetRef = useRef<EditingTarget | null>(null);
+ const [menuOpen, setMenuOpen] = useState(false);
+
+ const refresh = useCallback(() => {
+ void electronSystemService.getAppMenu().then(setNodes, (error: unknown) => {
+ console.error('Failed to load the app menu:', error);
+ });
+ }, []);
+
+ useEffect(() => {
+ refresh();
+ }, [refresh]);
+
+ const invoke = useCallback((id: string, role?: string) => {
+ const send = () => {
+ void electronSystemService.invokeAppMenuItem(id).catch((error: unknown) => {
+ console.error('Failed to invoke app menu item:', error);
+ });
+ };
+
+ if (!isEditingMenuRole(role)) {
+ send();
+ return;
+ }
+
+ const target = editingTargetRef.current;
+ runWhenMenuFocusSettles(() => {
+ restoreEditingTarget(target);
+ send();
+ });
+ }, []);
+
+ const items = useMemo(() => toAppMenuDropdownItems(nodes, invoke), [invoke, nodes]);
+
+ return (
+ <DropdownMenu
+ iconSpaceMode={'group'}
+ items={items}
+ placement={'bottomLeft'}
+ popupProps={{
+ className: styles.menu,
+ finalFocus: () => {
+ const element = editingTargetRef.current?.element;
+ return element?.isConnected ? element : true;
+ },
+ }}
+ onOpenChange={(open) => {
+ setMenuOpen(open);
+ if (open) refresh();
+ }}
+ >
+ <button
+ aria-label={t('navigation.appMenu')}
+ className={cx(electronStylish.nodrag, styles.trigger)}
+ type={'button'}
+ onPointerDown={() => {
+ if (menuOpen) return;
+ editingTargetRef.current = captureEditingTarget();
+ }}
+ >
+ <Tooltip
+ open={menuOpen ? false : undefined}
+ placement={'bottomLeft'}
+ title={t('navigation.appMenu')}
+ >
+ <span className={styles.logo}>
+ <ProductLogo size={16} type={'mono'} />
+ <ChevronDown aria-hidden className={styles.chevron} size={12} />
+ </span>
+ </Tooltip>
+ </button>
+ </DropdownMenu>
+ );
+});
+
+WindowsAppMenu.displayName = 'WindowsAppMenu';
+
+export default WindowsAppMenu;
diff --git a/src/features/Electron/titlebar/appMenuItems.test.ts b/src/features/Electron/titlebar/appMenuItems.test.ts
new file mode 100644
index 00000000000..bf58d7f7828
--- /dev/null
+++ b/src/features/Electron/titlebar/appMenuItems.test.ts
@@ -0,0 +1,63 @@
+import type { AppMenuNode } from '@lobechat/electron-client-ipc';
+import { describe, expect, it, vi } from 'vitest';
+
+import { formatMenuAccelerator, toAppMenuDropdownItems } from './appMenuItems';
+
+describe('formatMenuAccelerator', () => {
+ it('shows Windows modifiers', () => {
+ expect(formatMenuAccelerator('CmdOrCtrl+Shift+H')).toBe('Ctrl+Shift+H');
+ expect(formatMenuAccelerator('CommandOrControl+Plus')).toBe('Ctrl++');
+ expect(formatMenuAccelerator(undefined)).toBeUndefined();
+ });
+});
+
+describe('toAppMenuDropdownItems', () => {
+ const nodes: AppMenuNode[] = [
+ {
+ children: [
+ { accelerator: 'Ctrl+T', enabled: true, id: 'new-tab', label: 'New Tab', type: 'normal' },
+ { enabled: false, id: '', label: '', type: 'separator' },
+ { enabled: false, id: 'updates', label: 'Checking for updates...', type: 'normal' },
+ ],
+ enabled: true,
+ id: 'file',
+ label: 'File',
+ type: 'submenu',
+ },
+ { checked: true, enabled: true, id: 'trace', label: 'Trace', type: 'checkbox' },
+ { enabled: true, id: 'paste', label: 'Paste', role: 'paste', type: 'normal' },
+ ];
+
+ it('builds nested menu rows and invokes the clicked id', () => {
+ const invoke = vi.fn();
+ const items = toAppMenuDropdownItems(nodes, invoke);
+ const file = items[0];
+
+ expect(file).toMatchObject({ key: 'file', label: 'File', openOnHover: true, type: 'submenu' });
+ if (file?.type !== 'submenu') throw new Error('expected File submenu');
+
+ const newTab = file.children?.[0];
+ expect(newTab).toMatchObject({ extra: 'Ctrl+T', key: 'new-tab', label: 'New Tab' });
+ if (!newTab || !('onClick' in newTab) || !newTab.onClick) throw new Error('expected click');
+
+ newTab.onClick({} as never);
+ expect(invoke).toHaveBeenCalledWith('new-tab');
+
+ expect(file.children?.[1]).toMatchObject({ type: 'divider' });
+ expect(file.children?.[2]).toMatchObject({ disabled: true, key: 'updates' });
+
+ const trace = items[1];
+ expect(trace).toMatchObject({ checked: true, key: 'trace', type: 'checkbox' });
+ if (!trace || !('onCheckedChange' in trace) || !trace.onCheckedChange) {
+ throw new Error('expected checkbox');
+ }
+
+ trace.onCheckedChange(false);
+ expect(invoke).toHaveBeenCalledWith('trace');
+
+ const paste = items[2];
+ if (!paste || !('onClick' in paste) || !paste.onClick) throw new Error('expected paste');
+ paste.onClick({} as never);
+ expect(invoke).toHaveBeenCalledWith('paste', 'paste');
+ });
+});
diff --git a/src/features/Electron/titlebar/appMenuItems.ts b/src/features/Electron/titlebar/appMenuItems.ts
new file mode 100644
index 00000000000..ec6d25edf94
--- /dev/null
+++ b/src/features/Electron/titlebar/appMenuItems.ts
@@ -0,0 +1,57 @@
+import type { AppMenuNode } from '@lobechat/electron-client-ipc';
+import type { DropdownItem } from '@lobehub/ui/base-ui';
+
+export const formatMenuAccelerator = (accelerator?: string): string | undefined => {
+ if (!accelerator) return undefined;
+
+ return accelerator
+ .replaceAll('CommandOrControl', 'Ctrl')
+ .replaceAll('CmdOrCtrl', 'Ctrl')
+ .replaceAll('Plus', '+');
+};
+
+export const toAppMenuDropdownItems = (
+ nodes: AppMenuNode[],
+ invoke: (id: string, role?: string) => void,
+): DropdownItem[] =>
+ nodes.map((node, index) => {
+ if (node.type === 'separator') return { key: `separator-${index}`, type: 'divider' };
+
+ if (node.type === 'submenu') {
+ return {
+ children: toAppMenuDropdownItems(node.children ?? [], invoke),
+ disabled: !node.enabled,
+ key: node.id,
+ label: node.label,
+ openOnHover: true,
+ type: 'submenu',
+ };
+ }
+
+ const extra = formatMenuAccelerator(node.accelerator);
+ const activate = () => {
+ if (node.role) invoke(node.id, node.role);
+ else invoke(node.id);
+ };
+
+ if (node.type === 'checkbox' || node.type === 'radio') {
+ return {
+ checked: Boolean(node.checked),
+ closeOnClick: true,
+ disabled: !node.enabled,
+ extra,
+ key: node.id,
+ label: node.label,
+ onCheckedChange: activate,
+ type: 'checkbox',
+ };
+ }
+
+ return {
+ disabled: !node.enabled,
+ extra,
+ key: node.id,
+ label: node.label,
+ onClick: activate,
+ };
+ });
diff --git a/src/features/Electron/titlebar/editingFocus.test.ts b/src/features/Electron/titlebar/editingFocus.test.ts
new file mode 100644
index 00000000000..179e61aa65a
--- /dev/null
+++ b/src/features/Electron/titlebar/editingFocus.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ captureEditingTarget,
+ isEditingMenuRole,
+ restoreEditingTarget,
+ runWhenMenuFocusSettles,
+} from './editingFocus';
+
+describe('isEditingMenuRole', () => {
+ it('matches page editing roles only', () => {
+ expect(isEditingMenuRole('paste')).toBe(true);
+ expect(isEditingMenuRole('selectAll')).toBe(true);
+ expect(isEditingMenuRole('quit')).toBe(false);
+ expect(isEditingMenuRole(undefined)).toBe(false);
+ });
+});
+
+describe('captureEditingTarget', () => {
+ it('keeps an input selection and ignores non-editable focus', () => {
+ const input = document.createElement('input');
+ document.body.append(input);
+ input.focus();
+ input.value = 'hello';
+ input.setSelectionRange(1, 4);
+
+ const target = captureEditingTarget(input);
+
+ expect(target).toMatchObject({ element: input, selectionEnd: 4, selectionStart: 1 });
+ expect(captureEditingTarget(document.body)).toBeNull();
+
+ input.blur();
+ expect(restoreEditingTarget(target)).toBe(true);
+ expect(document.activeElement).toBe(input);
+ expect(input.selectionStart).toBe(1);
+ expect(input.selectionEnd).toBe(4);
+
+ input.remove();
+ expect(restoreEditingTarget(target)).toBe(false);
+ });
+
+ it('restores a contenteditable range', () => {
+ const editor = document.createElement('div');
+ editor.contentEditable = 'true';
+ editor.textContent = 'hello';
+ document.body.append(editor);
+ editor.focus();
+
+ const text = editor.firstChild;
+ if (!text) throw new Error('expected text');
+ const range = document.createRange();
+ range.setStart(text, 1);
+ range.setEnd(text, 4);
+ const selection = document.getSelection();
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+
+ const target = captureEditingTarget(editor);
+ editor.blur();
+ selection?.removeAllRanges();
+
+ expect(restoreEditingTarget(target)).toBe(true);
+ expect(selection?.toString()).toBe('ell');
+
+ editor.remove();
+ });
+});
+
+describe('runWhenMenuFocusSettles', () => {
+ it('runs the action on the second frame, after menu focus restoration', () => {
+ const frames: Array<() => void> = [];
+ const action = vi.fn();
+
+ runWhenMenuFocusSettles(action, (frame) => {
+ frames.push(frame);
+ });
+
+ expect(action).not.toHaveBeenCalled();
+ frames[0]?.();
+ expect(action).not.toHaveBeenCalled();
+ frames[1]?.();
+ expect(action).toHaveBeenCalledOnce();
+ });
+});
diff --git a/src/features/Electron/titlebar/editingFocus.ts b/src/features/Electron/titlebar/editingFocus.ts
new file mode 100644
index 00000000000..9f5a3684786
--- /dev/null
+++ b/src/features/Electron/titlebar/editingFocus.ts
@@ -0,0 +1,86 @@
+const EDITING_MENU_ROLES = new Set([
+ 'copy',
+ 'cut',
+ 'delete',
+ 'paste',
+ 'pasteAndMatchStyle',
+ 'redo',
+ 'selectAll',
+ 'undo',
+]);
+
+export const isEditingMenuRole = (role?: string): boolean =>
+ role !== undefined && EDITING_MENU_ROLES.has(role);
+
+export interface EditingTarget {
+ element: HTMLElement;
+ range: Range | null;
+ selectionEnd: number | null;
+ selectionStart: number | null;
+}
+
+const isTextControl = (element: HTMLElement): element is HTMLInputElement | HTMLTextAreaElement =>
+ element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement;
+
+const isEditableElement = (element: Element | null): element is HTMLElement => {
+ if (!(element instanceof HTMLElement)) return false;
+ if (element.isContentEditable) return true;
+
+ return isTextControl(element);
+};
+
+export const captureEditingTarget = (
+ active: Element | null = document.activeElement,
+): EditingTarget | null => {
+ if (!isEditableElement(active)) return null;
+
+ let range: Range | null = null;
+ if (active.isContentEditable) {
+ const selection = active.ownerDocument.getSelection();
+ if (selection && selection.rangeCount > 0 && active.contains(selection.anchorNode)) {
+ range = selection.getRangeAt(0).cloneRange();
+ }
+ }
+
+ return {
+ element: active,
+ range,
+ selectionEnd: isTextControl(active) ? active.selectionEnd : null,
+ selectionStart: isTextControl(active) ? active.selectionStart : null,
+ };
+};
+
+export const restoreEditingTarget = (target: EditingTarget | null): boolean => {
+ if (!target?.element.isConnected) return false;
+
+ target.element.focus();
+
+ if (
+ isTextControl(target.element) &&
+ target.selectionStart !== null &&
+ target.selectionEnd !== null
+ ) {
+ target.element.setSelectionRange(target.selectionStart, target.selectionEnd);
+ }
+
+ if (target.range) {
+ const selection = target.element.ownerDocument.getSelection();
+ selection?.removeAllRanges();
+ selection?.addRange(target.range);
+ }
+
+ return true;
+};
+
+/**
+ * Menu close returns focus in a microtask after paint. Wait two frames so an
+ * edit role runs against the restored editor, not the menu row that stole focus.
+ */
+export const runWhenMenuFocusSettles = (
+ action: () => void,
+ scheduleFrame: (frame: () => void) => void = requestAnimationFrame,
+): void => {
+ scheduleFrame(() => {
+ scheduleFrame(action);
+ });
+};
diff --git a/src/services/electron/system.ts b/src/services/electron/system.ts
index 595911ecf72..b17a071079f 100644
--- a/src/services/electron/system.ts
+++ b/src/services/electron/system.ts
@@ -1,4 +1,5 @@
import type {
+ AppMenuNode,
ElectronAppState,
PopupContextMenuParams,
PopupContextMenuResult,
@@ -109,6 +110,14 @@ class ElectronSystemService {
return this.ipc.menu.closePopupContextMenu();
};
+ getAppMenu = async (): Promise<AppMenuNode[]> => {
+ return this.ipc.menu.getAppMenu();
+ };
+
+ invokeAppMenuItem = async (id: string): Promise<{ success: boolean }> => {
+ return this.ipc.menu.invokeAppMenuItem({ id });
+ };
+
/**
* Open native folder picker dialog
*/