Skip to content

feat(mpp-idea): add Agent ToolWindow with tab-based navigation - #1

Merged
phodal merged 7 commits into
masterfrom
feat/idea-agent-toolwindow
Nov 29, 2025
Merged

phodal merged 7 commits into
masterfrom
feat/idea-agent-toolwindow

Conversation

@phodal

@phodal phodal commented Nov 29, 2025 •

Copy link
Copy Markdown
Member

Summary

Add a new Agent ToolWindow to the mpp-idea IntelliJ IDEA plugin with tab-based navigation, similar to TopBarMenuDesktop from mpp-ui.

Changes

New Files

  • IdeaAgentApp.kt - Main Compose UI with tabs header and chat interface
  • IdeaAgentViewModel.kt - ViewModel managing agent state, messages, and LLM integration
  • IdeaAgentToolWindowFactory.kt - Factory for creating the ToolWindow
  • AgentType.kt - Enum for agent types (CODING, CODE_REVIEW, KNOWLEDGE, REMOTE)
  • ChatMessage.kt - Data class for chat messages with MessageRole
  • LLMConfig.kt - Configuration model for LLM providers

Modified Files

  • build.gradle.kts - Changed kotlinx/ktor deps to compileOnly to avoid classloader conflicts
  • CoroutineScopeHolder.kt - Fixed to avoid platform childScope API classloader issues
  • plugin.xml - Registered new "AutoDev Agent" ToolWindow

Features

  • Tab-based navigation: Switch between Agentic, Review, Knowledge, Remote modes
  • Chat interface: Message bubbles with user/assistant distinction
  • Streaming output: Support for streaming LLM responses
  • Jewel native UI: Uses IntelliJ's bundled Jewel theme components

Technical Notes

Since mpp-idea uses Jewel theme (bundled with IntelliJ 2025.2+) while mpp-ui uses standalone Compose with Material3, this PR creates Jewel-native equivalents of the UI components rather than directly importing from mpp-ui.

Fixed classloader conflicts by:

  1. Using compileOnly for kotlinx-coroutines and ktor dependencies
  2. Avoiding platform-specific childScope extension function

Testing

  • Build passes (./gradlew :mpp-idea:build)
  • IDE runs without errors (./gradlew :mpp-idea:runIde)
  • ToolWindow displays correctly with tab navigation

Pull Request opened by Augment Code with guidance from the PR author

Summary by CodeRabbit

  • New Features

    • IntelliJ plugin with two AutoDev tool windows and Compose-based chat UIs.
    • Multi-agent modes (Coding, Code Review, Knowledge, Remote), plus chat, message threading and new-conversation controls.
    • LLM configuration UI and support for multiple providers; project-scoped coroutine service and UI icons.
  • Improvements

    • Enhanced domain-dictionary analysis to prioritize important packages.
    • Better streaming instrumentation, error handling and progressive response handling.

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

Changes:
- Reduce batch size from 500 to 100 terms for faster LLM responses
- Process max 3 batches (300 terms) per run with progress feedback
- Add detailed LLM logging (TTFB, chunk count, token usage, timing)
- Simplify filter lists: keep only pure technical terms, let AI decide business relevance
- Remove overly aggressive filtering of potentially business-related terms

The filter simplification allows terms like 'agent', 'chat', 'service' etc.
to be included if they are part of compound business concepts.
- Change maxIterations default expectation from 7 to 1
- Update schema example test to check for focusArea instead of userQuery
- Remove tests for deprecated Deep Research classes
…ation

feat(domain-dict): optimize batch processing and add LLM logging
- Add mpp-idea module as a composite build (includeBuild) to avoid plugin version conflicts
- Use IntelliJ Platform Gradle Plugin 2.10.2 for IDEA 252+ Compose support
- Main project continues to use plugin version 2.1.0 for compatibility
- Add ToolWindow with Compose UI using Jewel theme
- Add ChatApp, ChatViewModel, and CoroutineScopeHolder components
- Target IntelliJ IDEA 2025.2.1 (build 252)

The composite build approach allows mpp-idea to use a different version of the
IntelliJ Platform Gradle Plugin without affecting other modules.
feat(mpp-idea): add Compose UI module for IntelliJ IDEA 2025.2+
- Add IdeaAgentApp.kt with Compose UI for chat interface
- Add IdeaAgentViewModel.kt for managing agent state and messages
- Add IdeaAgentToolWindowFactory.kt for ToolWindow creation
- Add AgentType, ChatMessage, LLMConfig models
- Register AutoDev Agent ToolWindow in plugin.xml
- Fix CoroutineScopeHolder to avoid classloader conflicts
- Use compileOnly for kotlinx/ktor deps to use platform versions

Features:
- Tab-based navigation: Agentic, Review, Knowledge, Remote
- Chat interface with message bubbles
- Streaming output support
- LLM configuration support (placeholder)
@coderabbitai

coderabbitai Bot commented Nov 29, 2025 •

Copy link
Copy Markdown

Walkthrough

Adds package-aware, batched domain-dictionary extraction and stricter name validation in mpp-core; instruments LLM streaming with runtime metrics; and introduces a new IntelliJ plugin module (mpp-idea) providing Compose-based chat/agent tool windows, view models, coroutine scope service, resources, and build integration.

Changes

Cohort / File(s) Summary
mpp-core: Domain dictionary & validation
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/subagent/DomainDictAgent.kt
Adds package-structure analysis (analyzePackageStructure, extractPackagePath), prioritizes hot files by package, extends extractMeaningfulNames to accept importantPackages, switches name generation to batched processing (batchSize=100, maxBatches=3) with per-batch reporting, and tightens validation via isValidOutputEntry, isValidDomainName, isValidDomainConceptName.
mpp-core: LLM streaming instrumentation
mpp-core/src/commonMain/kotlin/cc/unitmesh/llm/KoogLLMService.kt
Adds runtime logging and timing for streaming prompts (prompt length, TTFB, chunk counts, chars, elapsed), per-frame accounting, robust try/catch around stream collection, end-of-stream token/compression handling, and error logging/rethrowing.
mpp-core: Tests trimmed/updated
mpp-core/src/commonTest/kotlin/cc/unitmesh/agent/subagent/DomainDictAgentTest.kt
Reduces default maxIterations (7 → 1), removes large Deep Research test block, updates schema test expectations (focusArea vs userQuery), and minor header/comment edits.
mpp-idea: Gradle & settings
mpp-idea/build.gradle.kts, mpp-idea/settings.gradle.kts, settings.gradle.kts
Adds new mpp-idea composite module with Kotlin/JVM Compose build script, repositories, dependencies, IntelliJ platform configuration (IDEA 2025.2+), and includes the composite build in root settings.
mpp-idea: Models & config
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/model/AgentType.kt, .../ChatMessage.kt, .../LLMConfig.kt
Adds AgentType enum with display names and lookup, ChatMessage data class and MessageRole enum, and LLMConfig/LLMProvider with validation and provider mapping.
mpp-idea: Icons & resources
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/AutoDevIcons.kt, mpp-idea/src/main/resources/META-INF/plugin.xml, mpp-idea/src/main/resources/messages/AutoDevIdeaBundle.properties
Adds Icon loader object for plugin SVGs, plugin.xml declaring service and two tool windows (AutoDev Compose, AutoDev Agent) and Compose dependency, and resource bundle with UI strings.
mpp-idea: Coroutine scope service
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/services/CoroutineScopeHolder.kt
Adds project-level service managing a SupervisorJob-backed CoroutineScope and createScope(name) for child scopes with CoroutineName and isolated SupervisorJob.
mpp-idea: Chat UI & ViewModel
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/AutoDevChatApp.kt, .../AutoDevChatViewModel.kt, .../AutoDevToolWindowFactory.kt
Implements Compose chat UI (header, message list, input), AutoDevChatViewModel with MessageInputState lifecycle and send/abort/new conversation flows, and ToolWindowFactory wiring scope and ViewModel into a Compose tab.
mpp-idea: Agent UI & ViewModel
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt, .../IdeaAgentViewModel.kt, .../IdeaAgentToolWindowFactory.kt
Implements tabbed agent UI with agent-type switching, streaming output handling, simulated LLM responses, LLM config state, and ToolWindowFactory that instantiates and disposes the ViewModel.
mpp-idea: Misc UI files
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/model/*, mpp-idea/src/main/resources/messages/*
Various supporting data classes, enums, and UI string resources for the new plugin module.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Areas requiring extra attention:

  • DomainDictAgent: batch accumulation, maxBatches enforcement, and integration of importantPackages into file prioritization.
  • New validation rules: isValidOutputEntry / isValidDomainConceptName / isValidDomainName for false positives/negatives on real-world names.
  • KoogLLMService: ensure streaming instrumentation doesn't alter timing or content flow and handles errors cleanly.
  • CoroutineScopeHolder lifecycle and child-scope cancellation semantics.
  • Tool window wiring and plugin.xml correctness (icon paths, service registration, tool-window declarations).
  • ViewModel lifecycle and cancellation handling in IdeaAgentViewModel and AutoDevChatViewModel.

Poem

🐰 I hopped through packages, sniffed the hottest files,
Batching carrot-names in tidy little piles.
Streams now whisper metrics, chunks counted with care,
IDE windows bloom—compose fields open and fair.
My whiskers twitch: code stitched, a new warren to share.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 38.18% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: adding an Agent ToolWindow with tab-based navigation to the mpp-idea module, which aligns with the PR objectives and the substantial code additions for this feature.
✨ 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 feat/idea-agent-toolwindow

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

@phodal

phodal commented Nov 29, 2025

Copy link
Copy Markdown
Member 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.

val prioritizedFiles = if (importantPackages.isNotEmpty()) {
insights.hotFiles.sortedByDescending { file ->
val pkg = extractPackagePath(file.path)
if (importantPackages.any { pkg.startsWith(it) || it.startsWith(pkg) }) 2 else 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

In the prioritization check, an empty pkg matches every importantPackages entry because it.startsWith("") is always true; consider skipping empty package paths to avoid unintentionally boosting unrelated files.

🤖 Was this useful? React with 👍 or 👎

* Extract package path from file path
* e.g., "src/main/kotlin/cc/unitmesh/agent/Tool.kt" -> "cc/unitmesh/agent"
*/
private fun extractPackagePath(filePath: String): String {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

extractPackagePath only handles / separators; on Windows-style paths with \ this may fail to extract packages—consider normalizing separators first to ensure cross-platform correctness.

🤖 Was this useful? React with 👍 or 👎

*/
private fun isValidOutputEntry(code: String): Boolean {
// Must have at least 2 capital letters (compound word)
val capitalCount = code.count { it.isUpperCase() }

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 "≥2 uppercase" rule will admit acronyms like "API", which conflicts with the prompt’s compound-word intent; consider excluding all-caps acronyms or enforcing PascalCase/CamelCase to ensure true compounds (also applies to isValidDomainConceptName).

🤖 Was this useful? React with 👍 or 👎

@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. 2 suggestions posted.

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

@Service(Level.PROJECT)
class CoroutineScopeHolder(private val project: Project) {

private val parentJob = SupervisorJob()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This project-level service creates a parent SupervisorJob but never cancels it; without implementing Disposable and cancelling the parent job on service disposal, child scopes can leak beyond the project lifecycle (Guideline: no_memory_leaks) (https://github.com/phodal/auto-dev-sketch/blob/feat/idea-agent-toolwindow/.augment/code_review_guidelines.yaml).

🤖 Was this useful? React with 👍 or 👎

id="AutoDev Compose"
anchor="right"
secondary="true"
icon="cc.unitmesh.devins.idea.AutoDevIcons.ToolWindow"/>

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 toolWindow "icon" attribute usually expects a resource path (e.g., "/icons/autodev-toolwindow.svg") or platform icon ID; using a Kotlin field reference ("cc.unitmesh.devins.idea.AutoDevIcons.ToolWindow") may not resolve at runtime and lead to a missing icon. Consider pointing the attribute to the SVG resource path instead (also applies to the "AutoDev Agent" entry).

🤖 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: 2

♻️ Duplicate comments (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/AutoDevChatViewModel.kt (1)

30-35: Duplicate ChatMessage class — already flagged in model layer.

This ChatMessage uses isUser: Boolean while cc.unitmesh.devins.idea.model.ChatMessage uses MessageRole enum. Consolidate to the model-layer version for consistency.

🧹 Nitpick comments (14)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/subagent/DomainDictAgent.kt (7)

191-206: Batching logic is clear; consider exposing limits or logging truncation

Hard‑coding batchSize = 100 and maxBatches = 3 is fine for now, and the progress messages per batch are helpful. If you expect very large newNames sets, it may be worth:

  • Making these thresholds configurable, or
  • Explicitly logging when newNames.size > namesToProcess.size so users know additional runs are needed to cover all candidates.

290-339: Package-structure heuristics look reasonable; path normalization would improve robustness

The package aggregation and infra filtering rules align with the goal of emphasizing business packages. To avoid surprises on platforms or tools that might emit \ in paths, consider normalizing before regex and substring operations, e.g. in extractPackagePath:

val normalized = filePath.replace('\\', '/')

and then run the existing replacements on normalized.


345-357: extractPackagePath is concise; same note about path separators

The stepwise stripping of common src/... prefixes and then taking substringBeforeLast("/") is straightforward. Applying the same normalization to forward slashes here would keep it safe if upstream ever changes how it formats paths.


359-375: File prioritization by important packages is sensible; consider secondary sort

Using a 2/1 weight to float files under important packages while preserving the original order is a simple and effective heuristic. If insights.hotFiles is not already ordered by change frequency, you might later introduce a secondary sort key (e.g. changeCount) to make prioritization deterministic and clearly hot‑file‑biased within each group.

Also applies to: 378-392


416-452: Stricter domain-concept validation matches the “compound term only” rule

Requiring at least two uppercase letters and expanding the technical skip set brings isValidDomainConceptName in line with the updated prompt and comments (favoring DomainDict over Agent). Just ensure you have/keep tests for representative borderline cases (e.g., acronyms + word, short compound names) so future tweaks don’t silently over‑filter useful concepts.


598-627: Extended infra/platform filters in isValidDomainName align with DDD focus

The added platformTerms and technical suffix filters help avoid JetBrains/platform/UI and DTO/VO‑style names entering the domain dict. This is consistent with the DDD intention; if you later find legitimate business names ending with these suffixes, it might be worth making these lists configurable rather than hardcoded.


743-767: Output entry filter is a good safety net; consider test coverage for it

Adding isValidOutputEntry in parseEntries to enforce “≥2 capitals” and skip purely technical tokens is a useful final guard in case the LLM drifts from the prompt. I’d recommend adding a few focused tests for this helper (e.g., accepting DomainDict, rejecting Agent, rejecting util) so changes to heuristics don’t accidentally widen or narrow the accepted space without notice.

mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/AutoDevChatViewModel.kt (1)

69-91: Placeholder implementation noted — ensure async handling when integrating LLM.

The TODO indicates AI integration is pending. When implementing, remember to:

  1. Launch coroutine for async LLM call
  2. Use Sending state during the request
  3. Handle errors with SendFailed state (currently unused)
  4. Support streaming responses by updating the assistant message content incrementally
mpp-idea/build.gradle.kts (1)

11-12: Consider extracting the version fallback to avoid duplication.

The version fallback logic project.findProperty("mppVersion") as String? ?: "0.3.2" is duplicated on lines 12 and 72.

 group = "cc.unitmesh.devins"
-version = project.findProperty("mppVersion") as String? ?: "0.3.2"
+val mppVersion = project.findProperty("mppVersion") as String? ?: "0.3.2"
+version = mppVersion

Then reference mppVersion in the plugin configuration:

     pluginConfiguration {
         name = "AutoDev Compose UI"
-        version = project.findProperty("mppVersion") as String? ?: "0.3.2"
+        version = mppVersion

Also applies to: 70-73

mpp-idea/src/main/resources/META-INF/plugin.xml (1)

7-10: Consider enriching the plugin description.

The description is minimal. For marketplace visibility, consider adding feature highlights such as:

  • Tab-based agent navigation (Agentic/Review/Knowledge/Remote)
  • Chat interface with streaming LLM support
  • Native Jewel UI integration
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt (1)

259-275: Review the nested Box + OutlinedButton structure.

The AgentTab wraps an OutlinedButton inside a Box with background styling. This creates a layered effect where the Box provides the background and the OutlinedButton renders with its own styling on top. This might produce unexpected visuals (double borders, conflicting backgrounds).

Consider simplifying to either:

  1. Apply the background directly to the OutlinedButton modifier, or
  2. Make the Box itself clickable without the nested button.

Example simplification:

-    Box(
-        modifier = Modifier
-            .height(28.dp)
-            .background(backgroundColor)
-            .padding(horizontal = 12.dp, vertical = 4.dp),
-        contentAlignment = Alignment.Center
-    ) {
-        OutlinedButton(onClick = onClick) {
-            Text(
-                text = type.displayName,
-                style = JewelTheme.defaultTextStyle.copy(
-                    fontSize = 12.sp,
-                    fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal
-                )
-            )
-        }
-    }
+    OutlinedButton(
+        onClick = onClick,
+        modifier = Modifier
+            .height(28.dp)
+            .background(backgroundColor)
+            .padding(horizontal = 12.dp, vertical = 4.dp)
+    ) {
+        Text(
+            text = type.displayName,
+            style = JewelTheme.defaultTextStyle.copy(
+                fontSize = 12.sp,
+                fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal
+            )
+        )
+    }
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/model/LLMConfig.kt (1)

9-22: Consider additional validation for configuration parameters.

The isValid() method checks for required fields but doesn't validate parameter ranges:

  • temperature is typically 0.0 to 2.0 for most LLM providers
  • maxTokens should be positive

Additionally, the default configuration is invalid (empty apiKey with OPENAI provider), which might cause confusion.

Consider adding range validation:

 fun isValid(): Boolean {
+    if (temperature < 0.0 || temperature > 2.0) return false
+    if (maxTokens <= 0) return false
     return when (provider) {
         LLMProvider.OLLAMA -> modelName.isNotEmpty() && baseUrl.isNotEmpty()
         else -> apiKey.isNotEmpty() && modelName.isNotEmpty()
     }
 }
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/AutoDevChatApp.kt (1)

127-150: Consider extracting shared components to reduce duplication.

The MessageBubble and ChatInput implementations in this file are very similar to MessageBubble, StreamingMessageBubble, and ChatInputArea in IdeaAgentApp.kt. This creates maintenance overhead if styling or behavior needs to change across both UIs.

Consider extracting shared composables to a common file (e.g., SharedChatComponents.kt) and parameterizing minor differences like max width and font sizes.

Example structure:

// SharedChatComponents.kt
@Composable
fun ChatMessageBubble(
    content: String,
    isUser: Boolean,
    maxWidth: Dp = 350.dp
) { /* shared implementation */ }

@Composable  
fun ChatInputField(
    enabled: Boolean,
    onSend: (String) -> Unit,
    onAbort: () -> Unit
) { /* shared implementation */ }

Also applies to: 152-208

mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.kt (1)

125-129: Consider preserving partial streaming output on abort.

When abortRequest() is called, the partial streaming output is cleared. For better UX, consider preserving the partial response with an indicator like "[Interrupted]" appended to the message history. This helps users see what was generated before cancellation.

Example:

 fun abortRequest() {
     currentJob?.cancel()
+    // Preserve partial output if any
+    if (_streamingOutput.value.isNotEmpty()) {
+        _messages.value = _messages.value + listOf(
+            ModelChatMessage(
+                content = _streamingOutput.value + "\n\n[Interrupted]",
+                role = MessageRole.ASSISTANT
+            )
+        )
+    }
     _isProcessing.value = false
     _streamingOutput.value = ""
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0632b7f and 89bb488.

⛔ Files ignored due to path filters (2)
  • mpp-idea/src/main/resources/icons/autodev-toolwindow.svg is excluded by !**/*.svg
  • mpp-idea/src/main/resources/icons/autodev.svg is excluded by !**/*.svg
📒 Files selected for processing (19)
  • mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/subagent/DomainDictAgent.kt (9 hunks)
  • mpp-core/src/commonMain/kotlin/cc/unitmesh/llm/KoogLLMService.kt (2 hunks)
  • mpp-core/src/commonTest/kotlin/cc/unitmesh/agent/subagent/DomainDictAgentTest.kt (3 hunks)
  • mpp-idea/build.gradle.kts (1 hunks)
  • mpp-idea/settings.gradle.kts (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/AutoDevIcons.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/model/AgentType.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/model/ChatMessage.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/model/LLMConfig.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/services/CoroutineScopeHolder.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/AutoDevChatApp.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/AutoDevChatViewModel.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/AutoDevToolWindowFactory.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentToolWindowFactory.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.kt (1 hunks)
  • mpp-idea/src/main/resources/META-INF/plugin.xml (1 hunks)
  • mpp-idea/src/main/resources/messages/AutoDevIdeaBundle.properties (1 hunks)
  • settings.gradle.kts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (6)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/AutoDevToolWindowFactory.kt (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/AutoDevChatApp.kt (1)
  • AutoDevChatApp (27-84)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.kt (1)
  • onAgentTypeChange (53-55)
mpp-core/src/commonMain/kotlin/cc/unitmesh/llm/KoogLLMService.kt (2)
mpp-core/src/commonMain/kotlin/cc/unitmesh/indexer/DomainDictGenerator.kt (1)
  • buildPrompt (77-119)
mpp-core/src/jsMain/kotlin/cc/unitmesh/llm/JsExports.kt (1)
  • getMaxTokens (128-131)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/AutoDevChatApp.kt (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/AutoDevChatViewModel.kt (1)
  • onInputChanged (58-64)
mpp-core/src/commonTest/kotlin/cc/unitmesh/agent/subagent/DomainDictAgentTest.kt (1)
mpp-core/src/commonMain/kotlin/cc/unitmesh/devins/test/DevInsTestCase.kt (2)
  • assertEquals (45-49)
  • assertTrue (29-33)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentToolWindowFactory.kt (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt (1)
  • IdeaAgentApp (33-100)
⏰ 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: Test mpp-core (KMP)
  • GitHub Check: Build (241)
  • GitHub Check: Build (223)
🔇 Additional comments (25)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/AutoDevIcons.kt (4)

1-4: LGTM!

The package declaration and imports are appropriate for an IntelliJ plugin icon provider.


6-9: LGTM!

The documentation clearly describes the purpose of the icon provider.


17-21: Icon resource file exists—review comment is not needed.

The /icons/autodev.svg file is present at mpp-idea/src/main/resources/icons/autodev.svg. The IconLoader path resolves correctly, and no runtime failure will occur due to a missing icon resource.


10-15: Icon resource file exists — no issue found.

The icon file is correctly located at mpp-idea/src/main/resources/icons/autodev-toolwindow.svg, matching the path specified in the code. The IconLoader.getIcon() call will successfully resolve the resource at runtime with no issues.

mpp-core/src/commonTest/kotlin/cc/unitmesh/agent/subagent/DomainDictAgentTest.kt (3)

7-10: Header comment now matches actual test scope

The updated description correctly reflects that this file now focuses on data classes only, in line with the removed Deep Research tests.


27-37: Default maxIterations assertion is consistent with DomainDictContext

The expectation of 1 as the default matches the DomainDictContext declaration, so this test will stay aligned with the model.


82-87: Schema example assertion correctly targets focusArea

Checking for focusArea in the example usage matches the new DomainDictAgentSchema.getExampleUsage behavior.

mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/subagent/DomainDictAgent.kt (2)

164-169: Package-aware prioritization integrates cleanly into Step 1

Wiring analyzePackageStructure in and threading importantPackages into extractMeaningfulNames keeps the pipeline linear and backward-compatible (empty set gracefully falls back to original behavior).


659-701: Prompt text is well-aligned with validation logic

The updated instructions (compound words only, explicit allowed/denied examples, JSON‑only output) match the constraints enforced in isValidDomainConceptName, isValidDomainName, and isValidOutputEntry, which should reduce downstream filtering and inconsistencies.

mpp-core/src/commonMain/kotlin/cc/unitmesh/llm/KoogLLMService.kt (2)

61-69: LGTM! Good observability instrumentation.

The added logging and timing instrumentation provides valuable metrics for monitoring LLM streaming performance (prompt length, TTFB, chunk counts, elapsed time). Counter initialization before the try block is correct.


70-83: LGTM! Solid error handling and streaming flow structure.

The try/catch wrapper with detailed error logging, TTFB measurement on first chunk, and .cancellable() for flow cancellation are all best practices for robust streaming LLM interactions.

Also applies to: 108-115

mpp-idea/src/main/resources/messages/AutoDevIdeaBundle.properties (1)

1-17: LGTM!

The resource bundle is well-structured with clear key naming conventions. The grouping by feature (Chat UI, Settings) makes it easy to maintain.

mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/AutoDevChatViewModel.kt (2)

13-25: Well-designed input state machine.

The sealed class provides clear, type-safe state transitions. SendFailed is ready for error handling when async LLM integration is added.


58-64: LGTM!

Input state transitions are handled correctly — preserving Sending state during active requests and properly toggling between Disabled/Enabled based on text content.

settings.gradle.kts (1)

20-20: Composite build setup looks intentional.

Using includeBuild instead of include for mpp-idea creates a separate Gradle build, which aligns with the PR's mention of resolving classloader conflicts with compileOnly dependencies. This isolation is appropriate for an IntelliJ plugin module with different dependency requirements.

mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/model/ChatMessage.kt (1)

6-11: Based on my verification, the original review comment is correct about the duplicate but incomplete in scope. I found:

  1. Both ChatMessage classes are new (added in the same commit)
  2. The toolwindow version is UI-specific with isUser: Boolean
  3. The model version uses a local MessageRole enum instead of the core module's canonical version
  4. There are actually 3 ChatMessage classes and 2 MessageRole enums across the codebase

The core module contains the canonical Message class and MessageRole enum used throughout the codebase (13 imports vs 2 for the model version).

Here is the rewritten review comment:


Consolidate duplicate ChatMessage definitions and use canonical MessageRole from core module.

Two ChatMessage data classes were introduced in this feature (added in the same commit): one in model package with role: MessageRole, another in toolwindow package (inside AutoDevChatViewModel.kt) with isUser: Boolean. Additionally, a local MessageRole enum is defined here instead of using the canonical version from cc.unitmesh.devins.llm.MessageRole (used 13 times across mpp-core, mpp-ui, and mpp-agent modules vs only 2 times for this local copy).

Recommended: Use the core module's Message and MessageRole in mpp-idea, or at minimum consolidate the toolwindow ChatMessage into the model version and replace the local MessageRole enum with an import from core.

mpp-idea/settings.gradle.kts (1)

1-16: LGTM!

Standard Gradle settings file with appropriate repository configuration for a Kotlin/Compose IntelliJ plugin module.

mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/AutoDevToolWindowFactory.kt (1)

18-41: LGTM!

Clean implementation with proper lifecycle management:

  • ViewModel is correctly registered with Disposer for automatic cleanup when the tool window is disposed
  • CoroutineScope is obtained from the project-scoped service, ensuring proper scope hierarchy
  • The Compose tab integration via addComposeTab is the recommended approach for Jewel/IntelliJ integration
mpp-idea/build.gradle.kts (2)

56-63: Bundled module configuration looks correct for IDEA 252+.

The bundled modules for Compose/Jewel support are appropriately specified. Ensure these module names remain stable across IDEA 2025.2.x releases.


41-45: Ktor 3.2.2 is valid and compatible—no issues found.

Verification confirms:

  • Ktor 3.2.2 was released July 14, 2025, and is published on Maven Central
  • Targets Java 8+ runtimes; your project uses JVM 21
  • Compatible with IntelliJ IDEA 2025.2.1 (target platform)
  • Appropriate use of compileOnly scope to avoid classloader conflicts in plugin development
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/model/AgentType.kt (1)

7-34: LGTM!

Well-structured enum with:

  • Clear documentation for each entry
  • Safe lookup function with case-insensitive matching
  • Sensible fallback to CODING as the default agent type
mpp-idea/src/main/resources/META-INF/plugin.xml (1)

23-33: Icon class and resource bundle are properly defined and accessible.

Both referenced resources exist and are correctly configured:

  • AutoDevIcons.ToolWindow is defined at line 15 of mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/AutoDevIcons.kt as a @JvmField and loads the SVG icon properly
  • AutoDevIdeaBundle.properties exists at mpp-idea/src/main/resources/messages/AutoDevIdeaBundle.properties with appropriate message keys including toolwindow.name and toolwindow.title

The plugin.xml tool window registrations are valid with no configuration issues.

mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentToolWindowFactory.kt (1)

36-46: LGTM! Proper lifecycle management.

The implementation correctly:

  • Creates a project-scoped coroutine scope via CoroutineScopeHolder
  • Registers the ViewModel with the tool window's disposable to ensure cleanup
  • Wires the Compose UI with the ViewModel
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.kt (2)

60-92: LGTM! Proper coroutine and error handling.

The sendMessage implementation correctly:

  • Guards against concurrent sends with the isProcessing check
  • Handles cancellation and generic exceptions separately
  • Uses finally block to ensure state cleanup
  • Provides user-facing error messages

153-156: I'll help you verify the concern about safely cancelling the coroutineScope in the dispose() method. Let me examine the CoroutineScopeHolder implementation.
<function_calls>


#!/bin/bash

Find CoroutineScopeHolder file

fd -t f "CoroutineScopeHolder" --extension kt


</function_calls>
<function_calls>


#!/bin/bash

Search for CoroutineScopeHolder class definition and createScope method

rg -n "class CoroutineScopeHolder|fun createScope" --type kotlin -B 2 -A 10


</function_calls>
<function_calls>


#!/bin/bash

Search more broadly for CoroutineScopeHolder

rg -n "CoroutineScopeHolder" --type kotlin -B 1 -A 5


</function_calls>
<function_calls>


#!/bin/bash

Check the IdeaAgentToolWindowFactory to understand scope creation context

fd -t f "IdeaAgentToolWindowFactory" --extension kt


</function_calls>
<function_calls>


#!/bin/bash

Search for the factory file with broader pattern

rg -l "IdeaAgentToolWindowFactory" --type kotlin


</function_calls>
<function_calls>


#!/bin/bash

Let's explore the directory structure first

find . -type f -name "*.kt" | grep -i "factory|holder|scope" | head -20


</function_calls>

Comment on lines +84 to 107
is StreamFrame.End -> {
val elapsed = Clock.System.now().toEpochMilliseconds() - startTime
logger.info { "✅ [LLM] Stream completed - chunks: $chunkCount, chars: $totalChars, time: ${elapsed}ms" }
logger.debug { "StreamFrame.End -> finishReason=${frame.finishReason}, metaInfo=${frame.metaInfo}" }
frame.metaInfo?.let { metaInfo ->
lastTokenInfo = TokenInfo(
totalTokens = metaInfo.totalTokensCount ?: 0,
inputTokens = metaInfo.inputTokensCount ?: 0,
outputTokens = metaInfo.outputTokensCount ?: 0,
timestamp = Clock.System.now().toEpochMilliseconds()
)
logger.info { "📊 [LLM] Token usage - input: ${lastTokenInfo.inputTokens}, output: ${lastTokenInfo.outputTokens}, total: ${lastTokenInfo.totalTokens}" }

onTokenUpdate?.invoke(lastTokenInfo)
if (compressionConfig.autoCompressionEnabled) {
val maxTokens = getMaxTokens()
if (lastTokenInfo.needsCompression(maxTokens, compressionConfig.contextPercentageThreshold)) {
onCompressionNeeded?.invoke(lastTokenInfo.inputTokens, maxTokens)
}
}
}

messagesSinceLastCompression++
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check KoogLLMService instantiation patterns and concurrent usage

echo "=== Searching for KoogLLMService instantiation patterns ==="
rg -n -C3 'KoogLLMService\(' --type=kt | head -50

echo -e "\n=== Searching for streamPrompt call sites ==="
rg -n -C3 '\.streamPrompt\(' --type=kt | head -50

echo -e "\n=== Checking for shared/singleton service instances ==="
rg -n -C3 'companion object|object :.*KoogLLMService|@Singleton|@Inject' --type=kt | grep -A3 -B3 'KoogLLMService\|LLMService' | head -50

echo -e "\n=== Looking for concurrent coroutine launches ==="
rg -n -C4 '(launch|async)\s*\{' --type=kt | grep -B5 -A5 'streamPrompt' | head -50

echo -e "\n=== Checking KoogLLMService class definition ==="
rg -n 'class KoogLLMService' --type=kt -A10

Repository: phodal/auto-dev-sketch

Length of output: 482


🏁 Script executed:

#!/bin/bash
# Description: Check KoogLLMService instantiation patterns and concurrent usage

echo "=== Finding Kotlin files in mpp-core ==="
fd -e kt . mpp-core/ 2>/dev/null | head -20

echo -e "\n=== Searching for KoogLLMService instantiation patterns ==="
rg -n 'KoogLLMService\(' --glob='*.kt' | head -40

echo -e "\n=== Searching for streamPrompt call sites ==="
rg -n '\.streamPrompt\(' --glob='*.kt' | head -40

echo -e "\n=== Checking class definition and scope ==="
rg -n 'class KoogLLMService' --glob='*.kt' -A20 | head -60

echo -e "\n=== Searching for singleton or companion object patterns ==="
rg -n 'companion object|object.*LLMService|@Singleton.*LLMService' --glob='*.kt' | head -30

echo -e "\n=== Looking at IntelliJ plugin integration for service usage ==="
fd -e kt . -path '*plugin*' 2>/dev/null | head -10

Repository: phodal/auto-dev-sketch

Length of output: 13069


🏁 Script executed:

#!/bin/bash
# Description: Examine streamPrompt call sites and service usage patterns

echo "=== ChatCallbacks.kt - streamPrompt call context ==="
rg -n 'streamPrompt' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/ChatCallbacks.kt -B10 -A10

echo -e "\n=== CodeReviewViewModel.kt - streamPrompt call context ==="
rg -n 'streamPrompt' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/codereview/CodeReviewViewModel.kt -B10 -A10

echo -e "\n=== Check if llmService is stored as instance variable ==="
rg -n 'val llmService|var llmService|this.llmService' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/ChatCallbacks.kt -B2 -A2

echo -e "\n=== Check AgentService for singleton pattern ==="
cat mpp-server/src/main/kotlin/cc/unitmesh/server/service/AgentService.kt | sed -n '210,230p'

echo -e "\n=== Look for concurrent calls - launch/async patterns around streamPrompt ==="
rg -n '(launch|async)' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/ChatCallbacks.kt -B3 -A3

rg -n '(launch|async)' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/codereview/CodeReviewViewModel.kt -B3 -A3

Repository: phodal/auto-dev-sketch

Length of output: 6189


🏁 Script executed:

#!/bin/bash
# Description: Determine how llmService is obtained/created in ChatCallbacks

echo "=== ChatCallbacks.kt - full context of streamPrompt usage ==="
head -150 mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/ChatCallbacks.kt | tail -80

echo -e "\n=== Check if llmService is a class property or function parameter ==="
rg -n 'fun.*llmService|llmService.*:.*KoogLLMService' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/ChatCallbacks.kt -B3 -A3

echo -e "\n=== Search for KoogLLMService pooling or caching patterns ==="
rg -n 'cache.*KoogLLMService|pool.*KoogLLMService|object.*LLMService.*singleton|@Singleton' --glob='*.kt'

echo -e "\n=== Check how handleSendMessage is called - from where does llmService come ==="
rg -n 'handleSendMessage' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/ChatCallbacks.kt -B2 -A2

echo -e "\n=== Search for where KoogLLMService instances are created or stored in UI layer ==="
rg -n 'KoogLLMService\(' mpp-ui/src/commonMain/kotlin -l | head -5

echo -e "\n=== Check ChatViewModel or similar for service management ==="
rg -n 'class.*ViewModel|val llmService' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/ --glob='*.kt' | head -20

Repository: phodal/auto-dev-sketch

Length of output: 3782


🏁 Script executed:

#!/bin/bash
# Description: Find where createChatCallbacks is called and how llmService is created

echo "=== Search for callers of createChatCallbacks ==="
rg -n 'createChatCallbacks' --glob='*.kt' -B3 -A3

echo -e "\n=== Look for ChatViewModel or similar that might manage llmService ==="
fd -e kt -path '*chat*' mpp-ui/src/commonMain/kotlin | head -20

echo -e "\n=== Check if there's a dedicated Chat service or manager ==="
fd -e kt -path '*chat*' mpp-ui/src/ | grep -i viewmodel | head -10

echo -e "\n=== Search for Chat-related files in UI layer ==="
find mpp-ui/src/commonMain/kotlin -name '*Chat*' -o -name '*chat*' | head -20

Repository: phodal/auto-dev-sketch

Length of output: 6121


🏁 Script executed:

#!/bin/bash
# Description: Check how llmService is managed in AutoDevApp

echo "=== AutoDevApp.kt - llmService initialization and management ==="
rg -n 'llmService' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/AutoDevApp.kt | head -30

echo -e "\n=== Look at context around llmService variable in AutoDevApp ==="
rg -n 'var llmService|val llmService' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/AutoDevApp.kt -B5 -A5

echo -e "\n=== Check AutoDevApp.kt file size and structure ==="
wc -l mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/AutoDevApp.kt

echo -e "\n=== Look for where llmService is created/initialized ==="
rg -n 'KoogLLMService|\.create\(' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/AutoDevApp.kt -B3 -A3

echo -e "\n=== Check for state management of llmService ==="
sed -n '280,310p' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/AutoDevApp.kt

Repository: phodal/auto-dev-sketch

Length of output: 5677


🏁 Script executed:

#!/bin/bash
# Description: Determine if multiple streamPrompt calls can happen concurrently on same service instance

echo "=== Check the scope parameter in sendToLLM - is it a ViewModelScope or CoroutineScope? ==="
rg -n 'scope.*CoroutineScope|scope.*=.*' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/AutoDevApp.kt | grep scope | head -10

echo -e "\n=== Look at where handleSendMessage is called from - UI button handler ==="
rg -n 'handleSendMessage' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/ -B5 -A2

echo -e "\n=== Check if onProcessingChange prevents concurrent calls ==="
rg -n 'onProcessingChange' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/ChatCallbacks.kt -B2 -A2

echo -e "\n=== Look for where handleSendMessage callback is used in UI ==="
rg -n 'callbacks.handleSendMessage|handleSendMessage' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/ | head -20

echo -e "\n=== Check AutoDevApp's scope initialization ==="
rg -n 'val scope|rememberCoroutineScope' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/AutoDevApp.kt

Repository: phodal/auto-dev-sketch

Length of output: 1802


🏁 Script executed:

#!/bin/bash
# Description: Check if UI prevents concurrent message sends

echo "=== Search for isProcessing or processing state in AutoDevApp ==="
rg -n 'isProcessing|processing' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/AutoDevApp.kt | head -20

echo -e "\n=== Look for send button implementation and enabled state ==="
rg -n 'Button.*enabled|enabled.*=|SendButton|send.*button' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/ -i -B2 -A2 | head -50

echo -e "\n=== Search for where callbacks are called in chat interface ==="
rg -n 'callbacks\.' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/ | head -30

echo -e "\n=== Look at chat input/send area where callbacks.handleSendMessage is invoked ==="
rg -n 'handleSendMessage\|ChatInput\|sendMessage' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/ -B5 -A5 | head -60

Repository: phodal/auto-dev-sketch

Length of output: 6081


🏁 Script executed:

#!/bin/bash
# Description: Find where handleSendMessage is called and if sends are serialized

echo "=== Search for BottomToolbar usage and sendEnabled state ==="
rg -n 'BottomToolbar' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/AutoDevApp.kt -B5 -A10 | head -40

echo -e "\n=== Look for onSendClick handler ==="
rg -n 'onSendClick' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/AutoDevApp.kt -B3 -A3

echo -e "\n=== Search for where callbacks.handleSendMessage is invoked ==="
rg -n 'callbacks\.handleSendMessage' mpp-ui/src/commonMain/ --glob='*.kt'

echo -e "\n=== Look for EditorCallbacks interface to understand callback structure ==="
rg -n 'interface EditorCallbacks|fun handleSendMessage' --glob='*.kt' -B2 -A8 | head -50

Repository: phodal/auto-dev-sketch

Length of output: 1356


🏁 Script executed:

#!/bin/bash
# Description: Find the complete EditorCallbacks interface and callback mapping

echo "=== Read full EditorCallbacks interface ==="
cat mpp-core/src/commonMain/kotlin/cc/unitmesh/devins/editor/EditorCallbacks.kt

echo -e "\n=== Look at full createChatCallbacks implementation ==="
cat mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/chat/ChatCallbacks.kt

echo -e "\n=== Search for where onSubmit is called ==="
rg -n 'onSubmit' mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/ --glob='*.kt' | head -20

Repository: phodal/auto-dev-sketch

Length of output: 8490


Based on my verification, I have confirmed the concurrency concern in the original review comment. Here are my findings:

Concurrency Issue Confirmed:

  1. Multiple streamPrompt calls can execute concurrently: The onSubmit() callback (line 30 in ChatCallbacks.kt) launches both compileDevIns() and sendToLLM() independently using scope.launch {} without synchronization. Users can trigger multiple onSubmit calls rapidly (via keyboard shortcuts, button clicks, enter key as shown in DevInEditorInput.kt lines 273, 398, 502, 582).

  2. Same service instance reused: The llmService is a Compose state variable (AutoDevApp.kt line 108) that persists for the entire chat session. When a new model config is selected, a new instance is created, but within a session, the same instance handles multiple streamPrompt() calls.

  3. Race conditions on shared mutable state: When multiple coroutines execute streamPrompt() concurrently:

    • Lines 89-94: lastTokenInfo updated without synchronization
    • Line 106: messagesSinceLastCompression incremented without synchronization
    • tryCompressHistory (line 180+): reads/writes hasFailedCompressionAttempt without synchronization
  4. Flow collection doesn't serialize: Each scope.launch creates an independent coroutine that collects the Flow, so there's no built-in serialization between multiple concurrent message sends.


Verify thread safety: concurrent access to shared mutable state.

When onSubmit() is called multiple times rapidly (e.g., user sends multiple messages before the first completes, or presses keyboard shortcuts), multiple coroutines execute streamPrompt() concurrently on the same KoogLLMService instance within a chat session. The mutable properties lastTokenInfo, messagesSinceLastCompression, and hasFailedCompressionAttempt are updated without synchronization, leading to race conditions.

Consider:

  • Using thread-safe primitives (e.g., AtomicReference, AtomicInteger for multiplatform, or Kotlin's Mutex/channels) for shared state
  • Serializing streamPrompt calls within a single service instance if concurrent execution is not required
  • Adding explicit documentation if the service is designed for single-threaded use only
🤖 Prompt for AI Agents
In mpp-core/src/commonMain/kotlin/cc/unitmesh/llm/KoogLLMService.kt around lines
84–107, shared mutable state (lastTokenInfo, messagesSinceLastCompression,
hasFailedCompressionAttempt and other reads/writes in tryCompressHistory) is
mutated from concurrently launched coroutines causing race conditions; protect
these mutations by adding a synchronization strategy (e.g., a Mutex in the
service or platform-safe atomic types) and wrap every read/write to those fields
(including updates inside Flow collection and tryCompressHistory) in a critical
section (withLock or atomic ops), or alternatively serialize streamPrompt calls
per service instance so concurrent collections cannot run simultaneously; apply
the chosen approach consistently across all accesses to these variables and
update any related logic (token update, compression decision, failure flag) to
use the synchronized values.

- CoroutineScopeHolder: implement Disposable to cancel parentJob on project disposal
- IdeaAgentViewModel: preserve partial streaming output on abort
- IdeaAgentApp: simplify AgentTab structure by removing nested Box
- build.gradle.kts: extract mppVersion variable to avoid duplication
- DomainDictAgent: normalize path separators and skip empty package paths
@phodal

phodal commented Nov 29, 2025

Copy link
Copy Markdown
Member 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. 1 suggestions posted.

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

* e.g., "src/main/kotlin/cc/unitmesh/agent/Tool.kt" -> "cc/unitmesh/agent"
* Handles both Unix (/) and Windows (\) path separators.
*/
private fun extractPackagePath(filePath: String): String {

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 handling Kotlin Multiplatform source sets in extractPackagePath (e.g., jvmMain/jsMain/androidMain/iosMain); otherwise paths like src/jvmMain/kotlin/... may leave jvmMain/kotlin in the package, reducing accuracy of business package detection.

🤖 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: 5

♻️ Duplicate comments (1)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/subagent/DomainDictAgent.kt (1)

453-456: Acronym handling noted in previous review.

The "≥2 uppercase" rule will still admit all-caps acronyms like "API" or "HTTP". This was flagged in a previous review. If this becomes problematic, consider adding an additional check to exclude all-caps strings (e.g., if (name.all { it.isUpperCase() }) return false), though this is already partially handled at line 641 in isValidDomainName.

🧹 Nitpick comments (4)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/services/CoroutineScopeHolder.kt (1)

23-36: Clarify or remove the unused projectWideCoroutineScope to match the KDoc

Right now projectWideCoroutineScope is created but never used; all relationships are expressed via parentJob instead, while the KDoc keeps referring to “projectWideCoroutineScope scope”. This can confuse readers about what the actual root scope is.

Two options you could consider:

  • If you intend callers to use a shared project-wide scope, expose it via a fun projectScope(): CoroutineScope (and update KDoc accordingly).
  • If the only thing you need is the parent Job, drop projectWideCoroutineScope and adjust the KDoc to talk about parentJob / “the service’s root job” instead.

For example, to simplify:

-    private val parentJob = SupervisorJob()
-    private val projectWideCoroutineScope: CoroutineScope = CoroutineScope(parentJob + Dispatchers.Default)
+    private val parentJob = SupervisorJob()

and then tweak the KDoc to describe the hierarchy in terms of the service’s root job rather than projectWideCoroutineScope.

mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt (3)

42-49: Consider simplifying the auto-scroll logic.

The conditional on line 46 is complex and could be more readable. Consider calculating the target index more explicitly or adding a comment explaining the logic.

Suggested refactor:

     // Auto-scroll to bottom when new messages arrive
     LaunchedEffect(messages.size, streamingOutput) {
         if (messages.isNotEmpty() || streamingOutput.isNotEmpty()) {
+            // Scroll to streaming message if active, otherwise to last message
+            val targetIndex = if (streamingOutput.isNotEmpty()) {
+                messages.size  // Streaming item comes after all messages
+            } else {
+                messages.lastIndex.coerceAtLeast(0)
+            }
             listState.animateScrollToItem(
-                if (streamingOutput.isNotEmpty()) messages.size else messages.lastIndex.coerceAtLeast(0)
+                targetIndex
             )
         }
     }

282-289: Remove redundant state synchronization.

Maintaining both textFieldState and inputText with a LaunchedEffect to sync them is unnecessary. Read directly from textFieldState.text.toString() when checking if the input is blank.

Apply this diff:

 private fun ChatInputArea(
     isProcessing: Boolean,
     onSend: (String) -> Unit,
     onAbort: () -> Unit
 ) {
     val textFieldState = rememberTextFieldState()
-    var inputText by remember { mutableStateOf("") }
-
-    LaunchedEffect(Unit) {
-        snapshotFlow { textFieldState.text.toString() }
-            .distinctUntilChanged()
-            .collect { inputText = it }
-    }
 
     Row(
         modifier = Modifier
             .fillMaxWidth()
             .padding(8.dp),
         horizontalArrangement = Arrangement.spacedBy(8.dp),
         verticalAlignment = Alignment.CenterVertically
     ) {
         TextField(
             state = textFieldState,
             placeholder = { Text("Type your message...") },
             modifier = Modifier
                 .weight(1f)
                 .onPreviewKeyEvent { keyEvent ->
                     if (keyEvent.key == Key.Enter && keyEvent.type == KeyEventType.KeyDown && !isProcessing) {
+                        val text = textFieldState.text.toString()
-                        if (inputText.isNotBlank()) {
+                        if (text.isNotBlank()) {
-                            onSend(inputText)
+                            onSend(text)
                             textFieldState.edit { replace(0, length, "") }
                         }
                         true
                     } else {
                         false
                     }
                 },
             enabled = !isProcessing
         )
 
         if (isProcessing) {
             DefaultButton(onClick = onAbort) {
                 Text("Stop")
             }
         } else {
+            val text = textFieldState.text.toString()
             DefaultButton(
                 onClick = {
+                    val currentText = textFieldState.text.toString()
-                    if (inputText.isNotBlank()) {
+                    if (currentText.isNotBlank()) {
-                        onSend(inputText)
+                        onSend(currentText)
                         textFieldState.edit { replace(0, length, "") }
                     }
                 },
-                enabled = inputText.isNotBlank()
+                enabled = text.isNotBlank()
             ) {
                 Text("Send")
             }
         }
     }
 }

303-313: Consider supporting Shift+Enter for multi-line input.

The current implementation sends the message on any Enter key press. Many users expect Shift+Enter to create a new line. Consider checking for shift modifier if multi-line input is desired.

Example enhancement:

                 .onPreviewKeyEvent { keyEvent ->
-                    if (keyEvent.key == Key.Enter && keyEvent.type == KeyEventType.KeyDown && !isProcessing) {
+                    val isShiftPressed = keyEvent.isShiftPressed
+                    if (keyEvent.key == Key.Enter && keyEvent.type == KeyEventType.KeyDown && !isShiftPressed && !isProcessing) {
                         val text = textFieldState.text.toString()
                         if (text.isNotBlank()) {
                             onSend(text)
                             textFieldState.edit { replace(0, length, "") }
                         }
                         true
                     } else {
                         false
                     }
                 },
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 89bb488 and 0c97915.

📒 Files selected for processing (5)
  • mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/subagent/DomainDictAgent.kt (9 hunks)
  • mpp-idea/build.gradle.kts (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/services/CoroutineScopeHolder.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.kt (1 hunks)
🔇 Additional comments (15)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/subagent/DomainDictAgent.kt (9)

164-168: LGTM!

The integration of package structure analysis flows cleanly into the name extraction step, enabling prioritization of business-relevant files.


191-206: LGTM! Batch processing improves responsiveness.

The chunked processing with progress reporting is well-structured. Consider whether partial results should be preserved if a later batch fails, though the current approach of failing fast is reasonable for this use case.


290-339: LGTM!

The heuristic approach to identify business packages by filtering infrastructure patterns and ranking by change frequency is a pragmatic solution for prioritizing domain-relevant code.


341-361: Cross-platform path handling addressed.

The normalization of backslashes to forward slashes (line 348) properly addresses the Windows path separator concern from the previous review.


370-382: Empty package path handling addressed.

Line 376 now correctly skips empty package paths to avoid the startsWith("") always-true issue flagged in the previous review.


599-654: LGTM!

The validation logic is thorough with appropriate skip lists. The all-uppercase check at line 641 properly excludes pure acronyms in this function.


666-708: LGTM!

The DDD-focused prompt with explicit compound word requirements and clear examples should effectively guide LLM output toward business-relevant domain terms.


746-756: LGTM!

Adding isValidOutputEntry validation at parse time provides a useful safety net to filter out non-compound terms that may slip through LLM output despite the prompt instructions.


758-774: LGTM!

Lean validation for LLM output is appropriate here—the compound word check is the key filter, and the minimal skip list handles obvious technical leakage.

mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/services/CoroutineScopeHolder.kt (1)

20-48: Coroutine lifecycle & disposal look correct for a project service

Using a project-scoped SupervisorJob as the parent plus SupervisorJob(parentJob) for each child scope gives the expected hierarchy: children can be canceled independently, while dispose() canceling parentJob tears down all outstanding work on project close. This addresses the earlier leak concern around never canceling the parent scope and is aligned with kotlinx-coroutines usage on the IntelliJ platform.

mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.kt (1)

23-55: LGTM: Clean state management setup.

The StateFlow declarations and basic state mutation methods are well-structured. The use of private mutable flows with public immutable StateFlow exposure follows best practices.

mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt (2)

33-100: LGTM: Well-structured Compose UI with clean separation.

The main IdeaAgentApp composable is well-organized with clear separation between tabs, content, and input areas. The state collection and event handling integration with the ViewModel follows Compose best practices.


117-117: I'll help you verify the review comment about the ChatMessage.id property usage. Let me start by exploring the codebase to find the ChatMessage model definition and confirm whether this concern is valid.
<function_calls>


#!/bin/bash

Find ChatMessage model definition

fd ChatMessage --type=kt


</function_calls>

Let me search more broadly for the ChatMessage class:
<function_calls>


#!/bin/bash

Search for ChatMessage class definition

rg -n "class ChatMessage|data class ChatMessage" --type=kt -A 15


</function_calls>

Let me also check the specific file mentioned in the review to understand the full context:
<function_calls>


#!/bin/bash

Read the IdeaAgentApp.kt file around line 117

wc -l "mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt" &&
head -130 "mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt" | tail -40


</function_calls>

mpp-idea/build.gradle.kts (2)

80-81: Confirm that disabling searchable options and instrumentation is intentional.

Lines 80-81 disable buildSearchableOptions and instrumentCode. This is typically safe for UI-focused plugins but confirm this aligns with your plugin requirements:

  • Disabling searchable options may hide plugin settings from IntelliJ's quick search.
  • Disabling instrumentation skips bytecode profiling hooks, which is usually fine unless you rely on coverage or performance metrics.

If these settings are necessary to avoid classloader conflicts (consistent with the compileOnly strategy), document this decision clearly in a comment or ADR.


70-78: Based on the verification results, I can now provide the rewritten review comment:


Plugin naming is correctly configured and consistent across configuration files.

The plugin name "AutoDev Compose UI" in build.gradle.kts (line 72) matches the plugin descriptor at mpp-idea/src/main/resources/META-INF/plugin.xml (line 4). The reference to "AutoDev Agent ToolWindow" in PR context is not the plugin name but rather one of two registered tool window IDs (id="AutoDev Agent" at line 30 of plugin.xml). This is intentional: the mpp-idea module provides two distinct tool windows—"AutoDev Compose" and "AutoDev Agent"—within a single plugin.

The versioning strategy is also consistent: mppVersion defaults to "0.3.2" (line 12 of build.gradle.kts) and is applied uniformly to both the project version (line 13) and plugin version (line 73).

Comment thread mpp-idea/build.gradle.kts
Comment on lines +36 to +47
dependencies {
// Use platform-provided kotlinx libraries to avoid classloader conflicts
compileOnly("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
compileOnly("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.1")

// Ktor HTTP Client for LLM API calls - use compileOnly for libraries that may conflict
compileOnly("io.ktor:ktor-client-core:3.2.2")
compileOnly("io.ktor:ktor-client-cio:3.2.2")
compileOnly("io.ktor:ktor-client-content-negotiation:3.2.2")
compileOnly("io.ktor:ktor-serialization-kotlinx-json:3.2.2")
compileOnly("io.ktor:ktor-client-logging:3.2.2")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# First, let's examine the full build.gradle.kts file to understand the build configuration
# and see if there are any intellijPlatform configurations that affect dependency resolution

cat mpp-idea/build.gradle.kts

Repository: phodal/auto-dev-sketch

Length of output: 2360


🏁 Script executed:

#!/bin/bash
# Search for intellijPlatform or bundled library references in the project
rg -i "intellij|platform|bundled" --type kotlin --type gradle -A 3 -B 3

Repository: phodal/auto-dev-sketch

Length of output: 50380


🌐 Web query:

IntelliJ IDEA 2025.2 build 252 bundled libraries kotlinx-coroutines ktor dependencies

💡 Result:

Short answer — what’s bundled in IntelliJ IDEA 2025.2 (build 252):

  • kotlinx.coroutines: JetBrains repackages kotlinx-coroutines artifacts under the com.intellij.platform group for the IDE (examples found on Maven: com.intellij.platform:kotlinx-coroutines-core-jvm and com.intellij.platform:kotlinx-coroutines-android, e.g. 1.10.1-intellij-* variants used in 2025 builds). [1][2]

  • Ktor: the IDE exposes Ktor client/server modules as bundled library artifacts under com.jetbrains.intellij.libraries (e.g. libraries-ktor-client, libraries-ktor-client.cio) with IDE-specific versions that match the IDE build (you can depend on them via bundledModule("intellij.libraries.ktor.client") / plugin dependency intellij.libraries.ktor.client). The IDE release repository lists these libraries keyed by IDE build version (252.* for 2025.2). [3][4]

If you need exact artifact coordinates and the precise intellij-* version shipped in your specific 252.x build (for example com.intellij.platform:kotlinx-coroutines-core-jvm:1.10.1-intellij-4 or com.jetbrains.intellij.libraries:libraries-ktor-client:252.23892.409), tell me your exact 252 build number (the full build string) and I’ll fetch the matching artifact coordinates. [2][4]

Sources:

  1. com.intellij.platform kotlinx-coroutines core/android artifacts on Maven (examples). [Maven / mvnrepository]. [1]
  2. com.intellij.platform:kotlinx-coroutines-core-jvm listings (intellij-* versions used in 2025). [2]
  3. JetBrains platform discussion / docs about intellij.libraries.ktor.client and using bundled Ktor in plugins. [3]
  4. IntelliJ release repository / Maven listing showing libraries keyed by IDE build (e.g. 252.23892.409). [4]

🌐 Web query:

IntelliJ IDEA plugin development compileOnly dependencies classpath resolution

💡 Result:

Short answer: compileOnly is compile-time only (mapped to IDEA's "Provided" scope) so it won't be on the runtime classpath. For IntelliJ plugin development you must either declare the dependency so the IntelliJ Platform provides it at runtime (use the plugin/bundledPlugin/bundledModule helpers and list the dependency in plugin.xml), or put the artifact onto the plugin runtime classpath (e.g. implementation/runtimeOnly or add it to the runIde task classpath). Example options:

  • Keep compile-time-only API for compilation in Gradle:
    dependencies {
    compileOnly "group:artifact:version" // available to compiler / IDEA (Provided scope) but not at runtime.
    }
    (Gradle docs: compileOnly semantics). [1]

  • If the dependency is an IntelliJ plugin or bundled module, declare it via the Gradle IntelliJ Plugin and also add a (or block) in plugin.xml so it’s available at runtime when your plugin runs in the IDE. Example: intellij { bundledPlugin("com.intellij.java") } + matching in plugin.xml. (Gradle IntelliJ Plugin / JetBrains docs). [2]

  • If the library should be present when running runIde locally, either make it a runtime/implementation dependency (so it's packaged/available at runtime) or explicitly add the compile classpath to the run task:
    tasks.named("runIde") {
    classpath += configurations.compileClasspath
    }
    or add the artifact to a configuration the plugin runtime uses. (Practical workaround discussed on StackOverflow). [3]

References

  • Gradle: compileOnly / provided semantics. [1]
  • JetBrains: Gradle-IntelliJ plugin + plugin dependency rules (declare bundledPlugin/plugin and add depends in plugin.xml). [2]
  • Community Q&A showing adding compileClasspath to run task when you need compileOnly artifacts at runtime. [3]

If you want, tell me which dependency you’re trying to use and your build.gradle, and I’ll give the exact snippet to make it available at compile time and (if needed) at runIde/runtime.


🏁 Script executed:

#!/bin/bash
# Find plugin.xml files
find . -name "plugin.xml" -o -name "plugin.xml.in" | head -20

Repository: phodal/auto-dev-sketch

Length of output: 503


🏁 Script executed:

#!/bin/bash
# Check mpp-idea directory structure for plugin configuration
ls -la mpp-idea/

Repository: phodal/auto-dev-sketch

Length of output: 369


🏁 Script executed:

#!/bin/bash
# Look for any plugin.xml in mpp-idea specifically
find mpp-idea -type f -name "*.xml" 2>/dev/null

Repository: phodal/auto-dev-sketch

Length of output: 113


🌐 Web query:

IntelliJ IDEA 2025.2 build 252 bundled Ktor client CIO libraries available bundledModule

💡 Result:

Short answer: Yes — IntelliJ 2025.2 (EAP/discussions for build 252) exposes bundled Ktor client libraries you can reference as bundled modules named like

  • intellij.libraries.ktor.client
  • intellij.libraries.ktor.client.cio

Use bundledModule("intellij.libraries.ktor.client") and bundledModule("intellij.libraries.ktor.client.cio") in your Gradle intellijPlatform dependencies. However, several threads report runtime NoClassDefFoundError unless you also declare the dependency in your plugin descriptor (and in some cases switch to the plugin-v2 dependency format / use with ). See reports and guidance: [1][2]. For general engine usage see Ktor docs. [3]

Sources:

  1. IntelliJ Platform forum thread showing bundledModule names and runtime issues. [1]
  2. JetBrains Platform blog note about extracted modules / explicit bundledModule + plugin.xml dependency requirements. [2]
  3. Ktor client engines docs. [3]

🏁 Script executed:

#!/bin/bash
# Read the plugin.xml for mpp-idea
cat mpp-idea/src/main/resources/META-INF/plugin.xml

Repository: phodal/auto-dev-sketch

Length of output: 1721


🏁 Script executed:

#!/bin/bash
# Check if there are any test sources that might provide evidence of runtime usage
ls -la mpp-idea/src/

Repository: phodal/auto-dev-sketch

Length of output: 227


🏁 Script executed:

#!/bin/bash
# Search for actual usage of Ktor and kotlinx in mpp-idea source code
rg "(ktor|kotlinx)" mpp-idea/src/main/kotlin --type kotlin -l

Repository: phodal/auto-dev-sketch

Length of output: 535


Explicitly declare bundled modules for Ktor and kotlinx libraries in build.gradle.kts.

The compileOnly dependencies (Ktor client, kotlinx-coroutines, kotlinx-serialization) are marked as "compile-time only" but lack corresponding bundledModule() declarations in the intellijPlatform block, despite being directly used in the code (e.g., CoroutineScopeHolder.kt, IdeaAgentViewModel.kt, and LLM API calls). The code currently relies on these libraries being transitively available through intellij.platform.compose, which is fragile.

Add explicit bundledModule() entries for:

  • intellij.libraries.ktor.client
  • intellij.libraries.ktor.client.cio
  • intellij.platform.kotlinx.coroutines.core
  • intellij.platform.kotlinx.serialization.json

Without these declarations, runtime ClassNotFoundException or NoSuchMethodError may occur if the platform's transitive dependency chain changes or if the plugin is used in environments where compose support is unavailable.

🤖 Prompt for AI Agents
In mpp-idea/build.gradle.kts around lines 36 to 47, the Ktor and kotlinx
libraries are declared as compileOnly but lack corresponding bundledModule()
entries in the intellijPlatform block; add explicit bundledModule declarations
for intellij.libraries.ktor.client, intellij.libraries.ktor.client.cio,
intellij.platform.kotlinx.coroutines.core, and
intellij.platform.kotlinx.serialization.json inside the intellijPlatform { ... }
configuration so the plugin bundles those platform-provided modules at runtime
and avoids ClassNotFoundException/NoSuchMethodError when compose or transitive
dependencies are not present.

Comment thread mpp-idea/build.gradle.kts
Comment on lines +50 to +68
intellijPlatform {
// Target IntelliJ IDEA 2025.2+ for Compose support
create("IC", "2025.2.1")

bundledPlugins("com.intellij.java")

// Compose support dependencies (bundled in IDEA 252+)
bundledModules(
"intellij.libraries.skiko",
"intellij.libraries.compose.foundation.desktop",
"intellij.platform.jewel.foundation",
"intellij.platform.jewel.ui",
"intellij.platform.jewel.ideLafBridge",
"intellij.platform.compose"
)

testFramework(TestFrameworkType.Platform)
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# First, let's understand the repository structure and locate the build file
git ls-files | head -20

Repository: phodal/auto-dev-sketch

Length of output: 681


🏁 Script executed:

#!/bin/bash
# Find the mpp-idea/build.gradle.kts file and examine its content
find . -path "*/mpp-idea/build.gradle.kts" -type f

Repository: phodal/auto-dev-sketch

Length of output: 93


🏁 Script executed:

#!/bin/bash
# Check file size and read the full content
wc -l ./mpp-idea/build.gradle.kts
echo "---"
cat -n ./mpp-idea/build.gradle.kts

Repository: phodal/auto-dev-sketch

Length of output: 3011


🌐 Web query:

IntelliJ IDEA 2025.2.1 build 252 bundled modules jewel compose skiko

💡 Result:

Short answer: Yes.

  • The Compose IDE plugin is bundled for the 252 (2025.2) release line (compose-ide-plugin artifacts for build 252 are present in the JetBrains releases repo). [1]
  • Skiko (the Skia bindings used by Compose) is provided as platform libraries / artifacts used by the 252 platform (Skiko-related library artifacts appear in the IntelliJ/JetBrains repositories). [1][2]
  • Jewel (the JetBrains "Jewel" Compose UI/theme) has published artifacts tied to the 252 platform and has been integrated/kept in sync with the IntelliJ platform (Jewel artifacts with 252 versions are available on Maven Central and discussions note its alignment/merging with the platform). [3][4]

Sources:

  1. JetBrains IntelliJ releases / plugin artifacts listing (compose, platform build 252). [JetBrains releases]. [1]
  2. Skiko project & IntelliJ/JetBrains skiko library artifacts. [Skiko repo / IntelliJ libraries]. [2]
  3. Jewel GitHub / docs (Jewel releases targeting IntelliJ 252). [3]
  4. Maven Central / mvnrepository listings for jewel artifacts with 252 coordinates. [4]

If you want, I can list the exact artifact coordinates (groupId:artifactId:version) for compose, skiko and jewel for build 252.


🌐 Web query:

intellij.platform.jewel.ideLafBridge bundled module name IDEA 2025

💡 Result:

The bundled module name is intellij.platform.jewel.ideLafBridgeStyling. [1]

Source:

  • IntelliJ IDEA package file list (intellij-idea-community-edition 2025.2.3) showing intellij.platform.jewel.markdown.ideLafBridgeStyling.jar in lib/modules. [1]

🌐 Web query:

IntelliJ IDEA 2025.2.1 jewel modules bundled lib/modules ideLafBridge

💡 Result:

The IDE includes the Jewel LAF bridge as a module jar named intellij.platform.jewel.ideLafBridge.jar located in the IDE installation under lib/modules (e.g. <IDE_HOME>/lib/modules/intellij.platform.jewel.ideLafBridge.jar). [1][2]

Sources:
[1] Arch Linux intellij-idea-community-edition file list (shows intellij.platform.jewel.ideLafBridge.jar).
[2] FreeBSD/ports commit showing lib/modules entries including intellij.platform.jewel.ideLafBridge.jar.


🌐 Web query:

IntelliJ IDEA 2025.2.1 intellij.platform.jewel.foundation intellij.platform.jewel.ui bundled modules

💡 Result:

Yes — the IntelliJ Platform includes Jewel modules and you can reference them as bundledModule entries (examples used by plugin authors include intellij.platform.jewel.). See the Jewel project description and a JetBrains Platform forum post showing bundledModule usage (e.g. intellij.platform.jewel.markdown. and other intellij.platform.jewel artifacts). [1][2]

Sources:

  • Jewel project (modules: foundation, ui, IDE LaF bridge, etc.). [1]
  • JetBrains Platform forum example showing bundledModule entries for intellij.platform.jewel artifacts. [2]

🌐 Web query:

IntelliJ IDEA 2025.2.1 intellij.libraries.skiko bundled module

💡 Result:

Yes — IntelliJ IDEA 2025.2.1 includes the bundled module intellij.libraries.skiko (artifact com.jetbrains.intellij.libraries:libraries-skiko). See examples referencing bundledModule("intellij.libraries.skiko") in IntelliJ Platform plugin configs and the libraries-skiko Maven artifact. [1][2][3]

Sources:

  • IntelliJ Platform forum example showing bundledModule("intellij.libraries.skiko"). [1]
  • Maven listing for com.jetbrains.intellij.libraries:libraries-skiko (libraries-skiko). [2]
  • IntelliJ IDEA 2025.2.1 release announcement. [3]

🌐 Web query:

IntelliJ IDEA 2025.2.1 intellij.libraries.compose.foundation.desktop bundled module

💡 Result:

Yes — IntelliJ IDEA 2025.2.x includes a bundled Compose desktop library module (intellij.libraries.compose.foundation.desktop). Evidence: the JetBrains platform discussion shows code using bundledModule("intellij.libraries.compose.foundation.desktop"), and the corresponding libraries artifact is published under com.jetbrains.intellij.libraries (build-series 251.* used by 2025.2). [1][2][3]

Sources:

  • IntelliJ IDEA 2025.2.1 release announcement. [1]
  • JetBrains Platform forum example referencing bundledModule("intellij.libraries.compose.foundation.desktop"). [2]
  • Maven listing for com.jetbrains.intellij.libraries:libraries-compose-foundation-desktop (251.*). [3]

🌐 Web query:

IntelliJ IDEA 2025.2.1 intellij.platform.compose bundled module

💡 Result:

Short answer: IntelliJ 2025.2.x does not expose a single bundled module called intellij.platform.compose — Compose artifacts are provided as separate bundled modules (libraries and Skiko) and some Compose runtime/artifacts live under com.jetbrains.intellij.libraries. Plugin projects must declare explicit bundledModule() dependencies (for example intellij.libraries.compose.foundation.desktop and intellij.libraries.skiko) to use the platform-provided Compose. See JetBrains Platform guidance and community examples. [1][2][3]

Sources:

  • JetBrains Platform blog — module extraction / explicit bundledModule dependency recommendation. [1]
  • JetBrains Platform forum examples showing bundledModule("intellij.libraries.compose.foundation.desktop") and bundledModule("intellij.libraries.skiko"). [2]
  • Kotlin/Compose blog and multiplatform plugin notes about Compose support in recent IntelliJ releases. [3]

References:
[1] IntelliJ Platform blog — "IntelliJ Platform 2025.3: What Plugin Developers Should Know".
[2] JetBrains Platform forum thread "What state management framework should I use with Jewel? (Compose)".
[3] Kotlin Blog / Kotlin Multiplatform plugin release notes (Compose Multiplatform support).


🌐 Web query:

IntelliJ IDEA 2025.2 jewel.foundation jewel.ui modules lib/modules

💡 Result:

IntelliJ IDEA 2025.2 includes the new "Jewel" UI platform modules (packaged under lib/modules) — e.g. intellij.platform.jewel.foundation.jar and intellij.platform.jewel.ui.jar — provided as platform modules in the IDE distribution (found under <IDE_INSTALL>/lib/modules). [1]

If you’re seeing plugin verification or classpath errors mentioning jewel.foundation / jewel.ui, they’re coming from those bundled platform modules and can affect plugin verifier or plugin dependencies that expect different module layout. See the IDE package file list for 2025.2.3 which shows the jewel modules. [1][2]

Sources:
[1] Arch Linux package file list for intellij-idea-community-edition (shows lib/modules entries including intellij.platform.jewel.foundation and intellij.platform.jewel.ui).
[2] JetBrains Platform / Plugin Verifier discussion referencing module/layout issues with recent IDE builds.


Remove the invalid intellij.platform.compose bundled module declaration.

The module intellij.platform.compose (line 63) does not exist as a bundled module in IDEA 2025.2.1. Compose artifacts are provided only through separate modules like intellij.libraries.compose.foundation.desktop. This declaration will cause build resolution failures or classpath issues during plugin compilation or IDE launch.

All other bundled modules are valid:

  • intellij.libraries.skiko ✓
  • intellij.libraries.compose.foundation.desktop ✓
  • intellij.platform.jewel.foundation ✓
  • intellij.platform.jewel.ui ✓
  • intellij.platform.jewel.ideLafBridge ✓

Remove line 63: "intellij.platform.compose"

🤖 Prompt for AI Agents
In mpp-idea/build.gradle.kts around lines 50 to 68, remove the invalid bundled
module declaration "intellij.platform.compose" (line 63) because that module
doesn't exist in IDEA 2025.2.1 and causes resolution/classpath failures; keep
the other bundledModules entries as-is and ensure only valid modules like
"intellij.libraries.compose.foundation.desktop" remain.

Comment on lines +60 to +92
fun sendMessage(content: String) {
if (content.isBlank() || _isProcessing.value) return

// Add user message
val userMessage = ModelChatMessage(
content = content,
role = MessageRole.USER
)
_messages.value = _messages.value + listOf(userMessage)

// Start processing
_isProcessing.value = true
_streamingOutput.value = ""

currentJob = coroutineScope.launch {
try {
// TODO: Integrate with actual LLM service
// For now, simulate a response
simulateResponse(content)
} catch (e: CancellationException) {
// Cancelled by user
} catch (e: Exception) {
val errorMessage = ModelChatMessage(
content = "Error: ${e.message}",
role = MessageRole.ASSISTANT
)
_messages.value = _messages.value + listOf(errorMessage)
} finally {
_isProcessing.value = false
_streamingOutput.value = ""
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Cancel existing job before starting a new one.

If the user sends multiple messages rapidly, previous jobs may still be running, leading to multiple concurrent LLM requests and potential state corruption. Cancel currentJob before launching a new coroutine.

Apply this diff:

     fun sendMessage(content: String) {
         if (content.isBlank() || _isProcessing.value) return
 
+        // Cancel any existing job
+        currentJob?.cancel()
+
         // Add user message
         val userMessage = ModelChatMessage(
🤖 Prompt for AI Agents
In
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.kt
around lines 60 to 92, currently a new coroutine is launched without cancelling
any prior job which can lead to concurrent LLM requests and state races; before
launching the new coroutine, check if currentJob is active and cancel it (e.g.,
call currentJob?.cancel()), optionally clear or null out currentJob, then
proceed to set up and assign the new coroutine to currentJob so only one
processing job runs at a time and cancellation is properly handled.

Comment on lines +94 to +120
private suspend fun simulateResponse(userMessage: String) {
val response = """
This is a simulated response for: "$userMessage"

To enable real LLM responses, please configure your API key in the settings.

Supported features:
- **Agentic**: Full coding agent with file operations
- **Review**: Code review and analysis
- **Knowledge**: Document reading and Q&A
- **Remote**: Connect to remote mpp-server
""".trimIndent()

// Simulate streaming
for (char in response) {
if (!coroutineScope.isActive) break
_streamingOutput.value += char
delay(10)
}

// Add final message
val assistantMessage = ModelChatMessage(
content = response,
role = MessageRole.ASSISTANT
)
_messages.value = _messages.value + listOf(assistantMessage)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Check current coroutine cancellation, not parent scope.

Line 109 checks coroutineScope.isActive, which verifies the parent scope's state. However, if only currentJob is cancelled (via abortRequest()), the parent scope remains active, and the loop won't stop. Use isActive from the current coroutine context or check ensureActive().

Apply this diff:

     private suspend fun simulateResponse(userMessage: String) {
         val response = """
             This is a simulated response for: "$userMessage"
             
             To enable real LLM responses, please configure your API key in the settings.
             
             Supported features:
             - **Agentic**: Full coding agent with file operations
             - **Review**: Code review and analysis
             - **Knowledge**: Document reading and Q&A
             - **Remote**: Connect to remote mpp-server
         """.trimIndent()
 
         // Simulate streaming
         for (char in response) {
-            if (!coroutineScope.isActive) break
+            ensureActive()
             _streamingOutput.value += char
             delay(10)
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private suspend fun simulateResponse(userMessage: String) {
val response = """
This is a simulated response for: "$userMessage"
To enable real LLM responses, please configure your API key in the settings.
Supported features:
- **Agentic**: Full coding agent with file operations
- **Review**: Code review and analysis
- **Knowledge**: Document reading and Q&A
- **Remote**: Connect to remote mpp-server
""".trimIndent()
// Simulate streaming
for (char in response) {
if (!coroutineScope.isActive) break
_streamingOutput.value += char
delay(10)
}
// Add final message
val assistantMessage = ModelChatMessage(
content = response,
role = MessageRole.ASSISTANT
)
_messages.value = _messages.value + listOf(assistantMessage)
}
private suspend fun simulateResponse(userMessage: String) {
val response = """
This is a simulated response for: "$userMessage"
To enable real LLM responses, please configure your API key in the settings.
Supported features:
- **Agentic**: Full coding agent with file operations
- **Review**: Code review and analysis
- **Knowledge**: Document reading and Q&A
- **Remote**: Connect to remote mpp-server
""".trimIndent()
// Simulate streaming
for (char in response) {
ensureActive()
_streamingOutput.value += char
delay(10)
}
// Add final message
val assistantMessage = ModelChatMessage(
content = response,
role = MessageRole.ASSISTANT
)
_messages.value = _messages.value + listOf(assistantMessage)
}
🤖 Prompt for AI Agents
In
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.kt
around lines 94 to 120, the simulated streaming loop checks
coroutineScope.isActive which only reflects the parent scope and won't stop when
the current job is cancelled; replace that check with the current coroutine's
activity (e.g., use kotlinx.coroutines.ensureActive() inside the loop or check
coroutineContext.isActive) so the loop respects cancellation of the current job
(abortRequest), and keep the rest of the streaming logic unchanged.

Comment on lines +162 to +165
override fun dispose() {
currentJob?.cancel()
coroutineScope.cancel()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Don't cancel the injected coroutineScope.

The ViewModel is cancelling a coroutineScope passed in from outside, which it doesn't own. This could disrupt other components sharing the same scope. Only cancel currentJob, not the entire scope.

Apply this diff:

 override fun dispose() {
     currentJob?.cancel()
-    coroutineScope.cancel()
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
override fun dispose() {
currentJob?.cancel()
coroutineScope.cancel()
}
override fun dispose() {
currentJob?.cancel()
}
🤖 Prompt for AI Agents
In
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.kt
around lines 162 to 165, the dispose() implementation currently cancels an
externally injected coroutineScope; remove the call to coroutineScope.cancel()
so the view model does not cancel a scope it doesn't own, and keep only
currentJob?.cancel() (or cancel children of a locally created scope if
applicable) to ensure only the job started by this view model is cancelled.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant