🤯 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: add controllers tests for desktop (#10536)
Arvin Xu66abd805ac31
diff --git a/apps/desktop/src/main/controllers/__tests__/McpInstallCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/McpInstallCtr.test.tsnew file mode 100644index 00000000000..0d092d54107--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/McpInstallCtr.test.ts@@ -0,0 +1,286 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import McpInstallController from '../McpInstallCtr';++// Mock logger+vi.mock('@/utils/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ }),+}));++// Mock browserManager+const mockBrowserManager = {+ broadcastToWindow: vi.fn(),+};++const mockApp = {+ browserManager: mockBrowserManager,+} as unknown as App;++describe('McpInstallController', () => {+ let controller: McpInstallController;++ beforeEach(() => {+ vi.clearAllMocks();+ controller = new McpInstallController(mockApp);+ });++ describe('handleInstallRequest', () => {+ const validStdioSchema = {+ identifier: 'test-plugin',+ name: 'Test Plugin',+ author: 'Test Author',+ description: 'A test plugin',+ version: '1.0.0',+ config: {+ type: 'stdio',+ command: 'npx',+ args: ['-y', 'test-mcp-server'],+ },+ };++ const validHttpSchema = {+ identifier: 'test-http-plugin',+ name: 'Test HTTP Plugin',+ author: 'Test Author',+ description: 'A test HTTP plugin',+ version: '1.0.0',+ config: {+ type: 'http',+ url: 'https://api.example.com/mcp',+ },+ };++ it('should return false when id is missing', async () => {+ const result = await controller.handleInstallRequest({+ id: '',+ });++ expect(result).toBe(false);+ expect(mockBrowserManager.broadcastToWindow).not.toHaveBeenCalled();+ });++ it('should return false when schema is missing for third-party marketplace', async () => {+ const result = await controller.handleInstallRequest({+ id: 'test-plugin',+ marketId: 'third-party',+ });++ expect(result).toBe(false);+ expect(mockBrowserManager.broadcastToWindow).not.toHaveBeenCalled();+ });++ it('should succeed for official market without schema', async () => {+ const result = await controller.handleInstallRequest({+ id: 'test-plugin',+ marketId: 'lobehub',+ });++ expect(result).toBe(true);+ expect(mockBrowserManager.broadcastToWindow).toHaveBeenCalledWith(+ 'chat',+ 'mcpInstallRequest',+ {+ marketId: 'lobehub',+ pluginId: 'test-plugin',+ schema: undefined,+ },+ );+ });++ it('should return false when schema is invalid JSON', async () => {+ const result = await controller.handleInstallRequest({+ id: 'test-plugin',+ marketId: 'third-party',+ schema: 'invalid json {',+ });++ expect(result).toBe(false);+ expect(mockBrowserManager.broadcastToWindow).not.toHaveBeenCalled();+ });++ it('should return false when schema structure is invalid', async () => {+ const invalidSchema = {+ identifier: 'test-plugin',+ // missing required fields+ };++ const result = await controller.handleInstallRequest({+ id: 'test-plugin',+ marketId: 'third-party',+ schema: JSON.stringify(invalidSchema),+ });++ expect(result).toBe(false);+ expect(mockBrowserManager.broadcastToWindow).not.toHaveBeenCalled();+ });++ it('should return false when schema identifier does not match id', async () => {+ const schema = { ...validStdioSchema, identifier: 'different-id' };++ const result = await controller.handleInstallRequest({+ id: 'test-plugin',+ marketId: 'third-party',+ schema: JSON.stringify(schema),+ });++ expect(result).toBe(false);+ expect(mockBrowserManager.broadcastToWindow).not.toHaveBeenCalled();+ });++ it('should succeed with valid stdio schema', async () => {+ const result = await controller.handleInstallRequest({+ id: 'test-plugin',+ marketId: 'third-party',+ schema: JSON.stringify(validStdioSchema),+ });++ expect(result).toBe(true);+ expect(mockBrowserManager.broadcastToWindow).toHaveBeenCalledWith(+ 'chat',+ 'mcpInstallRequest',+ {+ marketId: 'third-party',+ pluginId: 'test-plugin',+ schema: validStdioSchema,+ },+ );+ });++ it('should succeed with valid http schema', async () => {+ const result = await controller.handleInstallRequest({+ id: 'test-http-plugin',+ marketId: 'third-party',+ schema: JSON.stringify(validHttpSchema),+ });++ expect(result).toBe(true);+ expect(mockBrowserManager.broadcastToWindow).toHaveBeenCalledWith(+ 'chat',+ 'mcpInstallRequest',+ {+ marketId: 'third-party',+ pluginId: 'test-http-plugin',+ schema: validHttpSchema,+ },+ );+ });++ it('should return false when http schema has invalid URL', async () => {+ const invalidHttpSchema = {+ ...validHttpSchema,+ config: {+ type: 'http',+ url: 'not-a-valid-url',+ },+ };++ const result = await controller.handleInstallRequest({+ id: 'test-http-plugin',+ marketId: 'third-party',+ schema: JSON.stringify(invalidHttpSchema),+ });++ expect(result).toBe(false);+ expect(mockBrowserManager.broadcastToWindow).not.toHaveBeenCalled();+ });++ it('should return false when config type is unknown', async () => {+ const unknownTypeSchema = {+ ...validStdioSchema,+ config: {+ type: 'unknown',+ },+ };++ const result = await controller.handleInstallRequest({+ id: 'test-plugin',+ marketId: 'third-party',+ schema: JSON.stringify(unknownTypeSchema),+ });++ expect(result).toBe(false);+ expect(mockBrowserManager.broadcastToWindow).not.toHaveBeenCalled();+ });++ it('should return false when browserManager is not available', async () => {+ const controllerWithoutBrowserManager = new McpInstallController({} as App);++ const result = await controllerWithoutBrowserManager.handleInstallRequest({+ id: 'test-plugin',+ marketId: 'lobehub',+ });++ expect(result).toBe(false);+ });++ it('should handle schema with optional fields', async () => {+ const schemaWithOptionalFields = {+ ...validStdioSchema,+ homepage: 'https://example.com',+ icon: 'https://example.com/icon.png',+ };++ const result = await controller.handleInstallRequest({+ id: 'test-plugin',+ marketId: 'third-party',+ schema: JSON.stringify(schemaWithOptionalFields),+ });++ expect(result).toBe(true);+ expect(mockBrowserManager.broadcastToWindow).toHaveBeenCalledWith(+ 'chat',+ 'mcpInstallRequest',+ expect.objectContaining({+ schema: schemaWithOptionalFields,+ }),+ );+ });++ it('should return false when stdio config missing command', async () => {+ const invalidStdioSchema = {+ ...validStdioSchema,+ config: {+ type: 'stdio',+ // missing command+ },+ };++ const result = await controller.handleInstallRequest({+ id: 'test-plugin',+ marketId: 'third-party',+ schema: JSON.stringify(invalidStdioSchema),+ });++ expect(result).toBe(false);+ });++ it('should handle schema with env configuration', async () => {+ const schemaWithEnv = {+ ...validStdioSchema,+ config: {+ type: 'stdio',+ command: 'npx',+ args: ['-y', 'test-mcp-server'],+ env: {+ API_KEY: 'test-key',+ },+ },+ };++ const result = await controller.handleInstallRequest({+ id: 'test-plugin',+ marketId: 'third-party',+ schema: JSON.stringify(schemaWithEnv),+ });++ expect(result).toBe(true);+ });+ });+});diff --git a/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.tsnew file mode 100644index 00000000000..81820fc8062--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.ts@@ -0,0 +1,347 @@+import { ShowDesktopNotificationParams } from '@lobechat/electron-client-ipc';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import NotificationCtr from '../NotificationCtr';++// Mock logger+vi.mock('@/utils/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ }),+}));++// Mock electron+vi.mock('electron', () => {+ const mockNotificationInstance = {+ on: vi.fn(),+ show: vi.fn(),+ };+ const MockNotification = vi.fn(() => mockNotificationInstance) as any;+ MockNotification.isSupported = vi.fn(() => true);++ return {+ Notification: MockNotification,+ app: {+ setAppUserModelId: vi.fn(),+ },+ };+});++// Mock electron-is+vi.mock('electron-is', () => ({+ macOS: vi.fn(() => false),+ windows: vi.fn(() => false),+}));++// Mock browserManager+const mockBrowserWindow = {+ focus: vi.fn(),+ isDestroyed: vi.fn(() => false),+ isFocused: vi.fn(() => true),+ isMinimized: vi.fn(() => false),+ isVisible: vi.fn(() => true),+};++const mockMainWindow = {+ browserWindow: mockBrowserWindow,+ show: vi.fn(),+};++const mockBrowserManager = {+ getMainWindow: vi.fn(() => mockMainWindow),+};++const mockApp = {+ browserManager: mockBrowserManager,+} as unknown as App;++describe('NotificationCtr', () => {+ let controller: NotificationCtr;++ beforeEach(() => {+ vi.clearAllMocks();+ vi.useFakeTimers();+ controller = new NotificationCtr(mockApp);+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ describe('afterAppReady', () => {+ it('should setup notifications when supported', async () => {+ const { Notification } = await import('electron');+ vi.mocked(Notification.isSupported).mockReturnValue(true);++ controller.afterAppReady();++ expect(Notification.isSupported).toHaveBeenCalled();+ });++ it('should not setup when notifications are not supported', async () => {+ const { Notification } = await import('electron');+ vi.mocked(Notification.isSupported).mockReturnValue(false);++ controller.afterAppReady();++ expect(Notification.isSupported).toHaveBeenCalled();+ });++ it('should set app user model ID on Windows', async () => {+ const { windows } = await import('electron-is');+ const { app, Notification } = await import('electron');+ vi.mocked(windows).mockReturnValue(true);+ vi.mocked(Notification.isSupported).mockReturnValue(true);++ controller.afterAppReady();++ expect(app.setAppUserModelId).toHaveBeenCalledWith('com.lobehub.chat');++ vi.mocked(windows).mockReturnValue(false);+ });++ it('should handle macOS platform', async () => {+ const { macOS } = await import('electron-is');+ const { Notification } = await import('electron');+ vi.mocked(macOS).mockReturnValue(true);+ vi.mocked(Notification.isSupported).mockReturnValue(true);++ // Should not throw+ expect(() => controller.afterAppReady()).not.toThrow();++ vi.mocked(macOS).mockReturnValue(false);+ });+ });++ describe('showDesktopNotification', () => {+ const params: ShowDesktopNotificationParams = {+ body: 'Test body',+ title: 'Test title',+ };++ it('should return error when notifications are not supported', async () => {+ const { Notification } = await import('electron');+ vi.mocked(Notification.isSupported).mockReturnValue(false);++ const result = await controller.showDesktopNotification(params);++ expect(result).toEqual({+ error: 'Desktop notifications not supported',+ success: false,+ });+ });++ it('should skip notification when window is visible and focused', async () => {+ const { Notification } = await import('electron');+ vi.mocked(Notification.isSupported).mockReturnValue(true);+ mockBrowserWindow.isVisible.mockReturnValue(true);+ mockBrowserWindow.isFocused.mockReturnValue(true);+ mockBrowserWindow.isMinimized.mockReturnValue(false);++ const result = await controller.showDesktopNotification(params);++ expect(result).toEqual({+ reason: 'Window is visible',+ skipped: true,+ success: true,+ });+ });++ it('should show notification when window is hidden', async () => {+ const { Notification } = await import('electron');+ vi.mocked(Notification.isSupported).mockReturnValue(true);+ mockBrowserWindow.isVisible.mockReturnValue(false);++ const promise = controller.showDesktopNotification(params);+ vi.advanceTimersByTime(100);+ const result = await promise;++ expect(Notification).toHaveBeenCalledWith({+ body: 'Test body',+ hasReply: false,+ silent: false,+ timeoutType: 'default',+ title: 'Test title',+ urgency: 'normal',+ });+ expect(result).toEqual({ success: true });+ });++ it('should show notification when window is minimized', async () => {+ const { Notification } = await import('electron');+ vi.mocked(Notification.isSupported).mockReturnValue(true);+ mockBrowserWindow.isVisible.mockReturnValue(true);+ mockBrowserWindow.isFocused.mockReturnValue(true);+ mockBrowserWindow.isMinimized.mockReturnValue(true);++ const promise = controller.showDesktopNotification(params);+ vi.advanceTimersByTime(100);+ const result = await promise;++ expect(Notification).toHaveBeenCalled();+ expect(result).toEqual({ success: true });+ });++ it('should show notification when window is not focused', async () => {+ const { Notification } = await import('electron');+ vi.mocked(Notification.isSupported).mockReturnValue(true);+ mockBrowserWindow.isVisible.mockReturnValue(true);+ mockBrowserWindow.isFocused.mockReturnValue(false);+ mockBrowserWindow.isMinimized.mockReturnValue(false);++ const promise = controller.showDesktopNotification(params);+ vi.advanceTimersByTime(100);+ const result = await promise;++ expect(Notification).toHaveBeenCalled();+ expect(result).toEqual({ success: true });+ });++ it('should pass silent option to notification', async () => {+ const { Notification } = await import('electron');+ vi.mocked(Notification.isSupported).mockReturnValue(true);+ mockBrowserWindow.isVisible.mockReturnValue(false);++ const paramsWithSilent: ShowDesktopNotificationParams = {+ ...params,+ silent: true,+ };++ const promise = controller.showDesktopNotification(paramsWithSilent);+ vi.advanceTimersByTime(100);+ await promise;++ expect(Notification).toHaveBeenCalledWith(+ expect.objectContaining({+ silent: true,+ }),+ );+ });++ it('should register click handler to show main window', async () => {+ const { Notification } = await import('electron');+ vi.mocked(Notification.isSupported).mockReturnValue(true);+ mockBrowserWindow.isVisible.mockReturnValue(false);++ // Get the mock instance that will be created+ const mockInstance = { on: vi.fn(), show: vi.fn() };+ vi.mocked(Notification).mockReturnValue(mockInstance as any);++ const promise = controller.showDesktopNotification(params);+ vi.advanceTimersByTime(100);+ await promise;++ // Find the click handler+ const clickHandler = mockInstance.on.mock.calls.find((call) => call[0] === 'click')?.[1];++ expect(clickHandler).toBeDefined();++ // Simulate click+ clickHandler();++ expect(mockMainWindow.show).toHaveBeenCalled();+ expect(mockBrowserWindow.focus).toHaveBeenCalled();+ });++ it('should handle notification error', async () => {+ const { Notification } = await import('electron');+ vi.mocked(Notification.isSupported).mockReturnValue(true);+ mockBrowserWindow.isVisible.mockReturnValue(false);+ vi.mocked(Notification).mockImplementationOnce(() => {+ throw new Error('Notification error');+ });++ const result = await controller.showDesktopNotification(params);++ expect(result).toEqual({+ error: 'Notification error',+ success: false,+ });+ });++ it('should handle unknown error type', async () => {+ const { Notification } = await import('electron');+ vi.mocked(Notification.isSupported).mockReturnValue(true);+ mockBrowserWindow.isVisible.mockReturnValue(false);+ vi.mocked(Notification).mockImplementationOnce(() => {+ throw 'string error';+ });++ const result = await controller.showDesktopNotification(params);++ expect(result).toEqual({+ error: 'Unknown error',+ success: false,+ });+ });+ });++ describe('isMainWindowHidden', () => {+ it('should return false when window is visible and focused', () => {+ mockBrowserWindow.isVisible.mockReturnValue(true);+ mockBrowserWindow.isFocused.mockReturnValue(true);+ mockBrowserWindow.isMinimized.mockReturnValue(false);+ mockBrowserWindow.isDestroyed.mockReturnValue(false);++ const result = controller.isMainWindowHidden();++ expect(result).toBe(false);+ });++ it('should return true when window is not visible', () => {+ mockBrowserWindow.isVisible.mockReturnValue(false);+ mockBrowserWindow.isFocused.mockReturnValue(true);+ mockBrowserWindow.isMinimized.mockReturnValue(false);+ mockBrowserWindow.isDestroyed.mockReturnValue(false);++ const result = controller.isMainWindowHidden();++ expect(result).toBe(true);+ });++ it('should return true when window is minimized', () => {+ mockBrowserWindow.isVisible.mockReturnValue(true);+ mockBrowserWindow.isFocused.mockReturnValue(true);+ mockBrowserWindow.isMinimized.mockReturnValue(true);+ mockBrowserWindow.isDestroyed.mockReturnValue(false);++ const result = controller.isMainWindowHidden();++ expect(result).toBe(true);+ });++ it('should return true when window is not focused', () => {+ mockBrowserWindow.isVisible.mockReturnValue(true);+ mockBrowserWindow.isFocused.mockReturnValue(false);+ mockBrowserWindow.isMinimized.mockReturnValue(false);+ mockBrowserWindow.isDestroyed.mockReturnValue(false);++ const result = controller.isMainWindowHidden();++ expect(result).toBe(true);+ });++ it('should return true when window is destroyed', () => {+ mockBrowserWindow.isDestroyed.mockReturnValue(true);++ const result = controller.isMainWindowHidden();++ expect(result).toBe(true);+ });++ it('should return true on error', () => {+ mockBrowserManager.getMainWindow.mockImplementationOnce(() => {+ throw new Error('Window not available');+ });++ const result = controller.isMainWindowHidden();++ expect(result).toBe(true);+ });+ });+});diff --git a/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.tsnew file mode 100644index 00000000000..b854e88365f--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts@@ -0,0 +1,645 @@+import { DataSyncConfig } from '@lobechat/electron-client-ipc';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import RemoteServerConfigCtr from '../RemoteServerConfigCtr';++// Mock logger+vi.mock('@/utils/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ }),+}));++// Mock electron+vi.mock('electron', () => ({+ safeStorage: {+ decryptString: vi.fn((buffer: Buffer) => buffer.toString()),+ encryptString: vi.fn((str: string) => Buffer.from(str)),+ isEncryptionAvailable: vi.fn(() => true),+ },+}));++// Mock @/const/env+vi.mock('@/const/env', () => ({+ OFFICIAL_CLOUD_SERVER: 'https://cloud.lobehub.com',+}));++// Mock storeManager+const mockStoreManager = {+ delete: vi.fn(),+ get: vi.fn(),+ set: vi.fn(),+};++const mockApp = {+ storeManager: mockStoreManager,+} as unknown as App;++describe('RemoteServerConfigCtr', () => {+ let controller: RemoteServerConfigCtr;++ beforeEach(() => {+ vi.clearAllMocks();+ mockStoreManager.get.mockReturnValue({+ active: false,+ storageMode: 'local',+ });+ controller = new RemoteServerConfigCtr(mockApp);+ });++ describe('getRemoteServerConfig', () => {+ it('should return stored configuration', async () => {+ const config: DataSyncConfig = {+ active: true,+ remoteServerUrl: 'https://my-server.com',+ storageMode: 'selfHost',+ };+ mockStoreManager.get.mockReturnValue(config);++ const result = await controller.getRemoteServerConfig();++ expect(result).toEqual(config);+ expect(mockStoreManager.get).toHaveBeenCalledWith('dataSyncConfig');+ });+ });++ describe('setRemoteServerConfig', () => {+ it('should update configuration', async () => {+ const prevConfig: DataSyncConfig = {+ active: false,+ storageMode: 'local',+ };+ mockStoreManager.get.mockReturnValue(prevConfig);++ const newConfig: Partial<DataSyncConfig> = {+ active: true,+ remoteServerUrl: 'https://my-server.com',+ storageMode: 'selfHost',+ };++ const result = await controller.setRemoteServerConfig(newConfig);++ expect(result).toBe(true);+ expect(mockStoreManager.set).toHaveBeenCalledWith('dataSyncConfig', {+ ...prevConfig,+ ...newConfig,+ });+ });+ });++ describe('clearRemoteServerConfig', () => {+ it('should clear configuration and tokens', async () => {+ const result = await controller.clearRemoteServerConfig();++ expect(result).toBe(true);+ expect(mockStoreManager.set).toHaveBeenCalledWith('dataSyncConfig', { storageMode: 'local' });+ expect(mockStoreManager.delete).toHaveBeenCalledWith('encryptedTokens');+ });+ });++ describe('saveTokens', () => {+ it('should save encrypted tokens with expiration', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(true);++ await controller.saveTokens('access-token', 'refresh-token', 3600);++ expect(safeStorage.encryptString).toHaveBeenCalledWith('access-token');+ expect(safeStorage.encryptString).toHaveBeenCalledWith('refresh-token');+ expect(mockStoreManager.set).toHaveBeenCalledWith(+ 'encryptedTokens',+ expect.objectContaining({+ accessToken: expect.any(String),+ expiresAt: expect.any(Number),+ refreshToken: expect.any(String),+ }),+ );+ });++ it('should save tokens without expiration', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(true);++ await controller.saveTokens('access-token', 'refresh-token');++ expect(mockStoreManager.set).toHaveBeenCalledWith(+ 'encryptedTokens',+ expect.objectContaining({+ accessToken: expect.any(String),+ expiresAt: undefined,+ refreshToken: expect.any(String),+ }),+ );+ });++ it('should save unencrypted tokens when encryption is not available', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(false);++ await controller.saveTokens('access-token', 'refresh-token', 3600);++ expect(safeStorage.encryptString).not.toHaveBeenCalled();+ expect(mockStoreManager.set).toHaveBeenCalledWith(+ 'encryptedTokens',+ expect.objectContaining({+ accessToken: 'access-token',+ refreshToken: 'refresh-token',+ }),+ );+ });+ });++ describe('getAccessToken', () => {+ it('should return decrypted access token', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(true);++ // First save a token+ await controller.saveTokens('test-access-token', 'test-refresh-token');++ const result = await controller.getAccessToken();++ expect(result).toBe('test-access-token');+ });++ it('should load token from store if not in memory', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(true);+ vi.mocked(safeStorage.decryptString).mockReturnValue('stored-access-token');++ mockStoreManager.get.mockImplementation((key) => {+ if (key === 'encryptedTokens') {+ return {+ accessToken: Buffer.from('stored-access-token').toString('base64'),+ refreshToken: Buffer.from('stored-refresh-token').toString('base64'),+ };+ }+ return { active: false, storageMode: 'local' };+ });++ // Create new controller to test loading from store+ const newController = new RemoteServerConfigCtr(mockApp);+ const result = await newController.getAccessToken();++ expect(result).toBe('stored-access-token');+ });++ it('should return null when no token exists', async () => {+ mockStoreManager.get.mockImplementation((key) => {+ if (key === 'encryptedTokens') {+ return null;+ }+ return { active: false, storageMode: 'local' };+ });++ const newController = new RemoteServerConfigCtr(mockApp);+ const result = await newController.getAccessToken();++ expect(result).toBeNull();+ });++ it('should return raw token when encryption is not available', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(false);++ await controller.saveTokens('raw-access-token', 'raw-refresh-token');+ const result = await controller.getAccessToken();++ expect(result).toBe('raw-access-token');+ });++ it('should return null on decryption error', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(true);+ vi.mocked(safeStorage.decryptString).mockImplementation(() => {+ throw new Error('Decryption failed');+ });++ mockStoreManager.get.mockImplementation((key) => {+ if (key === 'encryptedTokens') {+ return {+ accessToken: 'invalid-encrypted-token',+ refreshToken: 'invalid-encrypted-token',+ };+ }+ return { active: false, storageMode: 'local' };+ });++ const newController = new RemoteServerConfigCtr(mockApp);+ const result = await newController.getAccessToken();++ expect(result).toBeNull();+ });+ });++ describe('getRefreshToken', () => {+ it('should return decrypted refresh token', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(true);+ vi.mocked(safeStorage.decryptString).mockImplementation((buffer: Buffer) =>+ buffer.toString(),+ );++ await controller.saveTokens('test-access-token', 'test-refresh-token');++ const result = await controller.getRefreshToken();++ expect(result).toBe('test-refresh-token');+ });++ it('should return null when no token exists', async () => {+ mockStoreManager.get.mockImplementation((key) => {+ if (key === 'encryptedTokens') {+ return null;+ }+ return { active: false, storageMode: 'local' };+ });++ const newController = new RemoteServerConfigCtr(mockApp);+ const result = await newController.getRefreshToken();++ expect(result).toBeNull();+ });+ });++ describe('clearTokens', () => {+ it('should clear all tokens from memory and store', async () => {+ await controller.saveTokens('access', 'refresh', 3600);+ await controller.clearTokens();++ expect(mockStoreManager.delete).toHaveBeenCalledWith('encryptedTokens');++ // Verify tokens are cleared from memory+ const accessToken = await controller.getAccessToken();+ expect(accessToken).toBeNull();+ });+ });++ describe('getTokenExpiresAt', () => {+ it('should return expiration time after saving tokens with expiration', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(true);++ const beforeSave = Date.now();+ await controller.saveTokens('access', 'refresh', 3600);+ const afterSave = Date.now();++ const expiresAt = controller.getTokenExpiresAt();++ expect(expiresAt).toBeDefined();+ expect(expiresAt).toBeGreaterThanOrEqual(beforeSave + 3600 * 1000);+ expect(expiresAt).toBeLessThanOrEqual(afterSave + 3600 * 1000);+ });++ it('should return undefined when no expiration is set', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(true);++ await controller.saveTokens('access', 'refresh');++ const expiresAt = controller.getTokenExpiresAt();++ expect(expiresAt).toBeUndefined();+ });+ });++ describe('isTokenExpiringSoon', () => {+ it('should return false when no expiration is set', () => {+ const result = controller.isTokenExpiringSoon();++ expect(result).toBe(false);+ });++ it('should return false when token is not expiring soon', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(true);++ // Token expires in 1 hour+ await controller.saveTokens('access', 'refresh', 3600);++ // Default buffer is 5 minutes+ const result = controller.isTokenExpiringSoon();++ expect(result).toBe(false);+ });++ it('should return true when token is within buffer time', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(true);++ // Token expires in 2 minutes+ await controller.saveTokens('access', 'refresh', 120);++ // Default buffer is 5 minutes, so token is expiring soon+ const result = controller.isTokenExpiringSoon();++ expect(result).toBe(true);+ });++ it('should respect custom buffer time', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(true);++ // Token expires in 10 minutes+ await controller.saveTokens('access', 'refresh', 600);++ // With 15 minute buffer, should be expiring soon+ const result = controller.isTokenExpiringSoon(15 * 60 * 1000);++ expect(result).toBe(true);+ });+ });++ describe('refreshAccessToken', () => {+ let mockFetch: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ mockFetch = vi.fn();+ global.fetch = mockFetch;+ });++ it('should return error when remote server is not active', async () => {+ mockStoreManager.get.mockImplementation((key) => {+ if (key === 'dataSyncConfig') {+ return { active: false, storageMode: 'local' };+ }+ return null;+ });++ const result = await controller.refreshAccessToken();++ expect(result.success).toBe(false);+ expect(result.error).toContain('not active');+ });++ it('should return error when no refresh token available', async () => {+ mockStoreManager.get.mockImplementation((key) => {+ if (key === 'dataSyncConfig') {+ return {+ active: true,+ remoteServerUrl: 'https://server.com',+ storageMode: 'selfHost',+ };+ }+ if (key === 'encryptedTokens') {+ return null;+ }+ return null;+ });++ const newController = new RemoteServerConfigCtr(mockApp);+ const result = await newController.refreshAccessToken();++ expect(result.success).toBe(false);+ expect(result.error).toContain('No refresh token');+ });++ it('should refresh token successfully', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(true);+ vi.mocked(safeStorage.decryptString).mockImplementation((buffer: Buffer) =>+ buffer.toString(),+ );++ mockStoreManager.get.mockImplementation((key) => {+ if (key === 'dataSyncConfig') {+ return {+ active: true,+ remoteServerUrl: 'https://server.com',+ storageMode: 'selfHost',+ };+ }+ return null;+ });++ // Save initial tokens+ await controller.saveTokens('old-access', 'old-refresh');++ mockFetch.mockResolvedValue({+ json: () =>+ Promise.resolve({+ access_token: 'new-access-token',+ expires_in: 3600,+ refresh_token: 'new-refresh-token',+ }),+ ok: true,+ });++ const result = await controller.refreshAccessToken();++ expect(result.success).toBe(true);+ expect(mockFetch).toHaveBeenCalledWith(+ 'https://server.com/oidc/token',+ expect.objectContaining({+ body: expect.stringContaining('grant_type=refresh_token'),+ method: 'POST',+ }),+ );+ });++ it('should handle refresh failure', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(true);+ vi.mocked(safeStorage.decryptString).mockImplementation((buffer: Buffer) =>+ buffer.toString(),+ );++ mockStoreManager.get.mockImplementation((key) => {+ if (key === 'dataSyncConfig') {+ return {+ active: true,+ remoteServerUrl: 'https://server.com',+ storageMode: 'selfHost',+ };+ }+ return null;+ });++ await controller.saveTokens('old-access', 'old-refresh');++ mockFetch.mockResolvedValue({+ json: () => Promise.resolve({ error: 'invalid_grant' }),+ ok: false,+ status: 400,+ statusText: 'Bad Request',+ });++ const result = await controller.refreshAccessToken();++ expect(result.success).toBe(false);+ expect(result.error).toContain('Token refresh failed');+ });++ it('should handle missing tokens in response', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(true);+ vi.mocked(safeStorage.decryptString).mockImplementation((buffer: Buffer) =>+ buffer.toString(),+ );++ mockStoreManager.get.mockImplementation((key) => {+ if (key === 'dataSyncConfig') {+ return {+ active: true,+ remoteServerUrl: 'https://server.com',+ storageMode: 'selfHost',+ };+ }+ return null;+ });++ await controller.saveTokens('old-access', 'old-refresh');++ mockFetch.mockResolvedValue({+ json: () => Promise.resolve({}), // Missing tokens+ ok: true,+ });++ const result = await controller.refreshAccessToken();++ expect(result.success).toBe(false);+ expect(result.error).toContain('Missing tokens');+ });++ it('should handle concurrent refresh requests by returning same result', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(true);+ vi.mocked(safeStorage.decryptString).mockImplementation((buffer: Buffer) =>+ buffer.toString(),+ );++ mockStoreManager.get.mockImplementation((key) => {+ if (key === 'dataSyncConfig') {+ return {+ active: true,+ remoteServerUrl: 'https://server.com',+ storageMode: 'selfHost',+ };+ }+ return null;+ });++ await controller.saveTokens('old-access', 'old-refresh');++ let resolvePromise: (value: any) => void;+ const delayedResponse = new Promise((resolve) => {+ resolvePromise = resolve;+ });++ mockFetch.mockReturnValue(delayedResponse);++ // Start two concurrent refresh requests+ const promise1 = controller.refreshAccessToken();+ const promise2 = controller.refreshAccessToken();++ // Resolve the fetch+ resolvePromise!({+ json: () =>+ Promise.resolve({+ access_token: 'new-access',+ expires_in: 3600,+ refresh_token: 'new-refresh',+ }),+ ok: true,+ });++ const [result1, result2] = await Promise.all([promise1, promise2]);++ // Both results should be equal (same success)+ expect(result1.success).toBe(true);+ expect(result2.success).toBe(true);+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });++ it('should handle network errors', async () => {+ const { safeStorage } = await import('electron');+ vi.mocked(safeStorage.isEncryptionAvailable).mockReturnValue(true);+ vi.mocked(safeStorage.decryptString).mockImplementation((buffer: Buffer) =>+ buffer.toString(),+ );++ mockStoreManager.get.mockImplementation((key) => {+ if (key === 'dataSyncConfig') {+ return {+ active: true,+ remoteServerUrl: 'https://server.com',+ storageMode: 'selfHost',+ };+ }+ return null;+ });++ await controller.saveTokens('old-access', 'old-refresh');++ mockFetch.mockRejectedValue(new Error('Network error'));++ const result = await controller.refreshAccessToken();++ expect(result.success).toBe(false);+ expect(result.error).toContain('Network error');+ });+ });++ describe('afterAppReady', () => {+ it('should load tokens from store', () => {+ mockStoreManager.get.mockImplementation((key) => {+ if (key === 'encryptedTokens') {+ return {+ accessToken: 'stored-access',+ expiresAt: Date.now() + 3600000,+ refreshToken: 'stored-refresh',+ };+ }+ return { active: false, storageMode: 'local' };+ });++ const newController = new RemoteServerConfigCtr(mockApp);+ newController.afterAppReady();++ // Verify tokens were loaded by checking getTokenExpiresAt+ expect(newController.getTokenExpiresAt()).toBeDefined();+ });+ });++ describe('getRemoteServerUrl', () => {+ it('should return official cloud server for cloud mode', async () => {+ mockStoreManager.get.mockReturnValue({+ active: true,+ storageMode: 'cloud',+ });++ const result = await controller.getRemoteServerUrl();++ expect(result).toBe('https://cloud.lobehub.com');+ });++ it('should return custom URL for selfHost mode', async () => {+ mockStoreManager.get.mockReturnValue({+ active: true,+ remoteServerUrl: 'https://my-server.com',+ storageMode: 'selfHost',+ });++ const result = await controller.getRemoteServerUrl();++ expect(result).toBe('https://my-server.com');+ });++ it('should use provided config instead of stored config', async () => {+ const customConfig: DataSyncConfig = {+ active: true,+ remoteServerUrl: 'https://custom-server.com',+ storageMode: 'selfHost',+ };++ const result = await controller.getRemoteServerUrl(customConfig);++ expect(result).toBe('https://custom-server.com');+ });+ });+});diff --git a/apps/desktop/src/main/controllers/__tests__/RemoteServerSyncCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/RemoteServerSyncCtr.test.tsnew file mode 100644index 00000000000..587cde24457--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/RemoteServerSyncCtr.test.ts@@ -0,0 +1,372 @@+import { ProxyTRPCRequestParams } from '@lobechat/electron-client-ipc';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import RemoteServerSyncCtr from '../RemoteServerSyncCtr';++// Mock logger+vi.mock('@/utils/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ }),+}));++// Mock electron+vi.mock('electron', () => ({+ app: {+ getAppPath: vi.fn(() => '/mock/app/path'),+ getPath: vi.fn(() => '/mock/user/data'),+ },+ ipcMain: {+ on: vi.fn(),+ },+}));++// Mock electron-is+vi.mock('electron-is', () => ({+ dev: vi.fn(() => false),+ linux: vi.fn(() => false),+ macOS: vi.fn(() => false),+ windows: vi.fn(() => false),+}));++// Mock http and https modules+vi.mock('node:http', () => ({+ default: {+ request: vi.fn(),+ },+}));++vi.mock('node:https', () => ({+ default: {+ request: vi.fn(),+ },+}));++// Mock proxy agents+vi.mock('http-proxy-agent', () => ({+ HttpProxyAgent: vi.fn().mockImplementation(() => ({})),+}));++vi.mock('https-proxy-agent', () => ({+ HttpsProxyAgent: vi.fn().mockImplementation(() => ({})),+}));++// Mock RemoteServerConfigCtr+const mockRemoteServerConfigCtr = {+ getRemoteServerConfig: vi.fn(),+ getRemoteServerUrl: vi.fn(),+ getAccessToken: vi.fn(),+ refreshAccessToken: vi.fn(),+};++const mockStoreManager = {+ get: vi.fn().mockReturnValue({+ enableProxy: false,+ proxyServer: '',+ proxyPort: '',+ proxyType: 'http',+ }),+};++const mockApp = {+ getController: vi.fn(() => mockRemoteServerConfigCtr),+ storeManager: mockStoreManager,+} as unknown as App;++describe('RemoteServerSyncCtr', () => {+ let controller: RemoteServerSyncCtr;++ beforeEach(() => {+ vi.clearAllMocks();+ controller = new RemoteServerSyncCtr(mockApp);+ });++ describe('proxyTRPCRequest', () => {+ const baseParams: ProxyTRPCRequestParams = {+ urlPath: '/trpc/test.query',+ method: 'GET',+ headers: { 'content-type': 'application/json' },+ };++ it('should return 503 when remote server sync is not active', async () => {+ mockRemoteServerConfigCtr.getRemoteServerConfig.mockResolvedValue({+ active: false,+ storageMode: 'cloud',+ });++ const result = await controller.proxyTRPCRequest(baseParams);++ expect(result.status).toBe(503);+ expect(result.statusText).toBe('Remote server sync not active or configured');+ });++ it('should return 503 when selfHost mode without remoteServerUrl', async () => {+ mockRemoteServerConfigCtr.getRemoteServerConfig.mockResolvedValue({+ active: true,+ storageMode: 'selfHost',+ remoteServerUrl: '',+ });++ const result = await controller.proxyTRPCRequest(baseParams);++ expect(result.status).toBe(503);+ expect(result.statusText).toBe('Remote server sync not active or configured');+ });++ it('should return 401 when no access token is available', async () => {+ mockRemoteServerConfigCtr.getRemoteServerConfig.mockResolvedValue({+ active: true,+ storageMode: 'cloud',+ });+ mockRemoteServerConfigCtr.getRemoteServerUrl.mockResolvedValue('https://api.example.com');+ mockRemoteServerConfigCtr.getAccessToken.mockResolvedValue(null);++ // Mock https.request to simulate the forwardRequest behavior+ const https = await import('node:https');+ const mockRequest = vi.fn().mockImplementation((options, callback) => {+ // Simulate response+ const mockResponse = {+ statusCode: 401,+ statusMessage: 'Authentication required, missing token',+ headers: {},+ on: vi.fn((event, handler) => {+ if (event === 'data') {+ handler(Buffer.from(''));+ }+ if (event === 'end') {+ handler();+ }+ }),+ };+ callback(mockResponse);+ return {+ on: vi.fn(),+ write: vi.fn(),+ end: vi.fn(),+ };+ });+ vi.mocked(https.default.request).mockImplementation(mockRequest);++ const result = await controller.proxyTRPCRequest(baseParams);++ expect(result.status).toBe(401);+ });++ it('should forward request successfully when configured properly', async () => {+ mockRemoteServerConfigCtr.getRemoteServerConfig.mockResolvedValue({+ active: true,+ storageMode: 'cloud',+ });+ mockRemoteServerConfigCtr.getRemoteServerUrl.mockResolvedValue('https://api.example.com');+ mockRemoteServerConfigCtr.getAccessToken.mockResolvedValue('valid-token');++ const https = await import('node:https');+ const mockRequest = vi.fn().mockImplementation((options, callback) => {+ const mockResponse = {+ statusCode: 200,+ statusMessage: 'OK',+ headers: { 'content-type': 'application/json' },+ on: vi.fn((event, handler) => {+ if (event === 'data') {+ handler(Buffer.from('{"success":true}'));+ }+ if (event === 'end') {+ handler();+ }+ }),+ };+ callback(mockResponse);+ return {+ on: vi.fn(),+ write: vi.fn(),+ end: vi.fn(),+ };+ });+ vi.mocked(https.default.request).mockImplementation(mockRequest);++ const result = await controller.proxyTRPCRequest(baseParams);++ expect(result.status).toBe(200);+ expect(result.statusText).toBe('OK');+ });++ it('should retry request after token refresh on 401', async () => {+ mockRemoteServerConfigCtr.getRemoteServerConfig.mockResolvedValue({+ active: true,+ storageMode: 'cloud',+ });+ mockRemoteServerConfigCtr.getRemoteServerUrl.mockResolvedValue('https://api.example.com');+ mockRemoteServerConfigCtr.getAccessToken+ .mockResolvedValueOnce('expired-token')+ .mockResolvedValueOnce('new-valid-token');+ mockRemoteServerConfigCtr.refreshAccessToken.mockResolvedValue({ success: true });++ const https = await import('node:https');+ let callCount = 0;+ const mockRequest = vi.fn().mockImplementation((options, callback) => {+ callCount++;+ const mockResponse = {+ statusCode: callCount === 1 ? 401 : 200,+ statusMessage: callCount === 1 ? 'Unauthorized' : 'OK',+ headers: { 'content-type': 'application/json' },+ on: vi.fn((event, handler) => {+ if (event === 'data') {+ handler(Buffer.from(callCount === 1 ? '' : '{"success":true}'));+ }+ if (event === 'end') {+ handler();+ }+ }),+ };+ callback(mockResponse);+ return {+ on: vi.fn(),+ write: vi.fn(),+ end: vi.fn(),+ };+ });+ vi.mocked(https.default.request).mockImplementation(mockRequest);++ const result = await controller.proxyTRPCRequest(baseParams);++ expect(mockRemoteServerConfigCtr.refreshAccessToken).toHaveBeenCalled();+ expect(result.status).toBe(200);+ });++ it('should keep 401 response when token refresh fails', async () => {+ mockRemoteServerConfigCtr.getRemoteServerConfig.mockResolvedValue({+ active: true,+ storageMode: 'cloud',+ });+ mockRemoteServerConfigCtr.getRemoteServerUrl.mockResolvedValue('https://api.example.com');+ mockRemoteServerConfigCtr.getAccessToken.mockResolvedValue('expired-token');+ mockRemoteServerConfigCtr.refreshAccessToken.mockResolvedValue({+ success: false,+ error: 'Refresh failed',+ });++ const https = await import('node:https');+ const mockRequest = vi.fn().mockImplementation((options, callback) => {+ const mockResponse = {+ statusCode: 401,+ statusMessage: 'Unauthorized',+ headers: {},+ on: vi.fn((event, handler) => {+ if (event === 'data') {+ handler(Buffer.from(''));+ }+ if (event === 'end') {+ handler();+ }+ }),+ };+ callback(mockResponse);+ return {+ on: vi.fn(),+ write: vi.fn(),+ end: vi.fn(),+ };+ });+ vi.mocked(https.default.request).mockImplementation(mockRequest);++ const result = await controller.proxyTRPCRequest(baseParams);++ expect(mockRemoteServerConfigCtr.refreshAccessToken).toHaveBeenCalled();+ expect(result.status).toBe(401);+ });++ it('should handle request error gracefully', async () => {+ mockRemoteServerConfigCtr.getRemoteServerConfig.mockResolvedValue({+ active: true,+ storageMode: 'cloud',+ });+ mockRemoteServerConfigCtr.getRemoteServerUrl.mockResolvedValue('https://api.example.com');+ mockRemoteServerConfigCtr.getAccessToken.mockResolvedValue('valid-token');++ const https = await import('node:https');+ const mockRequest = vi.fn().mockImplementation((options, callback) => {+ return {+ on: vi.fn((event, handler) => {+ if (event === 'error') {+ handler(new Error('Network error'));+ }+ }),+ write: vi.fn(),+ end: vi.fn(),+ };+ });+ vi.mocked(https.default.request).mockImplementation(mockRequest);++ const result = await controller.proxyTRPCRequest(baseParams);++ expect(result.status).toBe(502);+ expect(result.statusText).toBe('Error forwarding request');+ });++ it('should include request body when provided', async () => {+ mockRemoteServerConfigCtr.getRemoteServerConfig.mockResolvedValue({+ active: true,+ storageMode: 'cloud',+ });+ mockRemoteServerConfigCtr.getRemoteServerUrl.mockResolvedValue('https://api.example.com');+ mockRemoteServerConfigCtr.getAccessToken.mockResolvedValue('valid-token');++ const https = await import('node:https');+ const mockWrite = vi.fn();+ const mockRequest = vi.fn().mockImplementation((options, callback) => {+ const mockResponse = {+ statusCode: 200,+ statusMessage: 'OK',+ headers: {},+ on: vi.fn((event, handler) => {+ if (event === 'data') {+ handler(Buffer.from('{"success":true}'));+ }+ if (event === 'end') {+ handler();+ }+ }),+ };+ callback(mockResponse);+ return {+ on: vi.fn(),+ write: mockWrite,+ end: vi.fn(),+ };+ });+ vi.mocked(https.default.request).mockImplementation(mockRequest);++ const paramsWithBody: ProxyTRPCRequestParams = {+ ...baseParams,+ method: 'POST',+ body: '{"data":"test"}',+ };++ await controller.proxyTRPCRequest(paramsWithBody);++ expect(mockWrite).toHaveBeenCalledWith('{"data":"test"}', 'utf8');+ });+ });++ describe('afterAppReady', () => {+ it('should register stream:start IPC handler', async () => {+ const { ipcMain } = await import('electron');++ controller.afterAppReady();++ expect(ipcMain.on).toHaveBeenCalledWith('stream:start', expect.any(Function));+ });+ });++ describe('destroy', () => {+ it('should clean up resources', () => {+ // destroy method doesn't throw+ expect(() => controller.destroy()).not.toThrow();+ });+ });+});diff --git a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.tsnew file mode 100644index 00000000000..eb6dd37c028--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts@@ -0,0 +1,276 @@+import { ThemeMode } from '@lobechat/electron-client-ipc';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import SystemController from '../SystemCtr';++// Mock logger+vi.mock('@/utils/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ }),+}));++// Mock electron+vi.mock('electron', () => ({+ app: {+ getLocale: vi.fn(() => 'en-US'),+ getPath: vi.fn((name: string) => `/mock/path/${name}`),+ },+ nativeTheme: {+ on: vi.fn(),+ shouldUseDarkColors: false,+ },+ shell: {+ openExternal: vi.fn().mockResolvedValue(undefined),+ },+ systemPreferences: {+ isTrustedAccessibilityClient: vi.fn(() => true),+ },+}));++// Mock electron-is+vi.mock('electron-is', () => ({+ macOS: vi.fn(() => true),+}));++// Mock node:fs+vi.mock('node:fs', () => ({+ readFileSync: vi.fn(),+ writeFileSync: vi.fn(),+}));++// Mock @/const/dir+vi.mock('@/const/dir', () => ({+ DB_SCHEMA_HASH_FILENAME: 'db-schema-hash.txt',+ LOCAL_DATABASE_DIR: 'database',+ userDataDir: '/mock/user/data',+}));++// Mock browserManager+const mockBrowserManager = {+ broadcastToAllWindows: vi.fn(),+ handleAppThemeChange: vi.fn(),+};++// Mock storeManager+const mockStoreManager = {+ get: vi.fn(),+ set: vi.fn(),+};++// Mock i18n+const mockI18n = {+ changeLanguage: vi.fn().mockResolvedValue(undefined),+};++const mockApp = {+ appStoragePath: '/mock/storage',+ browserManager: mockBrowserManager,+ i18n: mockI18n,+ storeManager: mockStoreManager,+} as unknown as App;++describe('SystemController', () => {+ let controller: SystemController;++ beforeEach(() => {+ vi.clearAllMocks();+ controller = new SystemController(mockApp);+ });++ describe('getAppState', () => {+ it('should return app state with system info', async () => {+ const result = await controller.getAppState();++ expect(result).toMatchObject({+ arch: expect.any(String),+ platform: expect.any(String),+ systemAppearance: 'light',+ userPath: {+ desktop: '/mock/path/desktop',+ documents: '/mock/path/documents',+ downloads: '/mock/path/downloads',+ home: '/mock/path/home',+ music: '/mock/path/music',+ pictures: '/mock/path/pictures',+ userData: '/mock/path/userData',+ videos: '/mock/path/videos',+ },+ });+ });++ it('should return dark appearance when nativeTheme is dark', async () => {+ const { nativeTheme } = await import('electron');+ Object.defineProperty(nativeTheme, 'shouldUseDarkColors', { value: true });++ const result = await controller.getAppState();++ expect(result.systemAppearance).toBe('dark');++ // Reset+ Object.defineProperty(nativeTheme, 'shouldUseDarkColors', { value: false });+ });+ });++ describe('checkAccessibilityForMacOS', () => {+ it('should check accessibility on macOS', async () => {+ const { systemPreferences } = await import('electron');++ controller.checkAccessibilityForMacOS();++ expect(systemPreferences.isTrustedAccessibilityClient).toHaveBeenCalledWith(true);+ });++ it('should return undefined on non-macOS', async () => {+ const { macOS } = await import('electron-is');+ vi.mocked(macOS).mockReturnValue(false);++ const result = controller.checkAccessibilityForMacOS();++ expect(result).toBeUndefined();++ // Reset+ vi.mocked(macOS).mockReturnValue(true);+ });+ });++ describe('openExternalLink', () => {+ it('should open external link', async () => {+ const { shell } = await import('electron');++ await controller.openExternalLink('https://example.com');++ expect(shell.openExternal).toHaveBeenCalledWith('https://example.com');+ });+ });++ describe('updateLocale', () => {+ it('should update locale and broadcast change', async () => {+ const result = await controller.updateLocale('zh-CN');++ expect(mockStoreManager.set).toHaveBeenCalledWith('locale', 'zh-CN');+ expect(mockI18n.changeLanguage).toHaveBeenCalledWith('zh-CN');+ expect(mockBrowserManager.broadcastToAllWindows).toHaveBeenCalledWith('localeChanged', {+ locale: 'zh-CN',+ });+ expect(result).toEqual({ success: true });+ });++ it('should use system locale when set to auto', async () => {+ await controller.updateLocale('auto');++ expect(mockI18n.changeLanguage).toHaveBeenCalledWith('en-US');+ });+ });++ describe('updateThemeModeHandler', () => {+ it('should update theme mode and broadcast change', async () => {+ const themeMode: ThemeMode = 'dark';++ await controller.updateThemeModeHandler(themeMode);++ expect(mockStoreManager.set).toHaveBeenCalledWith('themeMode', 'dark');+ expect(mockBrowserManager.broadcastToAllWindows).toHaveBeenCalledWith('themeChanged', {+ themeMode: 'dark',+ });+ expect(mockBrowserManager.handleAppThemeChange).toHaveBeenCalled();+ });+ });++ describe('getDatabasePath', () => {+ it('should return database path', async () => {+ const result = await controller.getDatabasePath();++ expect(result).toBe('/mock/storage/database');+ });+ });++ describe('getDatabaseSchemaHash', () => {+ it('should return schema hash when file exists', async () => {+ const { readFileSync } = await import('node:fs');+ vi.mocked(readFileSync).mockReturnValue('abc123');++ const result = await controller.getDatabaseSchemaHash();++ expect(result).toBe('abc123');+ });++ it('should return undefined when file does not exist', async () => {+ const { readFileSync } = await import('node:fs');+ vi.mocked(readFileSync).mockImplementation(() => {+ throw new Error('File not found');+ });++ const result = await controller.getDatabaseSchemaHash();++ expect(result).toBeUndefined();+ });+ });++ describe('getUserDataPath', () => {+ it('should return user data path', async () => {+ const result = await controller.getUserDataPath();++ expect(result).toBe('/mock/user/data');+ });+ });++ describe('setDatabaseSchemaHash', () => {+ it('should write schema hash to file', async () => {+ const { writeFileSync } = await import('node:fs');++ await controller.setDatabaseSchemaHash('newhash123');++ expect(writeFileSync).toHaveBeenCalledWith(+ '/mock/storage/db-schema-hash.txt',+ 'newhash123',+ 'utf8',+ );+ });+ });++ describe('afterAppReady', () => {+ it('should initialize system theme listener', async () => {+ const { nativeTheme } = await import('electron');++ controller.afterAppReady();++ expect(nativeTheme.on).toHaveBeenCalledWith('updated', expect.any(Function));+ });++ it('should not initialize listener twice', async () => {+ const { nativeTheme } = await import('electron');++ controller.afterAppReady();+ controller.afterAppReady();++ // Should only be called once+ expect(nativeTheme.on).toHaveBeenCalledTimes(1);+ });++ it('should broadcast system theme change when theme updates', async () => {+ const { nativeTheme } = await import('electron');++ controller.afterAppReady();++ // Get the callback that was registered+ const callback = vi.mocked(nativeTheme.on).mock.calls[0][1] as () => void;++ // Simulate theme change to dark+ Object.defineProperty(nativeTheme, 'shouldUseDarkColors', { value: true });+ callback();++ expect(mockBrowserManager.broadcastToAllWindows).toHaveBeenCalledWith('systemThemeChanged', {+ themeMode: 'dark',+ });++ // Reset+ Object.defineProperty(nativeTheme, 'shouldUseDarkColors', { value: false });+ });+ });+});diff --git a/apps/desktop/src/main/controllers/__tests__/UploadFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/UploadFileCtr.test.tsnew file mode 100644index 00000000000..7c82c9fcc2c--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/UploadFileCtr.test.ts@@ -0,0 +1,171 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import UploadFileCtr from '../UploadFileCtr';++// Mock FileService module to prevent electron dependency issues+vi.mock('@/services/fileSrv', () => ({+ default: class MockFileService {},+}));++// Mock FileService instance methods+const mockFileService = {+ uploadFile: vi.fn(),+ getFilePath: vi.fn(),+ getFileHTTPURL: vi.fn(),+ deleteFiles: vi.fn(),+};++const mockApp = {+ getService: vi.fn(() => mockFileService),+} as unknown as App;++describe('UploadFileCtr', () => {+ let controller: UploadFileCtr;++ beforeEach(() => {+ vi.clearAllMocks();+ controller = new UploadFileCtr(mockApp);+ });++ describe('uploadFile', () => {+ it('should upload file successfully', async () => {+ const params = {+ hash: 'abc123',+ path: '/test/file.txt',+ dataType: 'base64' as const,+ data: 'dGVzdCBjb250ZW50',+ filename: 'file.txt',+ fileType: 'txt',+ };+ const expectedResult = { id: 'file-id-123', url: '/files/file-id-123' };+ mockFileService.uploadFile.mockResolvedValue(expectedResult);++ const result = await controller.uploadFile(params);++ expect(result).toEqual(expectedResult);+ expect(mockFileService.uploadFile).toHaveBeenCalledWith(params);+ });++ it('should handle upload error', async () => {+ const params = {+ hash: 'abc123',+ path: '/test/file.txt',+ dataType: 'base64' as const,+ data: 'dGVzdCBjb250ZW50',+ filename: 'file.txt',+ fileType: 'txt',+ };+ const error = new Error('Upload failed');+ mockFileService.uploadFile.mockRejectedValue(error);++ await expect(controller.uploadFile(params)).rejects.toThrow('Upload failed');+ });+ });++ describe('getFileUrlById', () => {+ it('should get file path by id successfully', async () => {+ const fileId = 'file-id-123';+ const expectedPath = '/files/abc123.txt';+ mockFileService.getFilePath.mockResolvedValue(expectedPath);++ const result = await controller.getFileUrlById(fileId);++ expect(result).toBe(expectedPath);+ expect(mockFileService.getFilePath).toHaveBeenCalledWith(fileId);+ });++ it('should handle get file path error', async () => {+ const fileId = 'non-existent-id';+ const error = new Error('File not found');+ mockFileService.getFilePath.mockRejectedValue(error);++ await expect(controller.getFileUrlById(fileId)).rejects.toThrow('File not found');+ });+ });++ describe('getFileHTTPURL', () => {+ it('should get file HTTP URL successfully', async () => {+ const filePath = '/files/abc123.txt';+ const expectedUrl = 'http://localhost:3000/files/abc123.txt';+ mockFileService.getFileHTTPURL.mockResolvedValue(expectedUrl);++ const result = await controller.getFileHTTPURL(filePath);++ expect(result).toBe(expectedUrl);+ expect(mockFileService.getFileHTTPURL).toHaveBeenCalledWith(filePath);+ });++ it('should handle get HTTP URL error', async () => {+ const filePath = '/files/abc123.txt';+ const error = new Error('Failed to generate URL');+ mockFileService.getFileHTTPURL.mockRejectedValue(error);++ await expect(controller.getFileHTTPURL(filePath)).rejects.toThrow('Failed to generate URL');+ });+ });++ describe('deleteFiles', () => {+ it('should delete files successfully', async () => {+ const paths = ['/files/file1.txt', '/files/file2.txt'];+ mockFileService.deleteFiles.mockResolvedValue(undefined);++ await controller.deleteFiles(paths);++ expect(mockFileService.deleteFiles).toHaveBeenCalledWith(paths);+ });++ it('should handle delete files error', async () => {+ const paths = ['/files/file1.txt'];+ const error = new Error('Delete failed');+ mockFileService.deleteFiles.mockRejectedValue(error);++ await expect(controller.deleteFiles(paths)).rejects.toThrow('Delete failed');+ });++ it('should handle empty paths array', async () => {+ const paths: string[] = [];+ mockFileService.deleteFiles.mockResolvedValue(undefined);++ await controller.deleteFiles(paths);++ expect(mockFileService.deleteFiles).toHaveBeenCalledWith([]);+ });+ });++ describe('createFile', () => {+ it('should create file successfully', async () => {+ const params = {+ hash: 'xyz789',+ path: '/test/newfile.txt',+ dataType: 'base64' as const,+ data: 'bmV3IGZpbGUgY29udGVudA==',+ filename: 'newfile.txt',+ fileType: 'txt',+ };+ const expectedResult = { id: 'new-file-id', url: '/files/new-file-id' };+ mockFileService.uploadFile.mockResolvedValue(expectedResult);++ const result = await controller.createFile(params);++ expect(result).toEqual(expectedResult);+ expect(mockFileService.uploadFile).toHaveBeenCalledWith(params);+ });++ it('should handle create file error', async () => {+ const params = {+ hash: 'xyz789',+ path: '/test/newfile.txt',+ dataType: 'base64' as const,+ data: 'bmV3IGZpbGUgY29udGVudA==',+ filename: 'newfile.txt',+ fileType: 'txt',+ };+ const error = new Error('Create failed');+ mockFileService.uploadFile.mockRejectedValue(error);++ await expect(controller.createFile(params)).rejects.toThrow('Create failed');+ });+ });+});