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.

✅ test(desktop): improve test coverage for multiple modules (#10543)

Arvin Xua73c9d1b9b7f
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 0fd25937778..01c32deaf63 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -62,6 +62,7 @@
"execa": "^9.6.1",
"fast-glob": "^3.3.3",
"fix-path": "^5.0.0",
+ "happy-dom": "^20.0.11",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.6",
"just-diff": "^6.0.2",
diff --git a/apps/desktop/src/main/core/ui/__tests__/MenuManager.test.ts b/apps/desktop/src/main/core/ui/__tests__/MenuManager.test.ts
new file mode 100644
index 00000000000..ae746e66cea
--- /dev/null
+++ b/apps/desktop/src/main/core/ui/__tests__/MenuManager.test.ts
@@ -0,0 +1,320 @@
+import { Menu } from 'electron';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { App } from '../../App';
+import { MenuManager } from '../MenuManager';
+
+// Mock electron modules
+vi.mock('electron', () => ({
+ Menu: {
+ buildFromTemplate: vi.fn(),
+ setApplicationMenu: vi.fn(),
+ },
+}));
+
+// Mock logger
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => ({
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+
+// Mock menu platform implementation
+const mockBuildAndSetAppMenu = vi.fn();
+const mockBuildContextMenu = vi.fn();
+const mockBuildTrayMenu = vi.fn();
+const mockRefresh = vi.fn();
+
+vi.mock('@/menus', () => ({
+ createMenuImpl: vi.fn(() => ({
+ buildAndSetAppMenu: mockBuildAndSetAppMenu,
+ buildContextMenu: mockBuildContextMenu,
+ buildTrayMenu: mockBuildTrayMenu,
+ refresh: mockRefresh,
+ })),
+}));
+
+describe('MenuManager', () => {
+ let menuManager: MenuManager;
+ let mockApp: App;
+ let mockMenu: any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ // Mock Menu instance
+ mockMenu = {
+ popup: vi.fn(),
+ append: vi.fn(),
+ insert: vi.fn(),
+ };
+
+ // Mock App
+ mockApp = {} as unknown as App;
+
+ // Setup mock returns
+ mockBuildContextMenu.mockReturnValue(mockMenu);
+ mockBuildTrayMenu.mockReturnValue(mockMenu);
+
+ menuManager = new MenuManager(mockApp);
+ });
+
+ describe('constructor', () => {
+ it('should initialize MenuManager with app instance', () => {
+ expect(menuManager.app).toBe(mockApp);
+ });
+
+ it('should create platform implementation', async () => {
+ const { createMenuImpl } = await import('@/menus');
+ expect(createMenuImpl).toHaveBeenCalledWith(mockApp);
+ });
+ });
+
+ describe('initialize', () => {
+ it('should initialize application menu without options', () => {
+ menuManager.initialize();
+
+ expect(mockBuildAndSetAppMenu).toHaveBeenCalledWith(undefined);
+ });
+
+ it('should initialize application menu with options', () => {
+ const options = { showDevItems: true };
+
+ menuManager.initialize(options);
+
+ expect(mockBuildAndSetAppMenu).toHaveBeenCalledWith(options);
+ });
+
+ it('should call buildAndSetAppMenu on platform implementation', () => {
+ menuManager.initialize();
+
+ expect(mockBuildAndSetAppMenu).toHaveBeenCalled();
+ });
+ });
+
+ describe('showContextMenu', () => {
+ it('should build and show context menu', () => {
+ const type = 'text-input';
+ const data = { text: 'sample' };
+
+ const result = menuManager.showContextMenu(type, data);
+
+ expect(mockBuildContextMenu).toHaveBeenCalledWith(type, data);
+ expect(mockMenu.popup).toHaveBeenCalled();
+ expect(result).toEqual({ success: true });
+ });
+
+ it('should build context menu without data', () => {
+ const type = 'simple-menu';
+
+ const result = menuManager.showContextMenu(type);
+
+ expect(mockBuildContextMenu).toHaveBeenCalledWith(type, undefined);
+ expect(mockMenu.popup).toHaveBeenCalled();
+ expect(result).toEqual({ success: true });
+ });
+
+ it('should handle different menu types', () => {
+ const types = ['edit', 'view', 'selection', 'link'];
+
+ types.forEach((type) => {
+ vi.clearAllMocks();
+ menuManager.showContextMenu(type);
+ expect(mockBuildContextMenu).toHaveBeenCalledWith(type, undefined);
+ expect(mockMenu.popup).toHaveBeenCalled();
+ });
+ });
+ });
+
+ describe('buildTrayMenu', () => {
+ it('should build tray menu', () => {
+ const result = menuManager.buildTrayMenu();
+
+ expect(mockBuildTrayMenu).toHaveBeenCalled();
+ expect(result).toBe(mockMenu);
+ });
+
+ it('should return Menu instance', () => {
+ const result = menuManager.buildTrayMenu();
+
+ expect(result).toBeDefined();
+ expect(result).toBe(mockMenu);
+ });
+ });
+
+ describe('refreshMenus', () => {
+ it('should refresh all menus without options', () => {
+ const result = menuManager.refreshMenus();
+
+ expect(mockRefresh).toHaveBeenCalledWith(undefined);
+ expect(result).toEqual({ success: true });
+ });
+
+ it('should refresh all menus with options', () => {
+ const options = { showDevItems: false };
+
+ const result = menuManager.refreshMenus(options);
+
+ expect(mockRefresh).toHaveBeenCalledWith(options);
+ expect(result).toEqual({ success: true });
+ });
+
+ it('should call refresh on platform implementation', () => {
+ menuManager.refreshMenus();
+
+ expect(mockRefresh).toHaveBeenCalled();
+ });
+ });
+
+ describe('rebuildAppMenu', () => {
+ it('should rebuild application menu without options', () => {
+ const result = menuManager.rebuildAppMenu();
+
+ expect(mockBuildAndSetAppMenu).toHaveBeenCalledWith(undefined);
+ expect(result).toEqual({ success: true });
+ });
+
+ it('should rebuild application menu with options', () => {
+ const options = { showDevItems: true };
+
+ const result = menuManager.rebuildAppMenu(options);
+
+ expect(mockBuildAndSetAppMenu).toHaveBeenCalledWith(options);
+ expect(result).toEqual({ success: true });
+ });
+
+ it('should call buildAndSetAppMenu on platform implementation', () => {
+ menuManager.rebuildAppMenu();
+
+ expect(mockBuildAndSetAppMenu).toHaveBeenCalled();
+ });
+ });
+
+ describe('integration tests', () => {
+ it('should handle complete menu lifecycle', () => {
+ // Initialize menus
+ menuManager.initialize({ showDevItems: true });
+ expect(mockBuildAndSetAppMenu).toHaveBeenCalledWith({ showDevItems: true });
+
+ // Show context menu
+ menuManager.showContextMenu('edit');
+ expect(mockBuildContextMenu).toHaveBeenCalledWith('edit', undefined);
+ expect(mockMenu.popup).toHaveBeenCalled();
+
+ // Build tray menu
+ const trayMenu = menuManager.buildTrayMenu();
+ expect(mockBuildTrayMenu).toHaveBeenCalled();
+ expect(trayMenu).toBe(mockMenu);
+
+ // Refresh menus
+ menuManager.refreshMenus({ showDevItems: false });
+ expect(mockRefresh).toHaveBeenCalledWith({ showDevItems: false });
+
+ // Rebuild app menu
+ menuManager.rebuildAppMenu({ showDevItems: true });
+ expect(mockBuildAndSetAppMenu).toHaveBeenCalledWith({ showDevItems: true });
+ });
+
+ it('should handle multiple context menu calls', () => {
+ menuManager.showContextMenu('edit');
+ menuManager.showContextMenu('view');
+ menuManager.showContextMenu('selection');
+
+ expect(mockBuildContextMenu).toHaveBeenCalledTimes(3);
+ expect(mockMenu.popup).toHaveBeenCalledTimes(3);
+ });
+
+ it('should handle menu toggling workflow', () => {
+ // Initialize with dev menu hidden
+ menuManager.initialize({ showDevItems: false });
+ expect(mockBuildAndSetAppMenu).toHaveBeenCalledWith({ showDevItems: false });
+
+ // Toggle dev menu on
+ menuManager.rebuildAppMenu({ showDevItems: true });
+ expect(mockBuildAndSetAppMenu).toHaveBeenCalledWith({ showDevItems: true });
+
+ // Toggle dev menu off
+ menuManager.rebuildAppMenu({ showDevItems: false });
+ expect(mockBuildAndSetAppMenu).toHaveBeenCalledWith({ showDevItems: false });
+ });
+ });
+
+ describe('error handling', () => {
+ it('should handle errors from buildContextMenu gracefully', () => {
+ mockBuildContextMenu.mockImplementation(() => {
+ throw new Error('Failed to build context menu');
+ });
+
+ expect(() => menuManager.showContextMenu('edit')).toThrow('Failed to build context menu');
+ });
+
+ it('should handle errors from buildTrayMenu gracefully', () => {
+ mockBuildTrayMenu.mockImplementation(() => {
+ throw new Error('Failed to build tray menu');
+ });
+
+ expect(() => menuManager.buildTrayMenu()).toThrow('Failed to build tray menu');
+ });
+
+ it('should handle errors from refresh gracefully', () => {
+ mockRefresh.mockImplementation(() => {
+ throw new Error('Failed to refresh menus');
+ });
+
+ expect(() => menuManager.refreshMenus()).toThrow('Failed to refresh menus');
+ });
+
+ it('should handle errors from buildAndSetAppMenu gracefully', () => {
+ mockBuildAndSetAppMenu.mockImplementation(() => {
+ throw new Error('Failed to build app menu');
+ });
+
+ expect(() => menuManager.initialize()).toThrow('Failed to build app menu');
+ });
+ });
+
+ describe('platform implementation delegation', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // Reset mocks to default behavior
+ mockBuildAndSetAppMenu.mockImplementation(() => {});
+ mockBuildContextMenu.mockReturnValue(mockMenu);
+ mockBuildTrayMenu.mockReturnValue(mockMenu);
+ mockRefresh.mockImplementation(() => {});
+ });
+
+ it('should delegate all menu operations to platform implementation', () => {
+ const options = { showDevItems: true };
+
+ // Test each method delegates to platform impl
+ menuManager.initialize(options);
+ expect(mockBuildAndSetAppMenu).toHaveBeenCalledWith(options);
+
+ menuManager.showContextMenu('edit', { test: 'data' });
+ expect(mockBuildContextMenu).toHaveBeenCalledWith('edit', { test: 'data' });
+
+ menuManager.buildTrayMenu();
+ expect(mockBuildTrayMenu).toHaveBeenCalled();
+
+ menuManager.refreshMenus(options);
+ expect(mockRefresh).toHaveBeenCalledWith(options);
+
+ menuManager.rebuildAppMenu(options);
+ expect(mockBuildAndSetAppMenu).toHaveBeenCalledWith(options);
+ });
+
+ it('should maintain consistent interface across all operations', () => {
+ // All modification operations should return success response
+ expect(menuManager.showContextMenu('edit')).toEqual({ success: true });
+ expect(menuManager.refreshMenus()).toEqual({ success: true });
+ expect(menuManager.rebuildAppMenu()).toEqual({ success: true });
+
+ // buildTrayMenu should return Menu instance
+ const trayMenu = menuManager.buildTrayMenu();
+ expect(trayMenu).toBe(mockMenu);
+ });
+ });
+});
diff --git a/apps/desktop/src/main/core/ui/__tests__/Tray.test.ts b/apps/desktop/src/main/core/ui/__tests__/Tray.test.ts
new file mode 100644
index 00000000000..c1dc5471a42
--- /dev/null
+++ b/apps/desktop/src/main/core/ui/__tests__/Tray.test.ts
@@ -0,0 +1,518 @@
+import { Tray as ElectronTray, Menu, app, nativeImage } from 'electron';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { App } from '../../App';
+import { Tray } from '../Tray';
+
+// Mock electron modules
+vi.mock('electron', () => ({
+ Tray: vi.fn(),
+ Menu: {
+ buildFromTemplate: vi.fn(),
+ },
+ nativeImage: {
+ createFromPath: vi.fn(),
+ },
+ app: {
+ quit: vi.fn(),
+ },
+}));
+
+// Mock logger
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => ({
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+
+// Mock dir constants
+vi.mock('@/const/dir', () => ({
+ resourcesDir: '/mock/resources',
+}));
+
+describe('Tray', () => {
+ let tray: Tray;
+ let mockApp: App;
+ let mockElectronTray: any;
+ let mockBrowserWindow: any;
+ let mockMainWindow: any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ // Mock Electron Tray instance
+ mockElectronTray = {
+ setToolTip: vi.fn(),
+ setContextMenu: vi.fn(),
+ setImage: vi.fn(),
+ on: vi.fn(),
+ destroy: vi.fn(),
+ displayBalloon: vi.fn(),
+ };
+
+ // Mock BrowserWindow
+ mockBrowserWindow = {
+ isVisible: vi.fn(),
+ isFocused: vi.fn(),
+ focus: vi.fn(),
+ };
+
+ // Mock MainWindow
+ mockMainWindow = {
+ browserWindow: mockBrowserWindow,
+ hide: vi.fn(),
+ show: vi.fn(),
+ broadcast: vi.fn(),
+ };
+
+ // Mock App
+ mockApp = {
+ browserManager: {
+ showMainWindow: vi.fn(),
+ getMainWindow: vi.fn(() => mockMainWindow),
+ },
+ } as unknown as App;
+
+ // Mock electron constructors
+ vi.mocked(ElectronTray).mockImplementation(() => mockElectronTray);
+ vi.mocked(nativeImage.createFromPath).mockReturnValue({} as any);
+ vi.mocked(Menu.buildFromTemplate).mockReturnValue({} as any);
+ });
+
+ describe('constructor', () => {
+ it('should initialize tray with provided options', () => {
+ tray = new Tray(
+ {
+ iconPath: 'tray.png',
+ identifier: 'test-tray',
+ tooltip: 'Test Tray',
+ },
+ mockApp,
+ );
+
+ expect(tray.identifier).toBe('test-tray');
+ expect(tray.options.iconPath).toBe('tray.png');
+ expect(tray.options.tooltip).toBe('Test Tray');
+ });
+
+ it('should call retrieveOrInitialize during construction', () => {
+ tray = new Tray(
+ {
+ iconPath: 'tray.png',
+ identifier: 'test-tray',
+ },
+ mockApp,
+ );
+
+ expect(nativeImage.createFromPath).toHaveBeenCalledWith('/mock/resources/tray.png');
+ expect(ElectronTray).toHaveBeenCalled();
+ });
+ });
+
+ describe('retrieveOrInitialize', () => {
+ it('should create new tray instance with icon and tooltip', () => {
+ tray = new Tray(
+ {
+ iconPath: 'tray.png',
+ identifier: 'test-tray',
+ tooltip: 'Test Tray',
+ },
+ mockApp,
+ );
+
+ expect(nativeImage.createFromPath).toHaveBeenCalledWith('/mock/resources/tray.png');
+ expect(ElectronTray).toHaveBeenCalled();
+ expect(mockElectronTray.setToolTip).toHaveBeenCalledWith('Test Tray');
+ });
+
+ it('should not set tooltip if not provided', () => {
+ tray = new Tray(
+ {
+ iconPath: 'tray.png',
+ identifier: 'test-tray',
+ },
+ mockApp,
+ );
+
+ expect(mockElectronTray.setToolTip).not.toHaveBeenCalled();
+ });
+
+ it('should return existing tray instance if already created', () => {
+ tray = new Tray(
+ {
+ iconPath: 'tray.png',
+ identifier: 'test-tray',
+ },
+ mockApp,
+ );
+
+ const firstTray = tray.tray;
+ const secondTray = tray.tray;
+
+ expect(firstTray).toBe(secondTray);
+ expect(ElectronTray).toHaveBeenCalledTimes(1);
+ });
+
+ it('should register click event handler', () => {
+ tray = new Tray(
+ {
+ iconPath: 'tray.png',
+ identifier: 'test-tray',
+ },
+ mockApp,
+ );
+
+ expect(mockElectronTray.on).toHaveBeenCalledWith('click', expect.any(Function));
+ });
+
+ it('should set default context menu', () => {
+ tray = new Tray(
+ {
+ iconPath: 'tray.png',
+ identifier: 'test-tray',
+ },
+ mockApp,
+ );
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(mockElectronTray.setContextMenu).toHaveBeenCalled();
+ });
+
+ it('should handle errors when creating tray', () => {
+ const error = new Error('Failed to create tray');
+ vi.mocked(ElectronTray).mockImplementation(() => {
+ throw error;
+ });
+
+ expect(() => {
+ tray = new Tray(
+ {
+ iconPath: 'tray.png',
+ identifier: 'test-tray',
+ },
+ mockApp,
+ );
+ }).toThrow(error);
+ });
+ });
+
+ describe('setContextMenu', () => {
+ beforeEach(() => {
+ tray = new Tray(
+ {
+ iconPath: 'tray.png',
+ identifier: 'test-tray',
+ },
+ mockApp,
+ );
+ vi.clearAllMocks();
+ });
+
+ it('should set default context menu when no template provided', () => {
+ tray.setContextMenu();
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalledWith(
+ expect.arrayContaining([
+ expect.objectContaining({ label: 'Show Main Window' }),
+ expect.objectContaining({ type: 'separator' }),
+ expect.objectContaining({ label: 'Quit' }),
+ ]),
+ );
+ expect(mockElectronTray.setContextMenu).toHaveBeenCalled();
+ });
+
+ it('should set custom context menu when template provided', () => {
+ const customTemplate = [
+ { label: 'Custom Item 1', click: vi.fn() },
+ { label: 'Custom Item 2', click: vi.fn() },
+ ];
+
+ tray.setContextMenu(customTemplate);
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalledWith(customTemplate);
+ expect(mockElectronTray.setContextMenu).toHaveBeenCalled();
+ });
+
+ it('should call showMainWindow when Show Main Window is clicked', () => {
+ tray.setContextMenu();
+
+ const templateArg = vi.mocked(Menu.buildFromTemplate).mock.calls[0][0];
+ const showMainWindowItem = templateArg.find((item: any) => item.label === 'Show Main Window');
+
+ showMainWindowItem?.click?.();
+
+ expect(mockApp.browserManager.showMainWindow).toHaveBeenCalled();
+ });
+
+ it('should call app.quit when Quit is clicked', () => {
+ tray.setContextMenu();
+
+ const templateArg = vi.mocked(Menu.buildFromTemplate).mock.calls[0][0];
+ const quitItem = templateArg.find((item: any) => item.label === 'Quit');
+
+ quitItem?.click?.();
+
+ expect(app.quit).toHaveBeenCalled();
+ });
+ });
+
+ describe('onClick', () => {
+ beforeEach(() => {
+ tray = new Tray(
+ {
+ iconPath: 'tray.png',
+ identifier: 'test-tray',
+ },
+ mockApp,
+ );
+ });
+
+ it('should hide window when it is visible and focused', () => {
+ mockBrowserWindow.isVisible.mockReturnValue(true);
+ mockBrowserWindow.isFocused.mockReturnValue(true);
+
+ tray.onClick();
+
+ expect(mockMainWindow.hide).toHaveBeenCalled();
+ expect(mockMainWindow.show).not.toHaveBeenCalled();
+ });
+
+ it('should show and focus window when it is not visible', () => {
+ mockBrowserWindow.isVisible.mockReturnValue(false);
+ mockBrowserWindow.isFocused.mockReturnValue(false);
+
+ tray.onClick();
+
+ expect(mockMainWindow.show).toHaveBeenCalled();
+ expect(mockBrowserWindow.focus).toHaveBeenCalled();
+ expect(mockMainWindow.hide).not.toHaveBeenCalled();
+ });
+
+ it('should show and focus window when it is visible but not focused', () => {
+ mockBrowserWindow.isVisible.mockReturnValue(true);
+ mockBrowserWindow.isFocused.mockReturnValue(false);
+
+ tray.onClick();
+
+ expect(mockMainWindow.show).toHaveBeenCalled();
+ expect(mockBrowserWindow.focus).toHaveBeenCalled();
+ expect(mockMainWindow.hide).not.toHaveBeenCalled();
+ });
+
+ it('should handle case when main window is null', () => {
+ vi.mocked(mockApp.browserManager.getMainWindow).mockReturnValue(null);
+
+ expect(() => tray.onClick()).not.toThrow();
+ });
+ });
+
+ describe('updateIcon', () => {
+ beforeEach(() => {
+ tray = new Tray(
+ {
+ iconPath: 'tray.png',
+ identifier: 'test-tray',
+ },
+ mockApp,
+ );
+ vi.clearAllMocks();
+ });
+
+ it('should update tray icon successfully', () => {
+ const newIcon = {};
+ vi.mocked(nativeImage.createFromPath).mockReturnValue(newIcon as any);
+
+ tray.updateIcon('new-icon.png');
+
+ expect(nativeImage.createFromPath).toHaveBeenCalledWith('/mock/resources/new-icon.png');
+ expect(mockElectronTray.setImage).toHaveBeenCalledWith(newIcon);
+ expect(tray.options.iconPath).toBe('new-icon.png');
+ });
+
+ it('should handle errors when updating icon', () => {
+ const error = new Error('Failed to load icon');
+ vi.mocked(nativeImage.createFromPath).mockImplementation(() => {
+ throw error;
+ });
+
+ expect(() => tray.updateIcon('bad-icon.png')).not.toThrow();
+ });
+ });
+
+ describe('updateTooltip', () => {
+ beforeEach(() => {
+ tray = new Tray(
+ {
+ iconPath: 'tray.png',
+ identifier: 'test-tray',
+ },
+ mockApp,
+ );
+ });
+
+ it('should update tray tooltip successfully', () => {
+ tray.updateTooltip('New Tooltip');
+
+ expect(mockElectronTray.setToolTip).toHaveBeenCalledWith('New Tooltip');
+ expect(tray.options.tooltip).toBe('New Tooltip');
+ });
+ });
+
+ describe('displayBalloon', () => {
+ const originalPlatform = process.platform;
+
+ afterEach(() => {
+ Object.defineProperty(process, 'platform', { value: originalPlatform });
+ });
+
+ beforeEach(() => {
+ tray = new Tray(
+ {
+ iconPath: 'tray.png',
+ identifier: 'test-tray',
+ },
+ mockApp,
+ );
+ });
+
+ it('should display balloon notification on Windows', () => {
+ Object.defineProperty(process, 'platform', { value: 'win32' });
+
+ const options = {
+ title: 'Test',
+ content: 'Test content',
+ };
+
+ tray.displayBalloon(options);
+
+ expect(mockElectronTray.displayBalloon).toHaveBeenCalledWith(options);
+ });
+
+ it('should not display balloon notification on macOS', () => {
+ Object.defineProperty(process, 'platform', { value: 'darwin' });
+
+ const options = {
+ title: 'Test',
+ content: 'Test content',
+ };
+
+ tray.displayBalloon(options);
+
+ expect(mockElectronTray.displayBalloon).not.toHaveBeenCalled();
+ });
+
+ it('should not display balloon notification on Linux', () => {
+ Object.defineProperty(process, 'platform', { value: 'linux' });
+
+ const options = {
+ title: 'Test',
+ content: 'Test content',
+ };
+
+ tray.displayBalloon(options);
+
+ expect(mockElectronTray.displayBalloon).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('broadcast', () => {
+ beforeEach(() => {
+ tray = new Tray(
+ {
+ iconPath: 'tray.png',
+ identifier: 'test-tray',
+ },
+ mockApp,
+ );
+ });
+
+ it('should broadcast message to main window', () => {
+ const channel = 'test-channel' as any;
+ const data = { test: 'data' };
+
+ tray.broadcast(channel, data);
+
+ expect(mockApp.browserManager.getMainWindow).toHaveBeenCalled();
+ expect(mockMainWindow.broadcast).toHaveBeenCalledWith(channel, data);
+ });
+
+ it('should handle case when main window is null', () => {
+ vi.mocked(mockApp.browserManager.getMainWindow).mockReturnValue(null);
+
+ expect(() => tray.broadcast('test-channel' as any)).not.toThrow();
+ });
+ });
+
+ describe('destroy', () => {
+ beforeEach(() => {
+ tray = new Tray(
+ {
+ iconPath: 'tray.png',
+ identifier: 'test-tray',
+ },
+ mockApp,
+ );
+ });
+
+ it('should destroy tray instance', () => {
+ tray.destroy();
+
+ expect(mockElectronTray.destroy).toHaveBeenCalled();
+ });
+
+ it('should handle multiple destroy calls', () => {
+ tray.destroy();
+ tray.destroy();
+
+ expect(mockElectronTray.destroy).toHaveBeenCalledTimes(1);
+ });
+
+ it('should allow creating new tray after destroy', () => {
+ tray.destroy();
+ vi.clearAllMocks();
+
+ const newTray = tray.tray;
+
+ expect(newTray).toBeDefined();
+ expect(ElectronTray).toHaveBeenCalled();
+ });
+ });
+
+ describe('integration tests', () => {
+ it('should handle complete tray lifecycle', () => {
+ tray = new Tray(
+ {
+ iconPath: 'tray.png',
+ identifier: 'test-tray',
+ tooltip: 'Test Tray',
+ },
+ mockApp,
+ );
+
+ // Verify creation
+ expect(tray.tray).toBeDefined();
+ expect(mockElectronTray.setToolTip).toHaveBeenCalledWith('Test Tray');
+
+ // Update icon
+ tray.updateIcon('new-icon.png');
+ expect(mockElectronTray.setImage).toHaveBeenCalled();
+
+ // Update tooltip
+ tray.updateTooltip('New Tooltip');
+ expect(mockElectronTray.setToolTip).toHaveBeenCalledWith('New Tooltip');
+
+ // Test click behavior
+ mockBrowserWindow.isVisible.mockReturnValue(true);
+ mockBrowserWindow.isFocused.mockReturnValue(true);
+ tray.onClick();
+ expect(mockMainWindow.hide).toHaveBeenCalled();
+
+ // Destroy
+ tray.destroy();
+ expect(mockElectronTray.destroy).toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/desktop/src/main/core/ui/__tests__/TrayManager.test.ts b/apps/desktop/src/main/core/ui/__tests__/TrayManager.test.ts
new file mode 100644
index 00000000000..f57bd6319d3
--- /dev/null
+++ b/apps/desktop/src/main/core/ui/__tests__/TrayManager.test.ts
@@ -0,0 +1,360 @@
+import { nativeTheme } from 'electron';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { App } from '../../App';
+import { Tray } from '../Tray';
+import { TrayManager } from '../TrayManager';
+
+// Mock electron modules
+vi.mock('electron', () => ({
+ nativeTheme: {
+ shouldUseDarkColors: false,
+ },
+}));
+
+// Mock logger
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => ({
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+
+// Mock environment constants
+vi.mock('@/const/env', () => ({
+ isMac: true,
+}));
+
+// Mock package.json
+vi.mock('@/../../package.json', () => ({
+ name: 'test-app',
+}));
+
+// Mock Tray class
+vi.mock('../Tray', () => ({
+ Tray: vi.fn(),
+}));
+
+describe('TrayManager', () => {
+ let trayManager: TrayManager;
+ let mockApp: App;
+ let mockTray: any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ // Mock Tray instance
+ mockTray = {
+ identifier: 'main',
+ broadcast: vi.fn(),
+ destroy: vi.fn(),
+ updateIcon: vi.fn(),
+ updateTooltip: vi.fn(),
+ };
+
+ // Mock App
+ mockApp = {} as unknown as App;
+
+ // Mock Tray constructor
+ vi.mocked(Tray).mockImplementation(() => mockTray);
+
+ trayManager = new TrayManager(mockApp);
+ });
+
+ describe('constructor', () => {
+ it('should initialize TrayManager with app instance', () => {
+ expect(trayManager.app).toBe(mockApp);
+ expect(trayManager.trays).toBeInstanceOf(Map);
+ expect(trayManager.trays.size).toBe(0);
+ });
+ });
+
+ describe('initializeTrays', () => {
+ it('should initialize main tray', () => {
+ trayManager.initializeTrays();
+
+ expect(Tray).toHaveBeenCalled();
+ expect(trayManager.trays.has('main')).toBe(true);
+ });
+
+ it('should call initializeMainTray', () => {
+ const spy = vi.spyOn(trayManager, 'initializeMainTray');
+
+ trayManager.initializeTrays();
+
+ expect(spy).toHaveBeenCalled();
+ });
+ });
+
+ describe('initializeMainTray', () => {
+ it('should create main tray with dark icon on macOS when dark mode is enabled', () => {
+ Object.defineProperty(nativeTheme, 'shouldUseDarkColors', {
+ value: true,
+ writable: true,
+ configurable: true,
+ });
+
+ const result = trayManager.initializeMainTray();
+
+ expect(Tray).toHaveBeenCalledWith(
+ expect.objectContaining({
+ iconPath: 'tray-dark.png',
+ identifier: 'main',
+ tooltip: 'test-app',
+ }),
+ mockApp,
+ );
+ expect(result).toBe(mockTray);
+ });
+
+ it('should create main tray with light icon on macOS when light mode is enabled', () => {
+ Object.defineProperty(nativeTheme, 'shouldUseDarkColors', {
+ value: false,
+ writable: true,
+ configurable: true,
+ });
+
+ trayManager.initializeMainTray();
+
+ expect(Tray).toHaveBeenCalledWith(
+ expect.objectContaining({
+ iconPath: 'tray-light.png',
+ identifier: 'main',
+ tooltip: 'test-app',
+ }),
+ mockApp,
+ );
+ });
+
+ it('should add created tray to trays map', () => {
+ trayManager.initializeMainTray();
+
+ expect(trayManager.trays.has('main')).toBe(true);
+ expect(trayManager.trays.get('main')).toBe(mockTray);
+ });
+
+ it('should return existing tray if already initialized', () => {
+ const firstTray = trayManager.initializeMainTray();
+ vi.clearAllMocks();
+
+ const secondTray = trayManager.initializeMainTray();
+
+ expect(firstTray).toBe(secondTray);
+ expect(Tray).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('getMainTray', () => {
+ it('should return main tray when it exists', () => {
+ trayManager.initializeMainTray();
+
+ const result = trayManager.getMainTray();
+
+ expect(result).toBe(mockTray);
+ });
+
+ it('should return undefined when main tray does not exist', () => {
+ const result = trayManager.getMainTray();
+
+ expect(result).toBeUndefined();
+ });
+ });
+
+ describe('retrieveByIdentifier', () => {
+ it('should return tray by identifier when it exists', () => {
+ trayManager.initializeMainTray();
+
+ const result = trayManager.retrieveByIdentifier('main');
+
+ expect(result).toBe(mockTray);
+ });
+
+ it('should return undefined when tray with identifier does not exist', () => {
+ const result = trayManager.retrieveByIdentifier('main');
+
+ expect(result).toBeUndefined();
+ });
+ });
+
+ describe('broadcastToAllTrays', () => {
+ it('should broadcast event to all trays', () => {
+ trayManager.initializeMainTray();
+
+ const event = 'test-event' as any;
+ const data = { test: 'data' };
+
+ trayManager.broadcastToAllTrays(event, data);
+
+ expect(mockTray.broadcast).toHaveBeenCalledWith(event, data);
+ });
+
+ it('should handle multiple trays', () => {
+ // Create main tray
+ trayManager.initializeMainTray();
+
+ // Mock another tray
+ const mockTray2 = {
+ identifier: 'secondary',
+ broadcast: vi.fn(),
+ destroy: vi.fn(),
+ };
+ trayManager.trays.set('secondary' as any, mockTray2 as any);
+
+ const event = 'test-event' as any;
+ const data = { test: 'data' };
+
+ trayManager.broadcastToAllTrays(event, data);
+
+ expect(mockTray.broadcast).toHaveBeenCalledWith(event, data);
+ expect(mockTray2.broadcast).toHaveBeenCalledWith(event, data);
+ });
+
+ it('should not throw when no trays exist', () => {
+ const event = 'test-event' as any;
+ const data = { test: 'data' };
+
+ expect(() => trayManager.broadcastToAllTrays(event, data)).not.toThrow();
+ });
+ });
+
+ describe('broadcastToTray', () => {
+ it('should broadcast event to specific tray', () => {
+ trayManager.initializeMainTray();
+
+ const event = 'test-event' as any;
+ const data = { test: 'data' };
+
+ trayManager.broadcastToTray('main', event, data);
+
+ expect(mockTray.broadcast).toHaveBeenCalledWith(event, data);
+ });
+
+ it('should not throw when tray does not exist', () => {
+ const event = 'test-event' as any;
+ const data = { test: 'data' };
+
+ expect(() => trayManager.broadcastToTray('main', event, data)).not.toThrow();
+ });
+
+ it('should not call broadcast when tray does not exist', () => {
+ const event = 'test-event' as any;
+ const data = { test: 'data' };
+
+ trayManager.broadcastToTray('main', event, data);
+
+ expect(mockTray.broadcast).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('destroyAll', () => {
+ it('should destroy all trays', () => {
+ trayManager.initializeMainTray();
+
+ trayManager.destroyAll();
+
+ expect(mockTray.destroy).toHaveBeenCalled();
+ expect(trayManager.trays.size).toBe(0);
+ });
+
+ it('should destroy multiple trays', () => {
+ // Create main tray
+ trayManager.initializeMainTray();
+
+ // Mock another tray
+ const mockTray2 = {
+ identifier: 'secondary',
+ broadcast: vi.fn(),
+ destroy: vi.fn(),
+ };
+ trayManager.trays.set('secondary' as any, mockTray2 as any);
+
+ trayManager.destroyAll();
+
+ expect(mockTray.destroy).toHaveBeenCalled();
+ expect(mockTray2.destroy).toHaveBeenCalled();
+ expect(trayManager.trays.size).toBe(0);
+ });
+
+ it('should clear trays map after destroying', () => {
+ trayManager.initializeMainTray();
+
+ trayManager.destroyAll();
+
+ expect(trayManager.trays.size).toBe(0);
+ });
+
+ it('should not throw when no trays exist', () => {
+ expect(() => trayManager.destroyAll()).not.toThrow();
+ });
+ });
+
+ describe('retrieveOrInitialize (private method)', () => {
+ it('should create new tray when it does not exist', () => {
+ const options = {
+ iconPath: 'test.png',
+ identifier: 'main',
+ tooltip: 'Test',
+ };
+
+ const result = trayManager['retrieveOrInitialize'](options);
+
+ expect(Tray).toHaveBeenCalledWith(options, mockApp);
+ expect(result).toBe(mockTray);
+ expect(trayManager.trays.has('main')).toBe(true);
+ });
+
+ it('should return existing tray when it already exists', () => {
+ const options = {
+ iconPath: 'test.png',
+ identifier: 'main',
+ tooltip: 'Test',
+ };
+
+ const firstResult = trayManager['retrieveOrInitialize'](options);
+ vi.clearAllMocks();
+
+ const secondResult = trayManager['retrieveOrInitialize'](options);
+
+ expect(firstResult).toBe(secondResult);
+ expect(Tray).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('integration tests', () => {
+ it('should handle complete tray manager lifecycle', () => {
+ // Initialize trays
+ trayManager.initializeTrays();
+ expect(trayManager.trays.size).toBe(1);
+
+ // Get main tray
+ const mainTray = trayManager.getMainTray();
+ expect(mainTray).toBeDefined();
+
+ // Broadcast to all
+ trayManager.broadcastToAllTrays('test-event' as any, { data: 'test' });
+ expect(mockTray.broadcast).toHaveBeenCalled();
+
+ // Broadcast to specific tray
+ vi.clearAllMocks();
+ trayManager.broadcastToTray('main', 'test-event' as any, { data: 'test' });
+ expect(mockTray.broadcast).toHaveBeenCalled();
+
+ // Destroy all
+ trayManager.destroyAll();
+ expect(mockTray.destroy).toHaveBeenCalled();
+ expect(trayManager.trays.size).toBe(0);
+ });
+
+ it('should handle multiple initialization calls safely', () => {
+ trayManager.initializeTrays();
+ trayManager.initializeTrays();
+ trayManager.initializeTrays();
+
+ // Should only create one tray instance
+ expect(Tray).toHaveBeenCalledTimes(1);
+ expect(trayManager.trays.size).toBe(1);
+ });
+ });
+});
diff --git a/apps/desktop/src/main/menus/impls/BaseMenuPlatform.test.ts b/apps/desktop/src/main/menus/impls/BaseMenuPlatform.test.ts
new file mode 100644
index 00000000000..3b32e4704f4
--- /dev/null
+++ b/apps/desktop/src/main/menus/impls/BaseMenuPlatform.test.ts
@@ -0,0 +1,49 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { App } from '@/core/App';
+
+import { BaseMenuPlatform } from './BaseMenuPlatform';
+
+// Create a concrete implementation for testing
+class TestMenuPlatform extends BaseMenuPlatform {}
+
+// Mock App instance
+const mockApp = {
+ i18n: {
+ ns: vi.fn(),
+ },
+ browserManager: {
+ getMainWindow: vi.fn(),
+ showMainWindow: vi.fn(),
+ retrieveByIdentifier: vi.fn(),
+ },
+ updaterManager: {
+ checkForUpdates: vi.fn(),
+ },
+ menuManager: {
+ rebuildAppMenu: vi.fn(),
+ },
+ storeManager: {
+ openInEditor: vi.fn(),
+ },
+} as unknown as App;
+
+describe('BaseMenuPlatform', () => {
+ let menuPlatform: TestMenuPlatform;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ menuPlatform = new TestMenuPlatform(mockApp);
+ });
+
+ describe('constructor', () => {
+ it('should initialize with app instance', () => {
+ expect(menuPlatform['app']).toBe(mockApp);
+ });
+
+ it('should store app reference for subclasses', () => {
+ const anotherInstance = new TestMenuPlatform(mockApp);
+ expect(anotherInstance['app']).toBe(mockApp);
+ });
+ });
+});
diff --git a/apps/desktop/src/main/menus/impls/linux.test.ts b/apps/desktop/src/main/menus/impls/linux.test.ts
new file mode 100644
index 00000000000..816eae79e1f
--- /dev/null
+++ b/apps/desktop/src/main/menus/impls/linux.test.ts
@@ -0,0 +1,552 @@
+import { Menu, app, dialog, shell } from 'electron';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { App } from '@/core/App';
+
+import { LinuxMenu } from './linux';
+
+// Mock Electron modules
+vi.mock('electron', () => ({
+ Menu: {
+ buildFromTemplate: vi.fn((template) => ({ template })),
+ setApplicationMenu: vi.fn(),
+ },
+ app: {
+ getName: vi.fn(() => 'LobeChat'),
+ getVersion: vi.fn(() => '1.0.0'),
+ },
+ shell: {
+ openExternal: vi.fn(),
+ },
+ dialog: {
+ showMessageBox: vi.fn(),
+ },
+}));
+
+// Mock isDev
+vi.mock('@/const/env', () => ({
+ isDev: false,
+}));
+
+// Mock App instance
+const createMockApp = () => {
+ const mockT = vi.fn((key: string, params?: any) => {
+ const translations: Record<string, string> = {
+ 'file.title': 'File',
+ 'file.preferences': 'Preferences',
+ 'file.quit': 'Quit',
+ 'common.checkUpdates': 'Check for Updates',
+ 'window.close': 'Close',
+ 'window.minimize': 'Minimize',
+ 'window.title': 'Window',
+ 'edit.title': 'Edit',
+ 'edit.undo': 'Undo',
+ 'edit.redo': 'Redo',
+ 'edit.cut': 'Cut',
+ 'edit.copy': 'Copy',
+ 'edit.paste': 'Paste',
+ 'edit.selectAll': 'Select All',
+ 'edit.delete': 'Delete',
+ 'view.title': 'View',
+ 'view.resetZoom': 'Reset Zoom',
+ 'view.zoomIn': 'Zoom In',
+ 'view.zoomOut': 'Zoom Out',
+ 'view.toggleFullscreen': 'Toggle Full Screen',
+ 'help.title': 'Help',
+ 'help.visitWebsite': 'Visit Website',
+ 'help.githubRepo': 'GitHub Repository',
+ 'help.about': 'About',
+ 'dev.title': 'Developer',
+ 'dev.reload': 'Reload',
+ 'dev.forceReload': 'Force Reload',
+ 'dev.devTools': 'Developer Tools',
+ 'dev.devPanel': 'Dev Panel',
+ 'tray.open': `Open ${params?.appName || 'App'}`,
+ 'tray.quit': 'Quit',
+ };
+ return translations[key] || key;
+ });
+
+ const mockCommonT = vi.fn((key: string) => {
+ const translations: Record<string, string> = {
+ 'actions.ok': 'OK',
+ };
+ return translations[key] || key;
+ });
+
+ const mockDialogT = vi.fn((key: string, params?: any) => {
+ const translations: Record<string, string> = {
+ 'about.title': 'About',
+ 'about.message': `${params?.appName || 'App'} ${params?.appVersion || '1.0.0'}`,
+ 'about.detail': 'LobeChat Desktop Application',
+ };
+ return translations[key] || key;
+ });
+
+ return {
+ i18n: {
+ ns: vi.fn((namespace: string) => {
+ if (namespace === 'common') return mockCommonT;
+ if (namespace === 'dialog') return mockDialogT;
+ return mockT;
+ }),
+ },
+ browserManager: {
+ showMainWindow: vi.fn(),
+ retrieveByIdentifier: vi.fn(() => ({
+ show: vi.fn(),
+ })),
+ },
+ updaterManager: {
+ checkForUpdates: vi.fn(),
+ },
+ } as unknown as App;
+};
+
+describe('LinuxMenu', () => {
+ let linuxMenu: LinuxMenu;
+ let mockApp: App;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockApp = createMockApp();
+ linuxMenu = new LinuxMenu(mockApp);
+ });
+
+ describe('buildAndSetAppMenu', () => {
+ it('should build and set application menu', () => {
+ const menu = linuxMenu.buildAndSetAppMenu();
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(Menu.setApplicationMenu).toHaveBeenCalled();
+ expect(menu).toBeDefined();
+ });
+
+ it('should include developer menu when showDevItems is true', () => {
+ linuxMenu.buildAndSetAppMenu({ showDevItems: true });
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+ expect(devMenu).toBeDefined();
+ });
+
+ it('should not include developer menu when showDevItems is false', () => {
+ linuxMenu.buildAndSetAppMenu({ showDevItems: false });
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+ expect(devMenu).toBeUndefined();
+ });
+
+ it('should create menu with File, Edit, View, Window, Help', () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const menuLabels = template.map((item: any) => item.label);
+
+ expect(menuLabels).toContain('File');
+ expect(menuLabels).toContain('Edit');
+ expect(menuLabels).toContain('View');
+ expect(menuLabels).toContain('Window');
+ expect(menuLabels).toContain('Help');
+ });
+ });
+
+ describe('buildContextMenu', () => {
+ it('should build chat context menu', () => {
+ const menu = linuxMenu.buildContextMenu('chat');
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(menu).toBeDefined();
+ });
+
+ it('should build editor context menu', () => {
+ const menu = linuxMenu.buildContextMenu('editor');
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(menu).toBeDefined();
+ });
+
+ it('should build default context menu for unknown type', () => {
+ const menu = linuxMenu.buildContextMenu('unknown');
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(menu).toBeDefined();
+ });
+
+ it('should pass data to context menu', () => {
+ const data = { selection: 'text' };
+ linuxMenu.buildContextMenu('chat', data);
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ });
+ });
+
+ describe('buildTrayMenu', () => {
+ it('should build tray menu', () => {
+ const menu = linuxMenu.buildTrayMenu();
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(menu).toBeDefined();
+ });
+
+ it('should include open and quit items in tray menu', () => {
+ linuxMenu.buildTrayMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ expect(template.length).toBeGreaterThan(0);
+ expect(template.some((item: any) => item.label?.includes('Open'))).toBe(true);
+ expect(template.some((item: any) => item.label === 'Quit')).toBe(true);
+ });
+ });
+
+ describe('refresh', () => {
+ it('should rebuild application menu', () => {
+ linuxMenu.refresh();
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(Menu.setApplicationMenu).toHaveBeenCalled();
+ });
+
+ it('should pass options to rebuild', () => {
+ linuxMenu.refresh({ showDevItems: true });
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+ expect(devMenu).toBeDefined();
+ });
+ });
+
+ describe('menu item click handlers', () => {
+ it('should handle preferences click', () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const fileMenu = template.find((item: any) => item.label === 'File');
+ const preferencesItem = fileMenu.submenu.find((item: any) => item.label === 'Preferences');
+
+ expect(preferencesItem).toBeDefined();
+ preferencesItem.click();
+ expect(mockApp.browserManager.retrieveByIdentifier).toHaveBeenCalledWith('settings');
+ });
+
+ it('should handle check for updates click', () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const fileMenu = template.find((item: any) => item.label === 'File');
+ const checkUpdatesItem = fileMenu.submenu.find(
+ (item: any) => item.label === 'Check for Updates',
+ );
+
+ expect(checkUpdatesItem).toBeDefined();
+ checkUpdatesItem.click();
+ expect(mockApp.updaterManager.checkForUpdates).toHaveBeenCalledWith({ manual: true });
+ });
+
+ it('should handle visit website click', async () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const helpMenu = template.find((item: any) => item.label === 'Help');
+ const visitWebsiteItem = helpMenu.submenu.find((item: any) => item.label === 'Visit Website');
+
+ expect(visitWebsiteItem).toBeDefined();
+ await visitWebsiteItem.click();
+ expect(shell.openExternal).toHaveBeenCalledWith('https://lobehub.com');
+ });
+
+ it('should handle github repo click', async () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const helpMenu = template.find((item: any) => item.label === 'Help');
+ const githubItem = helpMenu.submenu.find((item: any) => item.label === 'GitHub Repository');
+
+ expect(githubItem).toBeDefined();
+ await githubItem.click();
+ expect(shell.openExternal).toHaveBeenCalledWith('https://github.com/lobehub/lobe-chat');
+ });
+
+ it('should handle about dialog click', () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const helpMenu = template.find((item: any) => item.label === 'Help');
+ const aboutItem = helpMenu.submenu.find((item: any) => item.label === 'About');
+
+ expect(aboutItem).toBeDefined();
+ aboutItem.click();
+ expect(dialog.showMessageBox).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'info',
+ title: 'About',
+ buttons: ['OK'],
+ }),
+ );
+ });
+
+ it('should handle tray open click', () => {
+ linuxMenu.buildTrayMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const openItem = template.find((item: any) => item.label?.includes('Open'));
+
+ expect(openItem).toBeDefined();
+ openItem.click();
+ expect(mockApp.browserManager.showMainWindow).toHaveBeenCalled();
+ });
+ });
+
+ describe('menu accelerators', () => {
+ it('should use Ctrl prefix for Linux shortcuts', () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const editMenu = template.find((item: any) => item.label === 'Edit');
+ const copyItem = editMenu.submenu.find((item: any) => item.label === 'Copy');
+
+ expect(copyItem.accelerator).toBe('Ctrl+C');
+ });
+
+ it('should set correct accelerator for close', () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const fileMenu = template.find((item: any) => item.label === 'File');
+ const closeItem = fileMenu.submenu.find((item: any) => item.label === 'Close');
+
+ expect(closeItem.accelerator).toBe('Ctrl+W');
+ });
+
+ it('should set correct accelerator for minimize', () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const fileMenu = template.find((item: any) => item.label === 'File');
+ const minimizeItem = fileMenu.submenu.find((item: any) => item.label === 'Minimize');
+
+ expect(minimizeItem.accelerator).toBe('Ctrl+M');
+ });
+
+ it('should set Ctrl+Shift+Z for redo', () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const editMenu = template.find((item: any) => item.label === 'Edit');
+ const redoItem = editMenu.submenu.find((item: any) => item.label === 'Redo');
+
+ expect(redoItem.accelerator).toBe('Ctrl+Shift+Z');
+ });
+
+ it('should set F11 for fullscreen', () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const viewMenu = template.find((item: any) => item.label === 'View');
+ const fullscreenItem = viewMenu.submenu.find(
+ (item: any) => item.label === 'Toggle Full Screen',
+ );
+
+ expect(fullscreenItem.accelerator).toBe('F11');
+ });
+ });
+
+ describe('developer menu items', () => {
+ it('should include dev tools shortcuts in developer menu', () => {
+ linuxMenu.buildAndSetAppMenu({ showDevItems: true });
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+
+ expect(devMenu).toBeDefined();
+ expect(devMenu.submenu.length).toBeGreaterThan(0);
+ });
+
+ it('should handle dev panel click', () => {
+ linuxMenu.buildAndSetAppMenu({ showDevItems: true });
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+ const devPanelItem = devMenu.submenu.find((item: any) => item.label === 'Dev Panel');
+
+ expect(devPanelItem).toBeDefined();
+ devPanelItem.click();
+ expect(mockApp.browserManager.retrieveByIdentifier).toHaveBeenCalledWith('devtools');
+ });
+
+ it('should set Ctrl+Shift+I for developer tools', () => {
+ linuxMenu.buildAndSetAppMenu({ showDevItems: true });
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+ const devToolsItem = devMenu.submenu.find((item: any) => item.label === 'Developer Tools');
+
+ expect(devToolsItem.accelerator).toBe('Ctrl+Shift+I');
+ });
+
+ it('should include reload options in developer menu', () => {
+ linuxMenu.buildAndSetAppMenu({ showDevItems: true });
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+
+ const reloadItem = devMenu.submenu.find((item: any) => item.label === 'Reload');
+ const forceReloadItem = devMenu.submenu.find((item: any) => item.label === 'Force Reload');
+
+ expect(reloadItem).toBeDefined();
+ expect(forceReloadItem).toBeDefined();
+ });
+ });
+
+ describe('context menu templates', () => {
+ it('should include copy and paste in chat context menu', () => {
+ linuxMenu.buildContextMenu('chat');
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const copyItem = template.find((item: any) => item.role === 'copy');
+ const pasteItem = template.find((item: any) => item.role === 'paste');
+
+ expect(copyItem).toBeDefined();
+ expect(pasteItem).toBeDefined();
+ });
+
+ it('should use Ctrl accelerators in context menus', () => {
+ linuxMenu.buildContextMenu('editor');
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const copyItem = template.find((item: any) => item.role === 'copy');
+
+ expect(copyItem.accelerator).toBe('Ctrl+C');
+ });
+
+ it('should include cut in editor context menu', () => {
+ linuxMenu.buildContextMenu('editor');
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const cutItem = template.find((item: any) => item.role === 'cut');
+
+ expect(cutItem).toBeDefined();
+ expect(cutItem.accelerator).toBe('Ctrl+X');
+ });
+
+ it('should include delete in editor context menu', () => {
+ linuxMenu.buildContextMenu('editor');
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const deleteItem = template.find((item: any) => item.role === 'delete');
+
+ expect(deleteItem).toBeDefined();
+ });
+
+ it('should not include cut in chat context menu', () => {
+ linuxMenu.buildContextMenu('chat');
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const cutItem = template.find((item: any) => item.role === 'cut');
+
+ expect(cutItem).toBeUndefined();
+ });
+ });
+
+ describe('menu structure', () => {
+ it('should have separators in menus', () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const fileMenu = template.find((item: any) => item.label === 'File');
+ const hasSeparator = fileMenu.submenu.some((item: any) => item.type === 'separator');
+
+ expect(hasSeparator).toBe(true);
+ });
+
+ it('should have minimize and close in window menu', () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const windowMenu = template.find((item: any) => item.label === 'Window');
+
+ const minimizeItem = windowMenu.submenu.find((item: any) => item.role === 'minimize');
+ const closeItem = windowMenu.submenu.find((item: any) => item.role === 'close');
+
+ expect(minimizeItem).toBeDefined();
+ expect(closeItem).toBeDefined();
+ });
+
+ it('should have zoom controls in view menu', () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const viewMenu = template.find((item: any) => item.label === 'View');
+
+ const resetZoomItem = viewMenu.submenu.find((item: any) => item.role === 'resetZoom');
+ const zoomInItem = viewMenu.submenu.find((item: any) => item.role === 'zoomIn');
+ const zoomOutItem = viewMenu.submenu.find((item: any) => item.role === 'zoomOut');
+
+ expect(resetZoomItem).toBeDefined();
+ expect(zoomInItem).toBeDefined();
+ expect(zoomOutItem).toBeDefined();
+ });
+ });
+
+ describe('about dialog', () => {
+ it('should show about dialog with app info', () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const helpMenu = template.find((item: any) => item.label === 'Help');
+ const aboutItem = helpMenu.submenu.find((item: any) => item.label === 'About');
+
+ aboutItem.click();
+
+ expect(mockApp.i18n.ns).toHaveBeenCalledWith('common');
+ expect(mockApp.i18n.ns).toHaveBeenCalledWith('dialog');
+ expect(app.getName).toHaveBeenCalled();
+ expect(app.getVersion).toHaveBeenCalled();
+ expect(dialog.showMessageBox).toHaveBeenCalled();
+ });
+
+ it('should display app name and version in about dialog', () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const helpMenu = template.find((item: any) => item.label === 'Help');
+ const aboutItem = helpMenu.submenu.find((item: any) => item.label === 'About');
+
+ aboutItem.click();
+
+ const callArgs = (dialog.showMessageBox as any).mock.calls[0][0];
+ expect(callArgs.message).toContain('LobeChat');
+ expect(callArgs.message).toContain('1.0.0');
+ });
+ });
+
+ describe('i18n integration', () => {
+ it('should use i18n for all menu labels', () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ expect(mockApp.i18n.ns).toHaveBeenCalledWith('menu');
+ });
+
+ it('should request translations for tray menu', () => {
+ linuxMenu.buildTrayMenu();
+
+ expect(mockApp.i18n.ns).toHaveBeenCalled();
+ expect(app.getName).toHaveBeenCalled();
+ });
+
+ it('should use multiple i18n namespaces for about dialog', () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const helpMenu = template.find((item: any) => item.label === 'Help');
+ const aboutItem = helpMenu.submenu.find((item: any) => item.label === 'About');
+
+ vi.clearAllMocks();
+ aboutItem.click();
+
+ expect(mockApp.i18n.ns).toHaveBeenCalledWith('common');
+ expect(mockApp.i18n.ns).toHaveBeenCalledWith('dialog');
+ });
+ });
+});
diff --git a/apps/desktop/src/main/menus/impls/macOS.test.ts b/apps/desktop/src/main/menus/impls/macOS.test.ts
new file mode 100644
index 00000000000..a0c5c84b678
--- /dev/null
+++ b/apps/desktop/src/main/menus/impls/macOS.test.ts
@@ -0,0 +1,464 @@
+import { Menu, app, shell } from 'electron';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { App } from '@/core/App';
+
+import { MacOSMenu } from './macOS';
+
+// Mock Electron modules
+vi.mock('electron', () => ({
+ Menu: {
+ buildFromTemplate: vi.fn((template) => ({ template })),
+ setApplicationMenu: vi.fn(),
+ },
+ app: {
+ getName: vi.fn(() => 'LobeChat'),
+ getPath: vi.fn((type: string) => {
+ if (type === 'logs') return '/path/to/logs';
+ if (type === 'userData') return '/path/to/userData';
+ if (type === 'cache') return '/path/to/cache';
+ return '/path/to/default';
+ }),
+ },
+ shell: {
+ openExternal: vi.fn(),
+ openPath: vi.fn(() => Promise.resolve('')),
+ },
+}));
+
+// Mock isDev
+vi.mock('@/const/env', () => ({
+ isDev: false,
+}));
+
+// Mock App instance
+const createMockApp = () => {
+ const mockT = vi.fn((key: string, params?: any) => {
+ const translations: Record<string, string> = {
+ 'macOS.about': `About ${params?.appName || 'App'}`,
+ 'common.checkUpdates': 'Check for Updates',
+ 'macOS.preferences': 'Preferences',
+ 'macOS.services': 'Services',
+ 'macOS.hide': `Hide ${params?.appName || 'App'}`,
+ 'macOS.hideOthers': 'Hide Others',
+ 'macOS.unhide': 'Show All',
+ 'file.quit': 'Quit',
+ 'file.title': 'File',
+ 'file.preferences': 'Preferences',
+ 'window.close': 'Close Window',
+ 'window.title': 'Window',
+ 'window.minimize': 'Minimize',
+ 'edit.title': 'Edit',
+ 'edit.undo': 'Undo',
+ 'edit.redo': 'Redo',
+ 'edit.cut': 'Cut',
+ 'edit.copy': 'Copy',
+ 'edit.paste': 'Paste',
+ 'edit.selectAll': 'Select All',
+ 'edit.speech': 'Speech',
+ 'edit.startSpeaking': 'Start Speaking',
+ 'edit.stopSpeaking': 'Stop Speaking',
+ 'edit.delete': 'Delete',
+ 'view.title': 'View',
+ 'view.reload': 'Reload',
+ 'view.forceReload': 'Force Reload',
+ 'view.resetZoom': 'Actual Size',
+ 'view.zoomIn': 'Zoom In',
+ 'view.zoomOut': 'Zoom Out',
+ 'view.toggleFullscreen': 'Toggle Full Screen',
+ 'help.title': 'Help',
+ 'help.visitWebsite': 'Visit Website',
+ 'help.githubRepo': 'GitHub Repository',
+ 'help.reportIssue': 'Report Issue',
+ 'help.about': 'About',
+ 'dev.title': 'Developer',
+ 'dev.devPanel': 'Dev Panel',
+ 'dev.refreshMenu': 'Refresh Menu',
+ 'dev.devTools': 'Developer Tools',
+ 'dev.reload': 'Reload',
+ 'dev.forceReload': 'Force Reload',
+ 'tray.show': `Show ${params?.appName || 'App'}`,
+ 'tray.quit': 'Quit',
+ };
+ return translations[key] || key;
+ });
+
+ return {
+ i18n: {
+ ns: vi.fn(() => mockT),
+ },
+ browserManager: {
+ getMainWindow: vi.fn(() => ({
+ loadUrl: vi.fn(),
+ show: vi.fn(),
+ })),
+ showMainWindow: vi.fn(),
+ retrieveByIdentifier: vi.fn(() => ({
+ show: vi.fn(),
+ })),
+ },
+ updaterManager: {
+ checkForUpdates: vi.fn(),
+ simulateUpdateAvailable: vi.fn(),
+ simulateDownloadProgress: vi.fn(),
+ simulateUpdateDownloaded: vi.fn(),
+ },
+ menuManager: {
+ rebuildAppMenu: vi.fn(),
+ },
+ storeManager: {
+ openInEditor: vi.fn(),
+ },
+ } as unknown as App;
+};
+
+describe('MacOSMenu', () => {
+ let macOSMenu: MacOSMenu;
+ let mockApp: App;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockApp = createMockApp();
+ macOSMenu = new MacOSMenu(mockApp);
+ });
+
+ describe('buildAndSetAppMenu', () => {
+ it('should build and set application menu', () => {
+ const menu = macOSMenu.buildAndSetAppMenu();
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(Menu.setApplicationMenu).toHaveBeenCalled();
+ expect(menu).toBeDefined();
+ });
+
+ it('should include developer menu when showDevItems is true', () => {
+ const menu = macOSMenu.buildAndSetAppMenu({ showDevItems: true });
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+ expect(devMenu).toBeDefined();
+ });
+
+ it('should not include developer menu when showDevItems is false', () => {
+ const menu = macOSMenu.buildAndSetAppMenu({ showDevItems: false });
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+ expect(devMenu).toBeUndefined();
+ });
+
+ it('should create menu with correct structure', () => {
+ macOSMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ expect(template).toBeInstanceOf(Array);
+ expect(template.length).toBeGreaterThan(0);
+ });
+ });
+
+ describe('buildContextMenu', () => {
+ it('should build chat context menu', () => {
+ const menu = macOSMenu.buildContextMenu('chat');
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(menu).toBeDefined();
+ });
+
+ it('should build editor context menu', () => {
+ const menu = macOSMenu.buildContextMenu('editor');
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(menu).toBeDefined();
+ });
+
+ it('should build default context menu for unknown type', () => {
+ const menu = macOSMenu.buildContextMenu('unknown');
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(menu).toBeDefined();
+ });
+
+ it('should pass data to chat context menu', () => {
+ const data = { messageId: '123' };
+ macOSMenu.buildContextMenu('chat', data);
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ });
+ });
+
+ describe('buildTrayMenu', () => {
+ it('should build tray menu', () => {
+ const menu = macOSMenu.buildTrayMenu();
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(menu).toBeDefined();
+ });
+
+ it('should include show and quit items in tray menu', () => {
+ macOSMenu.buildTrayMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ expect(template.length).toBeGreaterThan(0);
+ expect(template.some((item: any) => item.label?.includes('Show'))).toBe(true);
+ expect(template.some((item: any) => item.label === 'Quit')).toBe(true);
+ });
+ });
+
+ describe('refresh', () => {
+ it('should rebuild application menu', () => {
+ macOSMenu.refresh();
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(Menu.setApplicationMenu).toHaveBeenCalled();
+ });
+
+ it('should pass options to rebuild', () => {
+ macOSMenu.refresh({ showDevItems: true });
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ });
+ });
+
+ describe('menu item click handlers', () => {
+ it('should handle check for updates click', () => {
+ macOSMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const appMenu = template[0];
+ const checkUpdatesItem = appMenu.submenu.find(
+ (item: any) => item.label === 'Check for Updates',
+ );
+
+ expect(checkUpdatesItem).toBeDefined();
+ checkUpdatesItem.click();
+ expect(mockApp.updaterManager.checkForUpdates).toHaveBeenCalledWith({ manual: true });
+ });
+
+ it('should handle preferences click', async () => {
+ macOSMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const appMenu = template[0];
+ const preferencesItem = appMenu.submenu.find((item: any) => item.label === 'Preferences');
+
+ expect(preferencesItem).toBeDefined();
+ await preferencesItem.click();
+ expect(mockApp.browserManager.getMainWindow).toHaveBeenCalled();
+ });
+
+ it('should handle visit website click', async () => {
+ macOSMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const helpMenu = template.find((item: any) => item.label === 'Help');
+ const visitWebsiteItem = helpMenu.submenu.find((item: any) => item.label === 'Visit Website');
+
+ expect(visitWebsiteItem).toBeDefined();
+ await visitWebsiteItem.click();
+ expect(shell.openExternal).toHaveBeenCalledWith('https://lobehub.com');
+ });
+
+ it('should handle github repo click', async () => {
+ macOSMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const helpMenu = template.find((item: any) => item.label === 'Help');
+ const githubItem = helpMenu.submenu.find((item: any) => item.label === 'GitHub Repository');
+
+ expect(githubItem).toBeDefined();
+ await githubItem.click();
+ expect(shell.openExternal).toHaveBeenCalledWith('https://github.com/lobehub/lobe-chat');
+ });
+
+ it('should handle open logs directory click', () => {
+ macOSMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const helpMenu = template.find((item: any) => item.label === 'Help');
+ const logsItem = helpMenu.submenu.find((item: any) => item.label === '打开日志目录');
+
+ expect(logsItem).toBeDefined();
+ logsItem.click();
+ expect(app.getPath).toHaveBeenCalledWith('logs');
+ expect(shell.openPath).toHaveBeenCalledWith('/path/to/logs');
+ });
+
+ it('should handle tray show click', () => {
+ macOSMenu.buildTrayMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const showItem = template.find((item: any) => item.label?.includes('Show'));
+
+ expect(showItem).toBeDefined();
+ showItem.click();
+ expect(mockApp.browserManager.showMainWindow).toHaveBeenCalled();
+ });
+ });
+
+ describe('menu accelerators', () => {
+ it('should set correct accelerator for preferences', () => {
+ macOSMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const appMenu = template[0];
+ const preferencesItem = appMenu.submenu.find((item: any) => item.label === 'Preferences');
+
+ expect(preferencesItem.accelerator).toBe('Command+,');
+ });
+
+ it('should set correct accelerator for quit', () => {
+ macOSMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const appMenu = template[0];
+ const quitItem = appMenu.submenu.find((item: any) => item.label === 'Quit');
+
+ expect(quitItem.accelerator).toBe('Command+Q');
+ });
+
+ it('should set correct accelerator for copy in edit menu', () => {
+ macOSMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const editMenu = template.find((item: any) => item.label === 'Edit');
+ const copyItem = editMenu.submenu.find((item: any) => item.label === 'Copy');
+
+ expect(copyItem.accelerator).toBe('Command+C');
+ });
+ });
+
+ describe('developer menu items', () => {
+ it('should include dev panel in developer menu', () => {
+ macOSMenu.buildAndSetAppMenu({ showDevItems: true });
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+ const devPanelItem = devMenu.submenu.find((item: any) => item.label === 'Dev Panel');
+
+ expect(devPanelItem).toBeDefined();
+ });
+
+ it('should handle dev panel click', () => {
+ macOSMenu.buildAndSetAppMenu({ showDevItems: true });
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+ const devPanelItem = devMenu.submenu.find((item: any) => item.label === 'Dev Panel');
+
+ devPanelItem.click();
+ expect(mockApp.browserManager.retrieveByIdentifier).toHaveBeenCalledWith('devtools');
+ });
+
+ it('should handle refresh menu click', () => {
+ macOSMenu.buildAndSetAppMenu({ showDevItems: true });
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+ const refreshMenuItem = devMenu.submenu.find((item: any) => item.label === 'Refresh Menu');
+
+ refreshMenuItem.click();
+ expect(mockApp.menuManager.rebuildAppMenu).toHaveBeenCalled();
+ });
+
+ it('should include updater simulation submenu', () => {
+ macOSMenu.buildAndSetAppMenu({ showDevItems: true });
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+ const updaterMenu = devMenu.submenu.find((item: any) => item.label === '自动更新测试模拟');
+
+ expect(updaterMenu).toBeDefined();
+ expect(updaterMenu.submenu).toBeInstanceOf(Array);
+ expect(updaterMenu.submenu.length).toBeGreaterThan(0);
+ });
+ });
+
+ describe('context menu templates', () => {
+ it('should include copy and paste in chat context menu', () => {
+ macOSMenu.buildContextMenu('chat');
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const copyItem = template.find((item: any) => item.role === 'copy');
+ const pasteItem = template.find((item: any) => item.role === 'paste');
+
+ expect(copyItem).toBeDefined();
+ expect(pasteItem).toBeDefined();
+ });
+
+ it('should include cut in editor context menu but not in chat', () => {
+ macOSMenu.buildContextMenu('editor');
+ const editorTemplate = (Menu.buildFromTemplate as any).mock.calls[0][0];
+
+ vi.clearAllMocks();
+
+ macOSMenu.buildContextMenu('chat');
+ const chatTemplate = (Menu.buildFromTemplate as any).mock.calls[0][0];
+
+ const editorCutItem = editorTemplate.find((item: any) => item.role === 'cut');
+ const chatCutItem = chatTemplate.find((item: any) => item.role === 'cut');
+
+ expect(editorCutItem).toBeDefined();
+ expect(chatCutItem).toBeUndefined();
+ });
+
+ it('should include delete in editor context menu', () => {
+ macOSMenu.buildContextMenu('editor');
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const deleteItem = template.find((item: any) => item.role === 'delete');
+
+ expect(deleteItem).toBeDefined();
+ });
+ });
+
+ describe('menu roles', () => {
+ it('should set window role for window menu', () => {
+ macOSMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const windowMenu = template.find((item: any) => item.label === 'Window');
+
+ expect(windowMenu.role).toBe('windowMenu');
+ });
+
+ it('should set help role for help menu', () => {
+ macOSMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const helpMenu = template.find((item: any) => item.label === 'Help');
+
+ expect(helpMenu.role).toBe('help');
+ });
+
+ it('should set services submenu in app menu', () => {
+ macOSMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const appMenu = template[0];
+ const servicesItem = appMenu.submenu.find((item: any) => item.role === 'services');
+
+ expect(servicesItem).toBeDefined();
+ expect(servicesItem.label).toBe('Services');
+ });
+ });
+
+ describe('i18n integration', () => {
+ it('should use i18n for all menu labels', () => {
+ macOSMenu.buildAndSetAppMenu();
+
+ expect(mockApp.i18n.ns).toHaveBeenCalledWith('menu');
+ });
+
+ it('should pass app name to translations', () => {
+ macOSMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const appMenu = template[0];
+
+ expect(app.getName).toHaveBeenCalled();
+ expect(appMenu.label).toBe('LobeChat');
+ });
+ });
+});
diff --git a/apps/desktop/src/main/menus/impls/windows.test.ts b/apps/desktop/src/main/menus/impls/windows.test.ts
new file mode 100644
index 00000000000..5e606b87d4a
--- /dev/null
+++ b/apps/desktop/src/main/menus/impls/windows.test.ts
@@ -0,0 +1,429 @@
+import { Menu, app, shell } from 'electron';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { App } from '@/core/App';
+
+import { WindowsMenu } from './windows';
+
+// Mock Electron modules
+vi.mock('electron', () => ({
+ Menu: {
+ buildFromTemplate: vi.fn((template) => ({ template })),
+ setApplicationMenu: vi.fn(),
+ },
+ app: {
+ getName: vi.fn(() => 'LobeChat'),
+ },
+ shell: {
+ openExternal: vi.fn(),
+ },
+}));
+
+// Mock isDev
+vi.mock('@/const/env', () => ({
+ isDev: false,
+}));
+
+// Mock App instance
+const createMockApp = () => {
+ const mockT = vi.fn((key: string, params?: any) => {
+ const translations: Record<string, string> = {
+ 'file.title': 'File',
+ 'file.preferences': 'Settings',
+ 'file.quit': 'Exit',
+ 'common.checkUpdates': 'Check for Updates',
+ 'window.close': 'Close',
+ 'window.minimize': 'Minimize',
+ 'window.title': 'Window',
+ 'edit.title': 'Edit',
+ 'edit.undo': 'Undo',
+ 'edit.redo': 'Redo',
+ 'edit.cut': 'Cut',
+ 'edit.copy': 'Copy',
+ 'edit.paste': 'Paste',
+ 'edit.selectAll': 'Select All',
+ 'edit.delete': 'Delete',
+ 'view.title': 'View',
+ 'view.resetZoom': 'Reset Zoom',
+ 'view.zoomIn': 'Zoom In',
+ 'view.zoomOut': 'Zoom Out',
+ 'view.toggleFullscreen': 'Full Screen',
+ 'help.title': 'Help',
+ 'help.visitWebsite': 'Visit Website',
+ 'help.githubRepo': 'GitHub Repository',
+ 'dev.title': 'Developer',
+ 'dev.reload': 'Reload',
+ 'dev.forceReload': 'Force Reload',
+ 'dev.devTools': 'Developer Tools',
+ 'dev.devPanel': 'Dev Panel',
+ 'tray.open': `Open ${params?.appName || 'App'}`,
+ 'tray.quit': 'Quit',
+ };
+ return translations[key] || key;
+ });
+
+ return {
+ i18n: {
+ ns: vi.fn(() => mockT),
+ },
+ browserManager: {
+ showMainWindow: vi.fn(),
+ retrieveByIdentifier: vi.fn(() => ({
+ show: vi.fn(),
+ })),
+ },
+ updaterManager: {
+ checkForUpdates: vi.fn(),
+ },
+ } as unknown as App;
+};
+
+describe('WindowsMenu', () => {
+ let windowsMenu: WindowsMenu;
+ let mockApp: App;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockApp = createMockApp();
+ windowsMenu = new WindowsMenu(mockApp);
+ });
+
+ describe('buildAndSetAppMenu', () => {
+ it('should build and set application menu', () => {
+ const menu = windowsMenu.buildAndSetAppMenu();
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(Menu.setApplicationMenu).toHaveBeenCalled();
+ expect(menu).toBeDefined();
+ });
+
+ it('should include developer menu when showDevItems is true', () => {
+ windowsMenu.buildAndSetAppMenu({ showDevItems: true });
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+ expect(devMenu).toBeDefined();
+ });
+
+ it('should not include developer menu when showDevItems is false', () => {
+ windowsMenu.buildAndSetAppMenu({ showDevItems: false });
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+ expect(devMenu).toBeUndefined();
+ });
+
+ it('should create menu with File, Edit, View, Window, Help', () => {
+ windowsMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const menuLabels = template.map((item: any) => item.label);
+
+ expect(menuLabels).toContain('File');
+ expect(menuLabels).toContain('Edit');
+ expect(menuLabels).toContain('View');
+ expect(menuLabels).toContain('Window');
+ expect(menuLabels).toContain('Help');
+ });
+ });
+
+ describe('buildContextMenu', () => {
+ it('should build chat context menu', () => {
+ const menu = windowsMenu.buildContextMenu('chat');
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(menu).toBeDefined();
+ });
+
+ it('should build editor context menu', () => {
+ const menu = windowsMenu.buildContextMenu('editor');
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(menu).toBeDefined();
+ });
+
+ it('should build default context menu for unknown type', () => {
+ const menu = windowsMenu.buildContextMenu('unknown');
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(menu).toBeDefined();
+ });
+
+ it('should pass data to context menu', () => {
+ const data = { text: 'selected text' };
+ windowsMenu.buildContextMenu('editor', data);
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ });
+ });
+
+ describe('buildTrayMenu', () => {
+ it('should build tray menu', () => {
+ const menu = windowsMenu.buildTrayMenu();
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(menu).toBeDefined();
+ });
+
+ it('should include open and quit items in tray menu', () => {
+ windowsMenu.buildTrayMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ expect(template.length).toBeGreaterThan(0);
+ expect(template.some((item: any) => item.label?.includes('Open'))).toBe(true);
+ expect(template.some((item: any) => item.label === 'Quit')).toBe(true);
+ });
+ });
+
+ describe('refresh', () => {
+ it('should rebuild application menu', () => {
+ windowsMenu.refresh();
+
+ expect(Menu.buildFromTemplate).toHaveBeenCalled();
+ expect(Menu.setApplicationMenu).toHaveBeenCalled();
+ });
+
+ it('should pass options to rebuild', () => {
+ windowsMenu.refresh({ showDevItems: true });
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+ expect(devMenu).toBeDefined();
+ });
+ });
+
+ describe('menu item click handlers', () => {
+ it('should handle preferences click', () => {
+ windowsMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const fileMenu = template.find((item: any) => item.label === 'File');
+ const preferencesItem = fileMenu.submenu.find((item: any) => item.label === 'Settings');
+
+ expect(preferencesItem).toBeDefined();
+ preferencesItem.click();
+ expect(mockApp.browserManager.retrieveByIdentifier).toHaveBeenCalledWith('settings');
+ });
+
+ it('should handle check for updates click', () => {
+ windowsMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const fileMenu = template.find((item: any) => item.label === 'File');
+ const checkUpdatesItem = fileMenu.submenu.find(
+ (item: any) => item.label === 'Check for Updates',
+ );
+
+ expect(checkUpdatesItem).toBeDefined();
+ checkUpdatesItem.click();
+ expect(mockApp.updaterManager.checkForUpdates).toHaveBeenCalledWith({ manual: true });
+ });
+
+ it('should handle visit website click', async () => {
+ windowsMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const helpMenu = template.find((item: any) => item.label === 'Help');
+ const visitWebsiteItem = helpMenu.submenu.find((item: any) => item.label === 'Visit Website');
+
+ expect(visitWebsiteItem).toBeDefined();
+ await visitWebsiteItem.click();
+ expect(shell.openExternal).toHaveBeenCalledWith('https://lobehub.com');
+ });
+
+ it('should handle github repo click', async () => {
+ windowsMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const helpMenu = template.find((item: any) => item.label === 'Help');
+ const githubItem = helpMenu.submenu.find((item: any) => item.label === 'GitHub Repository');
+
+ expect(githubItem).toBeDefined();
+ await githubItem.click();
+ expect(shell.openExternal).toHaveBeenCalledWith('https://github.com/lobehub/lobe-chat');
+ });
+
+ it('should handle tray open click', () => {
+ windowsMenu.buildTrayMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const openItem = template.find((item: any) => item.label?.includes('Open'));
+
+ expect(openItem).toBeDefined();
+ openItem.click();
+ expect(mockApp.browserManager.showMainWindow).toHaveBeenCalled();
+ });
+ });
+
+ describe('menu accelerators', () => {
+ it('should use Ctrl prefix for Windows shortcuts', () => {
+ windowsMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const editMenu = template.find((item: any) => item.label === 'Edit');
+ const copyItem = editMenu.submenu.find((item: any) => item.label === 'Copy');
+
+ expect(copyItem.accelerator).toBe('Ctrl+C');
+ });
+
+ it('should set correct accelerator for close', () => {
+ windowsMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const fileMenu = template.find((item: any) => item.label === 'File');
+ const closeItem = fileMenu.submenu.find((item: any) => item.label === 'Close');
+
+ expect(closeItem.accelerator).toBe('Alt+F4');
+ });
+
+ it('should set correct accelerator for minimize', () => {
+ windowsMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const fileMenu = template.find((item: any) => item.label === 'File');
+ const minimizeItem = fileMenu.submenu.find((item: any) => item.label === 'Minimize');
+
+ expect(minimizeItem.accelerator).toBe('Ctrl+M');
+ });
+
+ it('should set F11 for fullscreen', () => {
+ windowsMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const viewMenu = template.find((item: any) => item.label === 'View');
+ const fullscreenItem = viewMenu.submenu.find((item: any) => item.label === 'Full Screen');
+
+ expect(fullscreenItem.accelerator).toBe('F11');
+ });
+ });
+
+ describe('developer menu items', () => {
+ it('should include dev tools shortcuts in developer menu', () => {
+ windowsMenu.buildAndSetAppMenu({ showDevItems: true });
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+
+ expect(devMenu).toBeDefined();
+ expect(devMenu.submenu.length).toBeGreaterThan(0);
+ });
+
+ it('should handle dev panel click', () => {
+ windowsMenu.buildAndSetAppMenu({ showDevItems: true });
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+ const devPanelItem = devMenu.submenu.find((item: any) => item.label === 'Dev Panel');
+
+ expect(devPanelItem).toBeDefined();
+ devPanelItem.click();
+ expect(mockApp.browserManager.retrieveByIdentifier).toHaveBeenCalledWith('devtools');
+ });
+
+ it('should set Ctrl+Shift+I for developer tools', () => {
+ windowsMenu.buildAndSetAppMenu({ showDevItems: true });
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const devMenu = template.find((item: any) => item.label === 'Developer');
+ const devToolsItem = devMenu.submenu.find((item: any) => item.label === 'Developer Tools');
+
+ expect(devToolsItem.accelerator).toBe('Ctrl+Shift+I');
+ });
+ });
+
+ describe('context menu templates', () => {
+ it('should include copy and paste in chat context menu', () => {
+ windowsMenu.buildContextMenu('chat');
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const copyItem = template.find((item: any) => item.role === 'copy');
+ const pasteItem = template.find((item: any) => item.role === 'paste');
+
+ expect(copyItem).toBeDefined();
+ expect(pasteItem).toBeDefined();
+ });
+
+ it('should use Ctrl accelerators in context menus', () => {
+ windowsMenu.buildContextMenu('editor');
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const copyItem = template.find((item: any) => item.role === 'copy');
+
+ expect(copyItem.accelerator).toBe('Ctrl+C');
+ });
+
+ it('should include cut in editor context menu', () => {
+ windowsMenu.buildContextMenu('editor');
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const cutItem = template.find((item: any) => item.role === 'cut');
+
+ expect(cutItem).toBeDefined();
+ expect(cutItem.accelerator).toBe('Ctrl+X');
+ });
+
+ it('should include delete in editor context menu', () => {
+ windowsMenu.buildContextMenu('editor');
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const deleteItem = template.find((item: any) => item.role === 'delete');
+
+ expect(deleteItem).toBeDefined();
+ });
+ });
+
+ describe('menu structure', () => {
+ it('should have separators in menus', () => {
+ windowsMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const fileMenu = template.find((item: any) => item.label === 'File');
+ const hasSeparator = fileMenu.submenu.some((item: any) => item.type === 'separator');
+
+ expect(hasSeparator).toBe(true);
+ });
+
+ it('should have minimize and close in window menu', () => {
+ windowsMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const windowMenu = template.find((item: any) => item.label === 'Window');
+
+ const minimizeItem = windowMenu.submenu.find((item: any) => item.role === 'minimize');
+ const closeItem = windowMenu.submenu.find((item: any) => item.role === 'close');
+
+ expect(minimizeItem).toBeDefined();
+ expect(closeItem).toBeDefined();
+ });
+
+ it('should have zoom controls in view menu', () => {
+ windowsMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const viewMenu = template.find((item: any) => item.label === 'View');
+
+ const resetZoomItem = viewMenu.submenu.find((item: any) => item.role === 'resetZoom');
+ const zoomInItem = viewMenu.submenu.find((item: any) => item.role === 'zoomIn');
+ const zoomOutItem = viewMenu.submenu.find((item: any) => item.role === 'zoomOut');
+
+ expect(resetZoomItem).toBeDefined();
+ expect(zoomInItem).toBeDefined();
+ expect(zoomOutItem).toBeDefined();
+ });
+ });
+
+ describe('i18n integration', () => {
+ it('should use i18n for all menu labels', () => {
+ windowsMenu.buildAndSetAppMenu();
+
+ expect(mockApp.i18n.ns).toHaveBeenCalledWith('menu');
+ });
+
+ it('should request translations multiple times for tray menu', () => {
+ windowsMenu.buildTrayMenu();
+
+ expect(mockApp.i18n.ns).toHaveBeenCalled();
+ expect(app.getName).toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/desktop/src/main/modules/fileSearch/__tests__/macOS.integration.test.ts b/apps/desktop/src/main/modules/fileSearch/__tests__/macOS.integration.test.ts
index 5eb96ca1898..2e4a8500a4b 100644
--- a/apps/desktop/src/main/modules/fileSearch/__tests__/macOS.integration.test.ts
+++ b/apps/desktop/src/main/modules/fileSearch/__tests__/macOS.integration.test.ts
@@ -108,10 +108,10 @@ describe.skipIf(process.platform !== 'darwin')('MacOSSearchServiceImpl Integrati
expect(results.length).toBeGreaterThan(0);
- // Should find test files
+ // Should find test files (can be in __tests__ directory or co-located with source files)
const testFile = results.find((r) => r.name.endsWith('.test.ts'));
expect(testFile).toBeDefined();
- expect(testFile!.path).toContain('__tests__');
+ expect(testFile!.path).toMatch(/(__tests__|\.test\.ts$)/);
});
});
diff --git a/apps/desktop/src/main/services/__tests__/fileSearchSrv.test.ts b/apps/desktop/src/main/services/__tests__/fileSearchSrv.test.ts
new file mode 100644
index 00000000000..f8e28960814
--- /dev/null
+++ b/apps/desktop/src/main/services/__tests__/fileSearchSrv.test.ts
@@ -0,0 +1,402 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { App } from '@/core/App';
+import { FileSearchImpl } from '@/modules/fileSearch';
+import type { FileResult, SearchOptions } from '@/types/fileSearch';
+
+import FileSearchService from '../fileSearchSrv';
+
+// Mock the fileSearch module
+vi.mock('@/modules/fileSearch', () => {
+ const MockFileSearchImpl = vi.fn().mockImplementation(() => ({
+ search: vi.fn(),
+ checkSearchServiceStatus: vi.fn(),
+ updateSearchIndex: vi.fn(),
+ }));
+
+ return {
+ FileSearchImpl: vi.fn(),
+ createFileSearchModule: vi.fn(() => new MockFileSearchImpl()),
+ };
+});
+
+// Mock logger
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => ({
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+
+describe('FileSearchService', () => {
+ let fileSearchService: FileSearchService;
+ let mockApp: App;
+ let mockImpl: {
+ search: ReturnType<typeof vi.fn>;
+ checkSearchServiceStatus: ReturnType<typeof vi.fn>;
+ updateSearchIndex: ReturnType<typeof vi.fn>;
+ };
+
+ beforeEach(async () => {
+ vi.clearAllMocks();
+
+ // Setup mock app
+ mockApp = {} as unknown as App;
+
+ fileSearchService = new FileSearchService(mockApp);
+
+ // Get the mock implementation instance
+ mockImpl = (fileSearchService as any).impl;
+ });
+
+ describe('search', () => {
+ it('should perform search with query and default options', async () => {
+ const mockResults: FileResult[] = [
+ {
+ name: 'test.txt',
+ path: '/home/user/test.txt',
+ type: 'text/plain',
+ size: 1024,
+ isDirectory: false,
+ createdTime: new Date('2024-01-01'),
+ modifiedTime: new Date('2024-01-02'),
+ lastAccessTime: new Date('2024-01-03'),
+ },
+ ];
+
+ mockImpl.search.mockResolvedValue(mockResults);
+
+ const result = await fileSearchService.search('test');
+
+ expect(mockImpl.search).toHaveBeenCalledWith({ keywords: 'test' });
+ expect(result).toEqual(mockResults);
+ });
+
+ it('should perform search with query and custom options', async () => {
+ const mockResults: FileResult[] = [
+ {
+ name: 'document.pdf',
+ path: '/home/user/documents/document.pdf',
+ type: 'application/pdf',
+ size: 2048,
+ isDirectory: false,
+ createdTime: new Date('2024-02-01'),
+ modifiedTime: new Date('2024-02-02'),
+ lastAccessTime: new Date('2024-02-03'),
+ },
+ ];
+
+ const options: Omit<SearchOptions, 'keywords'> = {
+ limit: 10,
+ fileTypes: ['public.pdf'],
+ onlyIn: '/home/user/documents',
+ };
+
+ mockImpl.search.mockResolvedValue(mockResults);
+
+ const result = await fileSearchService.search('document', options);
+
+ expect(mockImpl.search).toHaveBeenCalledWith({
+ keywords: 'document',
+ limit: 10,
+ fileTypes: ['public.pdf'],
+ onlyIn: '/home/user/documents',
+ });
+ expect(result).toEqual(mockResults);
+ });
+
+ it('should perform search with date filters', async () => {
+ const mockResults: FileResult[] = [];
+ const createdAfter = new Date('2024-01-01');
+ const createdBefore = new Date('2024-12-31');
+
+ mockImpl.search.mockResolvedValue(mockResults);
+
+ await fileSearchService.search('test', {
+ createdAfter,
+ createdBefore,
+ });
+
+ expect(mockImpl.search).toHaveBeenCalledWith({
+ keywords: 'test',
+ createdAfter,
+ createdBefore,
+ });
+ });
+
+ it('should perform search with content filter', async () => {
+ const mockResults: FileResult[] = [];
+
+ mockImpl.search.mockResolvedValue(mockResults);
+
+ await fileSearchService.search('test', {
+ contentContains: 'specific text',
+ });
+
+ expect(mockImpl.search).toHaveBeenCalledWith({
+ keywords: 'test',
+ contentContains: 'specific text',
+ });
+ });
+
+ it('should perform search with sorting options', async () => {
+ const mockResults: FileResult[] = [];
+
+ mockImpl.search.mockResolvedValue(mockResults);
+
+ await fileSearchService.search('test', {
+ sortBy: 'date',
+ sortDirection: 'desc',
+ });
+
+ expect(mockImpl.search).toHaveBeenCalledWith({
+ keywords: 'test',
+ sortBy: 'date',
+ sortDirection: 'desc',
+ });
+ });
+
+ it('should perform search with exclude filter', async () => {
+ const mockResults: FileResult[] = [];
+
+ mockImpl.search.mockResolvedValue(mockResults);
+
+ await fileSearchService.search('test', {
+ exclude: ['/node_modules', '/dist'],
+ });
+
+ expect(mockImpl.search).toHaveBeenCalledWith({
+ keywords: 'test',
+ exclude: ['/node_modules', '/dist'],
+ });
+ });
+
+ it('should return empty array when no results found', async () => {
+ mockImpl.search.mockResolvedValue([]);
+
+ const result = await fileSearchService.search('nonexistent');
+
+ expect(result).toEqual([]);
+ });
+
+ it('should return results with metadata when detailed option is enabled', async () => {
+ const mockResults: FileResult[] = [
+ {
+ name: 'image.jpg',
+ path: '/home/user/images/image.jpg',
+ type: 'image/jpeg',
+ size: 4096,
+ isDirectory: false,
+ createdTime: new Date('2024-03-01'),
+ modifiedTime: new Date('2024-03-02'),
+ lastAccessTime: new Date('2024-03-03'),
+ metadata: {
+ width: 1920,
+ height: 1080,
+ orientation: 'landscape',
+ },
+ },
+ ];
+
+ mockImpl.search.mockResolvedValue(mockResults);
+
+ const result = await fileSearchService.search('image', { detailed: true });
+
+ expect(mockImpl.search).toHaveBeenCalledWith({
+ keywords: 'image',
+ detailed: true,
+ });
+ expect(result[0].metadata).toBeDefined();
+ expect(result[0].metadata?.width).toBe(1920);
+ });
+
+ it('should handle search errors gracefully', async () => {
+ mockImpl.search.mockRejectedValue(new Error('Search service unavailable'));
+
+ await expect(fileSearchService.search('test')).rejects.toThrow('Search service unavailable');
+ });
+
+ it('should perform search with all available options', async () => {
+ const mockResults: FileResult[] = [];
+ const allOptions: Omit<SearchOptions, 'keywords'> = {
+ limit: 50,
+ fileTypes: ['public.image', 'public.movie'],
+ onlyIn: '/home/user/media',
+ exclude: ['/home/user/media/temp'],
+ contentContains: 'vacation',
+ createdAfter: new Date('2024-01-01'),
+ createdBefore: new Date('2024-12-31'),
+ modifiedAfter: new Date('2024-06-01'),
+ modifiedBefore: new Date('2024-12-31'),
+ sortBy: 'size',
+ sortDirection: 'desc',
+ detailed: true,
+ liveUpdate: false,
+ };
+
+ mockImpl.search.mockResolvedValue(mockResults);
+
+ await fileSearchService.search('vacation photos', allOptions);
+
+ expect(mockImpl.search).toHaveBeenCalledWith({
+ keywords: 'vacation photos',
+ ...allOptions,
+ });
+ });
+ });
+
+ describe('checkSearchServiceStatus', () => {
+ it('should return true when search service is available', async () => {
+ mockImpl.checkSearchServiceStatus.mockResolvedValue(true);
+
+ const result = await fileSearchService.checkSearchServiceStatus();
+
+ expect(mockImpl.checkSearchServiceStatus).toHaveBeenCalled();
+ expect(result).toBe(true);
+ });
+
+ it('should return false when search service is unavailable', async () => {
+ mockImpl.checkSearchServiceStatus.mockResolvedValue(false);
+
+ const result = await fileSearchService.checkSearchServiceStatus();
+
+ expect(mockImpl.checkSearchServiceStatus).toHaveBeenCalled();
+ expect(result).toBe(false);
+ });
+
+ it('should handle status check errors', async () => {
+ mockImpl.checkSearchServiceStatus.mockRejectedValue(
+ new Error('Unable to check service status'),
+ );
+
+ await expect(fileSearchService.checkSearchServiceStatus()).rejects.toThrow(
+ 'Unable to check service status',
+ );
+ });
+ });
+
+ describe('updateSearchIndex', () => {
+ it('should update search index without path', async () => {
+ mockImpl.updateSearchIndex.mockResolvedValue(true);
+
+ const result = await fileSearchService.updateSearchIndex();
+
+ expect(mockImpl.updateSearchIndex).toHaveBeenCalledWith(undefined);
+ expect(result).toBe(true);
+ });
+
+ it('should update search index with specified path', async () => {
+ mockImpl.updateSearchIndex.mockResolvedValue(true);
+
+ const result = await fileSearchService.updateSearchIndex('/home/user/documents');
+
+ expect(mockImpl.updateSearchIndex).toHaveBeenCalledWith('/home/user/documents');
+ expect(result).toBe(true);
+ });
+
+ it('should return false when index update fails', async () => {
+ mockImpl.updateSearchIndex.mockResolvedValue(false);
+
+ const result = await fileSearchService.updateSearchIndex('/home/user/documents');
+
+ expect(result).toBe(false);
+ });
+
+ it('should handle index update errors', async () => {
+ mockImpl.updateSearchIndex.mockRejectedValue(new Error('Index update failed'));
+
+ await expect(fileSearchService.updateSearchIndex('/home/user/documents')).rejects.toThrow(
+ 'Index update failed',
+ );
+ });
+
+ it('should handle index update for multiple different paths', async () => {
+ mockImpl.updateSearchIndex.mockResolvedValue(true);
+
+ const paths = ['/home/user/documents', '/home/user/downloads', '/home/user/desktop'];
+
+ for (const path of paths) {
+ const result = await fileSearchService.updateSearchIndex(path);
+ expect(result).toBe(true);
+ }
+
+ expect(mockImpl.updateSearchIndex).toHaveBeenCalledTimes(paths.length);
+ });
+ });
+
+ describe('integration behavior', () => {
+ it('should maintain consistent state across multiple operations', async () => {
+ mockImpl.checkSearchServiceStatus.mockResolvedValue(true);
+ mockImpl.updateSearchIndex.mockResolvedValue(true);
+ mockImpl.search.mockResolvedValue([]);
+
+ const statusBefore = await fileSearchService.checkSearchServiceStatus();
+ expect(statusBefore).toBe(true);
+
+ await fileSearchService.updateSearchIndex('/home/user');
+
+ const statusAfter = await fileSearchService.checkSearchServiceStatus();
+ expect(statusAfter).toBe(true);
+
+ const results = await fileSearchService.search('test');
+ expect(results).toEqual([]);
+ });
+
+ it('should handle directory search results correctly', async () => {
+ const mockResults: FileResult[] = [
+ {
+ name: 'documents',
+ path: '/home/user/documents',
+ type: 'directory',
+ size: 0,
+ isDirectory: true,
+ createdTime: new Date('2024-01-01'),
+ modifiedTime: new Date('2024-01-02'),
+ lastAccessTime: new Date('2024-01-03'),
+ },
+ ];
+
+ mockImpl.search.mockResolvedValue(mockResults);
+
+ const result = await fileSearchService.search('documents');
+
+ expect(result[0].isDirectory).toBe(true);
+ expect(result[0].type).toBe('directory');
+ });
+
+ it('should handle mixed file and directory results', async () => {
+ const mockResults: FileResult[] = [
+ {
+ name: 'documents',
+ path: '/home/user/documents',
+ type: 'directory',
+ size: 0,
+ isDirectory: true,
+ createdTime: new Date('2024-01-01'),
+ modifiedTime: new Date('2024-01-02'),
+ lastAccessTime: new Date('2024-01-03'),
+ },
+ {
+ name: 'readme.txt',
+ path: '/home/user/documents/readme.txt',
+ type: 'text/plain',
+ size: 512,
+ isDirectory: false,
+ createdTime: new Date('2024-01-01'),
+ modifiedTime: new Date('2024-01-02'),
+ lastAccessTime: new Date('2024-01-03'),
+ },
+ ];
+
+ mockImpl.search.mockResolvedValue(mockResults);
+
+ const result = await fileSearchService.search('readme');
+
+ expect(result).toHaveLength(2);
+ expect(result[0].isDirectory).toBe(true);
+ expect(result[1].isDirectory).toBe(false);
+ });
+ });
+});
diff --git a/apps/desktop/src/main/utils/__tests__/file-system.test.ts b/apps/desktop/src/main/utils/__tests__/file-system.test.ts
new file mode 100644
index 00000000000..2977d426e8c
--- /dev/null
+++ b/apps/desktop/src/main/utils/__tests__/file-system.test.ts
@@ -0,0 +1,91 @@
+import { mkdirSync, statSync } from 'node:fs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { makeSureDirExist } from '../file-system';
+
+vi.mock('node:fs', () => ({
+ mkdirSync: vi.fn(),
+ statSync: vi.fn(),
+}));
+
+describe('file-system', () => {
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('makeSureDirExist', () => {
+ it('should not create directory if it already exists', () => {
+ const dir = '/test/path';
+ vi.mocked(statSync).mockReturnValue({} as any);
+
+ makeSureDirExist(dir);
+
+ expect(statSync).toHaveBeenCalledWith(dir);
+ expect(mkdirSync).not.toHaveBeenCalled();
+ });
+
+ it('should create directory if it does not exist', () => {
+ const dir = '/test/new-path';
+ vi.mocked(statSync).mockImplementation(() => {
+ throw new Error('ENOENT: no such file or directory');
+ });
+
+ makeSureDirExist(dir);
+
+ expect(statSync).toHaveBeenCalledWith(dir);
+ expect(mkdirSync).toHaveBeenCalledWith(dir, { recursive: true });
+ });
+
+ it('should create directory recursively', () => {
+ const dir = '/test/deeply/nested/path';
+ vi.mocked(statSync).mockImplementation(() => {
+ throw new Error('ENOENT: no such file or directory');
+ });
+
+ makeSureDirExist(dir);
+
+ expect(mkdirSync).toHaveBeenCalledWith(dir, { recursive: true });
+ });
+
+ it('should throw error if mkdir fails due to permission issues', () => {
+ const dir = '/test/permission-denied';
+ vi.mocked(statSync).mockImplementation(() => {
+ throw new Error('ENOENT: no such file or directory');
+ });
+ vi.mocked(mkdirSync).mockImplementation(() => {
+ throw new Error('EACCES: permission denied');
+ });
+
+ expect(() => makeSureDirExist(dir)).toThrowError(
+ `Could not create target directory: ${dir}. Error: EACCES: permission denied`,
+ );
+ });
+
+ it('should throw error if mkdir fails with custom error message', () => {
+ const dir = '/test/custom-error';
+ const customError = new Error('Custom mkdir error');
+ vi.mocked(statSync).mockImplementation(() => {
+ throw new Error('ENOENT: no such file or directory');
+ });
+ vi.mocked(mkdirSync).mockImplementation(() => {
+ throw customError;
+ });
+
+ expect(() => makeSureDirExist(dir)).toThrowError(
+ `Could not create target directory: ${dir}. Error: Custom mkdir error`,
+ );
+ });
+
+ it('should handle empty directory path', () => {
+ const dir = '';
+ vi.mocked(statSync).mockImplementation(() => {
+ throw new Error('ENOENT: no such file or directory');
+ });
+ vi.mocked(mkdirSync).mockImplementation(() => {});
+
+ makeSureDirExist(dir);
+
+ expect(mkdirSync).toHaveBeenCalledWith('', { recursive: true });
+ });
+ });
+});
diff --git a/apps/desktop/src/main/utils/__tests__/logger.test.ts b/apps/desktop/src/main/utils/__tests__/logger.test.ts
new file mode 100644
index 00000000000..538124d9930
--- /dev/null
+++ b/apps/desktop/src/main/utils/__tests__/logger.test.ts
@@ -0,0 +1,229 @@
+import debug from 'debug';
+import electronLog from 'electron-log';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createLogger } from '../logger';
+
+vi.mock('debug');
+vi.mock('electron-log', () => ({
+ default: {
+ transports: {
+ file: { level: 'info' },
+ console: { level: 'warn' },
+ },
+ error: vi.fn(),
+ info: vi.fn(),
+ verbose: vi.fn(),
+ warn: vi.fn(),
+ },
+}));
+
+describe('logger', () => {
+ const mockDebugLogger = vi.fn();
+
+ beforeEach(() => {
+ vi.mocked(debug).mockReturnValue(mockDebugLogger as any);
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ delete process.env.NODE_ENV;
+ delete process.env.DEBUG_VERBOSE;
+ });
+
+ describe('createLogger', () => {
+ it('should create logger with correct namespace', () => {
+ const namespace = 'test:logger';
+ createLogger(namespace);
+
+ expect(debug).toHaveBeenCalledWith(namespace);
+ });
+
+ it('should return logger object with all methods', () => {
+ const logger = createLogger('test:logger');
+
+ expect(logger).toHaveProperty('debug');
+ expect(logger).toHaveProperty('error');
+ expect(logger).toHaveProperty('info');
+ expect(logger).toHaveProperty('verbose');
+ expect(logger).toHaveProperty('warn');
+ expect(typeof logger.debug).toBe('function');
+ expect(typeof logger.error).toBe('function');
+ expect(typeof logger.info).toBe('function');
+ expect(typeof logger.verbose).toBe('function');
+ expect(typeof logger.warn).toBe('function');
+ });
+ });
+
+ describe('logger.debug', () => {
+ it('should call debug logger with message and args', () => {
+ const logger = createLogger('test:debug');
+ logger.debug('test message', { data: 'value' });
+
+ expect(mockDebugLogger).toHaveBeenCalledWith('test message', { data: 'value' });
+ });
+
+ it('should handle multiple arguments', () => {
+ const logger = createLogger('test:debug');
+ logger.debug('message', 'arg1', 'arg2', 'arg3');
+
+ expect(mockDebugLogger).toHaveBeenCalledWith('message', 'arg1', 'arg2', 'arg3');
+ });
+ });
+
+ describe('logger.error', () => {
+ it('should use electronLog.error in production', () => {
+ process.env.NODE_ENV = 'production';
+ const logger = createLogger('test:error');
+ logger.error('error message', { error: 'details' });
+
+ expect(electronLog.error).toHaveBeenCalledWith('error message', { error: 'details' });
+ expect(mockDebugLogger).not.toHaveBeenCalled();
+ });
+
+ it('should use console.error in development', () => {
+ process.env.NODE_ENV = 'development';
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const logger = createLogger('test:error');
+ logger.error('error message', { error: 'details' });
+
+ expect(consoleErrorSpy).toHaveBeenCalledWith('error message', { error: 'details' });
+ expect(electronLog.error).not.toHaveBeenCalled();
+
+ consoleErrorSpy.mockRestore();
+ });
+
+ it('should default to console.error when NODE_ENV is not set', () => {
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const logger = createLogger('test:error');
+ logger.error('error message');
+
+ expect(consoleErrorSpy).toHaveBeenCalledWith('error message');
+ expect(electronLog.error).not.toHaveBeenCalled();
+
+ consoleErrorSpy.mockRestore();
+ });
+ });
+
+ describe('logger.info', () => {
+ it('should use electronLog.info with namespace in production', () => {
+ process.env.NODE_ENV = 'production';
+ const logger = createLogger('test:info');
+ logger.info('info message', { data: 'value' });
+
+ expect(electronLog.info).toHaveBeenCalledWith('[test:info]', 'info message', {
+ data: 'value',
+ });
+ expect(mockDebugLogger).toHaveBeenCalledWith('INFO: info message', { data: 'value' });
+ });
+
+ it('should use debug logger in development', () => {
+ process.env.NODE_ENV = 'development';
+ const logger = createLogger('test:info');
+ logger.info('info message', { data: 'value' });
+
+ expect(electronLog.info).not.toHaveBeenCalled();
+ expect(mockDebugLogger).toHaveBeenCalledWith('INFO: info message', { data: 'value' });
+ });
+
+ it('should always call debug logger regardless of environment', () => {
+ const logger = createLogger('test:info');
+ logger.info('info message');
+
+ expect(mockDebugLogger).toHaveBeenCalledWith('INFO: info message');
+ });
+ });
+
+ describe('logger.verbose', () => {
+ it('should always call electronLog.verbose', () => {
+ const logger = createLogger('test:verbose');
+ logger.verbose('verbose message', { data: 'value' });
+
+ expect(electronLog.verbose).toHaveBeenCalledWith('verbose message', { data: 'value' });
+ });
+
+ it('should call debug logger when DEBUG_VERBOSE is set', () => {
+ process.env.DEBUG_VERBOSE = 'true';
+ const logger = createLogger('test:verbose');
+ logger.verbose('verbose message', { data: 'value' });
+
+ expect(electronLog.verbose).toHaveBeenCalledWith('verbose message', { data: 'value' });
+ expect(mockDebugLogger).toHaveBeenCalledWith('VERBOSE: verbose message', { data: 'value' });
+ });
+
+ it('should not call debug logger when DEBUG_VERBOSE is not set', () => {
+ const logger = createLogger('test:verbose');
+ logger.verbose('verbose message', { data: 'value' });
+
+ expect(electronLog.verbose).toHaveBeenCalledWith('verbose message', { data: 'value' });
+ expect(mockDebugLogger).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('logger.warn', () => {
+ it('should use electronLog.warn in production', () => {
+ process.env.NODE_ENV = 'production';
+ const logger = createLogger('test:warn');
+ logger.warn('warn message', { warning: 'details' });
+
+ expect(electronLog.warn).toHaveBeenCalledWith('warn message', { warning: 'details' });
+ expect(mockDebugLogger).toHaveBeenCalledWith('WARN: warn message', { warning: 'details' });
+ });
+
+ it('should not use electronLog.warn in development', () => {
+ process.env.NODE_ENV = 'development';
+ const logger = createLogger('test:warn');
+ logger.warn('warn message');
+
+ expect(electronLog.warn).not.toHaveBeenCalled();
+ expect(mockDebugLogger).toHaveBeenCalledWith('WARN: warn message');
+ });
+
+ it('should always call debug logger regardless of environment', () => {
+ const logger = createLogger('test:warn');
+ logger.warn('warn message');
+
+ expect(mockDebugLogger).toHaveBeenCalledWith('WARN: warn message');
+ });
+ });
+
+ describe('logger integration', () => {
+ it('should handle empty messages', () => {
+ const logger = createLogger('test:integration');
+ logger.debug('');
+ logger.info('');
+ logger.warn('');
+
+ expect(mockDebugLogger).toHaveBeenCalledWith('');
+ expect(mockDebugLogger).toHaveBeenCalledWith('INFO: ');
+ expect(mockDebugLogger).toHaveBeenCalledWith('WARN: ');
+ });
+
+ it('should handle no additional arguments', () => {
+ const logger = createLogger('test:integration');
+ logger.debug('message');
+ logger.error('message');
+ logger.info('message');
+ logger.verbose('message');
+ logger.warn('message');
+
+ expect(mockDebugLogger).toHaveBeenCalledWith('message');
+ });
+
+ it('should format messages consistently across different log levels', () => {
+ const logger = createLogger('app:test');
+ const message = 'test message';
+ const args = { key: 'value' };
+
+ logger.debug(message, args);
+ logger.info(message, args);
+ logger.warn(message, args);
+ logger.verbose(message, args);
+
+ expect(mockDebugLogger).toHaveBeenCalledWith(message, args);
+ expect(mockDebugLogger).toHaveBeenCalledWith(`INFO: ${message}`, args);
+ expect(mockDebugLogger).toHaveBeenCalledWith(`WARN: ${message}`, args);
+ expect(electronLog.verbose).toHaveBeenCalledWith(message, args);
+ });
+ });
+});
diff --git a/apps/desktop/src/preload/electronApi.test.ts b/apps/desktop/src/preload/electronApi.test.ts
new file mode 100644
index 00000000000..0f730efe96d
--- /dev/null
+++ b/apps/desktop/src/preload/electronApi.test.ts
@@ -0,0 +1,142 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// Mock electron modules
+const mockElectronAPI = { someAPI: 'mock-electron-api' };
+const mockContextBridgeExposeInMainWorld = vi.fn();
+
+vi.mock('electron', () => ({
+ contextBridge: {
+ exposeInMainWorld: mockContextBridgeExposeInMainWorld,
+ },
+}));
+
+vi.mock('@electron-toolkit/preload', () => ({
+ electronAPI: mockElectronAPI,
+}));
+
+// Mock the invoke and streamer modules
+const mockInvoke = vi.fn();
+const mockOnStreamInvoke = vi.fn();
+
+vi.mock('./invoke', () => ({
+ invoke: mockInvoke,
+}));
+
+vi.mock('./streamer', () => ({
+ onStreamInvoke: mockOnStreamInvoke,
+}));
+
+const { setupElectronApi } = await import('./electronApi');
+
+describe('setupElectronApi', () => {
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ it('should expose electron API to main world', () => {
+ setupElectronApi();
+
+ expect(mockContextBridgeExposeInMainWorld).toHaveBeenCalledWith('electron', mockElectronAPI);
+ });
+
+ it('should expose electronAPI with invoke and onStreamInvoke methods', () => {
+ setupElectronApi();
+
+ expect(mockContextBridgeExposeInMainWorld).toHaveBeenCalledWith('electronAPI', {
+ invoke: mockInvoke,
+ onStreamInvoke: mockOnStreamInvoke,
+ });
+ });
+
+ it('should expose both APIs in correct order', () => {
+ setupElectronApi();
+
+ expect(mockContextBridgeExposeInMainWorld).toHaveBeenCalledTimes(2);
+
+ // First call should be for 'electron'
+ expect(mockContextBridgeExposeInMainWorld.mock.calls[0][0]).toBe('electron');
+ expect(mockContextBridgeExposeInMainWorld.mock.calls[0][1]).toBe(mockElectronAPI);
+
+ // Second call should be for 'electronAPI'
+ expect(mockContextBridgeExposeInMainWorld.mock.calls[1][0]).toBe('electronAPI');
+ expect(mockContextBridgeExposeInMainWorld.mock.calls[1][1]).toEqual({
+ invoke: mockInvoke,
+ onStreamInvoke: mockOnStreamInvoke,
+ });
+ });
+
+ it('should handle errors when exposing electron API fails', () => {
+ const error = new Error('Failed to expose electron API');
+ mockContextBridgeExposeInMainWorld.mockImplementationOnce(() => {
+ throw error;
+ });
+
+ setupElectronApi();
+
+ expect(consoleErrorSpy).toHaveBeenCalledWith(error);
+ // Should still try to expose electronAPI even if first one fails
+ expect(mockContextBridgeExposeInMainWorld).toHaveBeenCalledTimes(2);
+ });
+
+ it('should continue execution if exposing electronAPI fails', () => {
+ mockContextBridgeExposeInMainWorld
+ .mockImplementationOnce(() => {}) // First call succeeds
+ .mockImplementationOnce(() => {
+ throw new Error('Failed to expose electronAPI');
+ }); // Second call fails
+
+ // The second call throws and is not caught, so it will throw
+ // The error handling only wraps the first contextBridge.exposeInMainWorld call
+ expect(() => setupElectronApi()).toThrow('Failed to expose electronAPI');
+
+ expect(mockContextBridgeExposeInMainWorld).toHaveBeenCalledTimes(2);
+ });
+
+ it('should only catch errors for electron API exposure', () => {
+ const error = new Error('Context bridge error');
+ mockContextBridgeExposeInMainWorld.mockImplementationOnce(() => {
+ throw error;
+ });
+
+ setupElectronApi();
+
+ // Error should be logged, not thrown
+ expect(consoleErrorSpy).toHaveBeenCalledWith(error);
+ expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('should expose correct invoke function reference', () => {
+ setupElectronApi();
+
+ const exposedAPI = mockContextBridgeExposeInMainWorld.mock.calls[1][1];
+ expect(exposedAPI.invoke).toBe(mockInvoke);
+ });
+
+ it('should expose correct onStreamInvoke function reference', () => {
+ setupElectronApi();
+
+ const exposedAPI = mockContextBridgeExposeInMainWorld.mock.calls[1][1];
+ expect(exposedAPI.onStreamInvoke).toBe(mockOnStreamInvoke);
+ });
+
+ it('should not modify the original functions', () => {
+ const originalInvoke = mockInvoke;
+ const originalOnStreamInvoke = mockOnStreamInvoke;
+
+ setupElectronApi();
+
+ expect(mockInvoke).toBe(originalInvoke);
+ expect(mockOnStreamInvoke).toBe(originalOnStreamInvoke);
+ });
+
+ it('should be callable multiple times without side effects', () => {
+ setupElectronApi();
+ setupElectronApi();
+
+ // Should be called 4 times total (2 per setup call)
+ expect(mockContextBridgeExposeInMainWorld).toHaveBeenCalledTimes(4);
+ });
+});
diff --git a/apps/desktop/src/preload/invoke.test.ts b/apps/desktop/src/preload/invoke.test.ts
new file mode 100644
index 00000000000..bad7d12f2f4
--- /dev/null
+++ b/apps/desktop/src/preload/invoke.test.ts
@@ -0,0 +1,145 @@
+import { ClientDispatchEventKey } from '@lobechat/electron-client-ipc';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// Mock electron module
+const mockIpcRendererInvoke = vi.fn();
+
+vi.mock('electron', () => ({
+ ipcRenderer: {
+ invoke: mockIpcRendererInvoke,
+ },
+}));
+
+const { invoke } = await import('./invoke');
+
+describe('invoke', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should invoke ipcRenderer with correct event name and no data', async () => {
+ const expectedResult = { success: true };
+ mockIpcRendererInvoke.mockResolvedValue(expectedResult);
+
+ const result = await invoke('getAppVersion' as ClientDispatchEventKey);
+
+ expect(mockIpcRendererInvoke).toHaveBeenCalledWith('getAppVersion');
+ expect(mockIpcRendererInvoke).toHaveBeenCalledTimes(1);
+ expect(result).toEqual(expectedResult);
+ });
+
+ it('should invoke ipcRenderer with event name and single data parameter', async () => {
+ const eventData = { path: '/settings' };
+ const expectedResult = { navigated: true };
+ mockIpcRendererInvoke.mockResolvedValue(expectedResult);
+
+ const result = await invoke('interceptRoute' as ClientDispatchEventKey, eventData);
+
+ expect(mockIpcRendererInvoke).toHaveBeenCalledWith('interceptRoute', eventData);
+ expect(mockIpcRendererInvoke).toHaveBeenCalledTimes(1);
+ expect(result).toEqual(expectedResult);
+ });
+
+ it('should invoke ipcRenderer with event name and multiple data parameters', async () => {
+ const param1 = 'test-param-1';
+ const param2 = { value: 42 };
+ const param3 = [1, 2, 3];
+ const expectedResult = { processed: true };
+ mockIpcRendererInvoke.mockResolvedValue(expectedResult);
+
+ const result = await invoke('someEvent' as ClientDispatchEventKey, param1, param2, param3);
+
+ expect(mockIpcRendererInvoke).toHaveBeenCalledWith('someEvent', param1, param2, param3);
+ expect(mockIpcRendererInvoke).toHaveBeenCalledTimes(1);
+ expect(result).toEqual(expectedResult);
+ });
+
+ it('should handle ipcRenderer invoke rejection', async () => {
+ const error = new Error('IPC communication failed');
+ mockIpcRendererInvoke.mockRejectedValue(error);
+
+ await expect(invoke('getAppVersion' as ClientDispatchEventKey)).rejects.toThrow(
+ 'IPC communication failed',
+ );
+ expect(mockIpcRendererInvoke).toHaveBeenCalledWith('getAppVersion');
+ });
+
+ it('should handle ipcRenderer returning undefined', async () => {
+ mockIpcRendererInvoke.mockResolvedValue(undefined);
+
+ const result = await invoke('someEvent' as ClientDispatchEventKey);
+
+ expect(mockIpcRendererInvoke).toHaveBeenCalledWith('someEvent');
+ expect(result).toBeUndefined();
+ });
+
+ it('should handle ipcRenderer returning null', async () => {
+ mockIpcRendererInvoke.mockResolvedValue(null);
+
+ const result = await invoke('someEvent' as ClientDispatchEventKey);
+
+ expect(mockIpcRendererInvoke).toHaveBeenCalledWith('someEvent');
+ expect(result).toBeNull();
+ });
+
+ it('should preserve complex data structures', async () => {
+ const complexData = {
+ array: [1, 2, 3],
+ nested: {
+ bool: true,
+ null: null,
+ string: 'test',
+ undefined: undefined,
+ },
+ number: 42,
+ };
+ mockIpcRendererInvoke.mockResolvedValue(complexData);
+
+ const result = await invoke('getData' as ClientDispatchEventKey);
+
+ expect(result).toEqual(complexData);
+ });
+
+ it('should maintain type safety with generic return type', async () => {
+ interface TestResponse {
+ message: string;
+ status: number;
+ }
+
+ const expectedResponse: TestResponse = { message: 'success', status: 200 };
+ mockIpcRendererInvoke.mockResolvedValue(expectedResponse);
+
+ const result = await invoke('testEvent' as ClientDispatchEventKey);
+
+ expect(result).toEqual(expectedResponse);
+ expect(typeof result.message).toBe('string');
+ expect(typeof result.status).toBe('number');
+ });
+
+ it('should handle concurrent invocations correctly', async () => {
+ mockIpcRendererInvoke
+ .mockResolvedValueOnce({ id: 1 })
+ .mockResolvedValueOnce({ id: 2 })
+ .mockResolvedValueOnce({ id: 3 });
+
+ const [result1, result2, result3] = await Promise.all([
+ invoke('event1' as ClientDispatchEventKey),
+ invoke('event2' as ClientDispatchEventKey),
+ invoke('event3' as ClientDispatchEventKey),
+ ]);
+
+ expect(result1).toEqual({ id: 1 });
+ expect(result2).toEqual({ id: 2 });
+ expect(result3).toEqual({ id: 3 });
+ expect(mockIpcRendererInvoke).toHaveBeenCalledTimes(3);
+ });
+
+ it('should handle empty string as data parameter', async () => {
+ mockIpcRendererInvoke.mockResolvedValue({ received: '' });
+
+ const result = await invoke('sendData' as ClientDispatchEventKey, '');
+
+ expect(mockIpcRendererInvoke).toHaveBeenCalledWith('sendData', '');
+ expect(result).toEqual({ received: '' });
+ });
+});
diff --git a/apps/desktop/src/preload/routeInterceptor.test.ts b/apps/desktop/src/preload/routeInterceptor.test.ts
new file mode 100644
index 00000000000..f6f6529b63a
--- /dev/null
+++ b/apps/desktop/src/preload/routeInterceptor.test.ts
@@ -0,0 +1,374 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { invoke } from './invoke';
+
+// Mock dependencies
+vi.mock('./invoke', () => ({
+ invoke: vi.fn(),
+}));
+
+vi.mock('~common/routes', () => ({
+ findMatchingRoute: vi.fn(),
+}));
+
+const { findMatchingRoute } = await import('~common/routes');
+const { setupRouteInterceptors } = await import('./routeInterceptor');
+
+describe('setupRouteInterceptors', () => {
+ let consoleLogSpy: ReturnType<typeof vi.spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ // Mock console methods
+ consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ // Setup happy-dom window and document
+ vi.stubGlobal('location', {
+ href: 'http://localhost:3000/chat',
+ origin: 'http://localhost:3000',
+ pathname: '/chat',
+ });
+
+ // Clear existing event listeners by resetting document
+ document.body.innerHTML = '';
+ });
+
+ describe('window.open interception', () => {
+ it('should intercept external URL and invoke openExternalLink', () => {
+ setupRouteInterceptors();
+
+ const externalUrl = 'https://google.com';
+ const result = window.open(externalUrl, '_blank');
+
+ expect(invoke).toHaveBeenCalledWith('openExternalLink', externalUrl);
+ expect(result).toBeNull();
+ });
+
+ it('should intercept URL object for external link', () => {
+ setupRouteInterceptors();
+
+ const externalUrl = new URL('https://github.com');
+ const result = window.open(externalUrl, '_blank');
+
+ expect(invoke).toHaveBeenCalledWith('openExternalLink', 'https://github.com/');
+ expect(result).toBeNull();
+ });
+
+ it('should allow internal link to proceed with original window.open', () => {
+ setupRouteInterceptors();
+
+ const originalWindowOpen = window.open;
+ const internalUrl = 'http://localhost:3000/settings';
+
+ // We can't fully test the original behavior in happy-dom, but we can verify invoke is not called
+ window.open(internalUrl);
+
+ expect(invoke).not.toHaveBeenCalledWith('openExternalLink', expect.anything());
+ });
+
+ it('should handle relative URL that resolves as internal link', () => {
+ setupRouteInterceptors();
+
+ // In happy-dom, 'invalid-url' is resolved relative to window.location.href
+ // So it becomes 'http://localhost:3000/invalid-url' which is internal
+ const relativeUrl = 'invalid-url';
+ window.open(relativeUrl);
+
+ // Since it's internal, it won't call invoke for external link
+ expect(invoke).not.toHaveBeenCalledWith('openExternalLink', expect.anything());
+ });
+ });
+
+ describe('link click interception', () => {
+ it('should intercept external link clicks', async () => {
+ setupRouteInterceptors();
+
+ const link = document.createElement('a');
+ link.href = 'https://example.com';
+ document.body.append(link);
+
+ const clickEvent = new MouseEvent('click', { bubbles: true, cancelable: true });
+ const preventDefaultSpy = vi.spyOn(clickEvent, 'preventDefault');
+ const stopPropagationSpy = vi.spyOn(clickEvent, 'stopPropagation');
+
+ link.dispatchEvent(clickEvent);
+
+ // Wait for async handling
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(invoke).toHaveBeenCalledWith('openExternalLink', 'https://example.com/');
+ expect(preventDefaultSpy).toHaveBeenCalled();
+ expect(stopPropagationSpy).toHaveBeenCalled();
+ });
+
+ it('should intercept internal link matching route pattern', async () => {
+ setupRouteInterceptors();
+
+ const matchedRoute = { pathPrefix: '/desktop/devtools', targetWindow: 'devtools' };
+ vi.mocked(findMatchingRoute).mockReturnValue(matchedRoute);
+
+ const link = document.createElement('a');
+ link.href = 'http://localhost:3000/desktop/devtools';
+ document.body.append(link);
+
+ const clickEvent = new MouseEvent('click', { bubbles: true, cancelable: true });
+ const preventDefaultSpy = vi.spyOn(clickEvent, 'preventDefault');
+
+ link.dispatchEvent(clickEvent);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(findMatchingRoute).toHaveBeenCalledWith('/desktop/devtools');
+ expect(invoke).toHaveBeenCalledWith('interceptRoute', {
+ path: '/desktop/devtools',
+ source: 'link-click',
+ url: 'http://localhost:3000/desktop/devtools',
+ });
+ expect(preventDefaultSpy).toHaveBeenCalled();
+ });
+
+ it('should not intercept if already on target page', async () => {
+ setupRouteInterceptors();
+
+ // Set current location to be in the target page
+ vi.stubGlobal('location', {
+ href: 'http://localhost:3000/desktop/devtools/console',
+ origin: 'http://localhost:3000',
+ pathname: '/desktop/devtools/console',
+ });
+
+ const matchedRoute = { pathPrefix: '/desktop/devtools', targetWindow: 'devtools' };
+ vi.mocked(findMatchingRoute).mockReturnValue(matchedRoute);
+
+ const link = document.createElement('a');
+ link.href = 'http://localhost:3000/desktop/devtools/network';
+ document.body.append(link);
+
+ const clickEvent = new MouseEvent('click', { bubbles: true, cancelable: true });
+ const preventDefaultSpy = vi.spyOn(clickEvent, 'preventDefault');
+
+ link.dispatchEvent(clickEvent);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(preventDefaultSpy).not.toHaveBeenCalled();
+ expect(invoke).not.toHaveBeenCalledWith('interceptRoute', expect.anything());
+ });
+
+ it('should handle non-HTTP link protocols as external links', async () => {
+ setupRouteInterceptors();
+
+ const link = document.createElement('a');
+ link.href = 'mailto:[email protected]';
+ document.body.append(link);
+
+ const clickEvent = new MouseEvent('click', { bubbles: true, cancelable: true });
+ const preventDefaultSpy = vi.spyOn(clickEvent, 'preventDefault');
+
+ link.dispatchEvent(clickEvent);
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ // mailto: links are treated as external links by the URL constructor
+ expect(invoke).toHaveBeenCalledWith('openExternalLink', 'mailto:[email protected]');
+ expect(preventDefaultSpy).toHaveBeenCalled();
+ });
+ });
+
+ describe('history.pushState interception', () => {
+ it('should intercept pushState for matched routes', () => {
+ setupRouteInterceptors();
+
+ const matchedRoute = { pathPrefix: '/desktop/devtools', targetWindow: 'devtools' };
+ vi.mocked(findMatchingRoute).mockReturnValue(matchedRoute);
+
+ const originalLength = history.length;
+ history.pushState({}, '', '/desktop/devtools');
+
+ expect(findMatchingRoute).toHaveBeenCalledWith('/desktop/devtools');
+ expect(invoke).toHaveBeenCalledWith('interceptRoute', {
+ path: '/desktop/devtools',
+ source: 'push-state',
+ url: 'http://localhost:3000/desktop/devtools',
+ });
+ // Ensure navigation was prevented
+ expect(history.length).toBe(originalLength);
+ });
+
+ it('should not intercept if already on target page', () => {
+ setupRouteInterceptors();
+
+ vi.stubGlobal('location', {
+ href: 'http://localhost:3000/desktop/devtools/console',
+ origin: 'http://localhost:3000',
+ pathname: '/desktop/devtools/console',
+ });
+
+ const matchedRoute = { pathPrefix: '/desktop/devtools', targetWindow: 'devtools' };
+ vi.mocked(findMatchingRoute).mockReturnValue(matchedRoute);
+
+ history.pushState({}, '', '/desktop/devtools/network');
+
+ expect(consoleLogSpy).toHaveBeenCalledWith(
+ expect.stringContaining('Skip pushState interception'),
+ );
+ });
+
+ it('should allow pushState for non-matched routes', () => {
+ setupRouteInterceptors();
+
+ vi.mocked(findMatchingRoute).mockReturnValue(undefined);
+
+ history.pushState({}, '', '/chat/new');
+
+ expect(invoke).not.toHaveBeenCalledWith('interceptRoute', expect.anything());
+ });
+
+ it('should handle pushState errors gracefully', () => {
+ setupRouteInterceptors();
+
+ vi.mocked(findMatchingRoute).mockImplementation(() => {
+ throw new Error('Route matching error');
+ });
+
+ history.pushState({}, '', '/some/path');
+
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
+ expect.stringContaining('pushState interception error'),
+ expect.any(Error),
+ );
+ });
+ });
+
+ describe('history.replaceState interception', () => {
+ it('should intercept replaceState for matched routes', () => {
+ setupRouteInterceptors();
+
+ const matchedRoute = { pathPrefix: '/desktop/devtools', targetWindow: 'devtools' };
+ vi.mocked(findMatchingRoute).mockReturnValue(matchedRoute);
+
+ history.replaceState({}, '', '/desktop/devtools');
+
+ expect(findMatchingRoute).toHaveBeenCalledWith('/desktop/devtools');
+ expect(invoke).toHaveBeenCalledWith('interceptRoute', {
+ path: '/desktop/devtools',
+ source: 'replace-state',
+ url: 'http://localhost:3000/desktop/devtools',
+ });
+ });
+
+ it('should not intercept if already on target page', () => {
+ setupRouteInterceptors();
+
+ vi.stubGlobal('location', {
+ href: 'http://localhost:3000/desktop/devtools/console',
+ origin: 'http://localhost:3000',
+ pathname: '/desktop/devtools/console',
+ });
+
+ const matchedRoute = { pathPrefix: '/desktop/devtools', targetWindow: 'devtools' };
+ vi.mocked(findMatchingRoute).mockReturnValue(matchedRoute);
+
+ history.replaceState({}, '', '/desktop/devtools/network');
+
+ expect(consoleLogSpy).toHaveBeenCalledWith(
+ expect.stringContaining('Skip replaceState interception'),
+ );
+ });
+
+ it('should allow replaceState for non-matched routes', () => {
+ setupRouteInterceptors();
+
+ vi.mocked(findMatchingRoute).mockReturnValue(undefined);
+
+ history.replaceState({}, '', '/chat/session-123');
+
+ expect(invoke).not.toHaveBeenCalledWith('interceptRoute', expect.anything());
+ });
+ });
+
+ describe('error event interception', () => {
+ it('should prevent navigation errors for prevented paths', () => {
+ setupRouteInterceptors();
+
+ // First trigger a route interception to add path to preventedPaths
+ const matchedRoute = { pathPrefix: '/desktop/devtools', targetWindow: 'devtools' };
+ vi.mocked(findMatchingRoute).mockReturnValue(matchedRoute);
+ history.pushState({}, '', '/desktop/devtools');
+
+ // Now trigger an error event with navigation in the message
+ const errorEvent = new ErrorEvent('error', {
+ bubbles: true,
+ cancelable: true,
+ message: 'navigation error occurred',
+ });
+ const preventDefaultSpy = vi.spyOn(errorEvent, 'preventDefault');
+
+ window.dispatchEvent(errorEvent);
+
+ expect(preventDefaultSpy).toHaveBeenCalled();
+ expect(consoleLogSpy).toHaveBeenCalledWith(
+ expect.stringContaining('Captured possible routing error'),
+ );
+ });
+
+ it('should not prevent non-navigation errors', () => {
+ setupRouteInterceptors();
+
+ const errorEvent = new ErrorEvent('error', {
+ bubbles: true,
+ cancelable: true,
+ message: 'some other error',
+ });
+ const preventDefaultSpy = vi.spyOn(errorEvent, 'preventDefault');
+
+ window.dispatchEvent(errorEvent);
+
+ expect(preventDefaultSpy).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('interceptRoute helper', () => {
+ it('should handle successful route interception', async () => {
+ vi.mocked(invoke).mockResolvedValue(undefined);
+
+ setupRouteInterceptors();
+
+ const matchedRoute = { pathPrefix: '/desktop/devtools', targetWindow: 'devtools' };
+ vi.mocked(findMatchingRoute).mockReturnValue(matchedRoute);
+
+ history.pushState({}, '', '/desktop/devtools');
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(invoke).toHaveBeenCalledWith('interceptRoute', {
+ path: '/desktop/devtools',
+ source: 'push-state',
+ url: 'http://localhost:3000/desktop/devtools',
+ });
+ });
+
+ it('should handle route interception errors gracefully', async () => {
+ const error = new Error('IPC communication failed');
+ vi.mocked(invoke).mockRejectedValue(error);
+
+ setupRouteInterceptors();
+
+ const matchedRoute = { pathPrefix: '/desktop/devtools', targetWindow: 'devtools' };
+ vi.mocked(findMatchingRoute).mockReturnValue(matchedRoute);
+
+ history.pushState({}, '', '/desktop/devtools');
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
+ expect.stringContaining('Route interception (push-state) call failed'),
+ error,
+ );
+ });
+ });
+});
diff --git a/apps/desktop/src/preload/streamer.test.ts b/apps/desktop/src/preload/streamer.test.ts
new file mode 100644
index 00000000000..e13f23aa1ee
--- /dev/null
+++ b/apps/desktop/src/preload/streamer.test.ts
@@ -0,0 +1,365 @@
+import type { ProxyTRPCRequestParams } from '@lobechat/electron-client-ipc';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// Mock electron module
+const mockIpcRendererOn = vi.fn();
+const mockIpcRendererOnce = vi.fn();
+const mockIpcRendererSend = vi.fn();
+const mockIpcRendererRemoveAllListeners = vi.fn();
+
+vi.mock('electron', () => ({
+ ipcRenderer: {
+ on: mockIpcRendererOn,
+ once: mockIpcRendererOnce,
+ removeAllListeners: mockIpcRendererRemoveAllListeners,
+ send: mockIpcRendererSend,
+ },
+}));
+
+// Mock uuid
+vi.mock('uuid', () => ({
+ v4: vi.fn(() => 'test-request-id-123'),
+}));
+
+const { onStreamInvoke } = await import('./streamer');
+
+describe('onStreamInvoke', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should set up stream listeners and send start event', () => {
+ const params: ProxyTRPCRequestParams = {
+ input: { query: 'test' },
+ path: 'test.endpoint',
+ type: 'query',
+ };
+
+ const callbacks = {
+ onData: vi.fn(),
+ onEnd: vi.fn(),
+ onError: vi.fn(),
+ onResponse: vi.fn(),
+ };
+
+ onStreamInvoke(params, callbacks);
+
+ // Verify listeners are registered
+ expect(mockIpcRendererOn).toHaveBeenCalledWith(
+ 'stream:data:test-request-id-123',
+ expect.any(Function),
+ );
+ expect(mockIpcRendererOnce).toHaveBeenCalledWith(
+ 'stream:end:test-request-id-123',
+ expect.any(Function),
+ );
+ expect(mockIpcRendererOnce).toHaveBeenCalledWith(
+ 'stream:error:test-request-id-123',
+ expect.any(Function),
+ );
+ expect(mockIpcRendererOnce).toHaveBeenCalledWith(
+ 'stream:response:test-request-id-123',
+ expect.any(Function),
+ );
+
+ // Verify start event is sent
+ expect(mockIpcRendererSend).toHaveBeenCalledWith('stream:start', {
+ ...params,
+ requestId: 'test-request-id-123',
+ });
+ });
+
+ it('should invoke onData callback when data is received', () => {
+ const callbacks = {
+ onData: vi.fn(),
+ onEnd: vi.fn(),
+ onError: vi.fn(),
+ onResponse: vi.fn(),
+ };
+
+ const params: ProxyTRPCRequestParams = {
+ input: {},
+ path: 'test',
+ type: 'query',
+ };
+
+ onStreamInvoke(params, callbacks);
+
+ // Get the data listener callback
+ const dataListener = mockIpcRendererOn.mock.calls.find((call) =>
+ call[0].includes('stream:data'),
+ )?.[1];
+
+ // Simulate data event
+ const testData = Buffer.from('test data');
+ dataListener?.(null, testData);
+
+ expect(callbacks.onData).toHaveBeenCalledWith(new Uint8Array(testData));
+ });
+
+ it('should invoke onResponse callback when response is received', () => {
+ const callbacks = {
+ onData: vi.fn(),
+ onEnd: vi.fn(),
+ onError: vi.fn(),
+ onResponse: vi.fn(),
+ };
+
+ const params: ProxyTRPCRequestParams = {
+ input: {},
+ path: 'test',
+ type: 'query',
+ };
+
+ onStreamInvoke(params, callbacks);
+
+ // Get the response listener callback
+ const responseListener = mockIpcRendererOnce.mock.calls.find((call) =>
+ call[0].includes('stream:response'),
+ )?.[1];
+
+ // Simulate response event
+ const testResponse = {
+ headers: { 'content-type': 'application/json' },
+ status: 200,
+ statusText: 'OK',
+ };
+ responseListener?.(null, testResponse);
+
+ expect(callbacks.onResponse).toHaveBeenCalledWith(testResponse);
+ });
+
+ it('should invoke onEnd callback and cleanup when stream ends', () => {
+ const callbacks = {
+ onData: vi.fn(),
+ onEnd: vi.fn(),
+ onError: vi.fn(),
+ onResponse: vi.fn(),
+ };
+
+ const params: ProxyTRPCRequestParams = {
+ input: {},
+ path: 'test',
+ type: 'query',
+ };
+
+ onStreamInvoke(params, callbacks);
+
+ // Get the end listener callback
+ const endListener = mockIpcRendererOnce.mock.calls.find((call) =>
+ call[0].includes('stream:end'),
+ )?.[1];
+
+ // Simulate end event
+ endListener?.(null);
+
+ expect(callbacks.onEnd).toHaveBeenCalled();
+
+ // Verify cleanup
+ expect(mockIpcRendererRemoveAllListeners).toHaveBeenCalledWith(
+ 'stream:data:test-request-id-123',
+ );
+ expect(mockIpcRendererRemoveAllListeners).toHaveBeenCalledWith(
+ 'stream:end:test-request-id-123',
+ );
+ expect(mockIpcRendererRemoveAllListeners).toHaveBeenCalledWith(
+ 'stream:error:test-request-id-123',
+ );
+ expect(mockIpcRendererRemoveAllListeners).toHaveBeenCalledWith(
+ 'stream:response:test-request-id-123',
+ );
+ });
+
+ it('should invoke onError callback and cleanup when error occurs', () => {
+ const callbacks = {
+ onData: vi.fn(),
+ onEnd: vi.fn(),
+ onError: vi.fn(),
+ onResponse: vi.fn(),
+ };
+
+ const params: ProxyTRPCRequestParams = {
+ input: {},
+ path: 'test',
+ type: 'query',
+ };
+
+ onStreamInvoke(params, callbacks);
+
+ // Get the error listener callback
+ const errorListener = mockIpcRendererOnce.mock.calls.find((call) =>
+ call[0].includes('stream:error'),
+ )?.[1];
+
+ // Simulate error event
+ const testError = new Error('Stream processing failed');
+ errorListener?.(null, testError);
+
+ expect(callbacks.onError).toHaveBeenCalledWith(testError);
+
+ // Verify cleanup
+ expect(mockIpcRendererRemoveAllListeners).toHaveBeenCalledWith(
+ 'stream:data:test-request-id-123',
+ );
+ expect(mockIpcRendererRemoveAllListeners).toHaveBeenCalledWith(
+ 'stream:end:test-request-id-123',
+ );
+ expect(mockIpcRendererRemoveAllListeners).toHaveBeenCalledWith(
+ 'stream:error:test-request-id-123',
+ );
+ expect(mockIpcRendererRemoveAllListeners).toHaveBeenCalledWith(
+ 'stream:response:test-request-id-123',
+ );
+ });
+
+ it('should return cleanup function that removes all listeners', () => {
+ const callbacks = {
+ onData: vi.fn(),
+ onEnd: vi.fn(),
+ onError: vi.fn(),
+ onResponse: vi.fn(),
+ };
+
+ const params: ProxyTRPCRequestParams = {
+ input: {},
+ path: 'test',
+ type: 'query',
+ };
+
+ const cleanup = onStreamInvoke(params, callbacks);
+
+ // Call cleanup function
+ cleanup();
+
+ // Verify all listeners are removed
+ expect(mockIpcRendererRemoveAllListeners).toHaveBeenCalledWith(
+ 'stream:data:test-request-id-123',
+ );
+ expect(mockIpcRendererRemoveAllListeners).toHaveBeenCalledWith(
+ 'stream:end:test-request-id-123',
+ );
+ expect(mockIpcRendererRemoveAllListeners).toHaveBeenCalledWith(
+ 'stream:error:test-request-id-123',
+ );
+ expect(mockIpcRendererRemoveAllListeners).toHaveBeenCalledWith(
+ 'stream:response:test-request-id-123',
+ );
+ });
+
+ it('should handle multiple data chunks', () => {
+ const callbacks = {
+ onData: vi.fn(),
+ onEnd: vi.fn(),
+ onError: vi.fn(),
+ onResponse: vi.fn(),
+ };
+
+ const params: ProxyTRPCRequestParams = {
+ input: {},
+ path: 'test',
+ type: 'query',
+ };
+
+ onStreamInvoke(params, callbacks);
+
+ const dataListener = mockIpcRendererOn.mock.calls.find((call) =>
+ call[0].includes('stream:data'),
+ )?.[1];
+
+ // Simulate multiple data chunks
+ const chunk1 = Buffer.from('chunk1');
+ const chunk2 = Buffer.from('chunk2');
+ const chunk3 = Buffer.from('chunk3');
+
+ dataListener?.(null, chunk1);
+ dataListener?.(null, chunk2);
+ dataListener?.(null, chunk3);
+
+ expect(callbacks.onData).toHaveBeenCalledTimes(3);
+ expect(callbacks.onData).toHaveBeenNthCalledWith(1, new Uint8Array(chunk1));
+ expect(callbacks.onData).toHaveBeenNthCalledWith(2, new Uint8Array(chunk2));
+ expect(callbacks.onData).toHaveBeenNthCalledWith(3, new Uint8Array(chunk3));
+ });
+
+ it('should handle complex request parameters', () => {
+ const callbacks = {
+ onData: vi.fn(),
+ onEnd: vi.fn(),
+ onError: vi.fn(),
+ onResponse: vi.fn(),
+ };
+
+ const params: ProxyTRPCRequestParams = {
+ input: {
+ filters: { active: true },
+ query: 'complex query',
+ sort: { field: 'date', order: 'desc' },
+ },
+ path: 'complex.nested.endpoint',
+ type: 'mutation',
+ };
+
+ onStreamInvoke(params, callbacks);
+
+ expect(mockIpcRendererSend).toHaveBeenCalledWith('stream:start', {
+ ...params,
+ requestId: 'test-request-id-123',
+ });
+ });
+
+ it('should not invoke callbacks after cleanup', () => {
+ const callbacks = {
+ onData: vi.fn(),
+ onEnd: vi.fn(),
+ onError: vi.fn(),
+ onResponse: vi.fn(),
+ };
+
+ const params: ProxyTRPCRequestParams = {
+ input: {},
+ path: 'test',
+ type: 'query',
+ };
+
+ const cleanup = onStreamInvoke(params, callbacks);
+
+ // Cleanup immediately
+ cleanup();
+
+ // Try to trigger callbacks after cleanup (this simulates late events)
+ const dataListener = mockIpcRendererOn.mock.calls.find((call) =>
+ call[0].includes('stream:data'),
+ )?.[1];
+
+ // Since listeners are removed, this shouldn't do anything
+ // The actual behavior depends on electron's implementation
+ // But we can verify cleanup was called
+ expect(mockIpcRendererRemoveAllListeners).toHaveBeenCalledTimes(4);
+ });
+
+ it('should handle empty buffer data', () => {
+ const callbacks = {
+ onData: vi.fn(),
+ onEnd: vi.fn(),
+ onError: vi.fn(),
+ onResponse: vi.fn(),
+ };
+
+ const params: ProxyTRPCRequestParams = {
+ input: {},
+ path: 'test',
+ type: 'query',
+ };
+
+ onStreamInvoke(params, callbacks);
+
+ const dataListener = mockIpcRendererOn.mock.calls.find((call) =>
+ call[0].includes('stream:data'),
+ )?.[1];
+
+ const emptyBuffer = Buffer.from('');
+ dataListener?.(null, emptyBuffer);
+
+ expect(callbacks.onData).toHaveBeenCalledWith(new Uint8Array(emptyBuffer));
+ });
+});
diff --git a/apps/desktop/vitest.config.mts b/apps/desktop/vitest.config.mts
index 7bbb72b6d64..0f547686dec 100644
--- a/apps/desktop/vitest.config.mts
+++ b/apps/desktop/vitest.config.mts
@@ -5,6 +5,7 @@ export default defineConfig({
test: {
alias: {
'@': resolve(__dirname, './src/main'),
+ '~common': resolve(__dirname, './src/common'),
},
coverage: {
all: false,