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): native macOS context menus for app-domain menus (#17648)

Innei4edba1b75a97
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 6ec0f4d358b..c29ea2f24a6 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -89,7 +89,7 @@
"diff": "^8.0.4",
"drizzle-kit": "^0.31.10",
"drizzle-orm": "^0.45.2",
- "electron": "41.3.0",
+ "electron": "43.2.0",
"electron-builder": "26.14.0",
"electron-is": "^3.0.0",
"electron-store": "^8.2.0",
diff --git a/apps/desktop/src/main/controllers/MenuCtr.ts b/apps/desktop/src/main/controllers/MenuCtr.ts
index 5de516b1d85..7728d8ea8f5 100644
--- a/apps/desktop/src/main/controllers/MenuCtr.ts
+++ b/apps/desktop/src/main/controllers/MenuCtr.ts
@@ -1,3 +1,8 @@
+import type { PopupContextMenuParams, PopupContextMenuResult } from '@lobechat/electron-client-ipc';
+import { BrowserWindow } from 'electron';
+
+import { getIpcContext } from '@/utils/ipc';
+
import { ControllerModule, IpcMethod } from './index';
export default class MenuController extends ControllerModule {
@@ -27,4 +32,16 @@ export default class MenuController extends ControllerModule {
// Call MenuManager method to rebuild application menu
return this.app.menuManager.rebuildAppMenu({ showDevItems: visible });
}
+
+ @IpcMethod()
+ popupContextMenu(params: PopupContextMenuParams): Promise<PopupContextMenuResult> {
+ const context = getIpcContext();
+ const window = context ? BrowserWindow.fromWebContents(context.sender) : null;
+ return this.app.menuManager.popupContextMenu(params, window);
+ }
+
+ @IpcMethod()
+ closePopupContextMenu() {
+ return this.app.menuManager.closePopupContextMenu();
+ }
}
diff --git a/apps/desktop/src/main/controllers/__tests__/MenuCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/MenuCtr.test.ts
index 2e6709780b4..9c28f17ad0c 100644
--- a/apps/desktop/src/main/controllers/__tests__/MenuCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/MenuCtr.test.ts
@@ -1,14 +1,20 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { App } from '@/core/App';
+import type { IpcContext } from '@/utils/ipc';
+import { runWithIpcContext } from '@/utils/ipc';
import MenuController from '../MenuCtr';
-const { ipcMainHandleMock } = vi.hoisted(() => ({
+const { fromWebContentsMock, ipcMainHandleMock } = vi.hoisted(() => ({
+ fromWebContentsMock: vi.fn(),
ipcMainHandleMock: vi.fn(),
}));
vi.mock('electron', () => ({
+ BrowserWindow: {
+ fromWebContents: fromWebContentsMock,
+ },
ipcMain: {
handle: ipcMainHandleMock,
},
@@ -18,12 +24,16 @@ vi.mock('electron', () => ({
const mockRefreshMenus = vi.fn();
const mockShowContextMenu = vi.fn();
const mockRebuildAppMenu = vi.fn();
+const mockPopupContextMenu = vi.fn();
+const mockClosePopupContextMenu = vi.fn();
const mockApp = {
menuManager: {
+ closePopupContextMenu: mockClosePopupContextMenu,
+ popupContextMenu: mockPopupContextMenu,
refreshMenus: mockRefreshMenus,
- showContextMenu: mockShowContextMenu,
rebuildAppMenu: mockRebuildAppMenu,
+ showContextMenu: mockShowContextMenu,
},
} as unknown as App;
@@ -89,4 +99,45 @@ describe('MenuController', () => {
expect(result).toBe(true);
});
});
+
+ describe('popupContextMenu', () => {
+ it('should resolve the calling window via BrowserWindow.fromWebContents and delegate to menuManager', async () => {
+ const params = { items: [{ id: 'copy', label: 'Copy', type: 'normal' as const }] };
+ const sender = {} as any;
+ const context = { event: { sender } as any, sender } as IpcContext;
+ const mockWindow = {} as any;
+ fromWebContentsMock.mockReturnValueOnce(mockWindow);
+ mockPopupContextMenu.mockResolvedValueOnce({ clickedId: 'copy' });
+
+ const result = await runWithIpcContext(context, () =>
+ menuController.popupContextMenu(params),
+ );
+
+ expect(fromWebContentsMock).toHaveBeenCalledWith(sender);
+ expect(mockPopupContextMenu).toHaveBeenCalledWith(params, mockWindow);
+ expect(result).toEqual({ clickedId: 'copy' });
+ });
+
+ it('should pass a null window through when there is no IPC context', async () => {
+ const params = { items: [] };
+ mockPopupContextMenu.mockResolvedValueOnce({ clickedId: null });
+
+ const result = await menuController.popupContextMenu(params);
+
+ expect(fromWebContentsMock).not.toHaveBeenCalled();
+ expect(mockPopupContextMenu).toHaveBeenCalledWith(params, null);
+ expect(result).toEqual({ clickedId: null });
+ });
+ });
+
+ describe('closePopupContextMenu', () => {
+ it('should call menuManager.closePopupContextMenu', () => {
+ mockClosePopupContextMenu.mockReturnValueOnce({ success: true });
+
+ const result = menuController.closePopupContextMenu();
+
+ expect(mockClosePopupContextMenu).toHaveBeenCalled();
+ 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 ab05bb1117c..fa73b0cf115 100644
--- a/apps/desktop/src/main/core/ui/MenuManager.ts
+++ b/apps/desktop/src/main/core/ui/MenuManager.ts
@@ -1,11 +1,16 @@
-import type { TrayNavigationSnapshot } from '@lobechat/electron-client-ipc';
-import type { Menu } from 'electron';
+import type {
+ PopupContextMenuParams,
+ PopupContextMenuResult,
+ TrayNavigationSnapshot,
+} from '@lobechat/electron-client-ipc';
+import type { BrowserWindow, Menu } from 'electron';
import type { IMenuPlatform, MenuOptions } from '@/menus';
import { createMenuImpl } from '@/menus';
import { createLogger } from '@/utils/logger';
import type { App } from '../App';
+import { closeNativeContextMenuPopup, popupNativeContextMenu } from './nativeContextMenu';
// Create logger
const logger = createLogger('core:MenuManager');
@@ -38,6 +43,20 @@ export class MenuManager {
return { success: true };
}
+ popupContextMenu(
+ params: PopupContextMenuParams,
+ window: BrowserWindow | null,
+ ): Promise<PopupContextMenuResult> {
+ logger.debug('Popping up native context menu');
+ return popupNativeContextMenu(params, window);
+ }
+
+ closePopupContextMenu() {
+ logger.debug('Closing native context menu popup');
+ closeNativeContextMenuPopup();
+ 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 37461940eec..ea26925f151 100644
--- a/apps/desktop/src/main/core/ui/__tests__/MenuManager.test.ts
+++ b/apps/desktop/src/main/core/ui/__tests__/MenuManager.test.ts
@@ -36,6 +36,16 @@ vi.mock('@/menus', () => ({
})),
}));
+const { mockCloseNativeContextMenuPopup, mockPopupNativeContextMenu } = vi.hoisted(() => ({
+ mockCloseNativeContextMenuPopup: vi.fn(),
+ mockPopupNativeContextMenu: vi.fn(),
+}));
+
+vi.mock('../nativeContextMenu', () => ({
+ closeNativeContextMenuPopup: mockCloseNativeContextMenuPopup,
+ popupNativeContextMenu: mockPopupNativeContextMenu,
+}));
+
describe('MenuManager', () => {
let menuManager: MenuManager;
let mockApp: App;
@@ -128,6 +138,38 @@ describe('MenuManager', () => {
});
});
+ describe('popupContextMenu', () => {
+ it('delegates to popupNativeContextMenu with the params and window', async () => {
+ const params = { items: [{ id: 'copy', label: 'Copy', type: 'normal' as const }] };
+ const window = { isDestroyed: () => false } as any;
+ mockPopupNativeContextMenu.mockResolvedValueOnce({ clickedId: 'copy' });
+
+ const result = await menuManager.popupContextMenu(params, window);
+
+ expect(mockPopupNativeContextMenu).toHaveBeenCalledWith(params, window);
+ expect(result).toEqual({ clickedId: 'copy' });
+ });
+
+ it('forwards a null window through to popupNativeContextMenu', async () => {
+ const params = { items: [] };
+ mockPopupNativeContextMenu.mockResolvedValueOnce({ clickedId: null });
+
+ const result = await menuManager.popupContextMenu(params, null);
+
+ expect(mockPopupNativeContextMenu).toHaveBeenCalledWith(params, null);
+ expect(result).toEqual({ clickedId: null });
+ });
+ });
+
+ describe('closePopupContextMenu', () => {
+ it('delegates to closeNativeContextMenuPopup and reports success', () => {
+ const result = menuManager.closePopupContextMenu();
+
+ expect(mockCloseNativeContextMenuPopup).toHaveBeenCalled();
+ expect(result).toEqual({ success: true });
+ });
+ });
+
describe('buildTrayMenu', () => {
it('should build tray menu', () => {
const result = menuManager.buildTrayMenu();
diff --git a/apps/desktop/src/main/core/ui/__tests__/nativeContextMenu.test.ts b/apps/desktop/src/main/core/ui/__tests__/nativeContextMenu.test.ts
new file mode 100644
index 00000000000..03fb5db626d
--- /dev/null
+++ b/apps/desktop/src/main/core/ui/__tests__/nativeContextMenu.test.ts
@@ -0,0 +1,502 @@
+import type { NativeContextMenuItemTemplate } from '@lobechat/electron-client-ipc';
+import type { MenuItemConstructorOptions } from 'electron';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ closeNativeContextMenuPopup,
+ convertNativeContextMenuItems,
+ popupNativeContextMenu,
+} from '../nativeContextMenu';
+
+const { buildFromTemplateMock, createMenuSymbolMock, loggerWarnMock } = vi.hoisted(() => ({
+ buildFromTemplateMock: vi.fn(),
+ createMenuSymbolMock: vi.fn(),
+ loggerWarnMock: vi.fn(),
+}));
+
+vi.mock('electron', () => ({
+ Menu: {
+ buildFromTemplate: buildFromTemplateMock,
+ },
+ nativeImage: {
+ createMenuSymbol: createMenuSymbolMock,
+ },
+}));
+
+vi.mock('@/const/env', () => ({
+ isDev: true,
+}));
+
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => ({
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: loggerWarnMock,
+ }),
+}));
+
+const invokeClick = (options: MenuItemConstructorOptions) =>
+ (options.click as (...args: any[]) => void)?.(
+ undefined as any,
+ undefined as any,
+ undefined as any,
+ );
+
+const originalPlatform = process.platform;
+
+const setPlatform = (platform: NodeJS.Platform) => {
+ Object.defineProperty(process, 'platform', { configurable: true, value: platform });
+};
+
+const setSystemVersion = (version: string) => {
+ Object.defineProperty(process, 'getSystemVersion', {
+ configurable: true,
+ value: vi.fn(() => version),
+ });
+};
+
+describe('nativeContextMenu', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ setPlatform('darwin');
+ setSystemVersion('14.4.1');
+ });
+
+ afterEach(() => {
+ Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform });
+ });
+
+ describe('convertNativeContextMenuItems', () => {
+ it('converts a normal item with label/sublabel/click', () => {
+ const onItemClick = vi.fn();
+ const items: NativeContextMenuItemTemplate[] = [
+ { id: 'copy', label: 'Copy', sublabel: 'Cmd+C', type: 'normal' },
+ ];
+
+ const [result] = convertNativeContextMenuItems(items, onItemClick);
+
+ expect(result.label).toBe('Copy');
+ expect(result.sublabel).toBe('Cmd+C');
+ expect(result.type).toBeUndefined();
+
+ invokeClick(result);
+ expect(onItemClick).toHaveBeenCalledWith('copy');
+ });
+
+ it('sets enabled: false only when explicitly disabled, otherwise omits the key', () => {
+ const items: NativeContextMenuItemTemplate[] = [
+ { enabled: false, id: 'a', label: 'A', type: 'normal' },
+ { id: 'b', label: 'B', type: 'normal' },
+ ];
+
+ const [a, b] = convertNativeContextMenuItems(items, vi.fn());
+
+ expect(a.enabled).toBe(false);
+ expect('enabled' in b).toBe(false);
+ });
+
+ it('applies enabled: false to checkbox and submenu items too', () => {
+ const items: NativeContextMenuItemTemplate[] = [
+ { checked: false, enabled: false, id: 'toggle', label: 'Toggle', type: 'checkbox' },
+ { enabled: false, label: 'More', submenu: [], type: 'submenu' },
+ ];
+
+ const [checkbox, submenu] = convertNativeContextMenuItems(items, vi.fn());
+
+ expect(checkbox.enabled).toBe(false);
+ expect(submenu.enabled).toBe(false);
+ });
+
+ it('converts a separator', () => {
+ const [result] = convertNativeContextMenuItems([{ type: 'separator' }], vi.fn());
+ expect(result).toEqual({ type: 'separator' });
+ });
+
+ it('converts a checkbox item with checked state and click wiring', () => {
+ const onItemClick = vi.fn();
+ const [result] = convertNativeContextMenuItems(
+ [{ checked: true, id: 'toggle', label: 'Toggle', type: 'checkbox' }],
+ onItemClick,
+ );
+
+ expect(result.type).toBe('checkbox');
+ expect(result.checked).toBe(true);
+ expect(result.label).toBe('Toggle');
+
+ invokeClick(result);
+ expect(onItemClick).toHaveBeenCalledWith('toggle');
+ });
+
+ it('attaches an icon to checkbox items when sfSymbol is provided', () => {
+ const fakeImage = { isEmpty: () => false };
+ createMenuSymbolMock.mockReturnValue(fakeImage);
+
+ const [result] = convertNativeContextMenuItems(
+ [
+ {
+ checked: false,
+ id: 'toggle',
+ label: 'Toggle',
+ sfSymbol: 'doc.on.doc',
+ type: 'checkbox',
+ },
+ ],
+ vi.fn(),
+ );
+
+ expect(result.icon).toBe(fakeImage);
+ });
+
+ it('converts a submenu recursively, wiring no click handler even when id is present', () => {
+ const [result] = convertNativeContextMenuItems(
+ [
+ {
+ id: 'not-clickable',
+ label: 'More',
+ submenu: [{ id: 'child', label: 'Child', type: 'normal' }],
+ type: 'submenu',
+ },
+ ],
+ vi.fn(),
+ );
+
+ expect(result.label).toBe('More');
+ expect('click' in result).toBe(false);
+ expect(result.submenu).toHaveLength(1);
+ expect((result.submenu as MenuItemConstructorOptions[])[0].label).toBe('Child');
+ });
+
+ it('attaches an icon to submenu items when sfSymbol is provided', () => {
+ const fakeImage = { isEmpty: () => false };
+ createMenuSymbolMock.mockReturnValue(fakeImage);
+
+ const [result] = convertNativeContextMenuItems(
+ [{ label: 'More', sfSymbol: 'doc.on.doc', submenu: [], type: 'submenu' }],
+ vi.fn(),
+ );
+
+ expect(result.icon).toBe(fakeImage);
+ });
+
+ it('applies sublabel to checkbox and submenu items too, subject to the version rule', () => {
+ const items: NativeContextMenuItemTemplate[] = [
+ {
+ checked: true,
+ id: 'toggle',
+ label: 'Toggle',
+ sublabel: 'desc-checkbox',
+ type: 'checkbox',
+ },
+ { label: 'More', sublabel: 'desc-submenu', submenu: [], type: 'submenu' },
+ ];
+
+ const [checkbox, submenu] = convertNativeContextMenuItems(items, vi.fn());
+
+ expect(checkbox.sublabel).toBe('desc-checkbox');
+ expect(submenu.sublabel).toBe('desc-submenu');
+ });
+
+ it('omits click wiring for clickable items without an id', () => {
+ const [result] = convertNativeContextMenuItems([{ label: 'No id', type: 'normal' }], vi.fn());
+
+ expect('click' in result).toBe(false);
+ });
+ });
+
+ describe('macOS version degradation', () => {
+ it('degrades header to separator and drops it when it is the first item at its level (macOS 13)', () => {
+ setSystemVersion('13.0');
+
+ const items: NativeContextMenuItemTemplate[] = [
+ { label: 'Section', type: 'header' },
+ { id: 'a', label: 'A', type: 'normal' },
+ ];
+
+ const result = convertNativeContextMenuItems(items, vi.fn());
+
+ expect(result).toHaveLength(1);
+ expect(result[0].label).toBe('A');
+ });
+
+ it('degrades header to a plain separator when it is not the first item at its level (macOS 13)', () => {
+ setSystemVersion('13.0');
+
+ const items: NativeContextMenuItemTemplate[] = [
+ { id: 'a', label: 'A', type: 'normal' },
+ { label: 'Section', type: 'header' },
+ { id: 'b', label: 'B', type: 'normal' },
+ ];
+
+ const result = convertNativeContextMenuItems(items, vi.fn());
+
+ expect(result).toHaveLength(3);
+ expect(result[1]).toEqual({ type: 'separator' });
+ });
+
+ it('keeps header but drops sublabel on macOS 14.0', () => {
+ setSystemVersion('14.0');
+
+ const items: NativeContextMenuItemTemplate[] = [
+ { label: 'Section', type: 'header' },
+ { id: 'a', label: 'A', sublabel: 'desc', type: 'normal' },
+ ];
+
+ const [header, normal] = convertNativeContextMenuItems(items, vi.fn());
+
+ expect(header).toEqual({ label: 'Section', type: 'header' });
+ expect('sublabel' in normal).toBe(false);
+ });
+
+ it('keeps sublabel on macOS 14.4.1', () => {
+ setSystemVersion('14.4.1');
+
+ const items: NativeContextMenuItemTemplate[] = [
+ { id: 'a', label: 'A', sublabel: 'desc', type: 'normal' },
+ ];
+
+ const [normal] = convertNativeContextMenuItems(items, vi.fn());
+
+ expect(normal.sublabel).toBe('desc');
+ });
+
+ it('drops sublabel uniformly across normal/checkbox/submenu on macOS 14.0', () => {
+ setSystemVersion('14.0');
+
+ const items: NativeContextMenuItemTemplate[] = [
+ { id: 'a', label: 'A', sublabel: 'd1', type: 'normal' },
+ { checked: false, id: 'b', label: 'B', sublabel: 'd2', type: 'checkbox' },
+ { label: 'C', sublabel: 'd3', submenu: [], type: 'submenu' },
+ ];
+
+ const [normal, checkbox, submenu] = convertNativeContextMenuItems(items, vi.fn());
+
+ expect('sublabel' in normal).toBe(false);
+ expect('sublabel' in checkbox).toBe(false);
+ expect('sublabel' in submenu).toBe(false);
+ });
+
+ it('keeps sublabel uniformly across normal/checkbox/submenu on macOS 14.4.1', () => {
+ setSystemVersion('14.4.1');
+
+ const items: NativeContextMenuItemTemplate[] = [
+ { id: 'a', label: 'A', sublabel: 'd1', type: 'normal' },
+ { checked: false, id: 'b', label: 'B', sublabel: 'd2', type: 'checkbox' },
+ { label: 'C', sublabel: 'd3', submenu: [], type: 'submenu' },
+ ];
+
+ const [normal, checkbox, submenu] = convertNativeContextMenuItems(items, vi.fn());
+
+ expect(normal.sublabel).toBe('d1');
+ expect(checkbox.sublabel).toBe('d2');
+ expect(submenu.sublabel).toBe('d3');
+ });
+ });
+
+ describe('sfSymbol icon fallback', () => {
+ it('sets icon when createMenuSymbol returns a usable image', () => {
+ const fakeImage = { isEmpty: () => false };
+ createMenuSymbolMock.mockReturnValue(fakeImage);
+
+ const [result] = convertNativeContextMenuItems(
+ [{ id: 'a', label: 'A', sfSymbol: 'doc.on.doc', type: 'normal' }],
+ vi.fn(),
+ );
+
+ expect(result.icon).toBe(fakeImage);
+ });
+
+ it('omits the icon key entirely when createMenuSymbol returns an empty image', () => {
+ createMenuSymbolMock.mockReturnValue({ isEmpty: () => true });
+
+ const [result] = convertNativeContextMenuItems(
+ [{ id: 'a', label: 'A', sfSymbol: 'doc.on.doc', type: 'normal' }],
+ vi.fn(),
+ );
+
+ expect('icon' in result).toBe(false);
+ expect(loggerWarnMock).toHaveBeenCalled();
+ });
+
+ it('omits the icon key when createMenuSymbol throws', () => {
+ createMenuSymbolMock.mockImplementation(() => {
+ throw new Error('boom');
+ });
+
+ const [result] = convertNativeContextMenuItems(
+ [{ id: 'a', label: 'A', sfSymbol: 'doc.on.doc', type: 'normal' }],
+ vi.fn(),
+ );
+
+ expect('icon' in result).toBe(false);
+ });
+
+ it('never resolves an icon on non-darwin platforms', () => {
+ setPlatform('win32');
+ createMenuSymbolMock.mockReturnValue({ isEmpty: () => false });
+
+ const [result] = convertNativeContextMenuItems(
+ [{ id: 'a', label: 'A', sfSymbol: 'doc.on.doc', type: 'normal' }],
+ vi.fn(),
+ );
+
+ expect('icon' in result).toBe(false);
+ expect(createMenuSymbolMock).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('popup lifecycle', () => {
+ const makeFakeMenu = () => ({
+ closePopup: vi.fn(),
+ popup: vi.fn(),
+ });
+
+ it('resolves the clicked id when an item is clicked', async () => {
+ const fakeMenu = makeFakeMenu();
+ buildFromTemplateMock.mockReturnValue(fakeMenu);
+ const window = { isDestroyed: () => false } as any;
+
+ const promise = popupNativeContextMenu(
+ { items: [{ id: 'copy', label: 'Copy', type: 'normal' }] },
+ window,
+ );
+
+ const template = buildFromTemplateMock.mock.calls[0][0] as MenuItemConstructorOptions[];
+ invokeClick(template[0]);
+
+ await expect(promise).resolves.toEqual({ clickedId: 'copy' });
+ });
+
+ it('resolves null when the popup closes without a click', async () => {
+ vi.useFakeTimers();
+ try {
+ const fakeMenu = makeFakeMenu();
+ buildFromTemplateMock.mockReturnValue(fakeMenu);
+ const window = { isDestroyed: () => false } as any;
+
+ const promise = popupNativeContextMenu(
+ { items: [{ id: 'copy', label: 'Copy', type: 'normal' }] },
+ window,
+ );
+
+ const popupOptions = fakeMenu.popup.mock.calls[0][0];
+ popupOptions.callback();
+ await vi.runAllTimersAsync();
+
+ await expect(promise).resolves.toEqual({ clickedId: null });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('lets a click that fires after the close callback still win (close-then-click)', async () => {
+ vi.useFakeTimers();
+ try {
+ const fakeMenu = makeFakeMenu();
+ buildFromTemplateMock.mockReturnValue(fakeMenu);
+ const window = { isDestroyed: () => false } as any;
+
+ const promise = popupNativeContextMenu(
+ { items: [{ id: 'copy', label: 'Copy', type: 'normal' }] },
+ window,
+ );
+
+ const template = buildFromTemplateMock.mock.calls[0][0] as MenuItemConstructorOptions[];
+ const popupOptions = fakeMenu.popup.mock.calls[0][0];
+
+ popupOptions.callback();
+ invokeClick(template[0]);
+ await vi.runAllTimersAsync();
+
+ await expect(promise).resolves.toEqual({ clickedId: 'copy' });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps the click result when the close callback fires right after it (click-then-close), and releases the popup', async () => {
+ vi.useFakeTimers();
+ try {
+ const fakeMenu = makeFakeMenu();
+ buildFromTemplateMock.mockReturnValue(fakeMenu);
+ const window = { isDestroyed: () => false } as any;
+
+ const promise = popupNativeContextMenu(
+ { items: [{ id: 'copy', label: 'Copy', type: 'normal' }] },
+ window,
+ );
+
+ const template = buildFromTemplateMock.mock.calls[0][0] as MenuItemConstructorOptions[];
+ const popupOptions = fakeMenu.popup.mock.calls[0][0];
+
+ invokeClick(template[0]);
+ expect(() => popupOptions.callback()).not.toThrow();
+ await vi.runAllTimersAsync();
+
+ await expect(promise).resolves.toEqual({ clickedId: 'copy' });
+
+ closeNativeContextMenuPopup();
+ expect(fakeMenu.closePopup).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('resolves null immediately when the window is already destroyed, without building a menu', async () => {
+ const window = { isDestroyed: () => true } as any;
+
+ await expect(popupNativeContextMenu({ items: [] }, window)).resolves.toEqual({
+ clickedId: null,
+ });
+ expect(buildFromTemplateMock).not.toHaveBeenCalled();
+ });
+
+ it('closes the previous popup when a new one opens, and the previous one resolves null', async () => {
+ vi.useFakeTimers();
+ try {
+ const firstMenu = makeFakeMenu();
+ const secondMenu = makeFakeMenu();
+ buildFromTemplateMock.mockReturnValueOnce(firstMenu).mockReturnValueOnce(secondMenu);
+ const window = { isDestroyed: () => false } as any;
+
+ const firstPromise = popupNativeContextMenu(
+ { items: [{ id: 'a', label: 'A', type: 'normal' }] },
+ window,
+ );
+ const secondPromise = popupNativeContextMenu(
+ { items: [{ id: 'b', label: 'B', type: 'normal' }] },
+ window,
+ );
+
+ expect(firstMenu.closePopup).toHaveBeenCalled();
+
+ const firstCallback = firstMenu.popup.mock.calls[0][0].callback;
+ firstCallback();
+ await vi.runAllTimersAsync();
+ await expect(firstPromise).resolves.toEqual({ clickedId: null });
+
+ const secondTemplate = buildFromTemplateMock.mock
+ .calls[1][0] as MenuItemConstructorOptions[];
+ invokeClick(secondTemplate[0]);
+ await expect(secondPromise).resolves.toEqual({ clickedId: 'b' });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('closeNativeContextMenuPopup closes the current popup and is a safe no-op when none is open', () => {
+ expect(() => closeNativeContextMenuPopup()).not.toThrow();
+
+ const fakeMenu = makeFakeMenu();
+ buildFromTemplateMock.mockReturnValue(fakeMenu);
+ const window = { isDestroyed: () => false } as any;
+ void popupNativeContextMenu({ items: [{ id: 'a', label: 'A', type: 'normal' }] }, window);
+
+ closeNativeContextMenuPopup();
+ expect(fakeMenu.closePopup).toHaveBeenCalled();
+
+ const callback = fakeMenu.popup.mock.calls[0][0].callback;
+ callback();
+ });
+ });
+});
diff --git a/apps/desktop/src/main/core/ui/nativeContextMenu.ts b/apps/desktop/src/main/core/ui/nativeContextMenu.ts
new file mode 100644
index 00000000000..d6ce0da31b9
--- /dev/null
+++ b/apps/desktop/src/main/core/ui/nativeContextMenu.ts
@@ -0,0 +1,157 @@
+import type {
+ NativeContextMenuItemTemplate,
+ PopupContextMenuParams,
+ PopupContextMenuResult,
+ SFSymbol,
+} from '@lobechat/electron-client-ipc';
+import type { BrowserWindow, MenuItemConstructorOptions, NativeImage } from 'electron';
+import { Menu, nativeImage } from 'electron';
+
+import { isDev } from '@/const/env';
+import { createLogger } from '@/utils/logger';
+
+const logger = createLogger('core:nativeContextMenu');
+
+interface MacMenuCapabilities {
+ supportsHeader: boolean;
+ supportsSublabel: boolean;
+}
+
+const parseDarwinVersion = (version: string): { major: number; minor: number } => {
+ const [major = 0, minor = 0] = version.split('.').map(Number);
+ return { major, minor };
+};
+
+const getMacMenuCapabilities = (): MacMenuCapabilities => {
+ if (process.platform !== 'darwin') return { supportsHeader: true, supportsSublabel: true };
+
+ const { major, minor } = parseDarwinVersion(process.getSystemVersion());
+ return {
+ supportsHeader: major >= 14,
+ supportsSublabel: major > 14 || (major === 14 && minor >= 4),
+ };
+};
+
+const resolveMenuSymbolIcon = (sfSymbol?: SFSymbol): NativeImage | undefined => {
+ if (!sfSymbol || process.platform !== 'darwin') return undefined;
+
+ try {
+ const image = nativeImage.createMenuSymbol(sfSymbol);
+ if (image.isEmpty()) {
+ if (isDev) logger.warn(`SF Symbol "${sfSymbol}" resolved to an empty image, omitting icon`);
+ return undefined;
+ }
+ return image;
+ } catch (error) {
+ if (isDev) logger.warn(`Failed to resolve SF Symbol "${sfSymbol}"`, error);
+ return undefined;
+ }
+};
+
+const convertItem = (
+ item: NativeContextMenuItemTemplate,
+ onItemClick: (id: string) => void,
+ capabilities: MacMenuCapabilities,
+ isFirstAtLevel: boolean,
+): MenuItemConstructorOptions | undefined => {
+ if (item.type === 'separator') return { type: 'separator' };
+
+ if (item.type === 'header') {
+ if (capabilities.supportsHeader) return { label: item.label, type: 'header' };
+ if (isFirstAtLevel) return undefined;
+ return { type: 'separator' };
+ }
+
+ const icon = resolveMenuSymbolIcon(item.sfSymbol);
+ const general: MenuItemConstructorOptions = {
+ ...(item.enabled === false ? { enabled: false } : {}),
+ ...(icon ? { icon } : {}),
+ label: item.label,
+ ...(capabilities.supportsSublabel && item.sublabel ? { sublabel: item.sublabel } : {}),
+ };
+
+ switch (item.type) {
+ case 'normal': {
+ return { ...general, ...(item.id ? { click: () => onItemClick(item.id!) } : {}) };
+ }
+ case 'checkbox': {
+ return {
+ ...general,
+ checked: item.checked,
+ type: 'checkbox',
+ ...(item.id ? { click: () => onItemClick(item.id!) } : {}),
+ };
+ }
+ case 'submenu': {
+ return {
+ ...general,
+ submenu: convertItemsAtLevel(item.submenu ?? [], onItemClick, capabilities),
+ };
+ }
+ }
+};
+
+const convertItemsAtLevel = (
+ items: NativeContextMenuItemTemplate[],
+ onItemClick: (id: string) => void,
+ capabilities: MacMenuCapabilities,
+): MenuItemConstructorOptions[] => {
+ const result: MenuItemConstructorOptions[] = [];
+
+ for (const item of items) {
+ const converted = convertItem(item, onItemClick, capabilities, result.length === 0);
+ if (converted) result.push(converted);
+ }
+
+ return result;
+};
+
+export const convertNativeContextMenuItems = (
+ items: NativeContextMenuItemTemplate[],
+ onItemClick: (id: string) => void,
+): MenuItemConstructorOptions[] =>
+ convertItemsAtLevel(items, onItemClick, getMacMenuCapabilities());
+
+interface CurrentPopup {
+ menu: Menu;
+}
+
+let currentPopup: CurrentPopup | null = null;
+
+export const popupNativeContextMenu = (
+ params: PopupContextMenuParams,
+ window: BrowserWindow | null,
+): Promise<PopupContextMenuResult> => {
+ if (!window || window.isDestroyed()) return Promise.resolve({ clickedId: null });
+
+ closeNativeContextMenuPopup();
+
+ return new Promise<PopupContextMenuResult>((resolve) => {
+ let resolved = false;
+
+ const resolveOnce = (result: PopupContextMenuResult) => {
+ if (resolved) return;
+ resolved = true;
+ if (currentPopup?.menu === menu) currentPopup = null;
+ resolve(result);
+ };
+
+ const template = convertNativeContextMenuItems(params.items, (id) =>
+ resolveOnce({ clickedId: id }),
+ );
+ const menu = Menu.buildFromTemplate(template);
+ currentPopup = { menu };
+
+ menu.popup({
+ callback: () => {
+ // Click-vs-close ordering isn't guaranteed across Electron versions/platforms, so defer this to let a real click win the resolve-once race.
+ setTimeout(() => resolveOnce({ clickedId: null }), 0);
+ },
+ window,
+ });
+ });
+};
+
+export const closeNativeContextMenuPopup = (): void => {
+ currentPopup?.menu.closePopup();
+};
diff --git a/package.json b/package.json
index 7d0487f2b6b..314a2d280e8 100644
--- a/package.json
+++ b/package.json
@@ -299,7 +299,7 @@
"@lobehub/icons": "^5.11.0",
"@lobehub/market-sdk": "0.39.2",
"@lobehub/tts": "^5.1.2",
- "@lobehub/ui": "^5.23.3",
+ "@lobehub/ui": "^5.24.0",
"@modelcontextprotocol/sdk": "^1.29.0",
"@napi-rs/canvas": "^0.1.100",
"@neondatabase/serverless": "^1.1.0",
diff --git a/packages/electron-client-ipc/package.json b/packages/electron-client-ipc/package.json
index 21d8d6e5573..7a5cc17d7e4 100644
--- a/packages/electron-client-ipc/package.json
+++ b/packages/electron-client-ipc/package.json
@@ -4,8 +4,11 @@
"private": true,
"main": "src/index.ts",
"types": "src/index.ts",
+ "dependencies": {
+ "sf-symbols-typescript": "^2.2.0"
+ },
"devDependencies": {
- "electron": "^39.8.10"
+ "electron": "^43.2.0"
},
"peerDependencies": {
"react": "*"
diff --git a/packages/electron-client-ipc/src/types/contextMenu.ts b/packages/electron-client-ipc/src/types/contextMenu.ts
new file mode 100644
index 00000000000..398aa2bb70e
--- /dev/null
+++ b/packages/electron-client-ipc/src/types/contextMenu.ts
@@ -0,0 +1,28 @@
+import type { SFSymbol } from 'sf-symbols-typescript';
+
+declare module 'sf-symbols-typescript' {
+ interface Overrides {
+ SFSymbolsVersion: '3.0';
+ }
+}
+
+export type { SFSymbol };
+
+export interface NativeContextMenuItemTemplate {
+ checked?: boolean;
+ enabled?: boolean;
+ id?: string;
+ label?: string;
+ sfSymbol?: SFSymbol;
+ sublabel?: string;
+ submenu?: NativeContextMenuItemTemplate[];
+ type: 'checkbox' | 'header' | 'normal' | 'separator' | 'submenu';
+}
+
+export interface PopupContextMenuParams {
+ items: NativeContextMenuItemTemplate[];
+}
+
+export interface PopupContextMenuResult {
+ clickedId: string | null;
+}
diff --git a/packages/electron-client-ipc/src/types/index.ts b/packages/electron-client-ipc/src/types/index.ts
index c47a6f80152..8563febfff6 100644
--- a/packages/electron-client-ipc/src/types/index.ts
+++ b/packages/electron-client-ipc/src/types/index.ts
@@ -1,6 +1,7 @@
export * from './binary';
export * from './browserControl';
export * from './browserSidebar';
+export * from './contextMenu';
export * from './dataSync';
export * from './git';
export * from './heterogeneousAgent';
diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
index 075b1e1225b..7c3b69086b5 100644
--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
@@ -1,7 +1,6 @@
import { AGENT_DOCUMENT_CATEGORY } from '@lobechat/const';
import { Center, Empty, Flexbox, Icon } from '@lobehub/ui';
import { SkillsIcon } from '@lobehub/ui/icons';
-import type { MenuProps } from 'antd';
import { createStaticStyles } from 'antd-style';
import { FileTextIcon, Maximize2Icon, PenLineIcon, Trash2Icon } from 'lucide-react';
import type { CSSProperties } from 'react';
@@ -23,6 +22,7 @@ import {
HIDE_POINTER_FOCUS_RING_CSS,
} from '@/features/ExplorerTree';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
import { agentDocumentService } from '@/services/agentDocument';
import { openConvertToSkillModal, slugifySkillName } from './ConvertToSkillModal';
@@ -279,7 +279,7 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen
);
const getContextMenuItems = useCallback(
- (node: ExplorerTreeNode<AgentDocumentItem>): MenuProps['items'] => {
+ (node: ExplorerTreeNode<AgentDocumentItem>): NativeContextMenuItem[] => {
const isSkill = node.data?.category === 'skill';
if (isSkill && !isRecoverableSkillBundle(node.data!)) {
return [];
@@ -296,7 +296,7 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen
const isMulti = selectedIds.length > 1 && selectedIds.includes(node.id);
const deleteIds = isMulti ? selectedIds : [node.id];
- const items: NonNullable<MenuProps['items']> = [];
+ const items: NativeContextMenuItem[] = [];
if (isFolder && !isSkill && !isMulti) {
items.push(
@@ -304,11 +304,13 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen
key: 'new-folder',
label: t('workingPanel.resources.tree.newFolder'),
onClick: () => handleCreateFolder(targetParentId),
+ sfSymbol: 'folder.badge.plus',
},
{
key: 'new-document',
label: t('workingPanel.resources.tree.newDocument'),
onClick: () => handleCreateDocument(targetParentId),
+ sfSymbol: 'doc.badge.plus',
},
{ key: 'div-1', type: 'divider' },
);
@@ -320,6 +322,7 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen
key: 'rename',
label: t('workingPanel.resources.tree.rename'),
onClick: () => startInlineRename(node.id),
+ sfSymbol: 'pencil',
});
}
@@ -331,6 +334,7 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen
key: 'open-as-page',
label: t('agentDocument.openAsPage'),
onClick: () => navigate(buildAgentDocumentPath(agentId, node.data!.documentId)),
+ sfSymbol: 'arrow.up.left.and.arrow.down.right',
});
}
@@ -344,6 +348,7 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen
key: 'convert-to-skill',
label: t('workingPanel.resources.tree.convertToSkill'),
onClick: () => handleConvertToSkill(node.data!),
+ sfSymbol: 'sparkles',
});
}
@@ -355,6 +360,7 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen
? t('workingPanel.resources.tree.deleteSelected', { count: deleteIds.length })
: t('delete', { ns: 'common' }),
onClick: () => ops.deleteDocuments(deleteIds),
+ sfSymbol: 'trash',
});
return items;
diff --git a/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx b/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx
index 5ac90a659d7..1e7640efa78 100644
--- a/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx
@@ -107,6 +107,7 @@ export const useTopicItemDropdownMenu = ({
markTopicCompleted(id);
}
},
+ sfSymbol: isCompleted ? 'tray.and.arrow.up' : 'archivebox',
},
{
disabled: !canEditTopic,
@@ -116,6 +117,7 @@ export const useTopicItemDropdownMenu = ({
onClick: () => {
favoriteTopic(id, !fav);
},
+ sfSymbol: fav ? 'star.slash' : 'star',
},
{
type: 'divider' as const,
@@ -128,6 +130,7 @@ export const useTopicItemDropdownMenu = ({
onClick: () => {
autoRenameTopicTitle(id);
},
+ sfSymbol: 'wand.and.stars',
},
{
disabled: !canEditTopic,
@@ -152,6 +155,7 @@ export const useTopicItemDropdownMenu = ({
title: t('renameModal.title', { ns: 'topic' }),
});
},
+ sfSymbol: 'pencil',
},
{
disabled: !canEditTopic,
@@ -161,6 +165,7 @@ export const useTopicItemDropdownMenu = ({
onClick: () => {
openTopicDoctorModal({ agentId: activeAgentId, topicId: id });
},
+ sfSymbol: 'stethoscope',
},
{
type: 'divider' as const,
@@ -254,6 +259,7 @@ export const useTopicItemDropdownMenu = ({
key: 'share',
label: t('shareModal.title', { ns: 'chat' }),
onClick: handleOpenShareModal,
+ sfSymbol: 'square.and.arrow.up',
},
{
type: 'divider' as const,
@@ -280,6 +286,7 @@ export const useTopicItemDropdownMenu = ({
topicIds: [id],
});
},
+ sfSymbol: 'trash',
},
].filter(Boolean) as MenuProps['items'];
}, [
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
index 83fc3c0a4a2..447915ac7a6 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
@@ -32,6 +32,7 @@ export const useThreadItemDropdownMenu = ({
onClick: () => {
toggleEditing(true);
},
+ sfSymbol: 'pencil',
},
{
type: 'divider' as const,
@@ -54,6 +55,7 @@ export const useThreadItemDropdownMenu = ({
title: t('delete', { ns: 'common' }),
});
},
+ sfSymbol: 'trash',
},
].filter(Boolean) as MenuProps['items'];
}, [id, canEditThread, removeThread, toggleEditing, t]);
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx
index 2c273012155..501fb16dc40 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx
@@ -10,6 +10,7 @@ import TaskSubtasks from './TaskSubtasks';
const mocks = vi.hoisted(() => ({
navigate: vi.fn(),
runReadySubtasks: vi.fn(),
+ showContextMenu: vi.fn(),
taskState: {
activeTaskId: 'T-parent',
taskDetailMap: {
@@ -56,7 +57,10 @@ vi.mock('@lobehub/ui', () => ({
Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
Icon: () => <span>icon</span>,
Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
- showContextMenu: vi.fn(),
+}));
+
+vi.mock('@/libs/contextMenu', () => ({
+ showContextMenu: mocks.showContextMenu,
}));
vi.mock('antd', () => ({
@@ -68,9 +72,11 @@ vi.mock('antd', () => ({
},
ConfigProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
Tree: ({
+ onRightClick,
onSelect,
treeData,
}: {
+ onRightClick?: (info: { event: unknown; node: { key: string } }) => void;
onSelect?: (keys: string[]) => void;
treeData?: Array<{ key: string; title: ReactNode }>;
}) => (
@@ -81,6 +87,10 @@ vi.mock('antd', () => ({
key={node.key}
type="button"
onClick={() => onSelect?.([node.key])}
+ onContextMenu={(event) => {
+ event.preventDefault();
+ onRightClick?.({ event, node: { key: node.key } });
+ }}
>
{node.title}
</button>
@@ -178,6 +188,7 @@ vi.mock('./TopicStatusIcon', () => ({
describe('TaskSubtasks', () => {
beforeEach(() => {
mocks.navigate.mockClear();
+ mocks.showContextMenu.mockClear();
mocks.taskState.taskDetailMap['T-parent'].subtasks = [
{
assignee: { avatar: null, backgroundColor: null, id: 'agt_child', title: 'Child' },
@@ -200,6 +211,14 @@ describe('TaskSubtasks', () => {
expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_child/task/T-child');
});
+ it('routes right-click on a subtask through @/libs/contextMenu', () => {
+ render(<TaskSubtasks />);
+
+ fireEvent.contextMenu(screen.getByTestId('subtask-tree-node'));
+
+ expect(mocks.showContextMenu).toHaveBeenCalledTimes(1);
+ });
+
it('falls back to the global task route when the selected subtask has no assignee', () => {
mocks.taskState.taskDetailMap['T-parent'].subtasks = [
{
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
index 653cb4d2c54..43fe0d10329 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
@@ -1,5 +1,5 @@
import type { TaskDetailSubtask } from '@lobechat/types';
-import { ActionIcon, Block, Flexbox, Icon, showContextMenu, Text } from '@lobehub/ui';
+import { ActionIcon, Block, Flexbox, Icon, Text } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { App, ConfigProvider, Tree } from 'antd';
import type { DataNode } from 'antd/es/tree';
@@ -11,6 +11,7 @@ import { useTranslation } from 'react-i18next';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { usePermission } from '@/hooks/usePermission';
+import { showContextMenu } from '@/libs/contextMenu';
import { taskService } from '@/services/task';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
diff --git a/src/features/AgentTasks/features/__snapshots__/useTaskItemContextMenu.test.tsx.snap b/src/features/AgentTasks/features/__snapshots__/useTaskItemContextMenu.test.tsx.snap
new file mode 100644
index 00000000000..dfb4387d992
--- /dev/null
+++ b/src/features/AgentTasks/features/__snapshots__/useTaskItemContextMenu.test.tsx.snap
@@ -0,0 +1,8 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`menu ownership > must stay web because the status/priority submenus depend on number-shortcut extra badges 1`] = `
+{
+ "menu": "AgentTasks/taskItem",
+ "native": false,
+}
+`;
diff --git a/src/features/AgentTasks/features/useTaskItemContextMenu.test.tsx b/src/features/AgentTasks/features/useTaskItemContextMenu.test.tsx
index 5f72e3d5055..52d375e5956 100644
--- a/src/features/AgentTasks/features/useTaskItemContextMenu.test.tsx
+++ b/src/features/AgentTasks/features/useTaskItemContextMenu.test.tsx
@@ -1,11 +1,14 @@
-import { renderHook } from '@testing-library/react';
+import { act, renderHook } from '@testing-library/react';
import type { ReactNode } from 'react';
import React from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { canGoNative } from '@/libs/contextMenu/canGoNative';
+
import { useTaskItemContextMenu } from './useTaskItemContextMenu';
const mocks = vi.hoisted(() => ({
+ closeContextMenu: vi.fn(),
copyToClipboard: vi.fn(),
deleteTask: vi.fn(),
messageSuccess: vi.fn(),
@@ -21,13 +24,16 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock('@lobehub/ui', () => ({
- closeContextMenu: vi.fn(),
copyToClipboard: mocks.copyToClipboard,
Flexbox: ({ children }: { children?: ReactNode }) => React.createElement('div', {}, children),
Icon: ({ icon: Icon }: { icon?: React.ComponentType }) =>
Icon ? React.createElement(Icon) : React.createElement('span'),
}));
+vi.mock('@/libs/contextMenu', () => ({
+ closeContextMenu: mocks.closeContextMenu,
+}));
+
vi.mock('antd', () => ({
App: {
useApp: () => ({
@@ -132,4 +138,54 @@ describe('useTaskItemContextMenu', () => {
expect(mocks.copyToClipboard).toHaveBeenCalledWith('https://example.com/task/T-1');
});
+
+ it('routes the keyboard-shortcut submenu selection through @/libs/contextMenu', () => {
+ const { result } = renderHook(() =>
+ useTaskItemContextMenu({
+ identifier: 'T-1',
+ priority: 0,
+ status: 'backlog',
+ }),
+ );
+
+ act(() => {
+ result.current.onContextMenu();
+ });
+
+ const statusItem = result.current.items.find(
+ (item) => item && typeof item === 'object' && 'key' in item && item.key === 'status',
+ ) as { onTitleMouseEnter?: () => void };
+
+ act(() => {
+ statusItem.onTitleMouseEnter?.();
+ });
+
+ act(() => {
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: '2' }));
+ });
+
+ expect(mocks.closeContextMenu).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('menu ownership', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('must stay web because the status/priority submenus depend on number-shortcut extra badges', () => {
+ const { result } = renderHook(() =>
+ useTaskItemContextMenu({
+ identifier: 'T-1',
+ priority: 0,
+ status: 'backlog',
+ }),
+ );
+
+ expect(canGoNative(result.current.items)).toBe(false);
+ expect({
+ menu: 'AgentTasks/taskItem',
+ native: canGoNative(result.current.items),
+ }).toMatchSnapshot();
+ });
});
diff --git a/src/features/AgentTasks/features/useTaskItemContextMenu.tsx b/src/features/AgentTasks/features/useTaskItemContextMenu.tsx
index c93246a716d..76db7788060 100644
--- a/src/features/AgentTasks/features/useTaskItemContextMenu.tsx
+++ b/src/features/AgentTasks/features/useTaskItemContextMenu.tsx
@@ -1,12 +1,5 @@
import type { TaskStatus } from '@lobechat/types';
-import {
- closeContextMenu,
- type ContextMenuItem,
- copyToClipboard,
- type GenericItemType,
- Icon,
- type MenuInfo,
-} from '@lobehub/ui';
+import { type ContextMenuItem, copyToClipboard, Icon, type MenuInfo } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { App } from 'antd';
import { cssVar } from 'antd-style';
@@ -26,6 +19,8 @@ import { useTaskTransferMenuItem } from '@/business/client/hooks/useTaskTransfer
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { useAppOrigin } from '@/hooks/useAppOrigin';
import { usePermission } from '@/hooks/usePermission';
+import { closeContextMenu } from '@/libs/contextMenu';
+import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useTaskStore } from '@/store/task';
@@ -41,7 +36,7 @@ type ActiveSubmenu = 'status' | 'priority' | null;
type TaskItemRouteScope = 'agent' | 'global';
interface TaskItemContextMenu {
- items: ContextMenuItem[];
+ items: NativeContextMenuItem[];
onContextMenu: () => void;
}
@@ -55,7 +50,7 @@ export interface TaskContextMenuTarget {
const RUN_NOW_STATUSES = new Set<TaskStatus>(['backlog', 'completed']);
export interface TaskContextMenuActions {
- buildItems: (task: TaskContextMenuTarget) => ContextMenuItem[];
+ buildItems: (task: TaskContextMenuTarget) => NativeContextMenuItem[];
installKeyboardHandlers: (task: TaskContextMenuTarget) => void;
}
@@ -94,7 +89,7 @@ export const useTaskContextMenuActions = (
});
};
- const buildItems = (task: TaskContextMenuTarget): ContextMenuItem[] => {
+ const buildItems = (task: TaskContextMenuTarget): NativeContextMenuItem[] => {
const currentStatus = task.status as TaskStatus;
const currentPriority = task.priority ?? 0;
@@ -164,9 +159,10 @@ export const useTaskContextMenuActions = (
}
await runTask(task.identifier);
},
+ sfSymbol: 'play.fill',
},
{ type: 'divider' },
- ] satisfies GenericItemType[])
+ ] satisfies NativeContextMenuItem[])
: []),
{
children: statusChildren,
@@ -198,6 +194,7 @@ export const useTaskContextMenuActions = (
await copyToClipboard(task.identifier);
message.success(t('taskList.contextMenu.copyIdSuccess'));
},
+ sfSymbol: 'doc.on.doc',
},
{
icon: <Icon icon={LinkIcon} />,
@@ -208,6 +205,7 @@ export const useTaskContextMenuActions = (
await copyToClipboard(taskUrl);
message.success(t('taskList.contextMenu.copyLinkSuccess'));
},
+ sfSymbol: 'doc.on.doc',
},
{ type: 'divider' },
{
@@ -221,6 +219,7 @@ export const useTaskContextMenuActions = (
if (!canEditTask) return;
triggerDelete(task.identifier);
},
+ sfSymbol: 'trash',
},
];
};
diff --git a/src/features/Conversation/WorkingSidebar/Files/index.tsx b/src/features/Conversation/WorkingSidebar/Files/index.tsx
index d5c816fd3de..ff6f864bfce 100644
--- a/src/features/Conversation/WorkingSidebar/Files/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/Files/index.tsx
@@ -3,7 +3,6 @@
import type { ProjectFileIndexEntry } from '@lobechat/electron-client-ipc';
import { Center, copyToClipboard, Empty, Flexbox, SearchBar, stopPropagation } from '@lobehub/ui';
import type { GitStatusEntry } from '@pierre/trees';
-import type { MenuProps } from 'antd';
import { message } from 'antd';
import { createStaticStyles } from 'antd-style';
import { FileIcon } from 'lucide-react';
@@ -21,6 +20,7 @@ import {
HIDE_POINTER_FOCUS_RING_CSS,
} from '@/features/ExplorerTree';
import type { ExplorerTreeHandle } from '@/features/ExplorerTree/types';
+import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
import { localFileService } from '@/services/electron/localFileService';
import { projectFileService } from '@/services/projectFile';
import { useChatStore } from '@/store/chat';
@@ -294,7 +294,7 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
);
const getContextMenuItems = useCallback(
- (node: ExplorerTreeNode<ProjectFileIndexEntry>): MenuProps['items'] => {
+ (node: ExplorerTreeNode<ProjectFileIndexEntry>): NativeContextMenuItem[] => {
if (!node.data) return [];
const { path, relativePath } = node.data;
@@ -302,7 +302,7 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
// OS-level actions (open in app / reveal in Finder) only work on the local
// machine — omit them for a remote device.
- const localActions: MenuProps['items'] = isRemote
+ const localActions: NativeContextMenuItem[] = isRemote
? []
: [
{
@@ -318,7 +318,7 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
},
];
- const reviewActions: MenuProps['items'] = isDirty
+ const reviewActions: NativeContextMenuItem[] = isDirty
? [
{
key: 'show-in-review',
@@ -340,6 +340,7 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
await copyToClipboard(path);
message.success(t('workingPanel.review.copied'));
},
+ sfSymbol: 'doc.on.doc',
},
{
key: 'copy-relative-path',
@@ -348,6 +349,7 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
await copyToClipboard(relativePath);
message.success(t('workingPanel.review.copied'));
},
+ sfSymbol: 'doc.on.doc',
},
];
},
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
index 1ca44d880aa..16705fe2177 100644
--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
@@ -439,6 +439,7 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
key: 'view',
label: t('workingPanel.skills.actions.view'),
onClick: openAgentSkill,
+ sfSymbol: 'eye',
},
{
disabled: !rowId,
@@ -466,6 +467,7 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
},
});
},
+ sfSymbol: 'pencil',
},
{
danger: true,
@@ -494,6 +496,7 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
title: t('workingPanel.skills.delete.title'),
});
},
+ sfSymbol: 'trash',
},
];
};
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx
index 68ffa829bc4..ab0a79bfa17 100644
--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx
@@ -80,6 +80,7 @@ const UserLevelSkills = memo<UserLevelSkillsProps>(({ hideHeader }) => {
key: 'view',
label: t('workingPanel.skills.actions.view'),
onClick: () => setDetailSkillId(skill.id),
+ sfSymbol: 'eye',
},
];
@@ -106,6 +107,7 @@ const UserLevelSkills = memo<UserLevelSkillsProps>(({ hideHeader }) => {
},
});
},
+ sfSymbol: 'pencil',
});
}
@@ -134,6 +136,7 @@ const UserLevelSkills = memo<UserLevelSkillsProps>(({ hideHeader }) => {
title: t('workingPanel.skills.delete.title'),
});
},
+ sfSymbol: 'trash',
});
return actions;
diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsx
index 90cf9e1f032..62b8fb10498 100644
--- a/src/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/index.tsx
@@ -1,6 +1,7 @@
+import type { SFSymbol } from '@lobechat/electron-client-ipc';
import { nanoid } from '@lobechat/utils';
import { ActionIcon, Flexbox, Icon, type IconProps, Skeleton } from '@lobehub/ui';
-import { type ContextMenuItem, type DropdownItem, DropdownMenu } from '@lobehub/ui/base-ui';
+import { type DropdownItem, DropdownMenu } from '@lobehub/ui/base-ui';
import { SkillsIcon } from '@lobehub/ui/icons';
import { createStaticStyles } from 'antd-style';
import {
@@ -48,6 +49,7 @@ import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
import { useLocalStorageState } from '@/hooks/useLocalStorageState';
+import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
@@ -495,7 +497,7 @@ const AgentWorkingSidebar = memo(() => {
})
.filter((tab): tab is SidebarTabDescriptor => Boolean(tab));
const createTabContextMenuItems = useCallback(
- (tab: string, index: number): ContextMenuItem[] => {
+ (tab: string, index: number): NativeContextMenuItem[] => {
const pinned = pinnedTabsSet.has(tab);
const leftTabs = openedTabs.slice(0, index);
const rightTabs = openedTabs.slice(index + 1);
@@ -510,7 +512,8 @@ const AgentWorkingSidebar = memo(() => {
key: pinned ? 'unpin' : 'pin',
label: t(pinned ? 'workingPanel.tabs.unpin' : 'workingPanel.tabs.pin'),
onClick: () => (pinned ? unpinTab(tab) : pinTab(tab)),
- } as ContextMenuItem,
+ sfSymbol: (pinned ? 'pin.slash' : 'pin') satisfies SFSymbol,
+ } as NativeContextMenuItem,
{ type: 'divider' as const },
]
: []),
@@ -544,7 +547,7 @@ const AgentWorkingSidebar = memo(() => {
},
[closeTab, closeTabs, openedTabs, pinTab, pinnedTabsSet, t, unpinTab],
);
- const overviewContextMenuItems = useMemo<ContextMenuItem[]>(
+ const overviewContextMenuItems = useMemo<NativeContextMenuItem[]>(
() => [
{
disabled: !openedTabs.some((tab) => !pinnedTabsSet.has(tab)),
diff --git a/src/features/Conversation/hooks/useChatItemContextMenu.tsx b/src/features/Conversation/hooks/useChatItemContextMenu.tsx
index ffafbd7c57f..931e0a88df1 100644
--- a/src/features/Conversation/hooks/useChatItemContextMenu.tsx
+++ b/src/features/Conversation/hooks/useChatItemContextMenu.tsx
@@ -1,10 +1,10 @@
+import type { SFSymbol } from '@lobechat/electron-client-ipc';
import {
type ActionIconGroupEvent,
type ActionIconGroupItemType,
- type DropdownItem,
type GenericItemType,
} from '@lobehub/ui';
-import { createRawModal, showContextMenu } from '@lobehub/ui';
+import { createRawModal } from '@lobehub/ui';
import { App } from 'antd';
import isEqual from 'fast-deep-equal';
import { type MouseEvent, type ReactNode } from 'react';
@@ -14,6 +14,8 @@ import { useTranslation } from 'react-i18next';
import { MSG_CONTENT_CLASSNAME } from '@/features/Conversation/ChatItem/components/MessageContent';
import { resolveHeteroErroredStepId } from '@/features/Conversation/Error/heterogeneous';
import { usePermission } from '@/hooks/usePermission';
+import { showContextMenu } from '@/libs/contextMenu';
+import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
import { useSessionStore } from '@/store/session';
import { sessionSelectors } from '@/store/session/selectors';
import { useUserStore } from '@/store/user';
@@ -36,6 +38,7 @@ interface ActionMenuItem extends ActionIconGroupItemType {
children?: { key: string; label: ReactNode }[];
disable?: boolean;
popupClassName?: string;
+ sfSymbol?: SFSymbol;
}
type MenuItem = ActionMenuItem | { type: 'divider' };
@@ -393,7 +396,8 @@ export const useChatItemContextMenu = ({
key: actionItem.key,
label: actionItem.label,
onClick: children ? undefined : handleMenuClick,
- } satisfies DropdownItem;
+ sfSymbol: actionItem.sfSymbol,
+ } satisfies NativeContextMenuItem;
});
}, [handleMenuClick, menuItems]);
diff --git a/src/features/Conversation/hooks/useChatListActionsBar.tsx b/src/features/Conversation/hooks/useChatListActionsBar.tsx
index bdcc6d70313..42e1199214c 100644
--- a/src/features/Conversation/hooks/useChatListActionsBar.tsx
+++ b/src/features/Conversation/hooks/useChatListActionsBar.tsx
@@ -1,3 +1,4 @@
+import type { SFSymbol } from '@lobechat/electron-client-ipc';
import { type ActionIconGroupItemType } from '@lobehub/ui';
import { css, cx } from 'antd-style';
import {
@@ -27,21 +28,23 @@ const translateStyle = css`
}
`;
+type ActionBarItem = ActionIconGroupItemType & { sfSymbol?: SFSymbol };
+
interface ChatListActionsBar {
- branching: ActionIconGroupItemType;
- collapse: ActionIconGroupItemType;
- continueGeneration: ActionIconGroupItemType;
- copy: ActionIconGroupItemType;
- del: ActionIconGroupItemType;
- delAndRegenerate: ActionIconGroupItemType;
+ branching: ActionBarItem;
+ collapse: ActionBarItem;
+ continueGeneration: ActionBarItem;
+ copy: ActionBarItem;
+ del: ActionBarItem;
+ delAndRegenerate: ActionBarItem;
divider: { type: 'divider' };
- edit: ActionIconGroupItemType;
- expand: ActionIconGroupItemType;
- export: ActionIconGroupItemType;
- regenerate: ActionIconGroupItemType;
- share: ActionIconGroupItemType;
- translate: ActionIconGroupItemType;
- tts: ActionIconGroupItemType;
+ edit: ActionBarItem;
+ expand: ActionBarItem;
+ export: ActionBarItem;
+ regenerate: ActionBarItem;
+ share: ActionBarItem;
+ translate: ActionBarItem;
+ tts: ActionBarItem;
}
export const useChatListActionsBar = ({
@@ -78,6 +81,7 @@ export const useChatListActionsBar = ({
icon: Copy,
key: 'copy',
label: t('copy'),
+ sfSymbol: 'doc.on.doc',
},
del: {
danger: true,
@@ -85,6 +89,7 @@ export const useChatListActionsBar = ({
icon: Trash,
key: 'del',
label: hasThread ? t('messageAction.deleteDisabledByThreads', { ns: 'chat' }) : t('delete'),
+ sfSymbol: 'trash',
},
delAndRegenerate: {
disabled: hasThread || isRegenerating,
@@ -101,6 +106,7 @@ export const useChatListActionsBar = ({
icon: Edit,
key: 'edit',
label: t('edit'),
+ sfSymbol: 'pencil',
},
expand: {
icon: ListChevronsUpDown,
@@ -111,18 +117,21 @@ export const useChatListActionsBar = ({
icon: DownloadIcon,
key: 'export',
label: 'Export as PDF',
+ sfSymbol: 'square.and.arrow.up',
},
regenerate: {
disabled: isRegenerating,
icon: RotateCcw,
key: 'regenerate',
label: t('regenerate'),
+ sfSymbol: 'arrow.clockwise',
spin: isRegenerating,
},
share: {
icon: Share2,
key: 'share',
label: t('share'),
+ sfSymbol: 'square.and.arrow.up',
},
translate: {
children: localeOptions.map((i) => ({
diff --git a/src/features/Electron/titlebar/TabBar/TabItem.tsx b/src/features/Electron/titlebar/TabBar/TabItem.tsx
index f8f655abb10..84d7970bf51 100644
--- a/src/features/Electron/titlebar/TabBar/TabItem.tsx
+++ b/src/features/Electron/titlebar/TabBar/TabItem.tsx
@@ -21,6 +21,7 @@ import { type ResolvedTab } from './hooks/useResolvedTabs';
import { useTabRunning } from './hooks/useTabRunning';
import { useTabUnread } from './hooks/useTabUnread';
import { useStyles } from './styles';
+import { buildTabContextMenuItems } from './tabContextMenu';
interface TabItemProps {
index: number;
@@ -73,33 +74,17 @@ const TabItem = memo<TabItemProps>(
);
const contextMenuItems = useCallback(
- (): GenericItemType[] => [
- {
- disabled: totalCount === 1,
- key: 'closeCurrentTab',
- label: t('tab.closeCurrentTab'),
- onClick: () => onClose(id),
- },
- {
- disabled: totalCount === 1,
- key: 'closeOtherTabs',
- label: t('tab.closeOtherTabs'),
- onClick: () => onCloseOthers(id),
- },
- { type: 'divider' },
- {
- disabled: index === 0,
- key: 'closeLeftTabs',
- label: t('tab.closeLeftTabs'),
- onClick: () => onCloseLeft(id),
- },
- {
- disabled: index === totalCount - 1,
- key: 'closeRightTabs',
- label: t('tab.closeRightTabs'),
- onClick: () => onCloseRight(id),
- },
- ],
+ (): GenericItemType[] =>
+ buildTabContextMenuItems({
+ id,
+ index,
+ onClose,
+ onCloseLeft,
+ onCloseOthers,
+ onCloseRight,
+ t,
+ totalCount,
+ }),
[t, id, index, totalCount, onClose, onCloseOthers, onCloseLeft, onCloseRight],
);
diff --git a/src/features/Electron/titlebar/TabBar/__snapshots__/tabContextMenu.test.ts.snap b/src/features/Electron/titlebar/TabBar/__snapshots__/tabContextMenu.test.ts.snap
new file mode 100644
index 00000000000..d7fd1f71570
--- /dev/null
+++ b/src/features/Electron/titlebar/TabBar/__snapshots__/tabContextMenu.test.ts.snap
@@ -0,0 +1,29 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`tab context menu ownership > goes native on macOS desktop (plain string labels, no web-only capabilities) 1`] = `
+[
+ {
+ "id": "0",
+ "label": "tab.closeCurrentTab",
+ "type": "normal",
+ },
+ {
+ "id": "1",
+ "label": "tab.closeOtherTabs",
+ "type": "normal",
+ },
+ {
+ "type": "separator",
+ },
+ {
+ "id": "3",
+ "label": "tab.closeLeftTabs",
+ "type": "normal",
+ },
+ {
+ "id": "4",
+ "label": "tab.closeRightTabs",
+ "type": "normal",
+ },
+]
+`;
diff --git a/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts b/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts
new file mode 100644
index 00000000000..18167387b06
--- /dev/null
+++ b/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { canGoNative } from '@/libs/contextMenu/canGoNative';
+import { toNativeTemplate } from '@/libs/contextMenu/toNativeTemplate';
+
+import { buildTabContextMenuItems } from './tabContextMenu';
+
+const build = (index: number, totalCount: number) =>
+ buildTabContextMenuItems({
+ id: 'tab-1',
+ index,
+ onClose: vi.fn(),
+ onCloseLeft: vi.fn(),
+ onCloseOthers: vi.fn(),
+ onCloseRight: vi.fn(),
+ t: (key) => key,
+ totalCount,
+ });
+
+describe('tab context menu ownership', () => {
+ it('goes native on macOS desktop (plain string labels, no web-only capabilities)', () => {
+ const items = build(1, 3);
+
+ expect(canGoNative(items)).toBe(true);
+ expect(toNativeTemplate(items).template).toMatchSnapshot();
+ });
+
+ it('stays native-eligible in the fully disabled single-tab state', () => {
+ expect(canGoNative(build(0, 1))).toBe(true);
+ });
+});
diff --git a/src/features/Electron/titlebar/TabBar/tabContextMenu.ts b/src/features/Electron/titlebar/TabBar/tabContextMenu.ts
new file mode 100644
index 00000000000..cb4a847ba6f
--- /dev/null
+++ b/src/features/Electron/titlebar/TabBar/tabContextMenu.ts
@@ -0,0 +1,52 @@
+import type { GenericItemType } from '@lobehub/ui';
+
+type TabContextMenuLabelKey =
+ 'tab.closeCurrentTab' | 'tab.closeLeftTabs' | 'tab.closeOtherTabs' | 'tab.closeRightTabs';
+
+interface TabContextMenuParams {
+ id: string;
+ index: number;
+ onClose: (id: string) => void;
+ onCloseLeft: (id: string) => void;
+ onCloseOthers: (id: string) => void;
+ onCloseRight: (id: string) => void;
+ t: (key: TabContextMenuLabelKey) => string;
+ totalCount: number;
+}
+
+export const buildTabContextMenuItems = ({
+ id,
+ index,
+ onClose,
+ onCloseLeft,
+ onCloseOthers,
+ onCloseRight,
+ t,
+ totalCount,
+}: TabContextMenuParams): GenericItemType[] => [
+ {
+ disabled: totalCount === 1,
+ key: 'closeCurrentTab',
+ label: t('tab.closeCurrentTab'),
+ onClick: () => onClose(id),
+ },
+ {
+ disabled: totalCount === 1,
+ key: 'closeOtherTabs',
+ label: t('tab.closeOtherTabs'),
+ onClick: () => onCloseOthers(id),
+ },
+ { type: 'divider' },
+ {
+ disabled: index === 0,
+ key: 'closeLeftTabs',
+ label: t('tab.closeLeftTabs'),
+ onClick: () => onCloseLeft(id),
+ },
+ {
+ disabled: index === totalCount - 1,
+ key: 'closeRightTabs',
+ label: t('tab.closeRightTabs'),
+ onClick: () => onCloseRight(id),
+ },
+];
diff --git a/src/features/ExplorerTree/types.ts b/src/features/ExplorerTree/types.ts
index 85b628ccb71..16e82b0ec49 100644
--- a/src/features/ExplorerTree/types.ts
+++ b/src/features/ExplorerTree/types.ts
@@ -1,7 +1,8 @@
import type { FileTreeRowDecoration, GitStatusEntry } from '@pierre/trees';
-import type { MenuProps } from 'antd';
import type { CSSProperties, DragEvent, MouseEvent, ReactNode } from 'react';
+import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
+
export interface ExplorerTreeNode<TData = unknown> {
children?: ExplorerTreeNode<TData>[];
data?: TData;
@@ -55,7 +56,7 @@ export interface ExplorerTreeProps<TData = unknown> {
defaultSelectedIds?: string[];
density?: 'compact' | 'default' | 'relaxed' | number;
expandedIds?: string[];
- getContextMenuItems?: (node: ExplorerTreeNode<TData>) => MenuProps['items'];
+ getContextMenuItems?: (node: ExplorerTreeNode<TData>) => NativeContextMenuItem[];
getRowDecoration?: (
ctx: ExplorerTreeRowDecorationCtx<TData>,
) => FileTreeRowDecoration | null | undefined;
diff --git a/src/features/ExplorerTree/view/ContextMenu.tsx b/src/features/ExplorerTree/view/ContextMenu.tsx
index 6a535ae9524..6ef20c5166b 100644
--- a/src/features/ExplorerTree/view/ContextMenu.tsx
+++ b/src/features/ExplorerTree/view/ContextMenu.tsx
@@ -1,17 +1,17 @@
-import { type ContextMenuItem, showContextMenu } from '@lobehub/ui';
-import type { MenuProps } from 'antd';
-
-type AntdItem = NonNullable<MenuProps['items']>[number];
+import { showContextMenu } from '@/libs/contextMenu';
+import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
// Defers the user's onClick to the next frame so base-ui's focus restoration
// on close completes before the action runs. Without this, actions like
// inline-rename briefly take focus and then lose it back to whatever was
// active before the menu opened, which makes the rename input invisible.
-const wrapItem = (item: AntdItem): ContextMenuItem => {
- if (!item || typeof item !== 'object') return item as ContextMenuItem;
+const wrapItem = (item: NativeContextMenuItem): NativeContextMenuItem => {
+ if (!item || typeof item !== 'object') return item;
const next = { ...(item as unknown as Record<string, unknown>) };
if ('children' in item && Array.isArray((item as { children?: unknown }).children)) {
- next.children = (item as { children: AntdItem[] }).children.map((child) => wrapItem(child));
+ next.children = (item as { children: NativeContextMenuItem[] }).children.map((child) =>
+ wrapItem(child),
+ );
}
const original = (item as { onClick?: (...args: unknown[]) => void }).onClick;
if (original) {
@@ -19,10 +19,10 @@ const wrapItem = (item: AntdItem): ContextMenuItem => {
requestAnimationFrame(() => original(...args));
};
}
- return next as unknown as ContextMenuItem;
+ return next as unknown as NativeContextMenuItem;
};
-export const openExplorerContextMenu = (items: MenuProps['items']) => {
+export const openExplorerContextMenu = (items: NativeContextMenuItem[]) => {
if (!items || items.length === 0) return;
- showContextMenu(items.map((item) => wrapItem(item as AntdItem)));
+ showContextMenu(items.map((item) => wrapItem(item)));
};
diff --git a/src/features/ExplorerTree/view/ExplorerTree.test.tsx b/src/features/ExplorerTree/view/ExplorerTree.test.tsx
index 6b8ba72d7e3..e788a1109ca 100644
--- a/src/features/ExplorerTree/view/ExplorerTree.test.tsx
+++ b/src/features/ExplorerTree/view/ExplorerTree.test.tsx
@@ -1,16 +1,122 @@
+import { AGENT_DOCUMENT_CATEGORY, CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
import { act, fireEvent, render, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
import { useRef } from 'react';
+import { MemoryRouter } from 'react-router';
import { describe, expect, it, vi } from 'vitest';
+import DocumentExplorerTree from '@/features/AgentDocumentsExplorer/DocumentExplorerTree';
+import type { AgentDocumentItem } from '@/features/AgentDocumentsExplorer/types';
+import { canGoNative } from '@/libs/contextMenu/canGoNative';
+import { toNativeTemplate } from '@/libs/contextMenu/toNativeTemplate';
+
import type { ExplorerTreeHandle } from '../types';
import ExplorerTree, { getItemPathFromEventPath } from './ExplorerTree';
const showContextMenu = vi.hoisted(() => vi.fn());
vi.mock('@lobehub/ui', () => ({
+ ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) => (
+ <button aria-label={title} onClick={onClick}>
+ {title}
+ </button>
+ ),
+ Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ genCdnUrl: () => '',
+ Icon: () => <span />,
showContextMenu,
+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+}));
+
+vi.mock('@/libs/contextMenu', () => ({
+ showContextMenu,
+}));
+
+vi.mock('@lobehub/ui/icons', () => ({
+ SkillsIcon: () => null,
+}));
+
+vi.mock('@lobehub/ui/base-ui', () => ({
+ confirmModal: vi.fn(),
+}));
+
+vi.mock('antd', () => ({
+ App: {
+ useApp: () => ({
+ message: { error: vi.fn(), success: vi.fn(), warning: vi.fn() },
+ modal: { confirm: vi.fn() },
+ }),
+ },
+}));
+
+vi.mock('@/services/agentDocument', () => ({
+ agentDocumentService: {
+ removeDocument: vi.fn(),
+ },
+}));
+
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => vi.fn(),
}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+const dispatchRealContextMenuEventRetargetedPastShadowRoot = (
+ shadowRow: HTMLElement,
+ shadowHost: Element,
+): void => {
+ const contextMenuEvent = new MouseEvent('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ });
+ Object.defineProperty(contextMenuEvent, 'target', { configurable: true, value: shadowHost });
+ shadowRow.dispatchEvent(contextMenuEvent);
+};
+
+const createFolderDocument = (overrides: Partial<AgentDocumentItem>): AgentDocumentItem =>
+ ({
+ accessPublic: 0,
+ accessSelf: 0,
+ accessShared: 0,
+ agentId: 'agent-1',
+ category: AGENT_DOCUMENT_CATEGORY,
+ content: '',
+ createdAt: new Date('2026-05-09T00:00:00Z'),
+ deletedAt: null,
+ deletedByAgentId: null,
+ deletedByUserId: null,
+ deleteReason: null,
+ description: null,
+ documentId: 'doc-1',
+ editorData: null,
+ filename: 'Notes',
+ fileType: CUSTOM_FOLDER_FILE_TYPE,
+ id: 'folder-row',
+ isFolder: true,
+ isSkillBundle: false,
+ isSkillIndex: false,
+ loadRules: {},
+ metadata: null,
+ parentId: null,
+ policy: null,
+ policyLoad: 'disabled',
+ policyLoadFormat: 'raw',
+ policyLoadPosition: 'before-first-user',
+ policyLoadRule: 'always',
+ source: null,
+ sourceType: 'file',
+ templateId: null,
+ title: 'Notes',
+ updatedAt: new Date('2026-05-09T00:00:00Z'),
+ userId: 'user-1',
+ ...overrides,
+ }) as AgentDocumentItem;
+
describe('ExplorerTree', () => {
it('commits folder renames through the canonical adapter path', async () => {
let handleRef: React.RefObject<ExplorerTreeHandle | null>;
@@ -69,3 +175,41 @@ describe('ExplorerTree', () => {
expect(getItemPathFromEventPath([row])).toBe('Parent/Child/');
});
});
+
+describe('DocumentExplorerTree menu ownership', () => {
+ it('goes native for the folder row context menu, reached through a real contextmenu DOM event', async () => {
+ showContextMenu.mockClear();
+
+ const data = [createFolderDocument({})];
+
+ const { container } = render(
+ <DocumentExplorerTree agentId="agent-1" data={data} mutate={vi.fn()} />,
+ { wrapper: MemoryRouter },
+ );
+
+ const host = container.querySelector('file-tree-container');
+
+ const folderRow = await waitFor(() => {
+ const el = host?.shadowRoot?.querySelector<HTMLElement>(
+ '[data-type="item"][data-item-path="Notes/"]',
+ );
+ expect(el).toBeInstanceOf(HTMLElement);
+ return el!;
+ });
+
+ dispatchRealContextMenuEventRetargetedPastShadowRoot(folderRow, host!);
+
+ await waitFor(() => {
+ expect(showContextMenu).toHaveBeenCalledTimes(1);
+ });
+
+ const [items] = showContextMenu.mock.calls[0];
+
+ expect(canGoNative(items)).toBe(true);
+ expect({
+ menu: 'ExplorerTree/documentNode',
+ native: canGoNative(items),
+ }).toMatchSnapshot();
+ expect(toNativeTemplate(items).template).toMatchSnapshot();
+ });
+});
diff --git a/src/features/ExplorerTree/view/__snapshots__/ExplorerTree.test.tsx.snap b/src/features/ExplorerTree/view/__snapshots__/ExplorerTree.test.tsx.snap
new file mode 100644
index 00000000000..ad64e0d09ee
--- /dev/null
+++ b/src/features/ExplorerTree/view/__snapshots__/ExplorerTree.test.tsx.snap
@@ -0,0 +1,40 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`DocumentExplorerTree menu ownership > goes native for the folder row context menu, reached through a real contextmenu DOM event 1`] = `
+{
+ "menu": "ExplorerTree/documentNode",
+ "native": true,
+}
+`;
+
+exports[`DocumentExplorerTree menu ownership > goes native for the folder row context menu, reached through a real contextmenu DOM event 2`] = `
+[
+ {
+ "id": "0",
+ "label": "workingPanel.resources.tree.newFolder",
+ "sfSymbol": "folder.badge.plus",
+ "type": "normal",
+ },
+ {
+ "id": "1",
+ "label": "workingPanel.resources.tree.newDocument",
+ "sfSymbol": "doc.badge.plus",
+ "type": "normal",
+ },
+ {
+ "type": "separator",
+ },
+ {
+ "id": "3",
+ "label": "workingPanel.resources.tree.rename",
+ "sfSymbol": "pencil",
+ "type": "normal",
+ },
+ {
+ "id": "4",
+ "label": "delete",
+ "sfSymbol": "trash",
+ "type": "normal",
+ },
+]
+`;
diff --git a/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx b/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx
index 04e8312afe5..fa6bf44bcd8 100644
--- a/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx
+++ b/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx
@@ -103,6 +103,7 @@ export const useDropdownMenu = ({
markTopicCompleted(topicId);
}
},
+ sfSymbol: isCompleted ? 'tray.and.arrow.up' : 'archivebox',
},
{
type: 'divider' as const,
@@ -117,6 +118,7 @@ export const useDropdownMenu = ({
onClick: () => {
favoriteTopic(topicId, !fav);
},
+ sfSymbol: fav ? 'star.slash' : 'star',
},
{
type: 'divider' as const,
@@ -129,6 +131,7 @@ export const useDropdownMenu = ({
onClick: () => {
autoRenameTopicTitle(topicId);
},
+ sfSymbol: 'wand.and.stars',
},
{
disabled: !canEditTopic,
@@ -145,6 +148,7 @@ export const useDropdownMenu = ({
title: t('renameModal.title', { ns: 'topic' }),
});
},
+ sfSymbol: 'pencil',
},
{
type: 'divider' as const,
@@ -222,6 +226,7 @@ export const useDropdownMenu = ({
key: 'share',
label: t('share'),
onClick: handleOpenShareModal,
+ sfSymbol: 'square.and.arrow.up',
},
{
type: 'divider' as const,
@@ -242,6 +247,7 @@ export const useDropdownMenu = ({
topicIds: [topicId],
});
},
+ sfSymbol: 'trash',
},
].filter(Boolean) as MenuProps['items'],
[
diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
index aa7392dbe37..1c59578d6d2 100644
--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
@@ -1,4 +1,5 @@
import { CUSTOM_FOLDER_FILE_TYPE, DERIVED_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';
+import type { SFSymbol } from '@lobechat/electron-client-ipc';
import { copyToClipboard, createRawModal, Icon, Tooltip } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { App } from 'antd';
@@ -49,8 +50,10 @@ interface UseFileItemDropdownParams {
visibility?: 'private' | 'public' | null;
}
+type FileMenuItem = ItemType & { sfSymbol?: SFSymbol };
+
interface UseFileItemDropdownReturn {
- menuItems: () => ItemType[];
+ menuItems: () => FileMenuItem[];
}
/**
@@ -345,6 +348,7 @@ export const useFileItemDropdown = ({
if (!canManage) return;
onRenameStart?.();
},
+ sfSymbol: 'pencil',
},
{
icon: <Icon icon={LinkIcon} />,
@@ -366,11 +370,13 @@ export const useFileItemDropdown = ({
await copyToClipboard(urlToCopy);
message.success(t('FileManager.actions.copyUrlSuccess'));
},
+ sfSymbol: 'doc.on.doc',
},
!isFolder && {
icon: <Icon icon={DownloadIcon} />,
key: 'download',
label: t('download', { ns: 'common' }),
+ sfSymbol: 'square.and.arrow.down',
onClick: async ({ domEvent }) => {
domEvent.stopPropagation();
const key = 'file-downloading';
@@ -459,8 +465,9 @@ export const useFileItemDropdown = ({
},
});
},
+ sfSymbol: 'trash',
},
- ] as ItemType[]
+ ] as FileMenuItem[]
).filter(Boolean);
}, [
addFilesToKnowledgeBase,
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
index 6d1a00e62e2..99aba66a239 100644
--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
@@ -3,11 +3,12 @@ import {
CUSTOM_FOLDER_FILE_TYPE,
MARKDOWN_MIME_TYPES,
} from '@lobechat/const';
-import { Checkbox, showContextMenu, stopPropagation } from '@lobehub/ui';
+import { Checkbox, stopPropagation } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { showContextMenu } from '@/libs/contextMenu';
import {
getTransparentDragImage,
useDragActive,
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
index 08b46237679..c7bc2a3c353 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
+++ b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
@@ -2,7 +2,7 @@
import { CaretDownFilled, LoadingOutlined } from '@ant-design/icons';
import { DERIVED_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';
-import { ActionIcon, Block, Flexbox, Icon, showContextMenu, stopPropagation } from '@lobehub/ui';
+import { ActionIcon, Block, Flexbox, Icon, stopPropagation } from '@lobehub/ui';
import { App, Input } from 'antd';
import { cx } from 'antd-style';
import { FileText, FolderIcon, FolderOpenIcon } from 'lucide-react';
@@ -12,6 +12,7 @@ import React, { memo, useCallback, useMemo, useRef, useState } from 'react';
import FileIcon from '@/components/FileIcon';
import { PAGE_FILE_TYPE } from '@/features/ResourceManager/constants';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { showContextMenu } from '@/libs/contextMenu';
import {
getTransparentDragImage,
useDragActive,
diff --git a/src/features/SkillsList/SkillsList.tsx b/src/features/SkillsList/SkillsList.tsx
index eeca2757a75..748b28aa68a 100644
--- a/src/features/SkillsList/SkillsList.tsx
+++ b/src/features/SkillsList/SkillsList.tsx
@@ -1,4 +1,5 @@
import { EMPTY_ARRAY } from '@lobechat/const';
+import type { SFSymbol } from '@lobechat/electron-client-ipc';
import {
ContextMenuTrigger,
Flexbox,
@@ -45,6 +46,7 @@ export interface SkillRowAction {
key: string;
label: string;
onClick: (item: SkillListItem) => void;
+ sfSymbol?: SFSymbol;
/** Hover-icon tooltip; falls back to `label`. Use for "coming soon" hints. */
tooltip?: string;
}
@@ -341,7 +343,7 @@ const SkillRow = memo<SkillRowProps>(
}, []);
const contextMenuItems = useCallback(
- (): GenericItemType[] =>
+ (): (GenericItemType & { sfSymbol?: SFSymbol })[] =>
actions.map((action) => ({
danger: action.danger,
disabled: action.disabled,
@@ -349,6 +351,7 @@ const SkillRow = memo<SkillRowProps>(
key: action.key,
label: action.label,
onClick: () => action.onClick(item),
+ sfSymbol: action.sfSymbol,
})),
[actions, item],
);
diff --git a/src/features/SkillsList/useProjectSkills.ts b/src/features/SkillsList/useProjectSkills.ts
index fed4dd5c64d..e9803ab6ddc 100644
--- a/src/features/SkillsList/useProjectSkills.ts
+++ b/src/features/SkillsList/useProjectSkills.ts
@@ -120,6 +120,7 @@ export const useProjectSkills = (
key: 'view',
label: t('workingPanel.skills.actions.view'),
onClick: onOpenSkill,
+ sfSymbol: 'eye',
},
{
// Renaming a filesystem skill needs an IPC/RPC that doesn't exist yet.
@@ -128,6 +129,7 @@ export const useProjectSkills = (
key: 'rename',
label: t('workingPanel.skills.actions.rename'),
onClick: () => {},
+ sfSymbol: 'pencil',
tooltip: comingSoon,
},
{
@@ -137,6 +139,7 @@ export const useProjectSkills = (
key: 'delete',
label: t('workingPanel.skills.actions.delete'),
onClick: () => {},
+ sfSymbol: 'trash',
tooltip: comingSoon,
},
];
diff --git a/src/layout/SPAGlobalProvider/index.test.tsx b/src/layout/SPAGlobalProvider/index.test.tsx
index 142f3f24109..5f5f6b54f20 100644
--- a/src/layout/SPAGlobalProvider/index.test.tsx
+++ b/src/layout/SPAGlobalProvider/index.test.tsx
@@ -25,6 +25,7 @@ vi.mock('@lobehub/ui', async () => {
ContextMenuHost: () => React.createElement('div', { 'data-testid': 'context-menu-host' }),
ModalHost: () => React.createElement('div', { 'data-testid': 'legacy-modal-host' }),
TooltipGroup: Passthrough,
+ setContextMenuInterceptor: vi.fn(),
};
});
diff --git a/src/layout/SPAGlobalProvider/index.tsx b/src/layout/SPAGlobalProvider/index.tsx
index b45bc025e7a..ee17eb23612 100644
--- a/src/layout/SPAGlobalProvider/index.tsx
+++ b/src/layout/SPAGlobalProvider/index.tsx
@@ -19,11 +19,14 @@ import { GroupWizardProvider } from '@/layout/GlobalProvider/GroupWizardProvider
import QueryProvider from '@/layout/GlobalProvider/Query';
import ServerVersionOutdatedAlert from '@/layout/GlobalProvider/ServerVersionOutdatedAlert';
import StoreInitialization from '@/layout/GlobalProvider/StoreInitialization';
+import { registerNativeContextMenuInterceptor } from '@/libs/contextMenu';
import { ServerConfigStoreProvider } from '@/store/serverConfig/Provider';
import type { SPAServerConfig } from '@/types/spaServerConfig';
import Locale from './Locale';
+registerNativeContextMenuInterceptor();
+
const ModalHost = lazy(() => import('@lobehub/ui').then((m) => ({ default: m.ModalHost })));
const BaseModalHost = lazy(() =>
import('@lobehub/ui/base-ui').then((m) => ({ default: m.ModalHost })),
diff --git a/src/libs/contextMenu/canGoNative.test.ts b/src/libs/contextMenu/canGoNative.test.ts
new file mode 100644
index 00000000000..60f1bbda937
--- /dev/null
+++ b/src/libs/contextMenu/canGoNative.test.ts
@@ -0,0 +1,156 @@
+import { describe, expect, it } from 'vitest';
+
+import { canGoNative } from './canGoNative';
+import type { NativeContextMenuItem } from './types';
+
+describe('canGoNative', () => {
+ describe('accepts', () => {
+ it('a plain normal item', () => {
+ expect(canGoNative([{ key: '1', label: 'Copy' }])).toBe(true);
+ });
+
+ it('a divider', () => {
+ expect(canGoNative([{ type: 'divider' }])).toBe(true);
+ });
+
+ it('a group with plain children', () => {
+ expect(canGoNative([{ children: [{ key: '1', label: 'Copy' }], type: 'group' }])).toBe(true);
+ });
+
+ it('a checkbox item', () => {
+ expect(canGoNative([{ checked: true, key: '1', label: 'Wrap', type: 'checkbox' }])).toBe(
+ true,
+ );
+ });
+
+ it('an item with sfSymbol present', () => {
+ expect(canGoNative([{ key: '1', label: 'Copy', sfSymbol: 'doc.on.doc' }])).toBe(true);
+ });
+
+ it('an item with a string desc', () => {
+ expect(canGoNative([{ desc: 'Ctrl+C', key: '1', label: 'Copy' }])).toBe(true);
+ });
+
+ it('an item with a numeric label', () => {
+ expect(canGoNative([{ key: '1', label: 42 }])).toBe(true);
+ });
+
+ it('a group with an empty children array (unlike a submenu, an empty group is not rejected)', () => {
+ expect(canGoNative([{ children: [], type: 'group' }])).toBe(true);
+ });
+ });
+
+ describe('rejects', () => {
+ it('a switch item', () => {
+ expect(canGoNative([{ checked: true, key: '1', label: 'Auto save', type: 'switch' }])).toBe(
+ false,
+ );
+ });
+
+ it('an item with non-empty extra', () => {
+ const items = [
+ { extra: '1', key: '1', label: 'Delete' },
+ ] as unknown as NativeContextMenuItem[];
+ expect(canGoNative(items)).toBe(false);
+ });
+
+ it('a loading item', () => {
+ const items = [
+ { key: '1', label: 'Save', loading: true },
+ ] as unknown as NativeContextMenuItem[];
+ expect(canGoNative(items)).toBe(false);
+ });
+
+ it('an item whose label is not a string/number', () => {
+ const items = [
+ { key: '1', label: { toString: () => 'react-node-ish' } },
+ ] as unknown as NativeContextMenuItem[];
+ expect(canGoNative(items)).toBe(false);
+ });
+
+ it('an item whose desc is present but not a string', () => {
+ const items = [{ desc: 42, key: '1', label: 'Copy' }] as unknown as NativeContextMenuItem[];
+ expect(canGoNative(items)).toBe(false);
+ });
+
+ it('a reject-rule hit inside a second-level submenu', () => {
+ const items: NativeContextMenuItem[] = [
+ {
+ children: [
+ {
+ children: [{ key: '1-1-1', label: 'Delete', loading: true } as never],
+ key: '1-1',
+ label: 'Nested',
+ },
+ ],
+ key: '1',
+ label: 'Top',
+ },
+ ];
+ expect(canGoNative(items)).toBe(false);
+ });
+
+ it('a reject-rule hit inside a group child', () => {
+ const items: NativeContextMenuItem[] = [
+ {
+ children: [{ checked: true, key: '1', label: 'Toggle', type: 'switch' }],
+ type: 'group',
+ },
+ ];
+ expect(canGoNative(items)).toBe(false);
+ });
+
+ it('when options.header is set', () => {
+ expect(canGoNative([{ key: '1', label: 'Copy' }], { header: 'Header' })).toBe(false);
+ });
+
+ it('when options.footer is set', () => {
+ expect(canGoNative([{ key: '1', label: 'Copy' }], { footer: 'Footer' })).toBe(false);
+ });
+
+ it('a submenu-shaped item with an empty children array', () => {
+ const items: NativeContextMenuItem[] = [{ children: [], key: '1', label: 'Empty submenu' }];
+ expect(canGoNative(items)).toBe(false);
+ });
+
+ it('a type: submenu item with no children field at all', () => {
+ const items: NativeContextMenuItem[] = [
+ { key: '1', label: 'Empty submenu', type: 'submenu' },
+ ];
+ expect(canGoNative(items)).toBe(false);
+ });
+
+ it('an item with closeOnClick: false', () => {
+ const items: NativeContextMenuItem[] = [{ closeOnClick: false, key: '1', label: 'Upload' }];
+ expect(canGoNative(items)).toBe(false);
+ });
+
+ it('a submenu item carrying an item-level header slot', () => {
+ const items: NativeContextMenuItem[] = [
+ {
+ children: [{ key: '1-1', label: 'Child' }],
+ header: 'Pinned header',
+ key: '1',
+ label: 'File',
+ },
+ ];
+ expect(canGoNative(items)).toBe(false);
+ });
+
+ it('a submenu item carrying an item-level footer slot', () => {
+ const items: NativeContextMenuItem[] = [
+ {
+ children: [{ key: '1-1', label: 'Child' }],
+ footer: 'Pinned footer',
+ key: '1',
+ label: 'File',
+ },
+ ];
+ expect(canGoNative(items)).toBe(false);
+ });
+ });
+
+ it('skips null items without rejecting the menu', () => {
+ expect(canGoNative([null, { key: '1', label: 'Copy' }])).toBe(true);
+ });
+});
diff --git a/src/libs/contextMenu/canGoNative.ts b/src/libs/contextMenu/canGoNative.ts
new file mode 100644
index 00000000000..c6814ffde2e
--- /dev/null
+++ b/src/libs/contextMenu/canGoNative.ts
@@ -0,0 +1,46 @@
+import type { NativeContextMenuItem, ShowContextMenuOptions } from './types';
+
+export const isSubmenuShaped = (item: Exclude<NativeContextMenuItem, null>): boolean =>
+ item.type !== 'group' &&
+ (item.type === 'submenu' || Boolean('children' in item && item.children));
+
+const isNativeSafe = (item: NativeContextMenuItem): boolean => {
+ if (item === null) return true;
+ if (item.type === 'switch') return false;
+
+ if ('extra' in item && item.extra) return false;
+ if ('loading' in item && item.loading) return false;
+ if ('closeOnClick' in item && item.closeOnClick === false) return false;
+
+ if ('label' in item) {
+ const { label } = item;
+ if (label !== undefined && typeof label !== 'string' && typeof label !== 'number') return false;
+ }
+
+ if ('desc' in item) {
+ const { desc } = item;
+ if (desc !== undefined && typeof desc !== 'string') return false;
+ }
+
+ const children = 'children' in item ? item.children : undefined;
+
+ if (isSubmenuShaped(item)) {
+ if ('header' in item && item.header) return false;
+ if ('footer' in item && item.footer) return false;
+ if (!children || children.length === 0) return false;
+ }
+
+ if (children) {
+ return children.every(isNativeSafe);
+ }
+
+ return true;
+};
+
+export const canGoNative = (
+ items: NativeContextMenuItem[],
+ options?: ShowContextMenuOptions,
+): boolean => {
+ if (options?.header || options?.footer) return false;
+ return items.every(isNativeSafe);
+};
diff --git a/src/libs/contextMenu/index.test.ts b/src/libs/contextMenu/index.test.ts
new file mode 100644
index 00000000000..91c5b03742e
--- /dev/null
+++ b/src/libs/contextMenu/index.test.ts
@@ -0,0 +1,276 @@
+import {
+ closeContextMenu as closeWebContextMenu,
+ type ContextMenuInterceptor,
+ setContextMenuInterceptor,
+ showContextMenu as showWebContextMenu,
+} from '@lobehub/ui';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { electronSystemService } from '@/services/electron/system';
+
+import { closeContextMenu, registerNativeContextMenuInterceptor, showContextMenu } from './index';
+import type { NativeContextMenuItem } from './types';
+
+vi.mock('@lobehub/ui', () => ({
+ closeContextMenu: vi.fn(),
+ setContextMenuInterceptor: vi.fn(),
+ showContextMenu: vi.fn(),
+}));
+
+vi.mock('@/services/electron/system', () => ({
+ electronSystemService: {
+ closePopupContextMenu: vi.fn(),
+ popupContextMenu: vi.fn(),
+ },
+}));
+
+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+const stubDarwin = () => {
+ window.lobeEnv = { platform: 'darwin' };
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ delete window.lobeEnv;
+});
+
+afterEach(() => {
+ delete window.lobeEnv;
+});
+
+describe('showContextMenu routing', () => {
+ it('delegates to the web menu verbatim on non-darwin platforms', () => {
+ const items: NativeContextMenuItem[] = [{ key: '1', label: 'Copy' }];
+ const options = { iconAlign: 'center' as const };
+
+ showContextMenu(items, options);
+
+ expect(showWebContextMenu).toHaveBeenCalledWith(items, options);
+ expect(electronSystemService.popupContextMenu).not.toHaveBeenCalled();
+ });
+
+ it('delegates to the web menu on darwin when the menu is not native-safe', () => {
+ stubDarwin();
+ const items = [{ extra: 'x', key: '1', label: 'Copy' }] as unknown as NativeContextMenuItem[];
+
+ showContextMenu(items);
+
+ expect(showWebContextMenu).toHaveBeenCalledWith(items, undefined);
+ expect(electronSystemService.popupContextMenu).not.toHaveBeenCalled();
+ });
+
+ it('goes native on darwin when the menu is native-safe', () => {
+ stubDarwin();
+ vi.mocked(electronSystemService.popupContextMenu).mockResolvedValue({ clickedId: null });
+
+ showContextMenu([{ key: '1', label: 'Copy' }]);
+
+ expect(electronSystemService.popupContextMenu).toHaveBeenCalledTimes(1);
+ expect(showWebContextMenu).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the web menu when the native template would be empty', () => {
+ stubDarwin();
+
+ showContextMenu([]);
+
+ expect(showWebContextMenu).toHaveBeenCalledWith([], undefined);
+ expect(electronSystemService.popupContextMenu).not.toHaveBeenCalled();
+ });
+});
+
+describe('native popup resolution', () => {
+ it('invokes the matching handler once the IPC call resolves', async () => {
+ stubDarwin();
+ const onClick = vi.fn();
+ vi.mocked(electronSystemService.popupContextMenu).mockResolvedValue({ clickedId: '0' });
+
+ showContextMenu([{ key: '1', label: 'Copy', onClick }]);
+
+ await vi.waitFor(() => expect(onClick).toHaveBeenCalledTimes(1));
+ });
+
+ it('invokes no handler when the menu is cancelled', async () => {
+ stubDarwin();
+ const onClick = vi.fn();
+ vi.mocked(electronSystemService.popupContextMenu).mockResolvedValue({ clickedId: null });
+
+ showContextMenu([{ key: '1', label: 'Copy', onClick }]);
+
+ await flush();
+
+ expect(onClick).not.toHaveBeenCalled();
+ });
+
+ it('does not throw when the IPC call rejects, and invokes no handler', async () => {
+ stubDarwin();
+ const onClick = vi.fn();
+ vi.mocked(electronSystemService.popupContextMenu).mockRejectedValue(new Error('boom'));
+
+ expect(() => showContextMenu([{ key: '1', label: 'Copy', onClick }])).not.toThrow();
+
+ await flush();
+
+ expect(onClick).not.toHaveBeenCalled();
+ });
+
+ it('ignores a stale popup resolution and keeps the newer popup live', async () => {
+ stubDarwin();
+
+ let resolveA: (result: { clickedId: string | null }) => void = () => {};
+ let resolveB: (result: { clickedId: string | null }) => void = () => {};
+ const promiseA = new Promise<{ clickedId: string | null }>((resolve) => {
+ resolveA = resolve;
+ });
+ const promiseB = new Promise<{ clickedId: string | null }>((resolve) => {
+ resolveB = resolve;
+ });
+
+ vi.mocked(electronSystemService.popupContextMenu)
+ .mockReturnValueOnce(promiseA)
+ .mockReturnValueOnce(promiseB);
+
+ const onClickA = vi.fn();
+ const onClickB = vi.fn();
+
+ showContextMenu([{ key: 'a', label: 'A', onClick: onClickA }]);
+ showContextMenu([{ key: 'b', label: 'B', onClick: onClickB }]);
+
+ resolveA({ clickedId: '0' });
+ await flush();
+
+ expect(onClickA).not.toHaveBeenCalled();
+ expect(onClickB).not.toHaveBeenCalled();
+
+ closeContextMenu();
+ expect(electronSystemService.closePopupContextMenu).toHaveBeenCalledTimes(1);
+ expect(closeWebContextMenu).not.toHaveBeenCalled();
+
+ resolveB({ clickedId: '0' });
+ await vi.waitFor(() => expect(onClickB).toHaveBeenCalledTimes(1));
+
+ expect(onClickA).not.toHaveBeenCalled();
+ });
+});
+
+describe('closeContextMenu routing', () => {
+ it('routes to the native IPC after a native menu was shown', () => {
+ stubDarwin();
+ vi.mocked(electronSystemService.popupContextMenu).mockResolvedValue({ clickedId: null });
+ showContextMenu([{ key: '1', label: 'Copy' }]);
+
+ closeContextMenu();
+
+ expect(electronSystemService.closePopupContextMenu).toHaveBeenCalledTimes(1);
+ expect(closeWebContextMenu).not.toHaveBeenCalled();
+ });
+
+ it('routes to the web menu after a web menu was shown', () => {
+ showContextMenu([{ key: '1', label: 'Copy' }]);
+
+ closeContextMenu();
+
+ expect(closeWebContextMenu).toHaveBeenCalledTimes(1);
+ expect(electronSystemService.closePopupContextMenu).not.toHaveBeenCalled();
+ });
+
+ it('routes to the web menu once a native popup has settled after a click', async () => {
+ stubDarwin();
+ vi.mocked(electronSystemService.popupContextMenu).mockResolvedValue({ clickedId: '0' });
+ showContextMenu([{ key: '1', label: 'Copy', onClick: vi.fn() }]);
+
+ await flush();
+
+ closeContextMenu();
+
+ expect(closeWebContextMenu).toHaveBeenCalledTimes(1);
+ expect(electronSystemService.closePopupContextMenu).not.toHaveBeenCalled();
+ });
+
+ it('routes to the web menu once a native popup has settled after a cancel', async () => {
+ stubDarwin();
+ vi.mocked(electronSystemService.popupContextMenu).mockResolvedValue({ clickedId: null });
+ showContextMenu([{ key: '1', label: 'Copy' }]);
+
+ await flush();
+
+ closeContextMenu();
+
+ expect(closeWebContextMenu).toHaveBeenCalledTimes(1);
+ expect(electronSystemService.closePopupContextMenu).not.toHaveBeenCalled();
+ });
+
+ it('routes to the web menu after a native popup settles by rejecting', async () => {
+ stubDarwin();
+ vi.mocked(electronSystemService.popupContextMenu).mockRejectedValue(new Error('boom'));
+ showContextMenu([{ key: '1', label: 'Copy' }]);
+
+ await flush();
+
+ closeContextMenu();
+
+ expect(closeWebContextMenu).toHaveBeenCalledTimes(1);
+ expect(electronSystemService.closePopupContextMenu).not.toHaveBeenCalled();
+ });
+});
+
+describe('registerNativeContextMenuInterceptor', () => {
+ const getInterceptor = (): ContextMenuInterceptor => {
+ registerNativeContextMenuInterceptor();
+ expect(setContextMenuInterceptor).toHaveBeenCalledTimes(1);
+ return vi.mocked(setContextMenuInterceptor).mock.calls[0][0] as ContextMenuInterceptor;
+ };
+
+ it('routes declarative shows to the native popup on darwin without touching the fallback', async () => {
+ stubDarwin();
+ vi.mocked(electronSystemService.popupContextMenu).mockResolvedValue({ clickedId: null });
+ const fallback = vi.fn();
+
+ getInterceptor().show?.([{ key: '1', label: 'Copy' }], undefined, fallback);
+ await flush();
+
+ expect(electronSystemService.popupContextMenu).toHaveBeenCalledTimes(1);
+ expect(fallback).not.toHaveBeenCalled();
+ });
+
+ it('invokes the fallback for native-unsafe items and off darwin', () => {
+ const fallback = vi.fn();
+ const interceptor = getInterceptor();
+
+ interceptor.show?.([{ key: '1', label: 'Copy' }], undefined, fallback);
+ expect(fallback).toHaveBeenCalledTimes(1);
+
+ stubDarwin();
+ interceptor.show?.(
+ [{ extra: 'x', key: '1', label: 'Copy' }] as unknown as NativeContextMenuItem[],
+ undefined,
+ fallback,
+ );
+ expect(fallback).toHaveBeenCalledTimes(2);
+ expect(electronSystemService.popupContextMenu).not.toHaveBeenCalled();
+ });
+
+ it('routes close to the native IPC while a native popup is open, else to the fallback', async () => {
+ stubDarwin();
+ let resolvePopup: (value: { clickedId: string | null }) => void = () => {};
+ vi.mocked(electronSystemService.popupContextMenu).mockImplementation(
+ () => new Promise((resolve) => (resolvePopup = resolve)),
+ );
+ const closeFallback = vi.fn();
+ const interceptor = getInterceptor();
+
+ interceptor.show?.([{ key: '1', label: 'Copy' }], undefined, vi.fn());
+ interceptor.close?.(closeFallback);
+
+ expect(electronSystemService.closePopupContextMenu).toHaveBeenCalledTimes(1);
+ expect(closeFallback).not.toHaveBeenCalled();
+
+ resolvePopup({ clickedId: null });
+ await flush();
+ interceptor.close?.(closeFallback);
+
+ expect(closeFallback).toHaveBeenCalledTimes(1);
+ expect(electronSystemService.closePopupContextMenu).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/libs/contextMenu/index.ts b/src/libs/contextMenu/index.ts
new file mode 100644
index 00000000000..e7630c473a4
--- /dev/null
+++ b/src/libs/contextMenu/index.ts
@@ -0,0 +1,94 @@
+import {
+ closeContextMenu as closeWebContextMenu,
+ setContextMenuInterceptor,
+ showContextMenu as showWebContextMenu,
+} from '@lobehub/ui';
+import debug from 'debug';
+
+import { electronSystemService } from '@/services/electron/system';
+
+import { canGoNative } from './canGoNative';
+import { isDarwinDesktop } from './platform';
+import { toNativeTemplate } from './toNativeTemplate';
+import type { NativeContextMenuItem, ShowContextMenuOptions } from './types';
+
+const log = debug('lobe-client:context-menu');
+
+let popupToken = 0;
+let activeMenu: 'native' | 'web' | null = null;
+
+const runNativePopup = (
+ template: ReturnType<typeof toNativeTemplate>['template'],
+ handlers: Map<string, () => void>,
+) => {
+ const token = ++popupToken;
+ activeMenu = 'native';
+
+ log('opening native context menu with %d item(s)', template.length);
+
+ electronSystemService
+ .popupContextMenu({ items: template })
+ .then((result) => {
+ if (token !== popupToken) return;
+ activeMenu = null;
+ const handler = result.clickedId ? handlers.get(result.clickedId) : undefined;
+ handlers.clear();
+ handler?.();
+ })
+ .catch((error) => {
+ if (token !== popupToken) return;
+ activeMenu = null;
+ handlers.clear();
+ log('popupContextMenu failed: %O', error);
+ });
+};
+
+const routeShow = (
+ items: NativeContextMenuItem[],
+ options: ShowContextMenuOptions | undefined,
+ showWeb: () => void,
+) => {
+ if (!isDarwinDesktop() || !canGoNative(items, options)) {
+ activeMenu = 'web';
+ showWeb();
+ return;
+ }
+
+ const { template, handlers } = toNativeTemplate(items);
+
+ if (template.length === 0) {
+ activeMenu = 'web';
+ showWeb();
+ return;
+ }
+
+ runNativePopup(template, handlers);
+};
+
+const routeClose = (closeWeb: () => void) => {
+ if (activeMenu === 'native') {
+ activeMenu = null;
+ void electronSystemService.closePopupContextMenu();
+ return;
+ }
+
+ closeWeb();
+};
+
+export const showContextMenu = (
+ items: NativeContextMenuItem[],
+ options?: ShowContextMenuOptions,
+): void => {
+ routeShow(items, options, () => showWebContextMenu(items, options));
+};
+
+export const closeContextMenu = (): void => {
+ routeClose(closeWebContextMenu);
+};
+
+export const registerNativeContextMenuInterceptor = (): void => {
+ setContextMenuInterceptor({
+ close: routeClose,
+ show: routeShow,
+ });
+};
diff --git a/src/libs/contextMenu/platform.ts b/src/libs/contextMenu/platform.ts
new file mode 100644
index 00000000000..86074986e97
--- /dev/null
+++ b/src/libs/contextMenu/platform.ts
@@ -0,0 +1,5 @@
+export type LobeEnv = NonNullable<Window['lobeEnv']>;
+
+export const getLobeEnv = (): LobeEnv | undefined => window.lobeEnv;
+
+export const isDarwinDesktop = (): boolean => getLobeEnv()?.platform === 'darwin';
diff --git a/src/libs/contextMenu/toNativeTemplate.test.ts b/src/libs/contextMenu/toNativeTemplate.test.ts
new file mode 100644
index 00000000000..23d03284785
--- /dev/null
+++ b/src/libs/contextMenu/toNativeTemplate.test.ts
@@ -0,0 +1,195 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { toNativeTemplate } from './toNativeTemplate';
+import type { NativeContextMenuItem } from './types';
+
+describe('toNativeTemplate', () => {
+ it('maps a divider to a separator', () => {
+ const { template } = toNativeTemplate([{ type: 'divider' }]);
+ expect(template).toEqual([{ type: 'separator' }]);
+ });
+
+ it('maps children to a submenu', () => {
+ const { template } = toNativeTemplate([
+ { children: [{ key: '1', label: 'Copy' }], key: 'root', label: 'File' },
+ ]);
+ expect(template).toEqual([
+ {
+ label: 'File',
+ submenu: [{ id: '0.0', label: 'Copy', type: 'normal' }],
+ type: 'submenu',
+ },
+ ]);
+ });
+
+ it('treats an item with undefined children as a plain actionable item, not an inert submenu', () => {
+ const onClick = vi.fn();
+ const { template, handlers } = toNativeTemplate([
+ { children: undefined, key: '1', label: 'Delete', onClick },
+ ]);
+
+ expect(template).toEqual([{ id: '0', label: 'Delete', type: 'normal' }]);
+
+ handlers.get('0')?.();
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('maps a checkbox item and its checked state', () => {
+ const { template } = toNativeTemplate([
+ { checked: true, key: '1', label: 'Wrap', type: 'checkbox' },
+ ]);
+ expect(template).toEqual([{ checked: true, id: '0', label: 'Wrap', type: 'checkbox' }]);
+ });
+
+ it('falls back to defaultChecked when checked is uncontrolled, and reports the correct toggled value', () => {
+ const onCheckedChange = vi.fn();
+ const { template, handlers } = toNativeTemplate([
+ { defaultChecked: true, key: '1', label: 'Wrap', onCheckedChange, type: 'checkbox' },
+ ]);
+
+ expect(template).toEqual([{ checked: true, id: '0', label: 'Wrap', type: 'checkbox' }]);
+
+ handlers.get('0')?.();
+ expect(onCheckedChange).toHaveBeenCalledWith(false);
+ });
+
+ it('maps a string desc to sublabel', () => {
+ const { template } = toNativeTemplate([{ desc: 'Ctrl+C', key: '1', label: 'Copy' }]);
+ expect(template).toEqual([{ id: '0', label: 'Copy', sublabel: 'Ctrl+C', type: 'normal' }]);
+ });
+
+ it('maps disabled to enabled: false', () => {
+ const { template } = toNativeTemplate([{ disabled: true, key: '1', label: 'Copy' }]);
+ expect(template).toEqual([{ enabled: false, id: '0', label: 'Copy', type: 'normal' }]);
+ });
+
+ it('stringifies a numeric label', () => {
+ const { template } = toNativeTemplate([{ key: '1', label: 42 }]);
+ expect(template[0].label).toBe('42');
+ });
+
+ it('passes sfSymbol through unchanged', () => {
+ const { template } = toNativeTemplate([{ key: '1', label: 'Copy', sfSymbol: 'doc.on.doc' }]);
+ expect(template[0].sfSymbol).toBe('doc.on.doc');
+ });
+
+ it('flattens a group into a header followed by its children as siblings', () => {
+ const { template } = toNativeTemplate([
+ {
+ children: [
+ { key: 'a', label: 'A' },
+ { key: 'b', label: 'B' },
+ ],
+ label: 'Section',
+ type: 'group',
+ },
+ ]);
+ expect(template).toEqual([
+ { type: 'header', label: 'Section' },
+ { id: '0.0', label: 'A', type: 'normal' },
+ { id: '0.1', label: 'B', type: 'normal' },
+ ]);
+ });
+
+ it('flattens an unlabeled group into just its children, with no header row', () => {
+ const { template } = toNativeTemplate([
+ {
+ children: [
+ { key: 'a', label: 'A' },
+ { key: 'b', label: 'B' },
+ ],
+ type: 'group',
+ },
+ ]);
+ expect(template).toEqual([
+ { id: '0.0', label: 'A', type: 'normal' },
+ { id: '0.1', label: 'B', type: 'normal' },
+ ]);
+ });
+
+ it('assigns tree-path ids and keeps ids stable across duplicate sibling keys at different levels', () => {
+ const { template } = toNativeTemplate([
+ {
+ children: [
+ {
+ children: [{ key: 'dup', label: 'Deep' }],
+ key: 'dup',
+ label: 'Nested',
+ },
+ ],
+ key: 'dup',
+ label: 'Top',
+ },
+ ]);
+ expect(template[0].id).toBeUndefined();
+ expect(template[0].submenu?.[0].id).toBeUndefined();
+ expect(template[0].submenu?.[0].submenu?.[0].id).toBe('0.0.0');
+ });
+
+ it('fires the right onClick handler with a synthetic MenuInfo whose domEvent supports stopPropagation', () => {
+ const onClickA = vi.fn();
+ const onClickB = vi.fn();
+ const { handlers } = toNativeTemplate([
+ { key: 'a', label: 'A', onClick: onClickA },
+ { key: 'b', label: 'B', onClick: onClickB },
+ ]);
+
+ handlers.get('1')?.();
+
+ expect(onClickA).not.toHaveBeenCalled();
+ expect(onClickB).toHaveBeenCalledTimes(1);
+
+ const info = onClickB.mock.calls[0][0];
+ expect(info.key).toBe('b');
+ expect(() => info.domEvent.stopPropagation()).not.toThrow();
+ });
+
+ it('invokes onCheckedChange with the toggled value', () => {
+ const onCheckedChange = vi.fn();
+ const { handlers } = toNativeTemplate([
+ { checked: true, key: '1', label: 'Wrap', onCheckedChange, type: 'checkbox' },
+ ]);
+
+ handlers.get('0')?.();
+
+ expect(onCheckedChange).toHaveBeenCalledWith(false);
+ });
+
+ it('drops icon, danger and popupClassName from the output', () => {
+ const items = [
+ {
+ danger: true,
+ icon: 'ShouldNotAppear',
+ key: '1',
+ label: 'Delete',
+ popupClassName: 'ShouldNotAppearEither',
+ },
+ ] as unknown as NativeContextMenuItem[];
+ const { template } = toNativeTemplate(items);
+ const serialized = JSON.stringify(template);
+ expect(serialized).not.toContain('ShouldNotAppear');
+ expect(serialized).not.toContain('danger');
+ expect(serialized).not.toContain('icon');
+ expect(serialized).not.toContain('popupClassName');
+ });
+
+ it('drops null items', () => {
+ const { template } = toNativeTemplate([null, { key: '1', label: 'Copy' }]);
+ expect(template).toEqual([{ id: '1', label: 'Copy', type: 'normal' }]);
+ });
+
+ it('produces a structured-cloneable template', () => {
+ const { template } = toNativeTemplate([
+ {
+ children: [
+ { checked: true, key: 'a', label: 'A', onCheckedChange: () => {}, type: 'checkbox' },
+ { type: 'divider' },
+ ],
+ key: 'root',
+ label: 'Root',
+ onClick: () => {},
+ },
+ ]);
+ expect(() => structuredClone(template)).not.toThrow();
+ });
+});
diff --git a/src/libs/contextMenu/toNativeTemplate.ts b/src/libs/contextMenu/toNativeTemplate.ts
new file mode 100644
index 00000000000..7dfa2181ce6
--- /dev/null
+++ b/src/libs/contextMenu/toNativeTemplate.ts
@@ -0,0 +1,115 @@
+import type { NativeContextMenuItemTemplate, SFSymbol } from '@lobechat/electron-client-ipc';
+import type { MenuInfo } from '@lobehub/ui';
+
+import { isSubmenuShaped } from './canGoNative';
+import type { NativeContextMenuItem } from './types';
+
+export interface ToNativeTemplateResult {
+ handlers: Map<string, () => void>;
+ template: NativeContextMenuItemTemplate[];
+}
+
+const compact = <T extends Record<string, unknown>>(obj: T): T => {
+ const result = {} as T;
+ for (const key of Object.keys(obj) as (keyof T)[]) {
+ if (obj[key] !== undefined) result[key] = obj[key];
+ }
+ return result;
+};
+
+const toLabel = (label: unknown): string | undefined =>
+ typeof label === 'string' || typeof label === 'number' ? String(label) : undefined;
+
+const toSublabel = (desc: unknown): string | undefined =>
+ typeof desc === 'string' ? desc : undefined;
+
+const buildMenuInfo = (key: string): MenuInfo =>
+ ({
+ domEvent: new MouseEvent('click'),
+ key,
+ keyPath: [key],
+ }) as unknown as MenuInfo;
+
+// FIXME: `danger` is dropped because Electron's MenuItem (as of 43) exposes no destructive/red styling API;
+// once upstream adds one (same route as createMenuSymbol, electron/electron#48911), map danger here instead of dropping it
+const baseFields = (item: {
+ desc?: unknown;
+ disabled?: boolean;
+ label?: unknown;
+ sfSymbol?: SFSymbol;
+}) =>
+ compact({
+ enabled: item.disabled ? false : undefined,
+ label: toLabel(item.label),
+ sfSymbol: item.sfSymbol,
+ sublabel: toSublabel(item.desc),
+ });
+
+const convertChildren = (
+ items: NativeContextMenuItem[],
+ parentId: string,
+ handlers: Map<string, () => void>,
+): NativeContextMenuItemTemplate[] =>
+ items.flatMap((item, index) => convertItem(item, `${parentId}.${index}`, handlers));
+
+const convertItem = (
+ item: NativeContextMenuItem,
+ id: string,
+ handlers: Map<string, () => void>,
+): NativeContextMenuItemTemplate[] => {
+ if (item === null) return [];
+
+ if (item.type === 'divider') {
+ return [{ type: 'separator' }];
+ }
+
+ if (item.type === 'group') {
+ const label = toLabel(item.label);
+ const children = convertChildren(item.children ?? [], id, handlers);
+ return label === undefined ? children : [{ label, type: 'header' }, ...children];
+ }
+
+ if (isSubmenuShaped(item)) {
+ const children = 'children' in item ? (item.children ?? []) : [];
+ return [
+ {
+ ...baseFields(item),
+ submenu: convertChildren(children, id, handlers),
+ type: 'submenu',
+ },
+ ];
+ }
+
+ if (item.type === 'switch') return [];
+
+ const clickable = item as {
+ checked?: boolean;
+ defaultChecked?: boolean;
+ key?: unknown;
+ onCheckedChange?: (checked: boolean) => void;
+ onClick?: (info: MenuInfo) => void;
+ };
+
+ if (item.type === 'checkbox') {
+ const resolvedChecked = clickable.checked ?? clickable.defaultChecked;
+ handlers.set(id, () => clickable.onCheckedChange?.(!resolvedChecked));
+ return [
+ {
+ ...baseFields(item),
+ ...(resolvedChecked !== undefined && { checked: resolvedChecked }),
+ id,
+ type: 'checkbox',
+ },
+ ];
+ }
+
+ const key = String(clickable.key ?? id);
+ handlers.set(id, () => clickable.onClick?.(buildMenuInfo(key)));
+ return [{ ...baseFields(item), id, type: 'normal' }];
+};
+
+export const toNativeTemplate = (items: NativeContextMenuItem[]): ToNativeTemplateResult => {
+ const handlers = new Map<string, () => void>();
+ const template = items.flatMap((item, index) => convertItem(item, String(index), handlers));
+ return { handlers, template };
+};
diff --git a/src/libs/contextMenu/types.ts b/src/libs/contextMenu/types.ts
new file mode 100644
index 00000000000..7144e20ac65
--- /dev/null
+++ b/src/libs/contextMenu/types.ts
@@ -0,0 +1,29 @@
+import type { SFSymbol } from '@lobechat/electron-client-ipc';
+import type { ContextMenuItem, showContextMenu as showWebContextMenu } from '@lobehub/ui';
+import type { ItemType } from 'antd/es/menu/interface';
+
+type NativeMenuIcon = {
+ sfSymbol?: SFSymbol;
+};
+
+type WithSfSymbol<T> = T extends null
+ ? null
+ : T extends { children: (infer Item)[] }
+ ? Omit<T, 'children'> & NativeMenuIcon & { children: WithSfSymbol<Item>[] }
+ : T extends { children?: (infer Item)[] }
+ ? Omit<T, 'children'> & NativeMenuIcon & { children?: WithSfSymbol<Item>[] }
+ : T & NativeMenuIcon;
+
+export type NativeContextMenuItem = WithSfSymbol<ContextMenuItem>;
+
+export type ShowContextMenuOptions = NonNullable<Parameters<typeof showWebContextMenu>[1]>;
+
+type AssertTrue<_T extends true> = never;
+
+export type AssertContextMenuItemArrayAssignable = AssertTrue<
+ ContextMenuItem[] extends NativeContextMenuItem[] ? true : false
+>;
+
+export type AssertAntdItemTypeArrayAssignable = AssertTrue<
+ ItemType[] extends NativeContextMenuItem[] ? true : false
+>;
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
index d094e60b579..0aae7f40dfd 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
@@ -85,6 +85,7 @@ export const useTopicItemDropdownMenu = ({
markTopicCompleted(id);
}
},
+ sfSymbol: isCompleted ? 'tray.and.arrow.up' : 'archivebox',
},
{
type: 'divider' as const,
@@ -97,6 +98,7 @@ export const useTopicItemDropdownMenu = ({
onClick: () => {
autoRenameTopicTitle(id);
},
+ sfSymbol: 'wand.and.stars',
},
{
disabled: !canEditTopic,
@@ -106,6 +108,7 @@ export const useTopicItemDropdownMenu = ({
onClick: () => {
toggleEditing(true);
},
+ sfSymbol: 'pencil',
},
{
type: 'divider' as const,
@@ -185,6 +188,7 @@ export const useTopicItemDropdownMenu = ({
topicIds: [id],
});
},
+ sfSymbol: 'trash',
},
].filter(Boolean) as MenuProps['items'];
}, [
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
index 83fc3c0a4a2..447915ac7a6 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
@@ -32,6 +32,7 @@ export const useThreadItemDropdownMenu = ({
onClick: () => {
toggleEditing(true);
},
+ sfSymbol: 'pencil',
},
{
type: 'divider' as const,
@@ -54,6 +55,7 @@ export const useThreadItemDropdownMenu = ({
title: t('delete', { ns: 'common' }),
});
},
+ sfSymbol: 'trash',
},
].filter(Boolean) as MenuProps['items'];
}, [id, canEditThread, removeThread, toggleEditing, t]);
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx
index d175bc63590..8e4b918c75d 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx
@@ -69,6 +69,7 @@ export const useGroupDropdownMenu = ({
key: 'pin',
label: t(pinned ? 'pinOff' : 'pin'),
onClick: () => pinAgentGroup(id, !pinned),
+ sfSymbol: pinned ? 'pin.slash' : 'pin',
},
{
icon: <Icon icon={Pen} />,
@@ -88,6 +89,7 @@ export const useGroupDropdownMenu = ({
});
}
},
+ sfSymbol: 'pencil',
},
{
icon: <Icon icon={LucideCopy} />,
@@ -97,6 +99,7 @@ export const useGroupDropdownMenu = ({
domEvent.stopPropagation();
duplicateAgentGroup(id);
},
+ sfSymbol: 'doc.on.doc',
},
]
: []),
@@ -108,6 +111,7 @@ export const useGroupDropdownMenu = ({
domEvent.stopPropagation();
openAgentInNewWindow(id);
},
+ sfSymbol: 'macwindow.badge.plus',
},
...(canConfigure && transferMenuItems?.length
? [{ type: 'divider' as const }, ...transferMenuItems]
@@ -144,6 +148,7 @@ export const useGroupDropdownMenu = ({
title: t('delete', { ns: 'common' }),
});
},
+ sfSymbol: 'trash',
},
]
: []),
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
index 0a8eade8758..ec686093b06 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
@@ -1,6 +1,8 @@
import { renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { canGoNative } from '@/libs/contextMenu/canGoNative';
+
import { useAgentDropdownMenu } from './useDropdownMenu';
const mocks = vi.hoisted(() => ({
@@ -147,4 +149,23 @@ describe('useAgentDropdownMenu', () => {
expect(getMenuKeys(result.current())).toEqual(['openInNewWindow']);
});
+
+ it('stays native-eligible (string labels only, including the Move to Category submenu)', () => {
+ mocks.canEditResource = true;
+
+ const { result } = renderHook(() =>
+ useAgentDropdownMenu({
+ anchor: null,
+ group: undefined,
+ id: 'agent-1',
+ openCreateGroupModal: vi.fn(),
+ pinned: false,
+ title: 'Public Agent',
+ userId: 'member-1',
+ visibility: 'public',
+ }),
+ );
+
+ expect(canGoNative(result.current() ?? [])).toBe(true);
+ });
});
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.tsx
index 93ff623b9bb..00157b151c2 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.tsx
@@ -150,6 +150,7 @@ export const useAgentDropdownMenu = ({
key: 'pin',
label: t(pinned ? 'pinOff' : 'pin'),
onClick: () => pinAgent(id, !pinned),
+ sfSymbol: pinned ? 'pin.slash' : 'pin',
},
]
: []),
@@ -167,6 +168,7 @@ export const useAgentDropdownMenu = ({
openEditingPopover({ anchor, avatar, id, title, type: 'agent' });
}
},
+ sfSymbol: 'pencil',
},
]
: []),
@@ -180,6 +182,7 @@ export const useAgentDropdownMenu = ({
domEvent.stopPropagation();
duplicateAgent(id);
},
+ sfSymbol: 'doc.on.doc',
},
]
: []),
@@ -191,6 +194,7 @@ export const useAgentDropdownMenu = ({
domEvent.stopPropagation();
openAgentInNewWindow(id);
},
+ sfSymbol: 'macwindow.badge.plus',
},
...(canEdit
? [
@@ -202,27 +206,31 @@ export const useAgentDropdownMenu = ({
key: groupId,
label: name,
onClick: () => updateAgentGroup(id, groupId),
+ sfSymbol: group === groupId ? 'checkmark' : undefined,
})),
{
icon: isDefault ? <Icon icon={Check} /> : <div />,
key: 'defaultList',
label: t('defaultList'),
onClick: () => updateAgentGroup(id, SessionDefaultGroup.Default),
+ sfSymbol: isDefault ? 'checkmark' : undefined,
},
{ type: 'divider' as const },
{
icon: <Icon icon={LucidePlus} />,
key: 'createGroup',
- label: <div>{t('sessionGroup.createGroup')}</div>,
+ label: t('sessionGroup.createGroup'),
onClick: ({ domEvent }: any) => {
domEvent.stopPropagation();
openCreateGroupModal();
},
+ sfSymbol: 'folder.badge.plus',
},
],
icon: <Icon icon={FolderInputIcon} />,
key: 'moveGroup',
label: t('sessionGroup.moveGroup'),
+ sfSymbol: 'folder',
},
]
: []),
@@ -286,6 +294,7 @@ export const useAgentDropdownMenu = ({
}),
});
},
+ sfSymbol: 'globe',
},
]
: []),
@@ -317,6 +326,7 @@ export const useAgentDropdownMenu = ({
title: t('makePrivate.confirm.title', { ns: 'common' }),
});
},
+ sfSymbol: 'eye.slash',
},
]
: []),
@@ -352,6 +362,7 @@ export const useAgentDropdownMenu = ({
title: t('delete', { ns: 'common' }),
});
},
+ sfSymbol: 'trash',
},
]
: []),
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/Group/useDropdownMenu.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/Group/useDropdownMenu.tsx
index 504fba02028..6f433d3331f 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/Group/useDropdownMenu.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/Group/useDropdownMenu.tsx
@@ -1,3 +1,4 @@
+import type { SFSymbol } from '@lobechat/electron-client-ipc';
import { type SidebarVisibility } from '@lobechat/types';
import { type MenuProps } from '@lobehub/ui';
import { Icon } from '@lobehub/ui';
@@ -65,6 +66,7 @@ export const useGroupDropdownMenu = ({
disabled: !canEdit,
icon: <Icon icon={GlobeIcon} />,
key: 'publishToWorkspace',
+ sfSymbol: 'globe' as SFSymbol,
label: t('sessionGroup.publishToWorkspace', {
defaultValue: 'Publish to Workspace',
ns: 'chat',
diff --git a/src/routes/(main)/home/_layout/Body/index.tsx b/src/routes/(main)/home/_layout/Body/index.tsx
index 771d515a1ff..ae9f0233956 100644
--- a/src/routes/(main)/home/_layout/Body/index.tsx
+++ b/src/routes/(main)/home/_layout/Body/index.tsx
@@ -14,6 +14,7 @@ import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useActiveTabKey } from '@/hooks/useActiveTabKey';
import type { NavItem as NavItemType } from '@/hooks/useNavLayout';
import { useNavLayout } from '@/hooks/useNavLayout';
+import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
import Recents from '@/routes/(main)/home/features/Recents';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -96,21 +97,26 @@ const Body = memo(() => {
);
const getContextMenuItems = useCallback(
- (key: string): MenuProps['items'] => [
- {
- icon: <Icon icon={EyeOffIcon} />,
- key: 'hideSection',
- label: t('navPanel.hideSection'),
- onClick: () => hideSection(key),
- },
- { type: 'divider' as const },
- {
- icon: <Icon icon={SlidersHorizontalIcon} />,
- key: 'customizeSidebar',
- label: t('navPanel.customizeSidebar'),
- onClick: () => openCustomizeSidebarModal(),
- },
- ],
+ (key: string): MenuProps['items'] => {
+ const items: NativeContextMenuItem[] = [
+ {
+ icon: <Icon icon={EyeOffIcon} />,
+ key: 'hideSection',
+ label: t('navPanel.hideSection'),
+ onClick: () => hideSection(key),
+ sfSymbol: 'eye.slash',
+ },
+ { type: 'divider' as const },
+ {
+ icon: <Icon icon={SlidersHorizontalIcon} />,
+ key: 'customizeSidebar',
+ label: t('navPanel.customizeSidebar'),
+ onClick: () => openCustomizeSidebarModal(),
+ sfSymbol: 'gearshape',
+ },
+ ];
+ return items as MenuProps['items'];
+ },
[t, hideSection],
);
diff --git a/src/routes/(main)/home/_layout/Header/components/InboxDrawer/NotificationItem.tsx b/src/routes/(main)/home/_layout/Header/components/InboxDrawer/NotificationItem.tsx
index dae00932eb1..de11a409dbd 100644
--- a/src/routes/(main)/home/_layout/Header/components/InboxDrawer/NotificationItem.tsx
+++ b/src/routes/(main)/home/_layout/Header/components/InboxDrawer/NotificationItem.tsx
@@ -8,6 +8,7 @@ import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
import { formatNotificationRelativeTime } from './formatNotificationRelativeTime';
import { createNotificationDetailModal } from './NotificationDetailModal';
@@ -102,17 +103,18 @@ const NotificationItem = memo<NotificationItemProps>(
const handleArchive = useCallback(() => onArchive(id), [id, onArchive]);
+ const contextMenuItems: NativeContextMenuItem[] = [
+ {
+ icon: ArchiveIcon,
+ key: 'archive',
+ label: t('inbox.archive'),
+ onClick: handleArchive,
+ sfSymbol: 'archivebox',
+ },
+ ];
+
return (
- <ContextMenuTrigger
- items={[
- {
- icon: ArchiveIcon,
- key: 'archive',
- label: t('inbox.archive'),
- onClick: handleArchive,
- },
- ]}
- >
+ <ContextMenuTrigger items={contextMenuItems}>
<Block
clickable
aria-label={title}
diff --git a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx
index 08a859a5b22..402f23318c3 100644
--- a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx
+++ b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx
@@ -1,4 +1,5 @@
import { isDesktop } from '@lobechat/const';
+import type { SFSymbol } from '@lobechat/electron-client-ipc';
import { HETEROGENEOUS_AGENT_CLIENT_CONFIGS } from '@lobechat/heterogeneous-agents/client';
import { Icon } from '@lobehub/ui';
import { GroupBotSquareIcon } from '@lobehub/ui/icons';
@@ -33,6 +34,8 @@ import { usePageStore } from '@/store/page';
import { useUserStore } from '@/store/user';
import { labPreferSelectors } from '@/store/user/selectors';
+type MenuItem = NonNullable<ItemType> & { sfSymbol?: SFSymbol };
+
interface CreateAgentOptions {
groupId?: string;
isPinned?: boolean;
@@ -238,13 +241,14 @@ export const useCreateMenuItems = () => {
* Create agent menu item
*/
const createAgentMenuItem = useCallback(
- (options?: CreateAgentOptions): ItemType => ({
+ (options?: CreateAgentOptions): MenuItem => ({
icon: <Icon icon={BotIcon} />,
disabled: !canCreate,
// Key needs to vary by visibility so the public and private "New
// Agent" entries can coexist (e.g. if a future menu lists both).
key: options?.visibility === 'private' ? 'newPrivateAgent' : 'newAgent',
label: t('newAgent'),
+ sfSymbol: 'plus.bubble',
onClick: async (info) => {
info.domEvent?.stopPropagation();
if (!canCreate) return;
@@ -266,11 +270,12 @@ export const useCreateMenuItems = () => {
* Add market agent menu item
*/
const createMarketAgentMenuItem = useCallback(
- (): ItemType => ({
+ (): MenuItem => ({
icon: <Icon icon={Store} />,
disabled: !canCreate,
key: 'addAgentFromMarket',
label: t('addAgentFromMarket'),
+ sfSymbol: 'bag',
onClick: (info) => {
info.domEvent?.stopPropagation();
if (!canCreate) return;
@@ -313,12 +318,13 @@ export const useCreateMenuItems = () => {
* Opens the 3-step creation modal
*/
const createPlatformAgentMenuItem = useCallback(
- (options?: CreateAgentOptions): ItemType => {
+ (options?: CreateAgentOptions): MenuItem | null => {
if (!enablePlatformAgent) return null;
return {
icon: <Icon icon={MonitorSmartphone} />,
key: 'newPlatformAgent',
label: t('newPlatformAgent'),
+ sfSymbol: 'laptopcomputer.and.iphone',
onClick: (info) => {
info.domEvent?.stopPropagation();
agentModal?.openCreatePlatformAgentModal(
@@ -337,11 +343,12 @@ export const useCreateMenuItems = () => {
* Creates an empty group and navigates to its profile page
*/
const createGroupChatMenuItem = useCallback(
- (options?: CreateAgentOptions): ItemType => ({
+ (options?: CreateAgentOptions): MenuItem => ({
icon: <Icon icon={GroupBotSquareIcon} />,
disabled: !canCreate,
key: options?.visibility === 'private' ? 'newPrivateGroupChat' : 'newGroupChat',
label: t('newGroupChat'),
+ sfSymbol: 'person.2',
onClick: async (info) => {
info.domEvent?.stopPropagation();
if (!canCreate) return;
@@ -363,11 +370,12 @@ export const useCreateMenuItems = () => {
* Add session group menu item
*/
const createSessionGroupMenuItem = useCallback(
- (options?: { visibility?: 'private' | 'public' }): ItemType => ({
+ (options?: { visibility?: 'private' | 'public' }): MenuItem => ({
icon: <Icon icon={FolderPlus} />,
disabled: !canCreate,
key: options?.visibility === 'private' ? 'addPrivateSessionGroup' : 'addSessionGroup',
label: t('sessionGroup.createGroup'),
+ sfSymbol: 'folder.badge.plus',
onClick: async (info) => {
info.domEvent?.stopPropagation();
if (!canCreate) return;
@@ -384,10 +392,11 @@ export const useCreateMenuItems = () => {
* Config menu item
*/
const configMenuItem = useCallback(
- (onOpenConfig: () => void): ItemType => ({
+ (onOpenConfig: () => void): MenuItem => ({
icon: <Icon icon={FolderCogIcon} />,
key: 'config',
label: t('sessionGroup.manageCategory'),
+ sfSymbol: 'folder.badge.gearshape',
onClick: (info) => {
info.domEvent?.stopPropagation();
onOpenConfig();
@@ -420,11 +429,12 @@ export const useCreateMenuItems = () => {
* Create page menu item
*/
const createPageMenuItem = useCallback(
- (): ItemType => ({
+ (): MenuItem => ({
icon: <Icon icon={FileTextIcon} />,
disabled: !canCreate,
key: 'newPage',
label: t('newPage'),
+ sfSymbol: 'doc.badge.plus',
onClick: async (info) => {
info.domEvent?.stopPropagation();
if (!canCreate) return;
diff --git a/src/routes/(main)/home/_layout/hooks/useSessionGroupMenuItems.tsx b/src/routes/(main)/home/_layout/hooks/useSessionGroupMenuItems.tsx
index 1a6e6ba2162..f1778e13948 100644
--- a/src/routes/(main)/home/_layout/hooks/useSessionGroupMenuItems.tsx
+++ b/src/routes/(main)/home/_layout/hooks/useSessionGroupMenuItems.tsx
@@ -1,3 +1,4 @@
+import type { SFSymbol } from '@lobechat/electron-client-ipc';
import { Icon } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { App } from 'antd';
@@ -14,6 +15,8 @@ import { useAgentStore } from '@/store/agent';
import { useAgentGroupStore } from '@/store/agentGroup';
import { useHomeStore } from '@/store/home';
+type MenuItem = NonNullable<ItemType> & { sfSymbol?: SFSymbol };
+
/**
* Hook for generating menu items for session group containers
* Used in List/Group/Actions.tsx
@@ -36,13 +39,14 @@ export const useSessionGroupMenuItems = () => {
* Rename group menu item
*/
const renameGroupMenuItem = useCallback(
- (groupId: string, groupName: string, anchor: HTMLElement | null): ItemType => {
+ (groupId: string, groupName: string, anchor: HTMLElement | null): MenuItem => {
const iconElement = <Icon icon={FolderPenIcon} />;
return {
disabled: !canEdit,
icon: iconElement,
key: 'rename',
label: t('sessionGroup.rename'),
+ sfSymbol: 'pencil',
onClick: (info: any) => {
info.domEvent?.stopPropagation();
if (!canEdit) return;
@@ -60,13 +64,14 @@ export const useSessionGroupMenuItems = () => {
* Config group menu item
*/
const configGroupMenuItem = useCallback(
- (onOpenConfig: () => void): ItemType => {
+ (onOpenConfig: () => void): MenuItem => {
const iconElement = <Icon icon={FolderCogIcon} />;
return {
disabled: !canEdit,
icon: iconElement,
key: 'config',
label: t('sessionGroup.config'),
+ sfSymbol: 'folder.badge.gearshape',
onClick: (info: any) => {
info.domEvent?.stopPropagation();
if (!canEdit) return;
@@ -82,7 +87,7 @@ export const useSessionGroupMenuItems = () => {
* Delete group menu item with confirmation modal
*/
const deleteGroupMenuItem = useCallback(
- (groupId: string): ItemType => {
+ (groupId: string): MenuItem => {
const trashIcon = <Icon icon={Trash} />;
return {
danger: true,
@@ -90,6 +95,7 @@ export const useSessionGroupMenuItems = () => {
icon: trashIcon,
key: 'delete',
label: t('delete', { ns: 'common' }),
+ sfSymbol: 'trash',
onClick: (info: any) => {
info.domEvent?.stopPropagation();
if (!canEdit) return;
@@ -114,13 +120,14 @@ export const useSessionGroupMenuItems = () => {
* Create agent in group menu item
*/
const createAgentInGroupMenuItem = useCallback(
- (groupId: string, _isPinned?: boolean): ItemType => {
+ (groupId: string, _isPinned?: boolean): MenuItem => {
const iconElement = <Icon icon={FolderPenIcon} />;
return {
disabled: !canCreate,
icon: iconElement,
key: 'createAgent',
label: t('newAgent'),
+ sfSymbol: 'plus.bubble',
onClick: async (info: any) => {
info.domEvent?.stopPropagation();
if (!canCreate) return;
@@ -159,13 +166,14 @@ export const useSessionGroupMenuItems = () => {
onCancel: () => void;
onConfirm: (selectedAgents: string[]) => Promise<void>;
}) => void,
- ): ItemType => {
+ ): MenuItem => {
const iconElement = <Icon icon={FolderPenIcon} />;
return {
disabled: !canCreate,
icon: iconElement,
key: 'createGroupChat',
label: t('newGroupChat'),
+ sfSymbol: 'person.2',
onClick: async (info: any) => {
info.domEvent?.stopPropagation();
if (!canCreate) return;
diff --git a/src/routes/(main)/home/features/Recents/useDropdownMenu.tsx b/src/routes/(main)/home/features/Recents/useDropdownMenu.tsx
index 25059eb4b02..222e218dc91 100644
--- a/src/routes/(main)/home/features/Recents/useDropdownMenu.tsx
+++ b/src/routes/(main)/home/features/Recents/useDropdownMenu.tsx
@@ -9,6 +9,7 @@ import { useDocumentTransferMenuItem } from '@/business/client/hooks/useDocument
import { useTaskTransferMenuItem } from '@/business/client/hooks/useTaskTransferMenuItem';
import { confirmRemoveTopic } from '@/features/DeleteTopicConfirm';
import { usePermission } from '@/hooks/usePermission';
+import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
import { type RecentItem } from '@/server/routers/lambda/recent';
import { documentService } from '@/services/document';
import { taskService } from '@/services/task';
@@ -103,13 +104,14 @@ export const useRecentItemDropdownMenu = (
}, [item, t, refreshRecents]);
const dropdownMenu = useCallback((): MenuProps['items'] => {
- return [
+ const items: NativeContextMenuItem[] = [
{
disabled: !canEdit,
icon: <Icon icon={PencilLineIcon} />,
key: 'rename',
label: t('rename'),
onClick: () => toggleEditing(true),
+ sfSymbol: 'pencil',
},
...(transferMenuItems ?? []),
...(transferMenuItems?.length ? [{ type: 'divider' as const }] : []),
@@ -120,8 +122,10 @@ export const useRecentItemDropdownMenu = (
key: 'delete',
label: t('delete'),
onClick: handleDelete,
+ sfSymbol: 'trash',
},
];
+ return items as MenuProps['items'];
}, [canEdit, t, toggleEditing, handleDelete, transferMenuItems]);
return { dropdownMenu, handleRename };
diff --git a/src/routes/(main)/settings/provider/ProviderMenu/useDropdownMenu.tsx b/src/routes/(main)/settings/provider/ProviderMenu/useDropdownMenu.tsx
index e041942c1d8..e0185a4e368 100644
--- a/src/routes/(main)/settings/provider/ProviderMenu/useDropdownMenu.tsx
+++ b/src/routes/(main)/settings/provider/ProviderMenu/useDropdownMenu.tsx
@@ -4,6 +4,8 @@ import { LucideCheck } from 'lucide-react';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import type { NativeContextMenuItem } from '@/libs/contextMenu/types';
+
// Sort type enumeration
export enum SortType {
Alphabetical = 'alphabetical',
@@ -22,13 +24,14 @@ export const useProviderDropdownMenu = ({
}: DropdownMenuProps): MenuProps['items'] => {
const { t } = useTranslation('modelProvider');
- return useMemo(
- () => [
+ return useMemo(() => {
+ const items: NativeContextMenuItem[] = [
{
icon: sortType === SortType.Default ? <Icon icon={LucideCheck} /> : <div />,
key: 'default',
label: t('menu.list.disabledActions.sortDefault'),
onClick: () => onSortChange(SortType.Default),
+ sfSymbol: sortType === SortType.Default ? 'checkmark' : undefined,
},
{
type: 'divider' as const,
@@ -38,14 +41,16 @@ export const useProviderDropdownMenu = ({
key: 'alphabetical',
label: t('menu.list.disabledActions.sortAlphabetical'),
onClick: () => onSortChange(SortType.Alphabetical),
+ sfSymbol: sortType === SortType.Alphabetical ? 'checkmark' : undefined,
},
{
icon: sortType === SortType.AlphabeticalDesc ? <Icon icon={LucideCheck} /> : <div />,
key: 'alphabeticalDesc',
label: t('menu.list.disabledActions.sortAlphabeticalDesc'),
onClick: () => onSortChange(SortType.AlphabeticalDesc),
+ sfSymbol: sortType === SortType.AlphabeticalDesc ? 'checkmark' : undefined,
},
- ],
- [sortType, onSortChange, t],
- );
+ ];
+ return items as MenuProps['items'];
+ }, [sortType, onSortChange, t]);
};
diff --git a/src/services/electron/system.ts b/src/services/electron/system.ts
index 95724227ccb..1ec57b56941 100644
--- a/src/services/electron/system.ts
+++ b/src/services/electron/system.ts
@@ -1,5 +1,7 @@
import type {
ElectronAppState,
+ PopupContextMenuParams,
+ PopupContextMenuResult,
WindowMinimumSizeParams,
WindowSizeParams,
} from '@lobechat/electron-client-ipc';
@@ -89,6 +91,14 @@ class ElectronSystemService {
return this.ipc.menu.showContextMenu({ data, type });
};
+ popupContextMenu = async (params: PopupContextMenuParams): Promise<PopupContextMenuResult> => {
+ return this.ipc.menu.popupContextMenu(params);
+ };
+
+ closePopupContextMenu = async (): Promise<void> => {
+ return this.ipc.menu.closePopupContextMenu();
+ };
+
/**
* Open native folder picker dialog
*/