Repository navigation
feat(mpp-idea): add Agent ToolWindow with tab-based navigation - #1
Conversation
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)
WalkthroughAdds 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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Areas requiring extra attention:
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
|
augment review |
| 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 |
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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() } |
There was a problem hiding this comment.
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 👎
| @Service(Level.PROJECT) | ||
| class CoroutineScopeHolder(private val project: Project) { | ||
|
|
||
| private val parentJob = SupervisorJob() |
There was a problem hiding this comment.
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"/> |
There was a problem hiding this comment.
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 👎
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/AutoDevChatViewModel.kt (1)
30-35: DuplicateChatMessageclass — already flagged in model layer.This
ChatMessageusesisUser: Booleanwhilecc.unitmesh.devins.idea.model.ChatMessageusesMessageRoleenum. 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 truncationHard‑coding
batchSize = 100andmaxBatches = 3is fine for now, and the progress messages per batch are helpful. If you expect very largenewNamessets, it may be worth:
- Making these thresholds configurable, or
- Explicitly logging when
newNames.size > namesToProcess.sizeso users know additional runs are needed to cover all candidates.
290-339: Package-structure heuristics look reasonable; path normalization would improve robustnessThe 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. inextractPackagePath:val normalized = filePath.replace('\\', '/')and then run the existing replacements on
normalized.
345-357:extractPackagePathis concise; same note about path separatorsThe stepwise stripping of common
src/...prefixes and then takingsubstringBeforeLast("/")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 sortUsing a 2/1 weight to float files under important packages while preserving the original order is a simple and effective heuristic. If
insights.hotFilesis 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” ruleRequiring at least two uppercase letters and expanding the technical skip set brings
isValidDomainConceptNamein line with the updated prompt and comments (favoringDomainDictoverAgent). 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 inisValidDomainNamealign with DDD focusThe added
platformTermsand 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 itAdding
isValidOutputEntryinparseEntriesto 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., acceptingDomainDict, rejectingAgent, rejectingutil) 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:
- Launch coroutine for async LLM call
- Use
Sendingstate during the request- Handle errors with
SendFailedstate (currently unused)- 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 = mppVersionThen reference
mppVersionin the plugin configuration:pluginConfiguration { name = "AutoDev Compose UI" - version = project.findProperty("mppVersion") as String? ?: "0.3.2" + version = mppVersionAlso 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:
- Apply the background directly to the OutlinedButton modifier, or
- 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:
temperatureis typically 0.0 to 2.0 for most LLM providersmaxTokensshould be positiveAdditionally, 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
MessageBubbleandChatInputimplementations in this file are very similar toMessageBubble,StreamingMessageBubble, andChatInputAreainIdeaAgentApp.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
⛔ Files ignored due to path filters (2)
mpp-idea/src/main/resources/icons/autodev-toolwindow.svgis excluded by!**/*.svgmpp-idea/src/main/resources/icons/autodev.svgis 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.svgfile is present atmpp-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. TheIconLoader.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 scopeThe updated description correctly reflects that this file now focuses on data classes only, in line with the removed Deep Research tests.
27-37: DefaultmaxIterationsassertion is consistent with DomainDictContextThe expectation of
1as the default matches theDomainDictContextdeclaration, so this test will stay aligned with the model.
82-87: Schema example assertion correctly targetsfocusAreaChecking for
focusAreain the example usage matches the newDomainDictAgentSchema.getExampleUsagebehavior.mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/subagent/DomainDictAgent.kt (2)
164-169: Package-aware prioritization integrates cleanly into Step 1Wiring
analyzePackageStructurein and threadingimportantPackagesintoextractMeaningfulNameskeeps the pipeline linear and backward-compatible (empty set gracefully falls back to original behavior).
659-701: Prompt text is well-aligned with validation logicThe updated instructions (compound words only, explicit allowed/denied examples, JSON‑only output) match the constraints enforced in
isValidDomainConceptName,isValidDomainName, andisValidOutputEntry, 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.
SendFailedis ready for error handling when async LLM integration is added.
58-64: LGTM!Input state transitions are handled correctly — preserving
Sendingstate during active requests and properly toggling betweenDisabled/Enabledbased on text content.settings.gradle.kts (1)
20-20: Composite build setup looks intentional.Using
includeBuildinstead ofincludeformpp-ideacreates a separate Gradle build, which aligns with the PR's mention of resolving classloader conflicts withcompileOnlydependencies. 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:
- Both
ChatMessageclasses are new (added in the same commit)- The toolwindow version is UI-specific with
isUser: Boolean- The model version uses a local
MessageRoleenum instead of the core module's canonical version- There are actually 3
ChatMessageclasses and 2MessageRoleenums across the codebaseThe core module contains the canonical
Messageclass andMessageRoleenum used throughout the codebase (13 imports vs 2 for the model version).Here is the rewritten review comment:
Consolidate duplicate
ChatMessagedefinitions and use canonicalMessageRolefrom core module.Two
ChatMessagedata classes were introduced in this feature (added in the same commit): one inmodelpackage withrole: MessageRole, another intoolwindowpackage (insideAutoDevChatViewModel.kt) withisUser: Boolean. Additionally, a localMessageRoleenum is defined here instead of using the canonical version fromcc.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
MessageandMessageRolein mpp-idea, or at minimum consolidate the toolwindowChatMessageinto the model version and replace the localMessageRoleenum 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
Disposerfor 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
addComposeTabis the recommended approach for Jewel/IntelliJ integrationmpp-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
compileOnlyscope to avoid classloader conflicts in plugin developmentmpp-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
CODINGas the default agent typempp-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.ToolWindowis defined at line 15 ofmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/AutoDevIcons.ktas a@JvmFieldand loads the SVG icon properlyAutoDevIdeaBundle.propertiesexists atmpp-idea/src/main/resources/messages/AutoDevIdeaBundle.propertieswith appropriate message keys includingtoolwindow.nameandtoolwindow.titleThe 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
sendMessageimplementation 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/bashFind CoroutineScopeHolder file
fd -t f "CoroutineScopeHolder" --extension kt
</function_calls>
<function_calls>
#!/bin/bashSearch for CoroutineScopeHolder class definition and createScope method
rg -n "class CoroutineScopeHolder|fun createScope" --type kotlin -B 2 -A 10
</function_calls>
<function_calls>
#!/bin/bashSearch more broadly for CoroutineScopeHolder
rg -n "CoroutineScopeHolder" --type kotlin -B 1 -A 5
</function_calls>
<function_calls>
#!/bin/bashCheck the IdeaAgentToolWindowFactory to understand scope creation context
fd -t f "IdeaAgentToolWindowFactory" --extension kt
</function_calls>
<function_calls>
#!/bin/bashSearch for the factory file with broader pattern
rg -l "IdeaAgentToolWindowFactory" --type kotlin
</function_calls>
<function_calls>
#!/bin/bashLet's explore the directory structure first
find . -type f -name "*.kt" | grep -i "factory|holder|scope" | head -20
</function_calls>
| 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++ | ||
| } |
There was a problem hiding this comment.
🧩 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 -A10Repository: 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 -10Repository: 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 -A3Repository: 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 -20Repository: 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 -20Repository: 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.ktRepository: 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.ktRepository: 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 -60Repository: 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 -50Repository: 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 -20Repository: 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:
-
Multiple streamPrompt calls can execute concurrently: The
onSubmit()callback (line 30 in ChatCallbacks.kt) launches bothcompileDevIns()andsendToLLM()independently usingscope.launch {}without synchronization. Users can trigger multipleonSubmitcalls rapidly (via keyboard shortcuts, button clicks, enter key as shown in DevInEditorInput.kt lines 273, 398, 502, 582). -
Same service instance reused: The
llmServiceis 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 multiplestreamPrompt()calls. -
Race conditions on shared mutable state: When multiple coroutines execute
streamPrompt()concurrently:- Lines 89-94:
lastTokenInfoupdated without synchronization - Line 106:
messagesSinceLastCompressionincremented without synchronization - tryCompressHistory (line 180+): reads/writes
hasFailedCompressionAttemptwithout synchronization
- Lines 89-94:
-
Flow collection doesn't serialize: Each
scope.launchcreates 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,AtomicIntegerfor multiplatform, or Kotlin'sMutex/channels) for shared state - Serializing
streamPromptcalls 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
|
augment review |
| * 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 { |
There was a problem hiding this comment.
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 👎
There was a problem hiding this comment.
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 inisValidDomainName.
🧹 Nitpick comments (4)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/services/CoroutineScopeHolder.kt (1)
23-36: Clarify or remove the unusedprojectWideCoroutineScopeto match the KDocRight now
projectWideCoroutineScopeis created but never used; all relationships are expressed viaparentJobinstead, 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, dropprojectWideCoroutineScopeand adjust the KDoc to talk aboutparentJob/ “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
textFieldStateandinputTextwith aLaunchedEffectto sync them is unnecessary. Read directly fromtextFieldState.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
📒 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
isValidOutputEntryvalidation 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 serviceUsing a project-scoped
SupervisorJobas the parent plusSupervisorJob(parentJob)for each child scope gives the expected hierarchy: children can be canceled independently, whiledispose()cancelingparentJobtears 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
IdeaAgentAppcomposable 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 theChatMessage.idproperty usage. Let me start by exploring the codebase to find the ChatMessage model definition and confirm whether this concern is valid.
<function_calls>
#!/bin/bashFind ChatMessage model definition
fd ChatMessage --type=kt
</function_calls>Let me search more broadly for the ChatMessage class:
<function_calls>
#!/bin/bashSearch 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/bashRead 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
buildSearchableOptionsandinstrumentCode. 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 atmpp-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:
mppVersiondefaults 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).
| 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") | ||
|
|
There was a problem hiding this comment.
🧩 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.ktsRepository: 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 3Repository: 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:
- com.intellij.platform kotlinx-coroutines core/android artifacts on Maven (examples). [Maven / mvnrepository]. [1]
- com.intellij.platform:kotlinx-coroutines-core-jvm listings (intellij-* versions used in 2025). [2]
- JetBrains platform discussion / docs about intellij.libraries.ktor.client and using bundled Ktor in plugins. [3]
- 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 -20Repository: 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/nullRepository: 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:
- IntelliJ Platform forum thread showing bundledModule names and runtime issues. [1]
- JetBrains Platform blog note about extracted modules / explicit bundledModule + plugin.xml dependency requirements. [2]
- 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.xmlRepository: 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 -lRepository: 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.clientintellij.libraries.ktor.client.ciointellij.platform.kotlinx.coroutines.coreintellij.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.
| 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) | ||
| } | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# First, let's understand the repository structure and locate the build file
git ls-files | head -20Repository: 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 fRepository: 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.ktsRepository: 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:
- JetBrains IntelliJ releases / plugin artifacts listing (compose, platform build 252). [JetBrains releases]. [1]
- Skiko project & IntelliJ/JetBrains skiko library artifacts. [Skiko repo / IntelliJ libraries]. [2]
- Jewel GitHub / docs (Jewel releases targeting IntelliJ 252). [3]
- 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.
| 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 = "" | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
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.
| 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) | ||
| } |
There was a problem hiding this comment.
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.
| 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.
| override fun dispose() { | ||
| currentJob?.cancel() | ||
| coroutineScope.cancel() | ||
| } |
There was a problem hiding this comment.
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.
| 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.
Summary
Add a new Agent ToolWindow to the mpp-idea IntelliJ IDEA plugin with tab-based navigation, similar to
TopBarMenuDesktopfrommpp-ui.Changes
New Files
IdeaAgentApp.kt- Main Compose UI with tabs header and chat interfaceIdeaAgentViewModel.kt- ViewModel managing agent state, messages, and LLM integrationIdeaAgentToolWindowFactory.kt- Factory for creating the ToolWindowAgentType.kt- Enum for agent types (CODING, CODE_REVIEW, KNOWLEDGE, REMOTE)ChatMessage.kt- Data class for chat messages with MessageRoleLLMConfig.kt- Configuration model for LLM providersModified Files
build.gradle.kts- Changed kotlinx/ktor deps tocompileOnlyto avoid classloader conflictsCoroutineScopeHolder.kt- Fixed to avoid platform childScope API classloader issuesplugin.xml- Registered new "AutoDev Agent" ToolWindowFeatures
Technical Notes
Since
mpp-ideauses Jewel theme (bundled with IntelliJ 2025.2+) whilempp-uiuses standalone Compose with Material3, this PR creates Jewel-native equivalents of the UI components rather than directly importing frommpp-ui.Fixed classloader conflicts by:
compileOnlyfor kotlinx-coroutines and ktor dependencieschildScopeextension functionTesting
./gradlew :mpp-idea:build)./gradlew :mpp-idea:runIde)Pull Request opened by Augment Code with guidance from the PR author
Summary by CodeRabbit
New Features
Improvements
✏️ Tip: You can customize this high-level summary in your review settings.