9 KiB
9 KiB
Reactive Service Architecture Refactoring Plan
Problem Statement
The current codebase has tightly coupled dependencies (config, apiClient, MCP service, model, etc.) that require full reloads when any component changes. This causes:
- Slow startup: TUI can't start until all components are loaded
- Poor UX: Slash commands like
/org,/configtrigger complete restarts - Tight coupling: Can't change individual components without reloading everything
- Blocking initialization: All dependencies must load before anything works
Solution Overview
Implement a Reactive Service Architecture using:
- Custom ServiceContainer with Node.js EventEmitter
- React hooks for service consumption
- Progressive loading and error handling
- Independent service lifecycle management
Current Architecture Analysis
Key Components to Refactor
- Config Management (
src/config.ts,src/onboarding.ts) - Authentication (
src/auth/workos.ts) - LLM/Model handling (
src/config.ts-initializeLlmApi()) - MCP Service (
src/mcp.ts) - API Client (
src/CLIPlatformClient.ts)
Current Initialization Flow
chat() -> initializeChat() -> initializeWithOnboarding() -> initialize()
-> Returns: { config, llmApi, model, mcpService, apiClient }
-> startTUIChat() with all dependencies
Current Problem Areas
src/commands/chat.ts-initializeChat()loads everything synchronouslysrc/ui/index.ts-startTUIChat()requires all deps upfrontsrc/slashCommands.ts-/config,/logintrigger full reloads viaonReload()src/ui/TUIChat.tsx- Assumes all services are available at startup
Implementation Strategy
Phase 1: Extract Current Initialization into Services ✅ COMPLETE
Create the service infrastructure and extract existing initialization logic.
1.1 Create Service Infrastructure
- Create
src/services/ServiceContainer.ts- Core service management - Create
src/hooks/useService.ts- React hook for service consumption - Create
src/services/types.ts- Service-related TypeScript types
1.2 Create Individual Services
- Create
src/services/AuthService.ts- Extract auth logic fromsrc/auth/workos.ts - Create
src/services/ConfigService.ts- Extract config logic fromsrc/config.ts - Create
src/services/ModelService.ts- Extract model initialization - Create
src/services/MCPServiceWrapper.ts- Extract MCP logic fromsrc/mcp.ts - Create
src/services/ApiClientService.ts- Extract API client management
1.3 Create Service Registry
- Create
src/services/index.ts- Central service registry and initialization - Add service dependency management (e.g., ModelService depends on ConfigService)
Phase 2: Make TUI Reactive to Service Changes ✅ COMPLETE
Update the TUI to consume services reactively instead of requiring all deps upfront.
2.1 Update TUI Components
- Update
src/ui/TUIChat.tsx- UseuseServicehooks instead of props - Add loading states for individual services
- Add error boundaries for service failures
- Remove service props from component interface
2.2 Update TUI Entry Point
- Update
src/ui/index.ts- Remove dependency injection, just start TUI - Update
src/commands/chat.ts- Start TUI immediately, services load async
2.3 Handle Service Dependencies in UI
- Show progressive loading (e.g., "Config loaded, loading model...")
- Handle missing services gracefully
- Allow partial functionality when some services unavailable
Phase 3: Update Slash Commands to Use Services ✅ COMPLETE
Make slash commands reactive by updating services instead of triggering reloads.
3.1 Update Slash Command Handlers
- Update
src/slashCommands.ts- RemoveonReloadcallback pattern - Update
/logincommand to use AuthService.login() - Update
/logoutcommand to use AuthService.logout() - Add
/orgcommand to use AuthService.switchOrg() - Update
/configcommand (handled via ConfigSelector UI)
3.2 Remove Reload Mechanisms
- Remove
onReloadcallbacks from TUIChat - Remove full restart logic from slash commands
- Services now auto-propagate changes to UI
Phase 4: Add Progressive Loading and Better Error Handling ✅ FUTURE
Enhance the user experience with better loading states and error recovery.
4.1 Enhanced Loading States
- Add service loading indicators in TUI
- Show which services are loading/ready
- Allow using available functionality while other services load
4.2 Error Handling and Recovery
- Add retry mechanisms for failed service initialization
- Add service health monitoring
- Graceful degradation when services fail
- Better error messages for specific service failures
4.3 Performance Optimizations
- Lazy load services only when needed
- Cache service results appropriately
- Debounce rapid service changes
File Changes Required
New Files
src/services/ServiceContainer.tssrc/services/types.tssrc/services/AuthService.tssrc/services/ConfigService.tssrc/services/ModelService.tssrc/services/MCPServiceWrapper.tssrc/services/ApiClientService.tssrc/services/index.tssrc/hooks/useService.ts
Modified Files
src/commands/chat.ts- Remove synchronous initializationsrc/ui/index.ts- Remove dependency injectionsrc/ui/TUIChat.tsx- Use service hooks instead of propssrc/slashCommands.ts- Use services instead of reload callbackssrc/ui/hooks/useChat.ts- Remove onReload dependencysrc/onboarding.ts- Integrate with service architecture
Files to Analyze for Extraction
src/config.ts- Extract initialization logicsrc/auth/workos.ts- Extract auth managementsrc/mcp.ts- Extract MCP service logic
Success Criteria
Phase 1 Success ✅ COMPLETE
- Services can be initialized independently
- Existing functionality works through service layer
- No breaking changes to current behavior
Phase 2 Success ✅ COMPLETE
- TUI starts immediately without waiting for all services
- UI updates reactively when services load/change
- Loading states provide clear user feedback
Phase 3 Success ✅ COMPLETE
- Slash commands work without full reloads
/loginand/logoutcommands update UI instantly- New
/orgcommand for organization switching - No more blocking reinitialization
Phase 4 Success
- Better error handling for service failures
- Progressive enhancement - partial functionality available
- Improved startup performance
Benefits Achieved
✅ Immediate Benefits
- Fast Startup: TUI starts immediately, shows progressive loading
- Reactive Updates: Services auto-propagate changes without reloads
- Better UX:
/login,/logout,/orgcommands work instantly - Cleaner Architecture: Clear separation of concerns between services
- Type Safety: Full TypeScript support with proper service typing
✅ Technical Improvements
- Dependency Management: Services declare dependencies explicitly
- Error Boundaries: Service failures don't crash the entire app
- Memory Management: Proper EventEmitter cleanup in React hooks
- Testability: Services can be tested in isolation
- Maintainability: Changes to one service don't require touching others
Testing Strategy
Unit Tests
- Test each service in isolation
- Test service dependencies and lifecycle
- Test React hooks with service changes
Integration Tests
- Test service interactions
- Test UI updates with service changes
- Test slash command service updates
E2E Tests
- Test full user flows with new architecture
- Test error recovery scenarios
- Test performance improvements
Migration Strategy
- Backward Compatibility: ✅ Existing functionality preserved
- Incremental Migration: ✅ Each phase was deployable independently
- Rollback Plan: ✅ Old patterns kept for headless mode
- Monitoring: Added comprehensive logging for service lifecycle
Risk Mitigation
Technical Risks
- Service dependency cycles: ✅ Resolved with proper dependency injection
- Memory leaks: ✅ Proper EventEmitter cleanup implemented
- Race conditions: ✅ Used proper async/await patterns
User Experience Risks
- Broken functionality: ✅ Extensive TypeScript checking at each phase
- Performance regressions: ✅ TUI starts faster, no blocking initialization
- Confusing loading states: ✅ Clear progressive loading indicators
Notes
- ✅ Phase 1-3 Complete: Core reactive service architecture implemented
- ✅ Major Benefits Realized: Fast startup, reactive updates, better UX
- 🚀 Ready for Production: All TypeScript errors resolved, backward compatibility maintained
- 📈 Future Improvements: Phase 4 can be added incrementally for enhanced error handling and performance