🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✅ test(desktop): add unit tests for Core Infrastructure module (#10533)
Arvin Xufa492b48fa09
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/I18nManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/I18nManager.test.tsnew file mode 100644index 00000000000..a46c5650862--- /dev/null+++ b/apps/desktop/src/main/core/infrastructure/__tests__/I18nManager.test.ts@@ -0,0 +1,353 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { App as AppCore } from '../../App';+import { I18nManager } from '../I18nManager';++// Use vi.hoisted to define mocks before hoisting+const { mockApp, mockI18nextInstance, mockLoadResources, mockCreateInstance } = vi.hoisted(() => {+ const mockI18nextInstance = {+ addResourceBundle: vi.fn(),+ changeLanguage: vi.fn().mockResolvedValue(undefined),+ init: vi.fn().mockResolvedValue(undefined),+ language: 'en-US',+ on: vi.fn(),+ t: vi.fn().mockImplementation((key: string) => key),+ };++ const mockCreateInstance = vi.fn().mockReturnValue(mockI18nextInstance);++ return {+ mockApp: {+ getLocale: vi.fn().mockReturnValue('en-US'),+ },+ mockCreateInstance,+ mockI18nextInstance,+ mockLoadResources: vi.fn().mockResolvedValue({ key: 'value' }),+ };+});++// Mock electron app+vi.mock('electron', () => ({+ app: mockApp,+}));++// Mock i18next+vi.mock('i18next', () => ({+ default: {+ createInstance: mockCreateInstance,+ },+}));++// Mock logger+vi.mock('@/utils/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ }),+}));++// Mock loadResources+vi.mock('@/locales/resources', () => ({+ loadResources: mockLoadResources,+}));++describe('I18nManager', () => {+ let manager: I18nManager;+ let mockAppCore: AppCore;+ let mockStoreManagerGet: ReturnType<typeof vi.fn>;+ let mockRefreshMenus: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ vi.clearAllMocks();++ // Reset i18next mock state+ mockI18nextInstance.language = 'en-US';+ mockI18nextInstance.t.mockImplementation((key: string) => key);+ mockI18nextInstance.init.mockResolvedValue(undefined);+ mockI18nextInstance.changeLanguage.mockResolvedValue(undefined);++ // Reset loadResources mock+ mockLoadResources.mockResolvedValue({ key: 'value' });++ // Reset electron app mock+ mockApp.getLocale.mockReturnValue('en-US');++ // Create mock App core+ mockStoreManagerGet = vi.fn().mockReturnValue('auto');+ mockRefreshMenus = vi.fn();++ mockAppCore = {+ menuManager: {+ refreshMenus: mockRefreshMenus,+ },+ storeManager: {+ get: mockStoreManagerGet,+ },+ } as unknown as AppCore;++ manager = new I18nManager(mockAppCore);+ });++ describe('constructor', () => {+ it('should create i18next instance', () => {+ expect(mockCreateInstance).toHaveBeenCalled();+ });+ });++ describe('init', () => {+ it('should initialize i18next with default settings', async () => {+ await manager.init();++ expect(mockI18nextInstance.init).toHaveBeenCalledWith({+ defaultNS: 'menu',+ fallbackLng: 'en-US',+ initAsync: true,+ interpolation: {+ escapeValue: false,+ },+ lng: 'en-US',+ ns: ['menu', 'dialog', 'common'],+ partialBundledLanguages: true,+ });+ });++ it('should use provided language parameter', async () => {+ await manager.init('zh-CN');++ expect(mockI18nextInstance.init).toHaveBeenCalledWith(+ expect.objectContaining({+ lng: 'zh-CN',+ }),+ );+ });++ it('should use stored locale when not auto', async () => {+ mockStoreManagerGet.mockReturnValue('ja-JP');++ await manager.init();++ expect(mockI18nextInstance.init).toHaveBeenCalledWith(+ expect.objectContaining({+ lng: 'ja-JP',+ }),+ );+ });++ it('should use system locale when stored locale is auto', async () => {+ mockStoreManagerGet.mockReturnValue('auto');+ mockApp.getLocale.mockReturnValue('fr-FR');++ await manager.init();++ expect(mockI18nextInstance.init).toHaveBeenCalledWith(+ expect.objectContaining({+ lng: 'fr-FR',+ }),+ );+ });++ it('should skip initialization if already initialized', async () => {+ await manager.init();+ vi.clearAllMocks();++ await manager.init();++ expect(mockI18nextInstance.init).not.toHaveBeenCalled();+ });++ it('should load locale resources after init', async () => {+ await manager.init();++ // Should load menu, dialog, common namespaces+ expect(mockLoadResources).toHaveBeenCalledWith('en-US', 'menu');+ expect(mockLoadResources).toHaveBeenCalledWith('en-US', 'dialog');+ expect(mockLoadResources).toHaveBeenCalledWith('en-US', 'common');+ });++ it('should refresh main UI after init', async () => {+ await manager.init();++ expect(mockRefreshMenus).toHaveBeenCalled();+ });++ it('should register languageChanged listener', async () => {+ await manager.init();++ expect(mockI18nextInstance.on).toHaveBeenCalledWith('languageChanged', expect.any(Function));+ });+ });++ describe('t', () => {+ beforeEach(async () => {+ await manager.init();+ });++ it('should call i18next t function', () => {+ mockI18nextInstance.t.mockReturnValue('translated');++ const result = manager.t('test.key');++ expect(mockI18nextInstance.t).toHaveBeenCalledWith('test.key', undefined);+ expect(result).toBe('translated');+ });++ it('should pass options to i18next', () => {+ mockI18nextInstance.t.mockReturnValue('translated with options');++ const result = manager.t('test.key', { count: 5 });++ expect(mockI18nextInstance.t).toHaveBeenCalledWith('test.key', { count: 5 });+ expect(result).toBe('translated with options');+ });++ it('should warn when translation key is not found', () => {+ // When translation is not found, i18next returns the key itself+ mockI18nextInstance.t.mockImplementation((key: string) => key);++ manager.t('missing.key');++ // The warn should be logged (we can't verify the log content with our mock setup)+ expect(mockI18nextInstance.t).toHaveBeenCalledWith('missing.key', undefined);+ });+ });++ describe('createNamespacedT', () => {+ beforeEach(async () => {+ await manager.init();+ });++ it('should return a function that adds namespace to options', () => {+ mockI18nextInstance.t.mockReturnValue('namespaced translation');++ const menuT = manager.createNamespacedT('menu');+ const result = menuT('test.key');++ expect(mockI18nextInstance.t).toHaveBeenCalledWith('test.key', { ns: 'menu' });+ expect(result).toBe('namespaced translation');+ });++ it('should merge provided options with namespace', () => {+ mockI18nextInstance.t.mockReturnValue('merged translation');++ const menuT = manager.createNamespacedT('dialog');+ const result = menuT('test.key', { count: 3 });++ expect(mockI18nextInstance.t).toHaveBeenCalledWith('test.key', { count: 3, ns: 'dialog' });+ expect(result).toBe('merged translation');+ });+ });++ describe('ns', () => {+ beforeEach(async () => {+ await manager.init();+ });++ it('should be an alias for createNamespacedT', () => {+ mockI18nextInstance.t.mockReturnValue('ns translation');++ const dialogT = manager.ns('dialog');+ const result = dialogT('test.key');++ expect(mockI18nextInstance.t).toHaveBeenCalledWith('test.key', { ns: 'dialog' });+ expect(result).toBe('ns translation');+ });+ });++ describe('getCurrentLanguage', () => {+ beforeEach(async () => {+ await manager.init();+ });++ it('should return current i18next language', () => {+ mockI18nextInstance.language = 'de-DE';++ expect(manager.getCurrentLanguage()).toBe('de-DE');+ });+ });++ describe('changeLanguage', () => {+ beforeEach(async () => {+ await manager.init();+ });++ it('should call i18next changeLanguage', async () => {+ await manager.changeLanguage('zh-CN');++ expect(mockI18nextInstance.changeLanguage).toHaveBeenCalledWith('zh-CN');+ });++ it('should initialize if not already initialized', async () => {+ // Create a new manager that is not initialized+ const uninitializedManager = new I18nManager(mockAppCore);++ await uninitializedManager.changeLanguage('zh-CN');++ expect(mockI18nextInstance.init).toHaveBeenCalled();+ expect(mockI18nextInstance.changeLanguage).toHaveBeenCalledWith('zh-CN');+ });+ });++ describe('handleLanguageChanged', () => {+ beforeEach(async () => {+ await manager.init();+ });++ it('should load locale and refresh UI on language change', async () => {+ // Get the languageChanged handler+ const languageChangedHandler = mockI18nextInstance.on.mock.calls.find(+ (call) => call[0] === 'languageChanged',+ )?.[1];++ expect(languageChangedHandler).toBeDefined();++ // Clear mocks to check only the handler's behavior+ mockLoadResources.mockClear();+ mockRefreshMenus.mockClear();++ // Trigger language change+ await languageChangedHandler('ja-JP');++ // Should load resources for new language+ expect(mockLoadResources).toHaveBeenCalledWith('ja-JP', 'menu');+ expect(mockLoadResources).toHaveBeenCalledWith('ja-JP', 'dialog');+ expect(mockLoadResources).toHaveBeenCalledWith('ja-JP', 'common');++ // Should refresh menus+ expect(mockRefreshMenus).toHaveBeenCalled();+ });+ });++ describe('loadNamespace', () => {+ beforeEach(async () => {+ await manager.init();+ vi.clearAllMocks();+ });++ it('should load resources and add to i18next', async () => {+ mockLoadResources.mockResolvedValue({ hello: 'world' });++ // Access private method+ const result = await manager['loadNamespace']('en-US', 'menu');++ expect(mockLoadResources).toHaveBeenCalledWith('en-US', 'menu');+ expect(mockI18nextInstance.addResourceBundle).toHaveBeenCalledWith(+ 'en-US',+ 'menu',+ { hello: 'world' },+ true,+ true,+ );+ expect(result).toBe(true);+ });++ it('should return false on error', async () => {+ mockLoadResources.mockRejectedValue(new Error('Load failed'));++ const result = await manager['loadNamespace']('en-US', 'menu');++ expect(result).toBe(false);+ });+ });+});diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/IoCContainer.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/IoCContainer.test.tsnew file mode 100644index 00000000000..9cbf1296808--- /dev/null+++ b/apps/desktop/src/main/core/infrastructure/__tests__/IoCContainer.test.ts@@ -0,0 +1,156 @@+import { beforeEach, describe, expect, it } from 'vitest';++import { IoCContainer } from '../IoCContainer';++describe('IoCContainer', () => {+ // Sample class targets for testing WeakMap storage+ class TestController {}+ class AnotherController {}++ beforeEach(() => {+ // Reset static WeakMaps by creating new instances+ // WeakMaps can't be cleared, but we can verify they work correctly+ // For each test, use fresh class instances+ });++ describe('controllers WeakMap', () => {+ it('should store controller metadata', () => {+ const metadata = [{ methodName: 'handleMessage', mode: 'client' as const, name: 'message' }];++ IoCContainer.controllers.set(TestController, metadata);++ expect(IoCContainer.controllers.get(TestController)).toEqual(metadata);+ });++ it('should allow multiple controllers', () => {+ const metadata1 = [{ methodName: 'method1', mode: 'client' as const, name: 'action1' }];+ const metadata2 = [{ methodName: 'method2', mode: 'server' as const, name: 'action2' }];++ IoCContainer.controllers.set(TestController, metadata1);+ IoCContainer.controllers.set(AnotherController, metadata2);++ expect(IoCContainer.controllers.get(TestController)).toEqual(metadata1);+ expect(IoCContainer.controllers.get(AnotherController)).toEqual(metadata2);+ });++ it('should allow overwriting controller metadata', () => {+ const oldMetadata = [{ methodName: 'oldMethod', mode: 'client' as const, name: 'old' }];+ const newMetadata = [{ methodName: 'newMethod', mode: 'server' as const, name: 'new' }];++ IoCContainer.controllers.set(TestController, oldMetadata);+ IoCContainer.controllers.set(TestController, newMetadata);++ expect(IoCContainer.controllers.get(TestController)).toEqual(newMetadata);+ });++ it('should support multiple methods per controller', () => {+ const metadata = [+ { methodName: 'method1', mode: 'client' as const, name: 'action1' },+ { methodName: 'method2', mode: 'server' as const, name: 'action2' },+ { methodName: 'method3', mode: 'client' as const, name: 'action3' },+ ];++ IoCContainer.controllers.set(TestController, metadata);++ const stored = IoCContainer.controllers.get(TestController);+ expect(stored).toHaveLength(3);+ expect(stored?.[0].mode).toBe('client');+ expect(stored?.[1].mode).toBe('server');+ });+ });++ describe('shortcuts WeakMap', () => {+ it('should store shortcut metadata', () => {+ const metadata = [{ methodName: 'toggleDarkMode', name: 'CmdOrCtrl+Shift+D' }];++ IoCContainer.shortcuts.set(TestController, metadata);++ expect(IoCContainer.shortcuts.get(TestController)).toEqual(metadata);+ });++ it('should allow multiple shortcuts per class', () => {+ const metadata = [+ { methodName: 'toggleDarkMode', name: 'CmdOrCtrl+Shift+D' },+ { methodName: 'openSettings', name: 'CmdOrCtrl+,' },+ { methodName: 'newChat', name: 'CmdOrCtrl+N' },+ ];++ IoCContainer.shortcuts.set(TestController, metadata);++ const stored = IoCContainer.shortcuts.get(TestController);+ expect(stored).toHaveLength(3);+ });++ it('should return undefined for unregistered class', () => {+ class UnregisteredClass {}++ expect(IoCContainer.shortcuts.get(UnregisteredClass)).toBeUndefined();+ });+ });++ describe('protocolHandlers WeakMap', () => {+ it('should store protocol handler metadata', () => {+ const metadata = [{ action: 'install', methodName: 'handleInstall', urlType: 'plugin' }];++ IoCContainer.protocolHandlers.set(TestController, metadata);++ expect(IoCContainer.protocolHandlers.get(TestController)).toEqual(metadata);+ });++ it('should support multiple protocol handlers', () => {+ const metadata = [+ { action: 'install', methodName: 'handleInstall', urlType: 'plugin' },+ { action: 'uninstall', methodName: 'handleUninstall', urlType: 'plugin' },+ { action: 'open', methodName: 'handleOpen', urlType: 'chat' },+ ];++ IoCContainer.protocolHandlers.set(TestController, metadata);++ const stored = IoCContainer.protocolHandlers.get(TestController);+ expect(stored).toHaveLength(3);+ expect(stored?.map((h) => h.urlType)).toContain('plugin');+ expect(stored?.map((h) => h.urlType)).toContain('chat');+ });++ it('should allow different classes to have different handlers', () => {+ const metadata1 = [{ action: 'install', methodName: 'handleInstall', urlType: 'plugin' }];+ const metadata2 = [{ action: 'open', methodName: 'handleOpen', urlType: 'chat' }];++ IoCContainer.protocolHandlers.set(TestController, metadata1);+ IoCContainer.protocolHandlers.set(AnotherController, metadata2);++ expect(IoCContainer.protocolHandlers.get(TestController)?.[0].urlType).toBe('plugin');+ expect(IoCContainer.protocolHandlers.get(AnotherController)?.[0].urlType).toBe('chat');+ });+ });++ describe('init', () => {+ it('should be callable without error', () => {+ const container = new IoCContainer();++ expect(() => container.init()).not.toThrow();+ });++ it('should return undefined', () => {+ const container = new IoCContainer();++ const result = container.init();++ expect(result).toBeUndefined();+ });+ });++ describe('static properties', () => {+ it('should have controllers as a WeakMap', () => {+ expect(IoCContainer.controllers).toBeInstanceOf(WeakMap);+ });++ it('should have shortcuts as a WeakMap', () => {+ expect(IoCContainer.shortcuts).toBeInstanceOf(WeakMap);+ });++ it('should have protocolHandlers as a WeakMap', () => {+ expect(IoCContainer.protocolHandlers).toBeInstanceOf(WeakMap);+ });+ });+});diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/ProtocolManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/ProtocolManager.test.tsnew file mode 100644index 00000000000..fbdf41ed71d--- /dev/null+++ b/apps/desktop/src/main/core/infrastructure/__tests__/ProtocolManager.test.ts@@ -0,0 +1,348 @@+import { app } from 'electron';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { getProtocolScheme, parseProtocolUrl } from '@/utils/protocol';++import type { App as AppCore } from '../../App';+import { ProtocolManager } from '../ProtocolManager';++// Use vi.hoisted to define mocks before hoisting+const { mockApp, mockGetProtocolScheme, mockParseProtocolUrl } = vi.hoisted(() => ({+ mockApp: {+ getPath: vi.fn().mockReturnValue('/mock/exe/path'),+ isDefaultProtocolClient: vi.fn().mockReturnValue(true),+ isReady: vi.fn().mockReturnValue(true),+ name: 'LobeHub',+ on: vi.fn(),+ setAsDefaultProtocolClient: vi.fn().mockReturnValue(true),+ },+ mockGetProtocolScheme: vi.fn().mockReturnValue('lobehub'),+ mockParseProtocolUrl: vi.fn(),+}));++// Mock electron app+vi.mock('electron', () => ({+ app: mockApp,+}));++// Mock logger+vi.mock('@/utils/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ }),+}));++// Mock protocol utils+vi.mock('@/utils/protocol', () => ({+ getProtocolScheme: mockGetProtocolScheme,+ parseProtocolUrl: mockParseProtocolUrl,+}));++// Mock isDev+vi.mock('@/const/env', () => ({+ isDev: false,+}));++describe('ProtocolManager', () => {+ let manager: ProtocolManager;+ let mockAppCore: AppCore;+ let mockShowMainWindow: ReturnType<typeof vi.fn>;+ let mockHandleProtocolRequest: ReturnType<typeof vi.fn>;++ // Store event handlers+ let openUrlHandler: ((event: any, url: string) => void) | undefined;+ let secondInstanceHandler: ((event: any, commandLine: string[]) => void) | undefined;++ beforeEach(() => {+ vi.clearAllMocks();++ // Reset electron app mock+ mockApp.isDefaultProtocolClient.mockReturnValue(true);+ mockApp.setAsDefaultProtocolClient.mockReturnValue(true);+ mockApp.isReady.mockReturnValue(true);++ // Capture event handlers+ openUrlHandler = undefined;+ secondInstanceHandler = undefined;+ mockApp.on.mockImplementation((event: string, handler: any) => {+ if (event === 'open-url') {+ openUrlHandler = handler;+ } else if (event === 'second-instance') {+ secondInstanceHandler = handler;+ }+ return mockApp;+ });++ // Reset protocol utils mock+ mockGetProtocolScheme.mockReturnValue('lobehub');+ mockParseProtocolUrl.mockReturnValue({+ action: 'install',+ params: { url: 'https://example.com' },+ urlType: 'plugin',+ });++ // Create mock App core+ mockShowMainWindow = vi.fn();+ mockHandleProtocolRequest = vi.fn().mockResolvedValue(true);++ mockAppCore = {+ browserManager: {+ showMainWindow: mockShowMainWindow,+ },+ handleProtocolRequest: mockHandleProtocolRequest,+ } as unknown as AppCore;++ manager = new ProtocolManager(mockAppCore);+ });++ describe('constructor', () => {+ it('should initialize with protocol scheme from getProtocolScheme', () => {+ expect(getProtocolScheme).toHaveBeenCalled();+ expect(manager.getScheme()).toBe('lobehub');+ });+ });++ describe('initialize', () => {+ it('should register protocol handlers', () => {+ manager.initialize();++ expect(app.setAsDefaultProtocolClient).toHaveBeenCalledWith('lobehub');+ });++ it('should set up event listeners', () => {+ manager.initialize();++ expect(app.on).toHaveBeenCalledWith('open-url', expect.any(Function));+ expect(app.on).toHaveBeenCalledWith('second-instance', expect.any(Function));+ });+ });++ describe('protocol registration', () => {+ it('should use simple registration in production mode', () => {+ manager.initialize();++ expect(app.setAsDefaultProtocolClient).toHaveBeenCalledWith('lobehub');+ });++ it('should use explicit parameters in development mode', async () => {+ vi.doMock('@/const/env', () => ({ isDev: true }));+ vi.resetModules();++ const { ProtocolManager: DevProtocolManager } = await import('../ProtocolManager');+ const devManager = new DevProtocolManager(mockAppCore);+ devManager.initialize();++ // In dev mode, should be called with additional arguments+ expect(app.setAsDefaultProtocolClient).toHaveBeenCalledWith(+ 'lobehub',+ expect.any(String),+ expect.any(Array),+ );+ });++ it('should verify registration status after registering', () => {+ manager.initialize();++ expect(app.isDefaultProtocolClient).toHaveBeenCalledWith('lobehub');+ });+ });++ describe('getProtocolUrlFromArgs', () => {+ beforeEach(() => {+ manager.initialize();+ });++ it('should extract protocol URL from command line arguments', () => {+ // Access private method through prototype+ const result = manager['getProtocolUrlFromArgs']([+ '/path/to/app',+ 'lobehub://plugin/install?url=https://example.com',+ ]);++ expect(result).toBe('lobehub://plugin/install?url=https://example.com');+ });++ it('should return null when no matching URL found', () => {+ const result = manager['getProtocolUrlFromArgs'](['/path/to/app', '--some-flag']);++ expect(result).toBeNull();+ });++ it('should return first matching URL when multiple exist', () => {+ const result = manager['getProtocolUrlFromArgs']([+ 'lobehub://first/action',+ 'lobehub://second/action',+ ]);++ expect(result).toBe('lobehub://first/action');+ });+ });++ describe('handleProtocolUrl', () => {+ beforeEach(() => {+ manager.initialize();+ });++ it('should store URL when app is not ready', () => {+ mockApp.isReady.mockReturnValue(false);++ manager['handleProtocolUrl']('lobehub://plugin/install');++ expect(manager['pendingUrls']).toContain('lobehub://plugin/install');+ expect(mockShowMainWindow).not.toHaveBeenCalled();+ });++ it('should process URL immediately when app is ready', async () => {+ mockApp.isReady.mockReturnValue(true);++ manager['handleProtocolUrl']('lobehub://plugin/install');++ // Allow async processing+ await vi.waitFor(() => {+ expect(mockShowMainWindow).toHaveBeenCalled();+ });+ });++ it('should ignore URLs with invalid protocol scheme', async () => {+ mockApp.isReady.mockReturnValue(true);++ manager['handleProtocolUrl']('invalid://plugin/install');++ await Promise.resolve(); // Allow any async work++ expect(mockHandleProtocolRequest).not.toHaveBeenCalled();+ });+ });++ describe('event listeners', () => {+ beforeEach(() => {+ manager.initialize();+ });++ it('should handle open-url event', async () => {+ expect(openUrlHandler).toBeDefined();++ const mockEvent = { preventDefault: vi.fn() };+ openUrlHandler!(mockEvent, 'lobehub://plugin/install');++ expect(mockEvent.preventDefault).toHaveBeenCalled();+ await vi.waitFor(() => {+ expect(mockShowMainWindow).toHaveBeenCalled();+ });+ });++ it('should handle second-instance event with protocol URL', async () => {+ expect(secondInstanceHandler).toBeDefined();++ const mockEvent = {};+ secondInstanceHandler!(mockEvent, ['/path/to/app', 'lobehub://plugin/install']);++ await vi.waitFor(() => {+ expect(mockShowMainWindow).toHaveBeenCalled();+ });+ });++ it('should show main window even without protocol URL in second-instance', () => {+ expect(secondInstanceHandler).toBeDefined();++ const mockEvent = {};+ secondInstanceHandler!(mockEvent, ['/path/to/app', '--some-flag']);++ expect(mockShowMainWindow).toHaveBeenCalled();+ });+ });++ describe('processPendingUrls', () => {+ beforeEach(() => {+ manager.initialize();+ });++ it('should process all pending URLs', async () => {+ // Add pending URLs+ manager['pendingUrls'] = ['lobehub://action1', 'lobehub://action2'];++ await manager.processPendingUrls();++ // Should have shown main window for each URL+ expect(mockShowMainWindow).toHaveBeenCalledTimes(2);+ });++ it('should clear pending URLs after processing', async () => {+ manager['pendingUrls'] = ['lobehub://action1'];++ await manager.processPendingUrls();++ expect(manager['pendingUrls']).toHaveLength(0);+ });++ it('should skip when no pending URLs', async () => {+ manager['pendingUrls'] = [];++ await manager.processPendingUrls();++ expect(mockShowMainWindow).not.toHaveBeenCalled();+ });+ });++ describe('getScheme', () => {+ it('should return the protocol scheme', () => {+ expect(manager.getScheme()).toBe('lobehub');+ });+ });++ describe('isRegistered', () => {+ it('should return true when registered', () => {+ mockApp.isDefaultProtocolClient.mockReturnValue(true);++ expect(manager.isRegistered()).toBe(true);+ });++ it('should return false when not registered', () => {+ mockApp.isDefaultProtocolClient.mockReturnValue(false);++ expect(manager.isRegistered()).toBe(false);+ });+ });++ describe('processProtocolUrl', () => {+ beforeEach(() => {+ manager.initialize();+ });++ it('should show main window and dispatch to handler', async () => {+ vi.mocked(parseProtocolUrl).mockReturnValue({+ action: 'install',+ params: { url: 'https://example.com' },+ urlType: 'plugin',+ });++ await manager['processProtocolUrl']('lobehub://plugin/install');++ expect(mockShowMainWindow).toHaveBeenCalled();+ expect(mockHandleProtocolRequest).toHaveBeenCalledWith('plugin', 'install', {+ url: 'https://example.com',+ });+ });++ it('should warn and return when parseProtocolUrl returns null', async () => {+ vi.mocked(parseProtocolUrl).mockReturnValue(null);++ await manager['processProtocolUrl']('lobehub://invalid');++ expect(mockShowMainWindow).toHaveBeenCalled();+ expect(mockHandleProtocolRequest).not.toHaveBeenCalled();+ });++ it('should handle errors gracefully', async () => {+ mockHandleProtocolRequest.mockRejectedValue(new Error('Handler error'));++ // Should not throw+ await expect(+ manager['processProtocolUrl']('lobehub://plugin/install'),+ ).resolves.not.toThrow();+ });+ });+});diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/StaticFileServerManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/StaticFileServerManager.test.tsnew file mode 100644index 00000000000..2d96ac53540--- /dev/null+++ b/apps/desktop/src/main/core/infrastructure/__tests__/StaticFileServerManager.test.ts@@ -0,0 +1,481 @@+import { getPort } from 'get-port-please';+import { createServer } from 'node:http';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '../../App';+import { StaticFileServerManager } from '../StaticFileServerManager';++// Mock get-port-please+vi.mock('get-port-please', () => ({+ getPort: vi.fn().mockResolvedValue(33250),+}));++// Create mock server and handler storage+const mockServerHandler = { current: null as any };+const mockServer = {+ close: vi.fn((cb?: () => void) => cb?.()),+ listen: vi.fn((_port: number, _host: string, cb: () => void) => cb()),+ on: vi.fn(),+};++// Mock node:http+vi.mock('node:http', () => ({+ createServer: vi.fn((handler: any) => {+ mockServerHandler.current = handler;+ return mockServer;+ }),+}));++// Mock logger+vi.mock('@/utils/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ }),+}));++// Mock LOCAL_STORAGE_URL_PREFIX+vi.mock('@/const/dir', () => ({+ LOCAL_STORAGE_URL_PREFIX: '/lobe-desktop-file',+}));++describe('StaticFileServerManager', () => {+ let manager: StaticFileServerManager;+ let mockApp: App;+ let mockFileService: { getFile: ReturnType<typeof vi.fn> };++ beforeEach(() => {+ vi.clearAllMocks();++ // Reset server handler+ mockServerHandler.current = null;++ // Reset getPort mock to default behavior+ vi.mocked(getPort).mockResolvedValue(33250);++ // Reset server mock behaviors+ mockServer.listen.mockImplementation((_port: number, _host: string, cb: () => void) => cb());+ mockServer.close.mockImplementation((cb?: () => void) => cb?.());+ mockServer.on.mockReset();++ // Create mock FileService+ mockFileService = {+ getFile: vi.fn().mockResolvedValue({+ content: new ArrayBuffer(10),+ mimeType: 'image/png',+ }),+ };++ // Create mock App+ mockApp = {+ getService: vi.fn().mockReturnValue(mockFileService),+ } as unknown as App;++ manager = new StaticFileServerManager(mockApp);+ });++ afterEach(() => {+ // Ensure cleanup+ if ((manager as any).isInitialized) {+ manager.destroy();+ }+ });++ describe('constructor', () => {+ it('should initialize with app reference and get FileService', () => {+ expect(mockApp.getService).toHaveBeenCalled();+ });+ });++ describe('initialize', () => {+ it('should get available port and start HTTP server', async () => {+ await manager.initialize();++ expect(getPort).toHaveBeenCalledWith({+ host: '127.0.0.1',+ port: 33_250,+ ports: [33_251, 33_252, 33_253, 33_254, 33_255],+ });+ expect(createServer).toHaveBeenCalled();+ expect(mockServer.listen).toHaveBeenCalledWith(33250, '127.0.0.1', expect.any(Function));+ });++ it('should skip initialization if already initialized', async () => {+ await manager.initialize();++ // Clear mocks after first initialization+ vi.mocked(getPort).mockClear();+ vi.mocked(createServer).mockClear();++ await manager.initialize();++ expect(getPort).not.toHaveBeenCalled();+ expect(createServer).not.toHaveBeenCalled();+ });++ it('should throw error when port acquisition fails', async () => {+ const error = new Error('No available port');+ vi.mocked(getPort).mockRejectedValue(error);++ await expect(manager.initialize()).rejects.toThrow('No available port');+ });++ it('should handle server startup error', async () => {+ const serverError = new Error('Address in use');++ // Mock server.on to capture error handler+ let errorHandler: ((err: Error) => void) | undefined;+ mockServer.on.mockImplementation((event: string, handler: any) => {+ if (event === 'error') {+ errorHandler = handler;+ }+ return mockServer;+ });++ // Mock listen to not call callback but trigger error+ mockServer.listen.mockImplementation(() => {+ // Trigger error after a tick+ setTimeout(() => {+ if (errorHandler) {+ errorHandler(serverError);+ }+ }, 0);+ return mockServer;+ });++ await expect(manager.initialize()).rejects.toThrow('Address in use');+ });+ });++ describe('HTTP request handling', () => {+ beforeEach(async () => {+ // Reset mock server behavior+ mockServer.listen.mockImplementation((_port, _host, cb) => cb());+ await manager.initialize();+ });++ it('should handle OPTIONS request with CORS headers', async () => {+ const req = {+ headers: { origin: 'http://localhost:3000' },+ method: 'OPTIONS',+ on: vi.fn(),+ setTimeout: vi.fn(),+ url: '/lobe-desktop-file/test.png',+ };+ const res = {+ destroyed: false,+ end: vi.fn(),+ headersSent: false,+ writeHead: vi.fn(),+ };++ await mockServerHandler.current(req, res);++ expect(res.writeHead).toHaveBeenCalledWith(204, {+ 'Access-Control-Allow-Headers': 'Content-Type',+ 'Access-Control-Allow-Methods': 'GET, OPTIONS',+ 'Access-Control-Allow-Origin': 'http://localhost:3000',+ 'Access-Control-Max-Age': '86400',+ });+ expect(res.end).toHaveBeenCalled();+ });++ it('should serve file with correct content type and CORS headers', async () => {+ const fileContent = new ArrayBuffer(100);+ mockFileService.getFile.mockResolvedValue({+ content: fileContent,+ mimeType: 'image/jpeg',+ });++ const req = {+ headers: { origin: 'http://127.0.0.1:3000' },+ method: 'GET',+ on: vi.fn(),+ setTimeout: vi.fn(),+ url: '/lobe-desktop-file/images/test.jpg',+ };+ const res = {+ destroyed: false,+ end: vi.fn(),+ headersSent: false,+ writeHead: vi.fn(),+ };++ await mockServerHandler.current(req, res);++ expect(mockFileService.getFile).toHaveBeenCalledWith('desktop://images/test.jpg');+ expect(res.writeHead).toHaveBeenCalledWith(200, {+ 'Access-Control-Allow-Origin': 'http://127.0.0.1:3000',+ 'Cache-Control': 'public, max-age=31536000',+ 'Content-Length': expect.any(Number),+ 'Content-Type': 'image/jpeg',+ });+ expect(res.end).toHaveBeenCalled();+ });++ it('should return 400 for empty file path', async () => {+ const req = {+ headers: {},+ method: 'GET',+ on: vi.fn(),+ setTimeout: vi.fn(),+ url: '/lobe-desktop-file/',+ };+ const res = {+ destroyed: false,+ end: vi.fn(),+ headersSent: false,+ writeHead: vi.fn(),+ };++ await mockServerHandler.current(req, res);++ expect(res.writeHead).toHaveBeenCalledWith(400, { 'Content-Type': 'text/plain' });+ expect(res.end).toHaveBeenCalledWith('Bad Request: Empty file path');+ });++ it('should return 404 when file not found', async () => {+ const notFoundError = new Error('File not found');+ notFoundError.name = 'FileNotFoundError';+ mockFileService.getFile.mockRejectedValue(notFoundError);++ const req = {+ headers: { origin: 'http://localhost:3000' },+ method: 'GET',+ on: vi.fn(),+ setTimeout: vi.fn(),+ url: '/lobe-desktop-file/nonexistent.png',+ };+ const res = {+ destroyed: false,+ end: vi.fn(),+ headersSent: false,+ writeHead: vi.fn(),+ };++ await mockServerHandler.current(req, res);++ expect(res.writeHead).toHaveBeenCalledWith(404, {+ 'Access-Control-Allow-Origin': 'http://localhost:3000',+ 'Content-Type': 'text/plain',+ });+ expect(res.end).toHaveBeenCalledWith('File Not Found');+ });++ it('should return 500 for server errors', async () => {+ mockFileService.getFile.mockRejectedValue(new Error('Database error'));++ const req = {+ headers: {},+ method: 'GET',+ on: vi.fn(),+ setTimeout: vi.fn(),+ url: '/lobe-desktop-file/test.png',+ };+ const res = {+ destroyed: false,+ end: vi.fn(),+ headersSent: false,+ writeHead: vi.fn(),+ };++ await mockServerHandler.current(req, res);++ expect(res.writeHead).toHaveBeenCalledWith(500, {+ 'Access-Control-Allow-Origin': '*',+ 'Content-Type': 'text/plain',+ });+ expect(res.end).toHaveBeenCalledWith('Internal Server Error');+ });++ it('should skip processing if response is already destroyed', async () => {+ const req = {+ headers: {},+ method: 'GET',+ on: vi.fn(),+ setTimeout: vi.fn(),+ url: '/lobe-desktop-file/test.png',+ };+ const res = {+ destroyed: true,+ end: vi.fn(),+ headersSent: false,+ writeHead: vi.fn(),+ };++ await mockServerHandler.current(req, res);++ expect(res.writeHead).not.toHaveBeenCalled();+ expect(res.end).not.toHaveBeenCalled();+ expect(mockFileService.getFile).not.toHaveBeenCalled();+ });++ it('should handle URL-encoded file paths', async () => {+ const req = {+ headers: {},+ method: 'GET',+ on: vi.fn(),+ setTimeout: vi.fn(),+ url: '/lobe-desktop-file/path%20with%20spaces/file%20name.png',+ };+ const res = {+ destroyed: false,+ end: vi.fn(),+ headersSent: false,+ writeHead: vi.fn(),+ };++ await mockServerHandler.current(req, res);++ expect(mockFileService.getFile).toHaveBeenCalledWith(+ 'desktop://path with spaces/file name.png',+ );+ });+ });++ describe('CORS handling', () => {+ beforeEach(async () => {+ mockServer.listen.mockImplementation((_port, _host, cb) => cb());+ await manager.initialize();+ });++ it('should return specific origin for localhost', async () => {+ const req = {+ headers: { origin: 'http://localhost:3000' },+ method: 'OPTIONS',+ on: vi.fn(),+ setTimeout: vi.fn(),+ url: '/test',+ };+ const res = {+ destroyed: false,+ end: vi.fn(),+ headersSent: false,+ writeHead: vi.fn(),+ };++ await mockServerHandler.current(req, res);++ expect(res.writeHead).toHaveBeenCalledWith(+ 204,+ expect.objectContaining({+ 'Access-Control-Allow-Origin': 'http://localhost:3000',+ }),+ );+ });++ it('should return specific origin for 127.0.0.1', async () => {+ const req = {+ headers: { origin: 'http://127.0.0.1:8080' },+ method: 'OPTIONS',+ on: vi.fn(),+ setTimeout: vi.fn(),+ url: '/test',+ };+ const res = {+ destroyed: false,+ end: vi.fn(),+ headersSent: false,+ writeHead: vi.fn(),+ };++ await mockServerHandler.current(req, res);++ expect(res.writeHead).toHaveBeenCalledWith(+ 204,+ expect.objectContaining({+ 'Access-Control-Allow-Origin': 'http://127.0.0.1:8080',+ }),+ );+ });++ it('should return * for other origins', async () => {+ const req = {+ headers: { origin: 'https://example.com' },+ method: 'OPTIONS',+ on: vi.fn(),+ setTimeout: vi.fn(),+ url: '/test',+ };+ const res = {+ destroyed: false,+ end: vi.fn(),+ headersSent: false,+ writeHead: vi.fn(),+ };++ await mockServerHandler.current(req, res);++ expect(res.writeHead).toHaveBeenCalledWith(+ 204,+ expect.objectContaining({+ 'Access-Control-Allow-Origin': '*',+ }),+ );+ });++ it('should return * for no origin', async () => {+ const req = {+ headers: {},+ method: 'OPTIONS',+ on: vi.fn(),+ setTimeout: vi.fn(),+ url: '/test',+ };+ const res = {+ destroyed: false,+ end: vi.fn(),+ headersSent: false,+ writeHead: vi.fn(),+ };++ await mockServerHandler.current(req, res);++ expect(res.writeHead).toHaveBeenCalledWith(+ 204,+ expect.objectContaining({+ 'Access-Control-Allow-Origin': '*',+ }),+ );+ });+ });++ describe('getFileServerDomain', () => {+ it('should return correct domain when initialized', async () => {+ mockServer.listen.mockImplementation((_port, _host, cb) => cb());+ await manager.initialize();++ const domain = manager.getFileServerDomain();++ expect(domain).toBe('http://127.0.0.1:33250');+ });++ it('should throw error when not initialized', () => {+ expect(() => manager.getFileServerDomain()).toThrow(+ 'StaticFileServerManager not initialized or server not started',+ );+ });+ });++ describe('destroy', () => {+ it('should close server and reset state', async () => {+ mockServer.listen.mockImplementation((_port, _host, cb) => cb());+ await manager.initialize();++ manager.destroy();++ expect(mockServer.close).toHaveBeenCalled();+ expect((manager as any).httpServer).toBeNull();+ expect((manager as any).serverPort).toBe(0);+ expect((manager as any).isInitialized).toBe(false);+ });++ it('should do nothing if not initialized', () => {+ manager.destroy();++ expect(mockServer.close).not.toHaveBeenCalled();+ });+ });+});diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/StoreManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/StoreManager.test.tsnew file mode 100644index 00000000000..347ddfbeae2--- /dev/null+++ b/apps/desktop/src/main/core/infrastructure/__tests__/StoreManager.test.ts@@ -0,0 +1,164 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { App as AppCore } from '../../App';+import { StoreManager } from '../StoreManager';++// Use vi.hoisted to define mocks before hoisting+const { mockStoreInstance, mockMakeSureDirExist, MockStore } = vi.hoisted(() => {+ const mockStoreInstance = {+ clear: vi.fn(),+ delete: vi.fn(),+ get: vi.fn().mockImplementation((key: string, defaultValue?: any) => {+ if (key === 'storagePath') return '/mock/storage/path';+ return defaultValue;+ }),+ has: vi.fn().mockReturnValue(false),+ openInEditor: vi.fn().mockResolvedValue(undefined),+ set: vi.fn(),+ };++ const MockStore = vi.fn().mockImplementation(() => mockStoreInstance);++ return {+ MockStore,+ mockMakeSureDirExist: vi.fn(),+ mockStoreInstance,+ };+});++// Mock electron-store+vi.mock('electron-store', () => ({+ default: MockStore,+}));++// Mock logger+vi.mock('@/utils/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ }),+}));++// Mock file-system utils+vi.mock('@/utils/file-system', () => ({+ makeSureDirExist: mockMakeSureDirExist,+}));++// Mock store constants+vi.mock('@/const/store', () => ({+ STORE_DEFAULTS: {+ locale: 'auto',+ storagePath: '/default/storage/path',+ },+ STORE_NAME: 'test-config',+}));++describe('StoreManager', () => {+ let manager: StoreManager;+ let mockAppCore: AppCore;++ beforeEach(() => {+ vi.clearAllMocks();++ // Reset store mock behaviors+ mockStoreInstance.get.mockImplementation((key: string, defaultValue?: any) => {+ if (key === 'storagePath') return '/mock/storage/path';+ return defaultValue;+ });+ mockStoreInstance.has.mockReturnValue(false);++ // Create mock App core+ mockAppCore = {} as unknown as AppCore;++ manager = new StoreManager(mockAppCore);+ });++ describe('constructor', () => {+ it('should create electron-store with correct options', () => {+ expect(MockStore).toHaveBeenCalledWith({+ defaults: {+ locale: 'auto',+ storagePath: '/default/storage/path',+ },+ name: 'test-config',+ });+ });++ it('should ensure storage directory exists', () => {+ expect(mockMakeSureDirExist).toHaveBeenCalledWith('/mock/storage/path');+ });+ });++ describe('get', () => {+ it('should call store.get with key', () => {+ mockStoreInstance.get.mockReturnValue('test-value');++ const result = manager.get('locale' as any);++ expect(mockStoreInstance.get).toHaveBeenCalledWith('locale', undefined);+ expect(result).toBe('test-value');+ });++ it('should call store.get with key and default value', () => {+ mockStoreInstance.get.mockImplementation((_key: string, defaultValue?: any) => defaultValue);++ const result = manager.get('locale' as any, 'en-US' as any);++ expect(mockStoreInstance.get).toHaveBeenCalledWith('locale', 'en-US');+ expect(result).toBe('en-US');+ });+ });++ describe('set', () => {+ it('should call store.set with key and value', () => {+ manager.set('locale' as any, 'zh-CN' as any);++ expect(mockStoreInstance.set).toHaveBeenCalledWith('locale', 'zh-CN');+ });+ });++ describe('delete', () => {+ it('should call store.delete with key', () => {+ manager.delete('locale' as any);++ expect(mockStoreInstance.delete).toHaveBeenCalledWith('locale');+ });+ });++ describe('clear', () => {+ it('should call store.clear', () => {+ manager.clear();++ expect(mockStoreInstance.clear).toHaveBeenCalled();+ });+ });++ describe('has', () => {+ it('should return true when key exists', () => {+ mockStoreInstance.has.mockReturnValue(true);++ const result = manager.has('locale' as any);++ expect(mockStoreInstance.has).toHaveBeenCalledWith('locale');+ expect(result).toBe(true);+ });++ it('should return false when key does not exist', () => {+ mockStoreInstance.has.mockReturnValue(false);++ const result = manager.has('nonExistent' as any);++ expect(result).toBe(false);+ });+ });++ describe('openInEditor', () => {+ it('should call store.openInEditor', async () => {+ await manager.openInEditor();++ expect(mockStoreInstance.openInEditor).toHaveBeenCalled();+ });+ });+});diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/UpdaterManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/UpdaterManager.test.tsnew file mode 100644index 00000000000..b04cbf7dac6--- /dev/null+++ b/apps/desktop/src/main/core/infrastructure/__tests__/UpdaterManager.test.ts@@ -0,0 +1,513 @@+import { autoUpdater } from 'electron-updater';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { App as AppCore } from '../../App';+import { UpdaterManager } from '../UpdaterManager';++// Use vi.hoisted to ensure mocks work with require()+const { mockGetAllWindows, mockReleaseSingleInstanceLock } = vi.hoisted(() => ({+ mockGetAllWindows: vi.fn().mockReturnValue([]),+ mockReleaseSingleInstanceLock: vi.fn(),+}));++// Mock electron-log+vi.mock('electron-log', () => ({+ default: {+ transports: {+ file: {+ level: 'info',+ getFile: vi.fn().mockReturnValue({ path: '/mock/log/path' }),+ },+ },+ },+}));++// Mock electron-updater+vi.mock('electron-updater', () => ({+ autoUpdater: {+ allowDowngrade: false,+ allowPrerelease: false,+ autoDownload: false,+ autoInstallOnAppQuit: false,+ channel: 'stable',+ checkForUpdates: vi.fn(),+ downloadUpdate: vi.fn(),+ forceDevUpdateConfig: false,+ logger: null as any,+ on: vi.fn(),+ quitAndInstall: vi.fn(),+ },+}));++// Mock electron - uses hoisted functions for require() compatibility+vi.mock('electron', () => ({+ BrowserWindow: {+ getAllWindows: mockGetAllWindows,+ },+ app: {+ releaseSingleInstanceLock: mockReleaseSingleInstanceLock,+ },+}));++// Mock logger+vi.mock('@/utils/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ }),+}));++// Mock updater configs+vi.mock('@/modules/updater/configs', () => ({+ UPDATE_CHANNEL: 'stable',+ updaterConfig: {+ app: {+ autoCheckUpdate: false,+ autoDownloadUpdate: true,+ checkUpdateInterval: 60 * 60 * 1000,+ },+ enableAppUpdate: true,+ enableRenderHotUpdate: true,+ },+}));++// Mock isDev+vi.mock('@/const/env', () => ({+ isDev: false,+}));++describe('UpdaterManager', () => {+ let updaterManager: UpdaterManager;+ let mockApp: AppCore;+ let mockBroadcast: ReturnType<typeof vi.fn>;+ let registeredEvents: Map<string, (...args: any[]) => void>;++ beforeEach(() => {+ vi.clearAllMocks();+ vi.useFakeTimers();++ // Reset autoUpdater state+ (autoUpdater as any).autoDownload = false;+ (autoUpdater as any).autoInstallOnAppQuit = false;+ (autoUpdater as any).channel = 'stable';+ (autoUpdater as any).allowPrerelease = false;+ (autoUpdater as any).allowDowngrade = false;+ (autoUpdater as any).forceDevUpdateConfig = false;++ // Capture registered events+ registeredEvents = new Map();+ vi.mocked(autoUpdater.on).mockImplementation((event: string, handler: any) => {+ registeredEvents.set(event, handler);+ return autoUpdater;+ });++ // Mock broadcast function+ mockBroadcast = vi.fn();++ // Create mock App+ mockApp = {+ browserManager: {+ getMainWindow: vi.fn().mockReturnValue({+ broadcast: mockBroadcast,+ }),+ },+ isQuiting: false,+ } as unknown as AppCore;++ updaterManager = new UpdaterManager(mockApp);+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ describe('constructor', () => {+ it('should set up electron-log for autoUpdater', () => {+ expect(autoUpdater.logger).not.toBeNull();+ });+ });++ describe('initialize', () => {+ it('should configure autoUpdater properties', async () => {+ await updaterManager.initialize();++ expect(autoUpdater.autoDownload).toBe(false);+ expect(autoUpdater.autoInstallOnAppQuit).toBe(false);+ expect(autoUpdater.channel).toBe('stable');+ expect(autoUpdater.allowPrerelease).toBe(false);+ expect(autoUpdater.allowDowngrade).toBe(false);+ });++ it('should register all event listeners', async () => {+ await updaterManager.initialize();++ expect(autoUpdater.on).toHaveBeenCalledWith('checking-for-update', expect.any(Function));+ expect(autoUpdater.on).toHaveBeenCalledWith('update-available', expect.any(Function));+ expect(autoUpdater.on).toHaveBeenCalledWith('update-not-available', expect.any(Function));+ expect(autoUpdater.on).toHaveBeenCalledWith('error', expect.any(Function));+ expect(autoUpdater.on).toHaveBeenCalledWith('download-progress', expect.any(Function));+ expect(autoUpdater.on).toHaveBeenCalledWith('update-downloaded', expect.any(Function));+ });+ });++ describe('checkForUpdates', () => {+ beforeEach(async () => {+ await updaterManager.initialize();+ vi.mocked(autoUpdater.checkForUpdates).mockResolvedValue({} as any);+ });++ it('should call autoUpdater.checkForUpdates', async () => {+ await updaterManager.checkForUpdates();++ expect(autoUpdater.checkForUpdates).toHaveBeenCalled();+ });++ it('should broadcast manualUpdateCheckStart when manual check', async () => {+ await updaterManager.checkForUpdates({ manual: true });++ expect(mockBroadcast).toHaveBeenCalledWith('manualUpdateCheckStart');+ });++ it('should not broadcast when auto check', async () => {+ await updaterManager.checkForUpdates({ manual: false });++ expect(mockBroadcast).not.toHaveBeenCalledWith('manualUpdateCheckStart');+ });++ it('should ignore duplicate check requests while checking', async () => {+ // Start first check but don't resolve+ vi.mocked(autoUpdater.checkForUpdates).mockImplementation(+ () => new Promise((resolve) => setTimeout(resolve, 1000)) as any,+ );++ const firstCheck = updaterManager.checkForUpdates();+ const secondCheck = updaterManager.checkForUpdates();++ await vi.advanceTimersByTimeAsync(1000);+ await Promise.all([firstCheck, secondCheck]);++ expect(autoUpdater.checkForUpdates).toHaveBeenCalledTimes(1);+ });++ it('should broadcast updateError when check fails during manual check', async () => {+ const error = new Error('Network error');+ vi.mocked(autoUpdater.checkForUpdates).mockRejectedValue(error);++ await updaterManager.checkForUpdates({ manual: true });++ expect(mockBroadcast).toHaveBeenCalledWith('updateError', 'Network error');+ });+ });++ describe('downloadUpdate', () => {+ beforeEach(async () => {+ await updaterManager.initialize();+ vi.mocked(autoUpdater.downloadUpdate).mockResolvedValue([] as any);++ // Simulate update available+ const updateAvailableHandler = registeredEvents.get('update-available');+ updateAvailableHandler?.({ version: '2.0.0' });+ });++ it('should call autoUpdater.downloadUpdate', async () => {+ await updaterManager.downloadUpdate();++ expect(autoUpdater.downloadUpdate).toHaveBeenCalled();+ });++ it('should ignore download request when no update available', async () => {+ // Create fresh manager without update available+ const freshManager = new UpdaterManager(mockApp);+ await freshManager.initialize();++ await freshManager.downloadUpdate();++ // Reset call count since downloadUpdate might have been called in beforeEach+ vi.mocked(autoUpdater.downloadUpdate).mockClear();+ await freshManager.downloadUpdate();++ // downloadUpdate should not be called on autoUpdater for fresh manager+ expect(autoUpdater.downloadUpdate).not.toHaveBeenCalled();+ });++ it('should ignore duplicate download requests while downloading', async () => {+ vi.mocked(autoUpdater.downloadUpdate).mockImplementation(+ () => new Promise((resolve) => setTimeout(resolve, 1000)) as any,+ );++ const firstDownload = updaterManager.downloadUpdate();+ const secondDownload = updaterManager.downloadUpdate();++ await vi.advanceTimersByTimeAsync(1000);+ await Promise.all([firstDownload, secondDownload]);++ expect(autoUpdater.downloadUpdate).toHaveBeenCalledTimes(1);+ });++ it('should broadcast updateDownloadStart when isManualCheck is true', async () => {+ // Create a fresh manager to avoid state pollution from beforeEach+ const freshManager = new UpdaterManager(mockApp);++ // Setup fresh event capture+ const freshEvents = new Map<string, (...args: any[]) => void>();+ vi.mocked(autoUpdater.on).mockImplementation((event: string, handler: any) => {+ freshEvents.set(event, handler);+ return autoUpdater;+ });+ await freshManager.initialize();++ // Trigger a manual check to set isManualCheck = true+ vi.mocked(autoUpdater.checkForUpdates).mockResolvedValue({} as any);+ await freshManager.checkForUpdates({ manual: true });++ // Manually set updateAvailable without triggering auto-download+ // Access private property to set state+ (freshManager as any).updateAvailable = true;++ // Clear previous broadcast calls+ mockBroadcast.mockClear();++ // Now download should broadcast updateDownloadStart because isManualCheck is true+ vi.mocked(autoUpdater.downloadUpdate).mockResolvedValue([] as any);+ await freshManager.downloadUpdate();++ expect(mockBroadcast).toHaveBeenCalledWith('updateDownloadStart');+ });++ it('should broadcast updateError when download fails with isManualCheck true', async () => {+ // Create a fresh manager to avoid state pollution from beforeEach+ const freshManager = new UpdaterManager(mockApp);++ // Setup fresh event capture+ const freshEvents = new Map<string, (...args: any[]) => void>();+ vi.mocked(autoUpdater.on).mockImplementation((event: string, handler: any) => {+ freshEvents.set(event, handler);+ return autoUpdater;+ });+ await freshManager.initialize();++ // Trigger a manual check to set isManualCheck = true+ vi.mocked(autoUpdater.checkForUpdates).mockResolvedValue({} as any);+ await freshManager.checkForUpdates({ manual: true });++ // Manually set updateAvailable without triggering auto-download+ (freshManager as any).updateAvailable = true;++ // Clear previous broadcast calls+ mockBroadcast.mockClear();++ // Setup error+ const error = new Error('Download failed');+ vi.mocked(autoUpdater.downloadUpdate).mockRejectedValue(error);++ await freshManager.downloadUpdate();++ expect(mockBroadcast).toHaveBeenCalledWith('updateError', 'Download failed');+ });+ });++ describe('installNow', () => {+ // Note: installNow uses require('electron') which is difficult to mock in vitest.+ // These tests are skipped because vi.mock doesn't work with dynamic require().+ // The functionality should be tested in integration tests or E2E tests.++ it.skip('should set app.isQuiting to true', () => {+ updaterManager.installNow();+ expect(mockApp.isQuiting).toBe(true);+ });++ it.skip('should close all windows', () => {+ const mockWindow1 = { close: vi.fn(), isDestroyed: vi.fn().mockReturnValue(false) };+ const mockWindow2 = { close: vi.fn(), isDestroyed: vi.fn().mockReturnValue(false) };+ mockGetAllWindows.mockReturnValue([mockWindow1, mockWindow2]);+ updaterManager.installNow();+ expect(mockWindow1.close).toHaveBeenCalled();+ expect(mockWindow2.close).toHaveBeenCalled();+ });++ it.skip('should not close destroyed windows', () => {+ const mockWindow = { close: vi.fn(), isDestroyed: vi.fn().mockReturnValue(true) };+ mockGetAllWindows.mockReturnValue([mockWindow]);+ updaterManager.installNow();+ expect(mockWindow.close).not.toHaveBeenCalled();+ });++ it.skip('should release single instance lock', () => {+ updaterManager.installNow();+ expect(mockReleaseSingleInstanceLock).toHaveBeenCalled();+ });++ it.skip('should call quitAndInstall with correct parameters after delay', async () => {+ updaterManager.installNow();+ expect(autoUpdater.quitAndInstall).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(100);+ expect(autoUpdater.quitAndInstall).toHaveBeenCalledWith(true, true);+ });+ });++ describe('installLater', () => {+ it('should set autoInstallOnAppQuit to true', () => {+ updaterManager.installLater();++ expect(autoUpdater.autoInstallOnAppQuit).toBe(true);+ });++ it('should broadcast updateWillInstallLater', () => {+ updaterManager.installLater();++ expect(mockBroadcast).toHaveBeenCalledWith('updateWillInstallLater');+ });+ });++ describe('event handlers', () => {+ beforeEach(async () => {+ await updaterManager.initialize();+ });++ describe('update-available', () => {+ it('should broadcast manualUpdateAvailable when manual check', async () => {+ // Trigger manual check first+ vi.mocked(autoUpdater.checkForUpdates).mockResolvedValue({} as any);+ await updaterManager.checkForUpdates({ manual: true });++ const updateInfo = { version: '2.0.0' };+ const handler = registeredEvents.get('update-available');+ handler?.(updateInfo);++ expect(mockBroadcast).toHaveBeenCalledWith('manualUpdateAvailable', updateInfo);+ });++ it('should auto download when auto check finds update', async () => {+ // Trigger auto check first+ vi.mocked(autoUpdater.checkForUpdates).mockResolvedValue({} as any);+ await updaterManager.checkForUpdates({ manual: false });++ vi.mocked(autoUpdater.downloadUpdate).mockResolvedValue([] as any);++ const handler = registeredEvents.get('update-available');+ handler?.({ version: '2.0.0' });++ expect(autoUpdater.downloadUpdate).toHaveBeenCalled();+ });+ });++ describe('update-not-available', () => {+ it('should broadcast manualUpdateNotAvailable when manual check', async () => {+ vi.mocked(autoUpdater.checkForUpdates).mockResolvedValue({} as any);+ await updaterManager.checkForUpdates({ manual: true });++ const info = { version: '1.0.0' };+ const handler = registeredEvents.get('update-not-available');+ handler?.(info);++ expect(mockBroadcast).toHaveBeenCalledWith('manualUpdateNotAvailable', info);+ });++ it('should not broadcast when auto check', async () => {+ vi.mocked(autoUpdater.checkForUpdates).mockResolvedValue({} as any);+ await updaterManager.checkForUpdates({ manual: false });++ const handler = registeredEvents.get('update-not-available');+ handler?.({ version: '1.0.0' });++ expect(mockBroadcast).not.toHaveBeenCalledWith(+ 'manualUpdateNotAvailable',+ expect.anything(),+ );+ });+ });++ describe('download-progress', () => {+ it('should broadcast progress when manual check', async () => {+ vi.mocked(autoUpdater.checkForUpdates).mockResolvedValue({} as any);+ await updaterManager.checkForUpdates({ manual: true });++ const progressObj = {+ bytesPerSecond: 1024,+ percent: 50,+ total: 1024 * 1024,+ transferred: 512 * 1024,+ };+ const handler = registeredEvents.get('download-progress');+ handler?.(progressObj);++ expect(mockBroadcast).toHaveBeenCalledWith('updateDownloadProgress', progressObj);+ });+ });++ describe('update-downloaded', () => {+ it('should broadcast updateDownloaded', async () => {+ await updaterManager.initialize();++ const info = { version: '2.0.0' };+ const handler = registeredEvents.get('update-downloaded');+ handler?.(info);++ expect(mockBroadcast).toHaveBeenCalledWith('updateDownloaded', info);+ });+ });++ describe('error', () => {+ it('should broadcast updateError when manual check', async () => {+ vi.mocked(autoUpdater.checkForUpdates).mockResolvedValue({} as any);+ await updaterManager.checkForUpdates({ manual: true });++ const error = new Error('Update error');+ const handler = registeredEvents.get('error');+ handler?.(error);++ expect(mockBroadcast).toHaveBeenCalledWith('updateError', 'Update error');+ });++ it('should not broadcast when auto check', async () => {+ vi.mocked(autoUpdater.checkForUpdates).mockResolvedValue({} as any);+ await updaterManager.checkForUpdates({ manual: false });++ const error = new Error('Update error');+ const handler = registeredEvents.get('error');+ handler?.(error);++ expect(mockBroadcast).not.toHaveBeenCalledWith('updateError', expect.anything());+ });+ });+ });++ describe('simulation methods (dev mode)', () => {+ it('simulateUpdateAvailable should do nothing when not in dev mode', () => {+ // Current mock has isDev = false+ updaterManager.simulateUpdateAvailable();++ // Should not broadcast anything since isDev is false+ expect(mockBroadcast).not.toHaveBeenCalledWith(+ 'manualUpdateAvailable',+ expect.objectContaining({ version: '1.0.0' }),+ );+ });++ it('simulateUpdateDownloaded should do nothing when not in dev mode', () => {+ updaterManager.simulateUpdateDownloaded();++ expect(mockBroadcast).not.toHaveBeenCalledWith(+ 'updateDownloaded',+ expect.objectContaining({ version: '1.0.0' }),+ );+ });++ it('simulateDownloadProgress should do nothing when not in dev mode', () => {+ updaterManager.simulateDownloadProgress();++ expect(mockBroadcast).not.toHaveBeenCalledWith('updateDownloadStart');+ });+ });++ describe('mainWindow getter', () => {+ it('should return main window from browserManager', () => {+ const mainWindow = updaterManager['mainWindow'];++ expect(mockApp.browserManager.getMainWindow).toHaveBeenCalled();+ expect(mainWindow.broadcast).toBe(mockBroadcast);+ });+ });+});