diff --git a/src/services/ServiceContainer.test.ts b/src/services/ServiceContainer.test.ts new file mode 100644 index 000000000..d586770a5 --- /dev/null +++ b/src/services/ServiceContainer.test.ts @@ -0,0 +1,173 @@ +import { describe, expect, test, beforeEach, jest } from '@jest/globals'; +import { ServiceContainer } from './ServiceContainer.js'; + +// Mock logger to avoid console output during tests +const mockLogger = { + debug: jest.fn(), + error: jest.fn(), + warn: jest.fn(), +}; + +// Mock the logger import using jest mock hoisting +jest.mock('../util/logger.js', () => mockLogger, { virtual: true }); + +describe('ServiceContainer', () => { + let container: ServiceContainer; + + beforeEach(() => { + container = new ServiceContainer(); + jest.clearAllMocks(); + }); + + describe('Dependency Cascade Reloading', () => { + test('should automatically reload all transitive dependents', async () => { + // Setup service dependency chain: auth -> apiClient -> config -> model + const authValue = { auth: 'auth-value' }; + const apiClientValue = { apiClient: 'api-client-value' }; + const configValue = { config: 'config-value' }; + const modelValue = { model: 'model-value' }; + + let authReloadCount = 0; + let apiClientReloadCount = 0; + let configReloadCount = 0; + let modelReloadCount = 0; + + // Register services with mock factories that track reload count + container.register( + 'auth', + async () => { + authReloadCount++; + return authValue; + }, + [] + ); + + container.register( + 'apiClient', + async () => { + apiClientReloadCount++; + return apiClientValue; + }, + ['auth'] + ); + + container.register( + 'config', + async () => { + configReloadCount++; + return configValue; + }, + ['auth', 'apiClient'] + ); + + container.register( + 'model', + async () => { + modelReloadCount++; + return modelValue; + }, + ['config'] + ); + + // Initial load of all services + await container.get('model'); + + // Verify initial load counts + expect(authReloadCount).toBe(1); + expect(apiClientReloadCount).toBe(1); + expect(configReloadCount).toBe(1); + expect(modelReloadCount).toBe(1); + + // Reload auth service - should cascade to all dependents + await container.reload('auth'); + + // Verify cascade reload occurred - all dependent services should reload + expect(authReloadCount).toBe(2); // auth reloaded + expect(apiClientReloadCount).toBe(2); // apiClient depends on auth + expect(configReloadCount).toBe(2); // config depends on auth and apiClient + expect(modelReloadCount).toBe(2); // model depends on config + }); + + test('should find all transitive dependents correctly', async () => { + // Setup complex dependency graph + container.register('serviceA', async () => ({}), []); + container.register('serviceB', async () => ({}), ['serviceA']); + container.register('serviceC', async () => ({}), ['serviceA']); + container.register('serviceD', async () => ({}), ['serviceB', 'serviceC']); + container.register('serviceE', async () => ({}), ['serviceD']); + + // Use reflection to access private method for testing + const findAllDependents = (container as any).findAllDependents.bind(container); + + const dependentsOfA = findAllDependents('serviceA'); + + // serviceA should have all others as transitive dependents + expect(dependentsOfA.sort()).toEqual(['serviceB', 'serviceC', 'serviceD', 'serviceE']); + }); + + test('should handle circular dependencies gracefully', async () => { + // This test ensures the findAllDependents doesn't get stuck in infinite loops + + // Setup a circular dependency (which shouldn't happen in practice but we handle it) + container.register('serviceX', async () => ({}), ['serviceY']); + container.register('serviceY', async () => ({}), ['serviceX']); + + // Use reflection to access private method for testing + const findAllDependents = (container as any).findAllDependents.bind(container); + + // Should not hang and should return both services as circular dependents + const dependentsOfX = findAllDependents('serviceX'); + const dependentsOfY = findAllDependents('serviceY'); + + // Both should contain each other due to circular dependency + expect(dependentsOfX).toContain('serviceY'); + expect(dependentsOfY).toContain('serviceX'); + }); + + test('should emit events during cascade reload', async () => { + const events: string[] = []; + + container.register('parent', async () => ({ parent: true }), []); + container.register('child', async () => ({ child: true }), ['parent']); + + // Listen for events + container.on('parent:loading', () => events.push('parent:loading')); + container.on('parent:ready', () => events.push('parent:ready')); + container.on('child:loading', () => events.push('child:loading')); + container.on('child:ready', () => events.push('child:ready')); + + // Initial load + await container.get('child'); + events.length = 0; // Clear events + + // Reload parent - should cascade to child + await container.reload('parent'); + + // Verify both services went through loading cycle + expect(events).toContain('parent:loading'); + expect(events).toContain('parent:ready'); + expect(events).toContain('child:loading'); + expect(events).toContain('child:ready'); + }); + + test('should preserve service state when no dependents exist', async () => { + let reloadCount = 0; + + container.register('standalone', async () => { + reloadCount++; + return { standalone: true }; + }, []); + + // Load initially + await container.get('standalone'); + expect(reloadCount).toBe(1); + + // Reload - only this service should reload + await container.reload('standalone'); + expect(reloadCount).toBe(2); + + // Should still be ready + expect(container.isReady('standalone')).toBe(true); + }); + }); +}); \ No newline at end of file diff --git a/src/services/ServiceContainer.ts b/src/services/ServiceContainer.ts index 24b2135fa..35f346034 100644 --- a/src/services/ServiceContainer.ts +++ b/src/services/ServiceContainer.ts @@ -128,22 +128,61 @@ export class ServiceContainer extends EventEmitter { } /** - * Reload a service (and dependents) + * Reload a service (and all transitive dependents) */ async reload(serviceName: string): Promise { logger.debug(`Reloading service: ${serviceName}`); - // Find all services that depend on this one - const dependents = Array.from(this.dependencies.entries()) - .filter(([_, deps]) => deps.includes(serviceName)) - .map(([name, _]) => name); + // Find all services that depend on this one (recursively) + const dependents = this.findAllDependents(serviceName); + + logger.debug(`Found dependents for ${serviceName}:`, dependents); - // Reset this service and all dependents + // Reset this service and all dependents to ensure fresh reload this.resetService(serviceName); dependents.forEach(dep => this.resetService(dep)); - // Reload - return this.load(serviceName); + // Now reload ALL services that were reset, starting with the root service + // This ensures proper dependency order and that all dependents get reloaded + const allToReload = [serviceName, ...dependents]; + + // Reset ALL services first to ensure clean state + allToReload.forEach(name => this.resetService(name)); + + // Load all services in dependency order - starting with the root service + // will naturally load its dependents when they're requested + const results = await Promise.all( + allToReload.map(name => this.load(name)) + ); + + // Return the value of the primary service that was reloaded + return results[0] as T; + } + + /** + * Find all services that transitively depend on the given service + */ + private findAllDependents(serviceName: string): string[] { + const result = new Set(); + const visited = new Set(); + + const findDeps = (name: string) => { + if (visited.has(name)) return; + visited.add(name); + + // Find direct dependents + const directDependents = Array.from(this.dependencies.entries()) + .filter(([_, deps]) => deps.includes(name)) + .map(([depName, _]) => depName); + + for (const dependent of directDependents) { + result.add(dependent); + findDeps(dependent); // Recurse for transitive dependencies + } + }; + + findDeps(serviceName); + return Array.from(result); } /** diff --git a/src/slashCommands.test.ts b/src/slashCommands.test.ts new file mode 100644 index 000000000..fe1cfd026 --- /dev/null +++ b/src/slashCommands.test.ts @@ -0,0 +1,216 @@ +import { describe, expect, test, beforeEach, afterEach, jest } from '@jest/globals'; +import { handleSlashCommands } from './slashCommands.js'; + +// Mock the services +const mockAuthService = { + login: jest.fn(), + logout: jest.fn(), + switchOrganization: jest.fn(), + getAvailableOrganizations: jest.fn(), +}; + +const mockServices = { + auth: mockAuthService, +}; + +const mockReloadService = jest.fn(); +const mockServiceNames = { + AUTH: 'auth', + API_CLIENT: 'apiClient', + CONFIG: 'config', + MODEL: 'model', + MCP: 'mcp', +}; + +// Mock the auth functions +const mockIsAuthenticated = jest.fn(); +const mockIsAuthenticatedConfig = jest.fn(); +const mockLoadAuthConfig = jest.fn(); + +// Mock command functions +const mockGetAllSlashCommands = jest.fn(); + +// Setup mocks +jest.mock('./services/index.js', () => ({ + services: mockServices, + reloadService: mockReloadService, + SERVICE_NAMES: mockServiceNames, +})); + +jest.mock('./auth/workos.js', () => ({ + isAuthenticated: mockIsAuthenticated, + isAuthenticatedConfig: mockIsAuthenticatedConfig, + loadAuthConfig: mockLoadAuthConfig, +})); + +jest.mock('./commands/commands.js', () => ({ + getAllSlashCommands: mockGetAllSlashCommands, +})); + +// Mock console to avoid output during tests +const originalConsole = console; +const mockConsole = { + info: jest.fn(), + error: jest.fn(), + log: jest.fn(), +}; + +describe('handleSlashCommands', () => { + const mockAssistant = { + name: 'test-assistant', + prompts: [ + { name: 'test', prompt: 'Test prompt: ' } + ] + }; + + beforeEach(() => { + Object.assign(console, mockConsole); + jest.clearAllMocks(); + + mockGetAllSlashCommands.mockReturnValue([ + { name: 'help', description: 'Show help' }, + { name: 'login', description: 'Login to Continue' } + ]); + }); + + afterEach(() => { + Object.assign(console, originalConsole); + }); + + describe('Automatic Service Cascade Reloading', () => { + test('login command should trigger automatic cascade reload via auth service', async () => { + const newAuthState = { + authConfig: { userEmail: 'test@example.com' }, + isAuthenticated: true, + }; + + mockAuthService.login.mockResolvedValue(newAuthState); + mockIsAuthenticatedConfig.mockReturnValue(true); + mockReloadService.mockResolvedValue(undefined); + + const result = await handleSlashCommands('/login', mockAssistant); + + expect(result).not.toBeNull(); + expect(result?.output).toContain('Login successful! All services updated automatically.'); + + // Verify auth service login was called + expect(mockAuthService.login).toHaveBeenCalledTimes(1); + + // Verify automatic cascade reload was triggered - only auth service reload needed + expect(mockReloadService).toHaveBeenCalledTimes(1); + expect(mockReloadService).toHaveBeenCalledWith(mockServiceNames.AUTH); + + // Verify manual service reloads are NOT called + expect(mockReloadService).not.toHaveBeenCalledWith(mockServiceNames.API_CLIENT); + expect(mockReloadService).not.toHaveBeenCalledWith(mockServiceNames.CONFIG); + }); + + test('org switch command should trigger automatic cascade reload via auth service', async () => { + mockAuthService.switchOrganization.mockResolvedValue({ organizationId: 'new-org' }); + mockReloadService.mockResolvedValue(undefined); + + const result = await handleSlashCommands('/org test-org', mockAssistant); + + expect(result).not.toBeNull(); + expect(result?.output).toContain('Switched to organization: test-org. All services updated automatically.'); + + // Verify organization switch was called + expect(mockAuthService.switchOrganization).toHaveBeenCalledWith('test-org'); + + // Verify automatic cascade reload was triggered - only auth service reload needed + expect(mockReloadService).toHaveBeenCalledTimes(1); + expect(mockReloadService).toHaveBeenCalledWith(mockServiceNames.AUTH); + + // Verify manual service reloads are NOT called + expect(mockReloadService).not.toHaveBeenCalledWith(mockServiceNames.CONFIG); + expect(mockReloadService).not.toHaveBeenCalledWith(mockServiceNames.MODEL); + expect(mockReloadService).not.toHaveBeenCalledWith(mockServiceNames.MCP); + }); + + test('org list command should not trigger any reloads', async () => { + const mockOrgs = [ + { id: 'org1', name: 'Organization 1' }, + { id: 'org2', name: 'Organization 2' }, + ]; + + mockAuthService.getAvailableOrganizations.mockResolvedValue(mockOrgs); + + const result = await handleSlashCommands('/org list', mockAssistant); + + expect(result).not.toBeNull(); + expect(result?.output).toContain('Available organizations:'); + expect(result?.output).toContain('org1: Organization 1'); + expect(result?.output).toContain('org2: Organization 2'); + + // Verify NO reload was triggered + expect(mockReloadService).not.toHaveBeenCalled(); + }); + + test('login failure should not trigger any reloads', async () => { + const loginError = new Error('Login failed'); + mockAuthService.login.mockRejectedValue(loginError); + + const result = await handleSlashCommands('/login', mockAssistant); + + expect(result).not.toBeNull(); + expect(result?.output).toContain('Login failed: Login failed'); + + // Verify NO reload was triggered on failure + expect(mockReloadService).not.toHaveBeenCalled(); + }); + + test('org switch failure should not trigger any reloads', async () => { + const switchError = new Error('Organization switch failed'); + mockAuthService.switchOrganization.mockRejectedValue(switchError); + + const result = await handleSlashCommands('/org invalid-org', mockAssistant); + + expect(result).not.toBeNull(); + expect(result?.output).toContain('Failed to switch organization: Organization switch failed'); + + // Verify NO reload was triggered on failure + expect(mockReloadService).not.toHaveBeenCalled(); + }); + }); + + describe('Other Commands (unchanged behavior)', () => { + test('help command should work normally', async () => { + const result = await handleSlashCommands('/help', mockAssistant); + + expect(result).not.toBeNull(); + expect(result?.output).toContain('Available commands:'); + expect(result?.output).toContain('/help - Show help'); + expect(result?.output).toContain('/login - Login to Continue'); + }); + + test('logout command should exit', async () => { + mockAuthService.logout.mockResolvedValue(undefined); + + const result = await handleSlashCommands('/logout', mockAssistant); + + expect(result).not.toBeNull(); + expect(result?.exit).toBe(true); + expect(result?.output).toContain('Logged out successfully'); + }); + + test('clear command should work normally', async () => { + const result = await handleSlashCommands('/clear', mockAssistant); + + expect(result).not.toBeNull(); + expect(result?.clear).toBe(true); + expect(result?.output).toBe('Chat history cleared'); + }); + + test('non-slash input should return null', async () => { + const result = await handleSlashCommands('regular input', mockAssistant); + expect(result).toBeNull(); + }); + + test('unknown slash command should return error', async () => { + const result = await handleSlashCommands('/unknown', mockAssistant); + + expect(result).not.toBeNull(); + expect(result?.output).toBe('Unknown command: unknown'); + }); + }); +}); \ No newline at end of file diff --git a/src/slashCommands.ts b/src/slashCommands.ts index 12fcc3e09..1cee4bda6 100644 --- a/src/slashCommands.ts +++ b/src/slashCommands.ts @@ -40,11 +40,9 @@ export async function handleSlashCommands( try { const newAuthState = await services.auth.login(); - // Reload dependent services - await Promise.all([ - reloadService(SERVICE_NAMES.API_CLIENT), - reloadService(SERVICE_NAMES.CONFIG), - ]); + // Automatically cascade reload from auth service - this will reload + // API_CLIENT -> CONFIG -> MODEL/MCP in the correct dependency order + await reloadService(SERVICE_NAMES.AUTH); const userInfo = newAuthState.authConfig && @@ -57,7 +55,7 @@ export async function handleSlashCommands( return { exit: false, - output: "Login successful! Services are updating...", + output: "Login successful! All services updated automatically.", }; } catch (error: any) { console.error(chalk.red(`\nLogin failed: ${error.message}`)); @@ -143,16 +141,13 @@ export async function handleSlashCommands( try { await services.auth.switchOrganization(orgId); - // Reload dependent services - await Promise.all([ - reloadService(SERVICE_NAMES.CONFIG), - reloadService(SERVICE_NAMES.MODEL), - reloadService(SERVICE_NAMES.MCP), - ]); + // Automatically cascade reload from auth service - this will reload + // API_CLIENT -> CONFIG -> MODEL/MCP in the correct dependency order + await reloadService(SERVICE_NAMES.AUTH); return { exit: false, - output: `Switched to organization: ${orgId}`, + output: `Switched to organization: ${orgId}. All services updated automatically.`, }; } catch (error: any) { return { @@ -174,4 +169,4 @@ export async function handleSlashCommands( } } return null; -} +} \ No newline at end of file