mirror of
https://github.com/CherryHQ/cherry-studio.git
synced 2026-01-03 11:11:59 +08:00
9d6a8f9225
6 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
1cb2af57ae
|
refactor: optimize DatabaseManager and fix libsql crash issues (#11392)
Some checks failed
Auto I18N Weekly / Auto I18N (push) Has been cancelled
* refactor: optimize DatabaseManager and fix libsql crash issues Major improvements: - Created DatabaseManager singleton to centralize database connection management - Auto-initialize database in constructor (no manual initialization needed) - Removed all manual initialize() and ensureInitialized() calls (47 occurrences) - Simplified initialization logic (removed retry loops that could cause crashes) - Removed unused close() and reinitialize() methods - Reduced code from ~270 lines to 172 lines (-36%) Key changes: 1. DatabaseManager.ts (new file): - Singleton pattern with auto-initialization - State management (INITIALIZING, INITIALIZED, FAILED) - Windows compatibility fixes (empty file detection, intMode: 'number') - Simplified waitForInitialization() logic 2. BaseService.ts: - Removed static initialize() and ensureInitialized() methods - Simplified database/rawClient getters to use DatabaseManager 3. Service classes (AgentService, SessionService, SessionMessageService): - Removed all initialize() methods - Removed all ensureInitialized() calls - Services now work out of the box 4. Main entry points (index.ts, server.ts): - Removed explicit database initialization calls - Database initializes automatically on first access Benefits: - Fixes Windows libsql crashes by removing dangerous retry logic - Simpler API - no need to remember to call initialize() - Better separation of concerns - Cleaner codebase with 36% less code 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: wait for database initialization on app startup Issue: "Database is still initializing" error on startup Root cause: Synchronous database getter was called before async initialization completed Solution: - Explicitly wait for database initialization in main index.ts - Import DatabaseManager and call getDatabase() to ensure initialization is complete - This guarantees database is ready before any service methods are called Changes: - src/main/index.ts: Added explicit database initialization wait before API server check 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * refactor: use static import for getDatabaseManager - Move import to top of file for better code organization - Remove unnecessary dynamic import 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * refactor: streamline database access in service classes - Replaced direct database access with asynchronous calls to getDatabase() in various service classes (AgentService, SessionService, SessionMessageService). - Updated the main index.ts to utilize runAsyncFunction for API server initialization, ensuring proper handling of asynchronous database access. - Improved code organization and readability by consolidating database access logic. This change enhances the reliability of database interactions across the application and ensures that services are correctly initialized before use. * refactor: remove redundant logging in ApiServer initialization - Removed the logging statement for 'AgentService ready' during server initialization. - This change streamlines the startup process by eliminating unnecessary log entries. This update contributes to cleaner logs and improved readability during server startup. * refactor: change getDatabase method to synchronous return type - Updated the getDatabase method in DatabaseManager to return a synchronous LibSQLDatabase instance instead of a Promise. - This change simplifies the database access pattern, aligning with the current initialization logic. This refactor enhances code clarity and reduces unnecessary asynchronous handling in the database access layer. * refactor: simplify sessionMessageRepository by removing transaction handling - Removed transaction handling parameters from message persistence methods in sessionMessageRepository. - Updated database access to use a direct call to getDatabase() instead of passing a transaction client. - Streamlined the upsertMessage and persistExchange methods for improved clarity and reduced complexity. This refactor enhances code readability and simplifies the database interaction logic. --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
36f86ff2b9
|
Refactor/agent align (#10276)
* Refactor agent streaming from EventEmitter to ReadableStream Replaced EventEmitter-based agent streaming with ReadableStream for better compatibility with AI SDK patterns. Modified SessionMessageService to return stream/completion pair instead of event emitter, updated HTTP handlers to use stream pumping, and added IPC contract for renderer-side message persistence. * Add accessible paths management to agent configuration Move accessible paths functionality from session modal to agent modal, add validation requiring at least one path, and update form handling to inherit agent paths in sessions. * Add provider_name field to model objects and improve display - Add provider_name field to ApiModel schema and transformation logic - Update model options to include providerName for better display - Improve provider label fallback chain in model transformation - Fix agent hook to use proper SWR key and conditional fetching - Enhance option rendering with better truncation and provider display * fix(i18n): Auto update translations for PR #10276 * Optimize chat components with memoization and shared layout - Wrap `SessionMessages` and `SessionInputBar` in `useMemo` to prevent unnecessary re-renders - Refactor `AgentSessionMessages` to use shared layout components and message grouping - Extract common styled components to `shared.tsx` for reuse across message components * Add smooth animations to SessionsTab and Sessions components - Replace static conditional rendering with Framer Motion animations for no-agent and session states - Animate session list items with staggered entrance and exit transitions - Add loading spinner animation with fade effect - Apply motion to session creation button with delayed entrance * Add loading state with spinner and i18n support to SessionsTab - Replace static "No active agent" message with a spinner and loading text - Integrate react-i18next for translation of loading message - Adjust animation timing and styling for smoother loading state transition * Support API models with provider_name field in getModelName - Add ApiModel type import and update function signature to accept ApiModel - Return formatted name using provider_name field for API models - Maintain backward compatibility for legacy models by looking up provider in store * Simplify provider display name logic and add debug logging - Replace complex fallback chain for provider display name with direct provider name access - Add console.log for model debugging in getModelName function * Extract model name from session model string - Use split and pop to isolate the model name after the colon - Fall back to the full model string if no colon is present - Maintain provider and group identifiers for model object consistency * Improve model name resolution for agent sessions - Extract actual model ID from session model string and resolve model details - Use resolved model name, provider, and group when available instead of defaults - Remove redundant API model handling in getModelName function * Set default active agent and session on load - Automatically select first agent if none active after loading - Automatically select first session per agent if none active after loading - Prevent empty selection states in UI components --------- Co-authored-by: GitHub Action <action@github.com> |
||
|
|
0d2dc2c257 |
🏗️ refactor: migrate agents service from custom migrations to Drizzle ORM
- Replace custom migration system with modern Drizzle ORM implementation - Add drizzle-orm and drizzle-kit dependencies for type-safe database operations - Refactor BaseService to use Drizzle client with full type safety - Create schema definitions in /database/schema/ using Drizzle patterns - Remove legacy migration files, queries, and migrator classes - Add comprehensive documentation for new Drizzle-based architecture - Maintain backward compatibility in service layer APIs - Simplify database operations with modern ORM patterns This migration eliminates custom SQL generation in favor of a proven, type-safe ORM solution that provides better developer experience and maintainability. |
||
|
|
c785be82dd |
♻️ refactor: rename SessionLog to SessionMessage for semantic clarity
- Rename SessionLogEntity → SessionMessageEntity type definition - Rename SessionLogService → SessionMessageService with all methods - Rename API routes /logs → /messages for better REST semantics - Update database queries and service layer naming - Update all Swagger documentation and validation middleware - Maintain backward compatibility in database schema This improves code readability by using more accurate terminology for conversational message data rather than generic "log" naming. |
||
|
|
d123eec476 |
♻️ refactor: eliminate database schema redundancy + add comprehensive documentation
Refactor database to migration-only approach and add complete documentation ### Database Architecture Improvements: - **Remove redundant schema files**: Eliminated duplicate table/index definitions - **Single source of truth**: Migration files now exclusively define database schema - **Simplified maintenance**: No more sync issues between schema files and migrations ### Files Removed: - `database/schema/tables.ts` - Redundant table definitions - `database/schema/indexes.ts` - Redundant index definitions ### Files Updated: - `database/schema/index.ts` - Now only exports migration utilities - `database/index.ts` - Simplified exports, removed redundant schema references - `BaseService.ts` - Updated documentation for migration-only approach - `migrator.ts` - Enhanced documentation and clarity ### Documentation Added: - **`database/README.md`** - Comprehensive 400+ line guide covering: - Architecture overview and migration-only approach - Complete directory structure explanation - Migration system lifecycle with diagrams - Query organization and API reference - Development workflow and best practices - Troubleshooting guide and examples ### Benefits: - ✅ Eliminated redundancy between schema and migration files - ✅ Reduced maintenance overhead and potential sync issues - ✅ Established single source of truth for database schema - ✅ Added comprehensive documentation for team development - ✅ Maintained full backward compatibility - ✅ All tests continue to pass (1420/1420) The database system now follows industry best practices with migrations as the sole schema definition method, while providing complete documentation for developers. |
||
|
|
002a443281 |
🏗️ refactor: restructure agents service with migration system and modular architecture
BREAKING CHANGE: Major refactoring of agents service structure - Split monolithic db.ts into focused query modules (agent, session, sessionLog) - Implement comprehensive migration system with transaction support - Reorganize services into dedicated services/ subdirectory - Add production-ready schema versioning with rollback capability ### New Architecture: - database/migrations/: Version-controlled schema evolution - database/queries/: Entity-specific CRUD operations - database/schema/: Table and index definitions - services/: Business logic layer (AgentService, SessionService, SessionLogService) ### Key Features: - ✅ Migration system with atomic transactions and checksums - ✅ Modular query organization by entity type - ✅ Backward compatibility maintained for existing code - ✅ Production-ready rollback support - ✅ Comprehensive validation and testing ### Benefits: - Single responsibility: Each file handles one specific concern - Better maintainability: Easy to locate and modify entity-specific code - Team-friendly: Reduced merge conflicts with smaller focused files - Scalable: Simple to add new entities without cluttering existing code - Production-ready: Safe schema evolution with migration tracking All existing functionality preserved. Comprehensive testing completed (1420 tests pass). |