refactor: consolidate agents module and reorganize test structure#247
refactor: consolidate agents module and reorganize test structure#247
Conversation
- Extract agent-definitions.ts (221 lines) with AGENT_DEFINITIONS and types - Extract path-prober.ts (489 lines) with platform-specific binary detection - Reduce agent-detector.ts from 865 to 283 lines (67% reduction) - Add helper functions: getAgentDefinition, getAgentIds, getVisibleAgentDefinitions - Maintain API compatibility via re-exports - Add 49 new tests (26 for definitions, 23 for path-prober)
Create src/main/agents/ directory with barrel exports: - Move agent-detector.ts → agents/detector.ts - Move agent-definitions.ts → agents/definitions.ts - Move agent-capabilities.ts → agents/capabilities.ts - Move agent-session-storage.ts → agents/session-storage.ts - Move path-prober.ts → agents/path-prober.ts - Add index.ts with centralized re-exports Reorganize tests to mirror source structure: - Move agent tests to __tests__/main/agents/ - Move process-listeners inline tests to __tests__/main/process-listeners/ - Move debug-package inline tests to __tests__/main/debug-package/ Add new tests for coverage gaps: - storage/claude-session-storage.test.ts (32 tests) - web-server/managers/CallbackRegistry.test.ts (29 tests) - web-server/managers/LiveSessionManager.test.ts (39 tests) Update all imports across codebase to use new agents/ module path. Test count: 16,201 → 16,301 (+100 tests)
Code Review: PR #247 - Refactor Agent Module ArchitectureThanks for this well-executed refactoring! The decomposition of 🟢 Overall Assessment: STRONG APPROVAL with minor recommendationsSummary:
Critical Issues: None 📋 Medium Priority Issues1. Type Safety for
|
…provements Type Safety (Medium Priority): - Replace `any` types in AgentConfigOption with discriminated union - Four specific types: CheckboxConfigOption, TextConfigOption, NumberConfigOption, SelectConfigOption - Update agent-args.ts to handle new types with proper assertions Error Handling (Medium Priority): - Add try/catch wrapper around runModelDiscovery to gracefully handle exceptions and return empty array on failure Performance (Medium Priority): - Implement parallel path probing using Promise.allSettled - Previously: sequential checks (6-10 paths, one after another) - Now: all paths checked concurrently, first success returned - Maintains priority order while reducing detection time - Significant improvement on slow file systems/network drives Configuration (Low Priority): - Make model cache TTL configurable via constructor parameter - Default remains 5 minutes, but can be customized for testing Logging (Low Priority): - Add debug logging for silent error swallowing in checkCustomPath Documentation (Low Priority): - Enhanced module-level JSDoc for detector.ts and path-prober.ts - Document detection strategy and caching behavior Testing: - Add cache TTL expiration test using fake timers - Add constructor TTL configuration test
Code Review: PR #247 - Agent Module RefactoringExecutive SummaryVerdict: ✅ APPROVE - Excellent refactoring with high-quality implementation This PR successfully decomposes the monolithic Strengths1. Architecture & Design (⭐⭐⭐⭐⭐)Clean Module Boundaries: Each module has a single, focused responsibility with zero circular dependencies. Type Safety:
Design Patterns:
2. Test Coverage (⭐⭐⭐⭐⭐)+100 tests across 5 comprehensive suites:
Test Quality Highlights:
3. Code Quality (⭐⭐⭐⭐⭐)Promise Deduplication (detector.ts:65-77): if (this.detectionInProgress) return this.detectionInProgress;
this.detectionInProgress = this.doDetectAgents();
try {
return await this.detectionInProgress;
} finally {
this.detectionInProgress = null;
}Prevents race conditions during parallel detection calls. Capability Feature Matrix (capabilities.ts):
Path Probing Strategy (path-prober.ts):
4. Migration Completeness (⭐⭐⭐⭐⭐)All 29 files updated with correct imports: // Old (scattered imports)
import { AgentDetector } from './agent-detector';
import { getAgentCapabilities } from './agent-capabilities';
// New (barrel export)
import { AgentDetector, getAgentCapabilities } from './agents';✅ No stale imports detected
5. Documentation (⭐⭐⭐⭐)
Areas for Enhancement1. Parallel Path Probing (Performance Optimization)Current: Sequential path checking in Recommendation: Use export async function probeWindowsPaths(binaryName: string): Promise<string | null> {
const pathsToCheck = getWindowsKnownPaths(binaryName);
const results = await Promise.allSettled(
pathsToCheck.map(async (probePath) => {
await fs.promises.access(probePath, fs.constants.F_OK);
return probePath;
})
);
const found = results.find(r => r.status === 'fulfilled');
return found?.status === 'fulfilled' ? found.value : null;
}Impact: Could reduce detection time by 50-80% when checking 20+ paths on slow filesystems. 2. Enhanced Error Handling in Model DiscoveryCurrent: File: Recommendation: Wrap discovery logic in try-catch: private async runModelDiscovery(agentId: string, agent: AgentConfig): Promise<string[]> {
try {
const env = getExpandedEnv();
const command = agent.path || agent.command;
switch (agentId) {
case 'opencode': {
const result = await execFileNoThrow(command, ['models'], undefined, env);
// ... parsing logic
}
}
} catch (error) {
logger.error(`Model discovery threw exception for ${agentId}`, LOG_CONTEXT, { error });
return [];
}
}Impact: Prevents uncaught promise rejections if 3. Reduce Path Pattern DuplicationCurrent: Many path patterns repeated across binaries in File: Recommendation: Extract common path builders: const commonPatterns = {
npmGlobal: (binary: string) => [
path.join(appData, 'npm', binary),
path.join(localAppData, 'npm', binary)
],
homebrewBin: (binary: string) => [
`/opt/homebrew/bin/${binary}`,
`/usr/local/bin/${binary}`
],
wingetLinks: (binary: string) => [
path.join(localAppData, 'Microsoft', 'WinGet', 'Links', binary),
path.join(programFiles, 'WinGet', 'Links', binary)
]
};Impact: Reduces maintenance burden when adding new agents. 4. Test Gap: Model Cache ExpirationMissing: No test verifies cache is invalidated after TTL expires Recommendation: Add test with fake timers: it('should invalidate model cache after TTL expires', async () => {
vi.useFakeTimers();
await detector.discoverModels('opencode');
vi.advanceTimersByTime(6 * 60 * 1000); // 6 minutes
mockExecFileNoThrow.mockClear();
await detector.discoverModels('opencode');
expect(mockExecFileNoThrow).toHaveBeenCalled();
vi.useRealTimers();
});5. Improved Error LoggingCurrent: Silent error swallowing in File: Recommendation: } catch (error) {
logger.debug(`Error checking custom path ${customPath}`, LOG_CONTEXT, { error });
return { exists: false };
}Impact: Aids debugging when custom paths fail validation. Security Assessment
No security concerns identified. Performance Assessment
No performance regressions. One optimization opportunity identified above. Checklist
Recommendation✅ APPROVE AND MERGE This refactoring is production-ready. All identified issues are enhancements rather than blockers. The code successfully achieves:
Follow-up Issues (Optional):
Excellent work! 🎉 Reviewed by: Claude Sonnet 4.5 (AI Code Review) |
…cation Addresses code review suggestion to reduce repeated path patterns across binary definitions by extracting shared builders (npmGlobal, localBin, homebrew, wingetLinks, etc.) as closures within each platform function.
Code Review: Agent Module RefactoringOverall AssessmentVerdict: Strong refactoring with excellent architectural improvements ✅ This PR demonstrates thoughtful architectural restructuring with clear separation of concerns. The refactor significantly improves code maintainability, testability, and discoverability. Strengths 💪1. Excellent Module Organization
2. Type Safety Improvements
3. Performance Optimizations
4. Error Handling
5. Test Quality
Issues & Recommendations 🔍Critical IssuesNone identified - No blocking issues found. Medium Priority
Low Priority
Security Considerations 🔒No Security Issues Found ✅
Test Coverage 📊Excellent Coverage
Suggestions:
Architecture & Design 🏗️Excellent Patterns:
Consistency:
Performance Impact 📈Positive Improvements:
Recommendations SummaryMust Address Before Merge: None - PR is merge-ready Should Address (Nice to Have):
Optional Future Improvements:
ConclusionThis is excellent refactoring work demonstrating strong architectural vision, attention to type safety, thoughtful performance optimization, and comprehensive test coverage. Recommendation: APPROVE ✅ Great work @reachraza! This refactor significantly improves the maintainability and testability of the agent detection system. Testing ChecklistBefore merging:
Review conducted by Claude Code in accordance with CLAUDE.md guidelines |
Refactor Agent Module Architecture and Test Organization
Summary
This PR restructures the agent-related code into a well-organized module with proper separation of concerns and ensures the test directory mirrors the source structure with comprehensive coverage.
Changes
1. Agent Module Decomposition (
e95ef0c3)agent-detector.tsinto focused, single-responsibility modules:definitions.ts- Agent configuration definitions and registrycapabilities.ts- Agent capability flags and queriespath-prober.ts- Binary detection and path probing utilitiesdetector.ts- High-level agent detection orchestration2. Module Consolidation & Test Reorganization (
454cdefd)src/main/agents/index.tsbarrel file for clean importsprocess-listeners/__tests__/→src/__tests__/main/process-listeners/debug-package/__tests__/→src/__tests__/main/debug-package/claude-session-storage.test.ts(32 tests)CallbackRegistry.test.ts(29 tests)LiveSessionManager.test.ts(39 tests)Test Coverage
Benefits
import { AgentDetector, getAgentCapabilities } from './agents'Testing