Skip to content

feat(chatdb): add ChatDB agent for text-to-SQL interactions - #509

Merged
phodal merged 34 commits into
masterfrom
feature/chatdb-agent
Dec 10, 2025
Merged

phodal merged 34 commits into
masterfrom
feature/chatdb-agent

Conversation

@phodal

@phodal phodal commented Dec 9, 2025 •

Copy link
Copy Markdown
Owner

Summary

This PR adds a new ChatDB agent type for text-to-SQL interactions, allowing users to connect to databases and use natural language to query them.

Changes

New Files

  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/ChatDBPage.kt - Main page with split layout
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/ChatDBViewModel.kt - ViewModel for managing data sources and chat
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/DataSourcePanel.kt - Left panel for data source management
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/DataSourceConfigDialog.kt - Dialog for adding/editing data sources
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/ChatDBChatPane.kt - Right panel for chat interactions
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/model/DataSourceModels.kt - Data models for data sources

Modified Files

  • mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/AgentType.kt - Added CHAT_DB agent type
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentInterfaceRouter.kt - Added routing for ChatDB
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentChatInterface.kt - Added CHAT_DB to when expression
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/TopBarMenuDesktop.kt - Added CHAT_DB icon
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/TopBarMenuMobile.kt - Added CHAT_DB icon
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/icons/AutoDevComposeIcons.kt - Added Database and Schema icons

Features

  • Data Source Management: Add, edit, delete, and connect to database sources
  • Multiple Database Dialects: Support for PostgreSQL, MySQL, SQLite, SQL Server, Oracle, MariaDB
  • Text-to-SQL Chat: Natural language queries converted to SQL using LLM
  • Query Execution: Automatic SQL extraction and execution with result display
  • Schema Display: View connected database schema

Screenshots

(UI implementation - screenshots can be added after testing)

Closes #508

Summary by CodeRabbit

Release Notes

  • New Features

    • Added ChatDB (Text-to-SQL) agent for converting natural language queries to SQL with multi-database support.
    • Implemented data source management UI for creating and configuring database connections.
    • Added SQL validation and automatic revision with error handling.
    • Integrated schema linking to identify relevant database tables for queries.
  • Enhancements

    • Improved agent interface with workspace context support.
    • Fixed database metadata queries to properly scope to current catalog.
  • Style

    • Added Database and Schema icons for UI clarity.

✏️ Tip: You can customize this high-level summary in your review settings.

Copilot AI review requested due to automatic review settings December 9, 2025 14:35
@coderabbitai

coderabbitai Bot commented Dec 9, 2025 •

Copy link
Copy Markdown

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

This PR introduces a comprehensive Text2SQL (ChatDB) Agent feature enabling natural language to SQL conversion with schema linking, multi-database support, SQL validation/revision, and optional visualization. It adds new AgentType.CHAT_DB with corresponding UI components, core agent implementations, NLP tokenization, database infrastructure, platform-specific SQL validators, and a multiplatform data source repository with SQLDelight persistence.

Changes

Cohort / File(s) Summary
AgentType Extension
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/AgentType.kt
Adds KNOWLEDGE and CHAT_DB enum constants with KDoc, extends getDisplayName() mapping and fromString() parsing to recognize "chatdb" and "database"
ChatDB UI Core Components
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/ChatDBPage.kt, ChatDBViewModel.kt, components/ChatDBChatPane.kt, components/DataSourcePanel.kt, components/DataSourceConfigPane.kt, components/ChatDBStepCard.kt
Implements ChatDB page with two-pane layout (data source panel + chat/config pane), view model for state management, chat interface with connection status and message rendering, data source management with CRUD operations, configuration form for database connections, and execution step visualization
ChatDB Data Models
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/model/DataSourceModels.kt
Defines DatabaseDialect enum, DataSourceConfig data class with validation, ChatDBState for UI state management, ChatDBMessage, MessageRole, QueryResultDisplay, ConnectionStatus, and ValidationResult types
ChatDB Core Agent
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/chatdb/ChatDBAgent.kt, ChatDBAgentExecutor.kt, MultiDatabaseChatDBAgent.kt, MultiDatabaseChatDBExecutor.kt
Implements Text2SQL agent orchestration, single and multi-database executors with schema linking, SQL generation/validation/revision workflow, and visualization generation
Schema Linking
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/chatdb/SchemaLinker.kt, KeywordSchemaLinker.kt, LlmSchemaLinker.kt, DatabaseContentSchemaLinker.kt, ChatDBModels.kt
Adds abstract SchemaLinker base class with utility functions, keyword-based implementation, LLM-based implementation with fallback, and content-driven implementation using database samples; defines ChatDBTask, ChatDBResult, SchemaLinkingResult data classes
NLP Tokenization
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/chatdb/NlpTokenizer.kt, FallbackNlpTokenizer.kt, mpp-core/src/{jvmMain,jsMain,iosMain,androidMain,wasmJsMain}/kotlin/cc/unitmesh/agent/chatdb/NlpTokenizer.*.kt
Introduces multiplatform NLP tokenizer expect/actual pattern; commonMain provides FallbackNlpTokenizer with Porter Stemmer, Chinese BiMM segmentation, RAKE keyword extraction, and mixed-language support; platform implementations delegate to FallbackNlpTokenizer or use platform-specific libraries (MyNLP for JVM)
SQL Validation & Revision
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/subagent/SqlValidator.kt, SqlReviseAgent.kt, mpp-core/src/{jvmMain,jsMain,iosMain,androidMain,wasmJsMain}/kotlin/cc/unitmesh/agent/subagent/SqlValidator.*.kt
Adds expect/actual SqlValidator interface with platform implementations (JSqlParser for JVM, regex-based for others), and SqlReviseAgent for iterative SQL correction with optional whitelist validation
Database Infrastructure
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/database/DatabaseConnection.kt, mpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/database/ExposedDatabaseConnection.kt
Defines DatabaseConnection interface with executeQuery, getSchema, getSampleRows, getDistinctValues; JVM implementation using Exposed framework; QueryResult.toTableString enhanced with pagination support
Data Source Persistence
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/db/DataSourceRepository.kt, mpp-ui/src/sqldelight/cc/unitmesh/devins/db/DataSource.sq, mpp-ui/src/{jvmMain,jsMain,iosMain,wasmJsMain}/kotlin/cc/unitmesh/devins/db/DataSourceRepository.*.kt
Adds expect/actual DataSourceRepository CRUD interface; SQLDelight schema for persistence; platform-specific implementations (JVM with SQL, JS/WASM with localStorage, iOS with database, Android stub)
Rendering Infrastructure
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/render/CodingAgentRenderer.kt, RendererModels.kt
Adds renderInfo() and renderChatDBStep() methods to CodingAgentRenderer; introduces ChatDBStepType, ChatDBStepStatus enums and TimelineItem.ChatDBStepItem, TimelineItem.InfoItem for progress tracking
UI Integration
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentChatInterface.kt, AgentInterfaceRouter.kt, AutoDevApp.kt, ComposeRenderer.kt, AgentMessageList.kt
Extends agent routing to handle CHAT_DB type, adds workspace parameter to router, implements ChatDB rendering in ComposeRenderer with renderInfo/renderChatDBStep overrides, adds conditional session sidebar visibility, updates message list rendering for new timeline items
Desktop & Mobile UI Updates
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/TopBarMenuDesktop.kt, TopBarMenuMobile.kt, mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/icons/AutoDevComposeIcons.kt
Adds CHAT_DB case with Database icon mapping in agent type tabs
IDEA Integration
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/header/IdeaAgentTabsHeader.kt, toolwindow/IdeaAgentApp.kt, toolwindow/IdeaComposeIcons.kt, toolwindow/IdeaAgentViewModel.kt
Adds CHAT_DB icon (cyan color) and Database icon definition, placeholder UI for ChatDB agent, refactors agent type persistence to use getDisplayName()
Desktop State & App Integration
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/state/DesktopUiState.kt, mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/app/SessionApp.kt
Adds coroutine-based persistence for agent type preference in DesktopUiState; removes SessionApp.kt entire file (auth flow, project/task management)
CLI & Server Integration
mpp-ui/src/jvmMain/kotlin/cc/unitmesh/server/cli/ChatDBCli.kt, mpp-ui/build.gradle.kts
Adds ChatDBCli main entry point for testing ChatDB workflow via CLI with database/LLM configuration; adds runChatDBCli Gradle task
LLM Executor Factory
mpp-core/src/commonMain/kotlin/cc/unitmesh/llm/ExecutorFactory.kt, mpp-core/src/{jvmMain,jsMain,iosMain,wasmJsMain}/kotlin/cc/unitmesh/llm/ExecutorFactory.*.kt
Introduces platform-specific createExecutorBlocking() API for blocking executor creation; JVM uses runBlocking, non-JVM platforms return null with documentation
Database Connection (IDEA)
mpp-idea/mpp-idea-exts/ext-database/src/main/kotlin/cc/unitmesh/database/connection/IdeaDatabaseConnection.kt
Updates package path and createFromIdea() signature to accept DbDataSource object instead of name string
Testing
mpp-core/src/commonTest/kotlin/cc/unitmesh/agent/chatdb/SchemaLinkerTest.kt, FallbackNlpTokenizerTest.kt, mpp-core/src/commonTest/kotlin/cc/unitmesh/agent/subagent/SqlReviseAgentTest.kt, mpp-core/src/jvmTest/kotlin/cc/unitmesh/agent/chatdb/NlpTokenizerTest.kt, JSqlParserValidatorTest.kt, mpp-idea/mpp-idea-core/src/test/kotlin/.../*Test.kt
Adds comprehensive test suites for schema linking, NLP tokenization, SQL revision, SQL validation, and updates existing tests to use Kotlin assertions instead of AssertJ
Build Configuration
mpp-core/build.gradle.kts, mpp-ui/build.gradle.kts, mpp-idea/build.gradle.kts
Adds MyNLP dependency for Chinese tokenization, ChatDB CLI Gradle task, AssertJ test dependency; duplicates runChatDBCli task definition

Sequence Diagram

sequenceDiagram
    participant User as User
    participant UI as ChatDB UI
    participant VM as ChatDBViewModel
    participant Agent as ChatDBAgent
    participant Executor as ChatDBAgentExecutor
    participant SchemaLinker as SchemaLinker
    participant LLM as LLM Service
    participant Validator as SQL Validator
    participant Reviser as SqlReviseAgent
    participant DB as Database

    User->>UI: Enter natural language query
    UI->>VM: sendMessage(text)
    VM->>Agent: execute(ChatDBTask)
    Agent->>Executor: execute(task)
    
    rect rgb(200, 220, 255)
    Note over Executor,DB: Schema Linking Phase
    Executor->>SchemaLinker: link(query, schema)
    SchemaLinker->>SchemaLinker: extractKeywords(query)
    SchemaLinker->>DB: (optional) fetch schema context
    SchemaLinker-->>Executor: SchemaLinkingResult
    Executor->>VM: renderChatDBStep(SCHEMA_LINKING, SUCCESS)
    end
    
    rect rgb(200, 255, 220)
    Note over Executor,LLM: SQL Generation Phase
    Executor->>Executor: buildInitialUserMessage(task, schema)
    Executor->>LLM: generateSQL(systemPrompt, userMessage)
    LLM-->>Executor: response with SQL
    Executor->>Executor: extractSqlFromResponse(response)
    Executor->>VM: renderChatDBStep(GENERATE_SQL, SUCCESS)
    end
    
    rect rgb(255, 240, 200)
    Note over Executor,Validator: Validation & Revision Phase
    Executor->>Validator: validate(sql)
    alt SQL Invalid
        Executor->>Reviser: execute(SqlRevisionInput)
        Reviser->>LLM: askLLMForRevision(context)
        LLM-->>Reviser: revised sql
        Reviser->>Validator: validate(revisedSql)
        Validator-->>Reviser: result
        Reviser-->>Executor: revised sql or error
        Executor->>VM: renderChatDBStep(REVISE_SQL, SUCCESS)
    else SQL Valid
        Executor->>VM: renderChatDBStep(VALIDATE_SQL, SUCCESS)
    end
    end
    
    rect rgb(255, 220, 220)
    Note over Executor,DB: Execution Phase
    Executor->>DB: executeQuery(sql)
    DB-->>Executor: QueryResult
    Executor->>VM: renderChatDBStep(EXECUTE_SQL, SUCCESS)
    end
    
    rect rgb(220, 220, 255)
    Note over Executor,LLM: Visualization Phase (optional)
    alt generateVisualization flag
        Executor->>Executor: buildTableContext(result)
        Executor->>LLM: generateVisualization(data)
        LLM-->>Executor: PlotDSL code
        Executor->>VM: renderChatDBStep(GENERATE_VISUALIZATION, SUCCESS)
    end
    end
    
    Executor-->>Agent: ChatDBResult
    Agent-->>VM: ToolResult.AgentResult
    VM->>UI: update state with result
    UI->>User: Display SQL, results, visualization
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Areas requiring extra attention:

  • Schema Linking implementations (SchemaLinker.kt, KeywordSchemaLinker.kt, LlmSchemaLinker.kt, DatabaseContentSchemaLinker.kt) — Multiple competing strategies with LLM integration and fallback chains; ensure correctness of keyword extraction and schema matching logic
  • ChatDB Agent & Executor classes (ChatDBAgent.kt, ChatDBAgentExecutor.kt, MultiDatabaseChatDBAgent.kt, MultiDatabaseChatDBExecutor.kt) — Complex orchestration with iterative loops, SQL extraction/validation/revision workflows; verify error handling and termination conditions
  • NLP Tokenization (FallbackNlpTokenizer.kt) — Substantial NLP logic including Porter Stemmer, Chinese BiMM segmentation, RAKE keyword extraction; validate correctness against test cases
  • SQL Validators (platform-specific implementations) — Multiple regex-based and parser-based approaches across platforms; ensure consistent whitelist and table extraction behavior
  • Multiplatform data source persistence (DataSourceRepository.kt and platform implementations) — Different backends (SQL, localStorage, stub implementations); verify CRUD operations and default handling across platforms
  • SessionApp.kt removal — Entire file deleted; verify no orphaned references or broken imports elsewhere in codebase
  • Gradle configuration — runChatDBCli task defined twice in build.gradle.kts (potential duplicate); MyNLP dependency added for Chinese tokenization
  • Database infrastructure changes (ExposedDatabaseConnection.kt) — Catalog-scoped metadata queries; ensure compatibility with target databases

Possibly related PRs

Poem

🐰 A database whisperer emerges today,
ChatDB hops through schema in its clever way,
From keywords to SQL, through revision's dance,
Multi-database queries get their second chance—
LLM magic meets the table's truth,
Auto-Dev gains wisdom in its youthful youth! 🌟

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.71% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly and concisely summarizes the main change: adding a ChatDB agent for text-to-SQL interactions. It is specific, avoids vague terms, and accurately reflects the primary focus of the changeset.
Linked Issues check ✅ Passed The PR substantially implements the core coding requirements from issue #508, including cross-platform database provider infrastructure, JVM/IDEA implementations, schema linking components, SQL validation and revision agents, NLP tokenization, multi-database support, and corresponding UI integration.
Out of Scope Changes check ✅ Passed All changes align with the stated objectives of adding a comprehensive ChatDB agent feature. Modifications to AgentType, routing, UI components, database abstractions, NLP tokenization, SQL validation, and supporting infrastructure are all directly related to implementing text-to-SQL functionality as specified in issue #508.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/chatdb-agent

Comment @coderabbitai help to get the list of available commands and usage tips.

@phodal

phodal commented Dec 9, 2025

Copy link
Copy Markdown
Owner Author

augment review

@augmentcode augmentcode Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review completed. 3 suggestions posted.

Comment augment review to trigger a new review at any time.

if (match != null && currentConnection != null) {
val sql = match.groupValues[1].trim()
try {
val result = currentConnection!!.executeQuery(sql)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider enforcing read-only execution before running LLM-generated SQL; currently any SQL inside the code fence will be executed, which risks destructive statements despite the prompt guidance. Add a validation (e.g., ensure it starts with SELECT and contains no write/DDL keywords) before calling executeQuery.

🤖 Was this useful? React with 👍 or 👎

dataSources = state.dataSources.filter { it.id != id },
selectedDataSourceId = if (state.selectedDataSourceId == id) null else state.selectedDataSourceId
)
if (state.selectedDataSourceId == id) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The check for state.selectedDataSourceId == id happens after you set it to null, so disconnect() won’t run when deleting the currently selected source; check before updating state or cache the previous selection to ensure the connection is closed. This avoids leaking an open DB connection (also relates to resource cleanup) (Guideline: no_memory_leaks).

🤖 Was this useful? React with 👍 or 👎

@Composable
fun ChatDBPage(
workspace: Workspace,
llmService: KoogLLMService?,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

llmService parameter is currently unused; the ViewModel creates its own instance instead. Consider threading the provided llmService through to avoid duplicate initialization and ensure consistent configuration.

🤖 Was this useful? React with 👍 or 👎

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 9

🧹 Nitpick comments (10)
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/TopBarMenuMobile.kt (1)

256-263: Consider extracting duplicated icon mapping logic.

The same AgentType -> Icon mapping appears in three places now (desktop tab, mobile header, mobile submenu). Consider extracting a shared helper function to reduce duplication and ensure consistency.

// In AutoDevComposeIcons.kt or a shared location
fun AgentType.toIcon(): ImageVector = when (this) {
    AgentType.REMOTE -> AutoDevComposeIcons.Cloud
    AgentType.CODE_REVIEW -> AutoDevComposeIcons.RateReview
    AgentType.KNOWLEDGE -> AutoDevComposeIcons.Article
    AgentType.CODING -> AutoDevComposeIcons.Code
    AgentType.LOCAL_CHAT -> AutoDevComposeIcons.Chat
    AgentType.CHAT_DB -> AutoDevComposeIcons.Database
}
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/ChatDBChatPane.kt (2)

23-23: Unused import.

Platform is imported but not used in this file. Consider removing it to keep imports clean.

-import cc.unitmesh.agent.Platform

151-152: Consider handling Connecting and Error states explicitly.

The empty else branch silently ignores ConnectionStatus.Connecting and ConnectionStatus.Error states. While these may be handled elsewhere, the user may benefit from visual feedback in the chat pane during these states (e.g., a "Connecting..." indicator or error message banner).

mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/DataSourceConfigDialog.kt (1)

212-213: Consider providing validation feedback to users.

Currently, the Save button is simply disabled when validation fails. Users may not understand why they can't save. Consider showing inline error messages or validation hints for required fields.

mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/DataSourcePanel.kt (2)

231-245: Consider adding delete confirmation.

The delete action executes immediately without confirmation. Users could accidentally delete data source configurations. Consider showing a confirmation dialog before deletion.


283-290: CircularProgressIndicator color may not be visible on disabled button.

The indicator uses MaterialTheme.colorScheme.onPrimary, but the button is disabled, which typically reduces the container color opacity. The indicator might be hard to see. Consider using MaterialTheme.colorScheme.onSurface or the primary color instead.

                     CircularProgressIndicator(
                         modifier = Modifier.size(16.dp),
                         strokeWidth = 2.dp,
-                        color = MaterialTheme.colorScheme.onPrimary
+                        color = MaterialTheme.colorScheme.primary
                     )
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/model/DataSourceModels.kt (2)

16-23: Silent fallback to MYSQL may cause confusion.

fromString silently returns MYSQL when no match is found. This could mask data corruption or configuration errors. Consider throwing an exception or returning null to make failures explicit.

     companion object {
-        fun fromString(value: String): DatabaseDialect {
-            return entries.find { 
+        fun fromString(value: String): DatabaseDialect? {
+            return entries.find {
                 it.name.equals(value, ignoreCase = true) || 
                 it.displayName.equals(value, ignoreCase = true) 
-            } ?: MYSQL
+            }
         }
     }

Alternatively, if a default is preferred, add logging or documentation:

fun fromString(value: String): DatabaseDialect {
    return entries.find { ... } 
        ?: MYSQL.also { /* log warning about unknown dialect */ }
}

30-35: Default port doesn't match dialect default.

The default port = 3306 is hardcoded, but this doesn't match all dialects (e.g., PostgreSQL uses 5432). While dialect.defaultPort exists, the class default could mislead. This is minor since the dialog updates the port when dialect changes.

mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/ChatDBViewModel.kt (2)

64-66: Use structured logging instead of println.

println is not suitable for production logging. Consider using a proper logging framework that supports log levels and structured output.

             } catch (e: Exception) {
-                println("[ChatDB] Failed to initialize LLM service: ${e.message}")
+                // TODO: Use proper logging framework
+                // logger.error("[ChatDB] Failed to initialize LLM service", e)
             }

198-199: Pass system prompt as a separate message instead of concatenating with user input.

The streamPrompt method accepts historyMessages: List<Message> which supports proper message roles via MessageRole.SYSTEM. Instead of concatenating the system prompt with the user text (userPrompt = "$systemPrompt\n\nUser: $text"), pass it as a separate message:

service.streamPrompt(
    userPrompt = text,
    historyMessages = listOf(Message(role = MessageRole.SYSTEM, content = systemPrompt)),
    compileDevIns = false
).collect { chunk ->
    // ...
}

This allows the LLM to properly distinguish system instructions from user queries, following the standard message role pattern already implemented in KoogLLMService.buildPrompt.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f7ea233 and 5229c24.

📒 Files selected for processing (12)
  • mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/AgentType.kt (4 hunks)
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentChatInterface.kt (1 hunks)
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentInterfaceRouter.kt (2 hunks)
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/ChatDBPage.kt (1 hunks)
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/ChatDBViewModel.kt (1 hunks)
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/ChatDBChatPane.kt (1 hunks)
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/DataSourceConfigDialog.kt (1 hunks)
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/DataSourcePanel.kt (1 hunks)
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/model/DataSourceModels.kt (1 hunks)
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/TopBarMenuDesktop.kt (1 hunks)
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/TopBarMenuMobile.kt (2 hunks)
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/icons/AutoDevComposeIcons.kt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.kt

📄 CodeRabbit inference engine (AGENTS.md)

**/*.kt: Use expect/actual pattern for platform-specific code (for example: Platform implementations)
Use concrete classes (not interfaces) and Promise (not Flow) for @JsExport annotations
Avoid emoji and UTF-8 characters in WASM code
When modifying CodingAgentRenderer, update ALL implementations: DefaultCodingAgentRenderer, ComposeRenderer, JewelRenderer, ServerSideRenderer, and JsRendererAdapter in Kotlin
When modifying CodingAgentRenderer, update JVM CLI implementations: CodingCliRenderer and ConsoleRenderer
Use AutoDevColors or MaterialTheme.colorScheme for Compose styling

Files:

  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/ChatDBChatPane.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/DataSourceConfigDialog.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/DataSourcePanel.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/ChatDBPage.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/TopBarMenuDesktop.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/model/DataSourceModels.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentInterfaceRouter.kt
  • mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/AgentType.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentChatInterface.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/TopBarMenuMobile.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/ChatDBViewModel.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/icons/AutoDevComposeIcons.kt
**/*.{kt,ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Never use hardcoded colors - always use design tokens from the design system

Files:

  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/ChatDBChatPane.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/DataSourceConfigDialog.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/DataSourcePanel.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/ChatDBPage.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/TopBarMenuDesktop.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/model/DataSourceModels.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentInterfaceRouter.kt
  • mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/AgentType.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentChatInterface.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/TopBarMenuMobile.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/ChatDBViewModel.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/icons/AutoDevComposeIcons.kt
🧠 Learnings (3)
📚 Learning: 2025-12-07T08:40:10.850Z
Learnt from: CR
Repo: phodal/auto-dev PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-07T08:40:10.850Z
Learning: Applies to mpp-vscode/src/**/*.ts : When modifying `CodingAgentRenderer`, update VSCode implementations: `mpp-vscode/src/bridge/mpp-core.ts` and `mpp-vscode/src/providers/chat-view.ts`

Applied to files:

  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentInterfaceRouter.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentChatInterface.kt
📚 Learning: 2025-12-07T08:40:10.850Z
Learnt from: CR
Repo: phodal/auto-dev PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-07T08:40:10.850Z
Learning: Applies to **/*.kt : When modifying `CodingAgentRenderer`, update ALL implementations: `DefaultCodingAgentRenderer`, `ComposeRenderer`, `JewelRenderer`, `ServerSideRenderer`, and `JsRendererAdapter` in Kotlin

Applied to files:

  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentChatInterface.kt
📚 Learning: 2025-12-07T08:40:10.850Z
Learnt from: CR
Repo: phodal/auto-dev PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-07T08:40:10.850Z
Learning: Applies to **/*.kt : When modifying `CodingAgentRenderer`, update JVM CLI implementations: `CodingCliRenderer` and `ConsoleRenderer`

Applied to files:

  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentChatInterface.kt
🧬 Code graph analysis (3)
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/ChatDBChatPane.kt (2)
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentMessageList.kt (1)
  • AgentMessageList (31-158)
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/ChatDBViewModel.kt (1)
  • sendMessage (177-221)
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/ChatDBPage.kt (3)
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/DataSourcePanel.kt (1)
  • DataSourcePanel (23-82)
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/ChatDBChatPane.kt (1)
  • ChatDBChatPane (33-78)
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/DataSourceConfigDialog.kt (1)
  • DataSourceConfigDialog (23-221)
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentInterfaceRouter.kt (1)
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/ChatDBPage.kt (1)
  • ChatDBPage (22-126)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Agent
  • GitHub Check: Test mpp-core (KMP)
  • GitHub Check: Build
🔇 Additional comments (19)
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/icons/AutoDevComposeIcons.kt (1)

116-118: LGTM!

The new Database and Schema icon aliases are well-placed under a clear category comment and follow the established pattern of mapping to Material icons. Using Storage for database and TableChart for schema are semantically appropriate choices.

mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/TopBarMenuDesktop.kt (1)

283-290: LGTM!

The CHAT_DB icon mapping is consistent with other agent type mappings in the when expression. Uses the design token AutoDevComposeIcons.Database as per coding guidelines.

mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/TopBarMenuMobile.kt (1)

221-228: LGTM!

The CHAT_DB icon mapping is correctly added for the Agent Type header display, consistent with the desktop implementation.

mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentInterfaceRouter.kt (1)

6-9: LGTM on new imports.

The imports for ChatDBPage and Workspace are necessary for the new routing logic.

mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/AgentType.kt (3)

35-38: LGTM!

The CHAT_DB enum constant is well-documented and follows the established pattern. The KDoc clearly describes its purpose for text-to-SQL interactions.


45-52: LGTM on display name mapping.

The getDisplayName() extension correctly returns "ChatDB" for the new agent type, maintaining consistency with the feature naming throughout the PR.


54-65: LGTM on string parsing.

The fromString() method handles both "chatdb" and "database" as valid inputs for CHAT_DB, providing flexibility for different input sources.

mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/ChatDBChatPane.kt (2)

264-271: Keyboard handling looks correct.

Enter sends the message, Shift+Enter allows newlines. The implementation correctly prevents send when shift is pressed.


33-78: Well-structured composable layout.

The ChatDBChatPane follows good Compose patterns with clear separation of concerns: status banner, message area with welcome overlay, and input area. The use of MaterialTheme.colorScheme throughout adheres to the design system guidelines.

mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/DataSourceConfigDialog.kt (2)

155-170: Password field implementation looks good.

The password field correctly uses PasswordVisualTransformation with a visibility toggle. Not trimming the password value (line 207) is the correct behavior.


199-210: The empty ID is properly handled by the viewModel layer. When DataSourceConfigDialog passes id = "" to onSave, it calls viewModel.addDataSource(), which generates a unique UUID before storing: id = if (config.id.isBlank()) Uuid.random().toString() else config.id. This ensures no empty IDs reach the LazyColumn, which uses key = { it.id } for recomposition. The design correctly separates concerns: UI layer doesn't generate IDs; viewModel ensures uniqueness before state updates.

mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/ChatDBPage.kt (2)

128-168: SchemaInfoDialog implementation is clean and functional.

The dialog properly handles null schema, limits display to 10 tables with an overflow indicator, and uses Material theme styling correctly. Good implementation.


31-31: No issue: llmService is not a constructor parameter.

The ChatDBViewModel constructor intentionally takes only the workspace parameter. The llmService is initialized internally via the initializeLLMService() method in the init block, which loads configuration from ConfigManager and creates the service asynchronously. The sendMessage() function properly handles the case where the service is null and displays a user-friendly error message (lines 185-190).

Likely an incorrect or invalid review comment.

mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/components/DataSourcePanel.kt (1)

23-82: Well-structured panel component.

The DataSourcePanel follows good practices with clear separation into private composables (DataSourceHeader, SearchField, DataSourceItem, ConnectionControls). Using key = { it.id } in LazyColumn ensures efficient recomposition. The component correctly uses MaterialTheme.colorScheme for all colors per the coding guidelines.

mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/model/DataSourceModels.kt (2)

92-105: Good use of sealed classes for type-safe state modeling.

ValidationResult and ConnectionStatus are well-designed sealed classes that provide exhaustive pattern matching and clear state representation. This is idiomatic Kotlin.


144-167: ChatDBState is well-structured.

The state class correctly uses derived properties for selectedDataSource and filteredDataSources. For small to moderate data source lists, the on-access computation is acceptable. If performance becomes an issue with large lists, these could be cached.

mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/chatdb/ChatDBViewModel.kt (3)

118-139: L