Repository navigation
feat(mpp-idea): add IdeaDiffActions, IdeaCodeActions, IdeaPlanActions, IdeaTerminalActions, IdeaDiagramActions - #26
Conversation
* chore(plugin): update plugin name, vendor email, and description Renamed plugin to "AutoDev Next", updated vendor email, and revised description for clarity. * feat(ui): add platform-specific UTF-8 font support Introduce getUtf8FontFamily() for proper CJK/UTF-8 rendering on WASM using Noto Sans SC, while other platforms use system defaults. Also exclude heavy dependencies and large font assets from the IntelliJ plugin build to reduce size.
- Create IdeaDiffActions.kt to encapsulate diff business logic - Reuse core module's PatchProcessor, DiffRepair, showSingleDiff() - Add action buttons to IdeaDiffRenderer (Accept/Reject/View Diff/Repair) - Update IdeaSketchRenderer to pass project parameter - Fix IdeaAnalysisComponents to use named parameters Related to #25
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. WalkthroughMakes IDEA renderers project-aware and interactive (diff/code/plan/terminal), centralizes IDE actions, adds live/asynchronous shell sessions and session management across core and UI, introduces UTF‑8 font API with platform implementations, updates plugin metadata, and tightens build/sandbox dependency and asset exclusions. Changes
Sequence Diagram(s)sequenceDiagram
participant Agent as ToolOrchestrator / CodingAgentExecutor
participant LiveExec as LiveShellExecutor (DefaultShellExecutor)
participant ShellMgr as ShellSessionManager
participant Renderer as JewelRenderer / ComposeRenderer / CodingCli
participant Background as BackgroundMonitor
Agent->>LiveExec: startLiveExecution(command, config)
LiveExec->>ShellMgr: registerSession(sessionId, processHandle)
LiveExec->>Renderer: addLiveTerminal(sessionId, command, workingDirectory, ptyHandle)
Agent-->>Renderer: return ToolExecutionResult.pending(sessionId)
Note right of Background: background monitoring started
Background->>ShellMgr: await completion / read output
ShellMgr-->>Background: final status + output
Background->>Renderer: updateLiveTerminalStatus(sessionId, exitCode, executionTimeMs, output)
Renderer->>Agent: resume awaiting coroutine -> ToolResult (Success/Error/Pending)
sequenceDiagram
participant User
participant Sketch as IdeaSketchRenderer
participant Diff as IdeaDiffRenderer
participant Actions as IdeaDiffActions
participant IntelliJ as IntelliJ Patch API
participant AI as DiffRepair
User->>Sketch: render content (includes Project)
Sketch->>Diff: render diff (project)
Diff->>User: show DiffToolbar (Accept/Reject/View/Repair)
alt Accept
User->>Diff: click Accept
Diff->>Actions: acceptPatch(patchContent)
Actions->>IntelliJ: parse & apply patches
IntelliJ-->>Actions: apply result
Actions-->>Diff: success/failure
else Repair
User->>Diff: click Repair
Diff->>Actions: repairPatch(patchContent)
Actions->>AI: request repair
AI-->>Actions: repaired patch
Actions-->>Diff: onRepaired callback
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
| val additionalInfo = reader.getAdditionalInfo(pathsFromGroups) | ||
|
|
||
| shelfExecutor.apply(filePatches, patchGroups, null, "AutoDev.diff", additionalInfo) | ||
| success = true |
There was a problem hiding this comment.
success is set to true unconditionally after apply(...); if applying the patch fails or is a no-op, this still returns true. Consider determining success from the apply result/exception instead of always marking success.
🤖 Was this useful? React with 👍 or 👎
| return | ||
| } | ||
|
|
||
| ApplicationManager.getApplication().invokeLater { |
There was a problem hiding this comment.
DiffRepair.applyDiffRepairSuggestion(...) is invoked inside invokeLater, which runs on the EDT; if this does network/AI work, it can freeze the UI. Consider running the repair in a background task and updating UI on the EDT. (Guideline: edt_violations)
🤖 Was this useful? React with 👍 or 👎
| isRepairing = isRepairing, | ||
| patchApplied = patchApplied, | ||
| onAccept = { | ||
| val success = IdeaDiffActions.acceptPatch(project, diffContent) |
There was a problem hiding this comment.
IdeaDiffActions.acceptPatch(...) is called directly from the click handler, which can block the EDT if patch application is slow. Consider wrapping it in a background task with a progress indicator. (Guideline: edt_violations)
🤖 Was this useful? React with 👍 or 👎
- Create IdeaCodeActions.kt with copy/insert/save methods - Update IdeaCodeBlockRenderer.kt with toolbar (Copy/Insert/Save buttons) - Pass project parameter to IdeaCodeBlockRenderer for action buttons Phase 2 of #25
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaDiffActions.kt (1)
32-40: Consider logging parse failures for debugging.Swallowing all exceptions silently may hide useful diagnostic information when patches fail to parse unexpectedly.
fun parsePatches(patchContent: String): List<TextFilePatch> { return try { val reader = PatchReader(patchContent) reader.parseAllPatches() reader.textPatches } catch (e: Exception) { + // Log for debugging - silent failure is intentional for UI + com.intellij.openapi.diagnostic.Logger.getInstance(IdeaDiffActions::class.java) + .debug("Failed to parse patch content", e) emptyList() } }mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaDiffRenderer.kt (1)
202-212: Remove unuseddiffContentparameter.The
diffContentparameter is passed toDiffToolbarbut never used within the composable.@Composable private fun DiffToolbar( - diffContent: String, project: Project, isRepairing: Boolean, patchApplied: Boolean, onAccept: () -> Unit, onReject: () -> Unit, onViewDiff: () -> Unit, onRepair: () -> Unit )And update the call site at line 50-51:
DiffToolbar( - diffContent = diffContent, project = project,
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (15)
mpp-idea/build.gradle.kts(3 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaDiffRenderer.kt(3 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt(3 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaDiffActions.kt(1 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/codereview/IdeaAnalysisComponents.kt(2 hunks)mpp-idea/src/main/resources/META-INF/plugin.xml(1 hunks)mpp-ui/build.gradle.kts(1 hunks)mpp-ui/src/androidMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.android.kt(2 hunks)mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentMessageList.kt(2 hunks)mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/editor/DevInEditorInput.kt(2 hunks)mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.kt(2 hunks)mpp-ui/src/iosMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ios.kt(2 hunks)mpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.kt(2 hunks)mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.jvm.kt(2 hunks)mpp-ui/src/wasmJsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.wasmJs.kt(1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.kt
📄 CodeRabbit inference engine (AGENTS.md)
**/*.kt: Useexpect/actualfor platform-specific code (e.g., file I/O on JVM/JS/Wasm) in Kotlin Multiplatform projects
Check export first if some functions are not working well with CLI (TypeScript)
In Kotlin/JS @JsExport: AvoidFlow, usePromiseinstead
In Kotlin/JS @JsExport: Use concrete classes as return types and parameter types; avoid interface types
For WASM platform, avoid using emoji and UTF-8 in code
Files:
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/editor/DevInEditorInput.ktmpp-ui/src/androidMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.android.ktmpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ktmpp-ui/src/wasmJsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.wasmJs.ktmpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.jvm.ktmpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaDiffRenderer.ktmpp-ui/src/iosMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ios.ktmpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentMessageList.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/codereview/IdeaAnalysisComponents.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaDiffActions.kt
**/compose/**/*.{kt,kts}
📄 CodeRabbit inference engine (AGENTS.md)
In Compose (Desktop/Android), use
AutoDevColorsfromcc.unitmesh.devins.ui.compose.themeorMaterialTheme.colorScheme
Files:
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/editor/DevInEditorInput.ktmpp-ui/src/androidMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.android.ktmpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ktmpp-ui/src/wasmJsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.wasmJs.ktmpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.jvm.ktmpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.ktmpp-ui/src/iosMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ios.ktmpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentMessageList.kt
{**/compose/**/*.kt,mpp-ui/src/jsMain/typescript/**/*.{ts,tsx}}
📄 CodeRabbit inference engine (AGENTS.md)
DO NOT hardcode colors (e.g.,
Color(0xFF...)or#hex). Always use design tokens for consistency across platforms
Files:
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/editor/DevInEditorInput.ktmpp-ui/src/androidMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.android.ktmpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ktmpp-ui/src/wasmJsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.wasmJs.ktmpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.jvm.ktmpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.ktmpp-ui/src/iosMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ios.ktmpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentMessageList.kt
**/idea/**/*.kt
📄 CodeRabbit inference engine (AGENTS.md)
**/idea/**/*.kt: For SwingPanel z-index issues with Compose popups, enable Jewel's custom popup renderer:JewelFlags.useCustomPopupRenderer = trueinIdeaAgentToolWindowFactory
For popup/dropdown menus in IntelliJ plugins, use Jewel'sPopupMenuinstead ofandroidx.compose.ui.window.Popup
For dialogs in IntelliJ plugins, use IntelliJ'sDialogWrapperwithorg.jetbrains.jewel.bridge.composeinstead ofandroidx.compose.ui.window.Dialog
Files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaDiffRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/codereview/IdeaAnalysisComponents.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaDiffActions.kt
🧠 Learnings (10)
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/compose/**/*.{kt,kts} : In Compose (Desktop/Android), use `AutoDevColors` from `cc.unitmesh.devins.ui.compose.theme` or `MaterialTheme.colorScheme`
Applied to files:
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/editor/DevInEditorInput.ktmpp-ui/src/androidMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.android.ktmpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ktmpp-ui/src/wasmJsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.wasmJs.ktmpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.jvm.ktmpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.ktmpp-idea/src/main/resources/META-INF/plugin.xmlmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaDiffRenderer.ktmpp-ui/src/iosMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ios.ktmpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentMessageList.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to {**/compose/**/*.kt,mpp-ui/src/jsMain/typescript/**/*.{ts,tsx}} : DO NOT hardcode colors (e.g., `Color(0xFF...)` or `#hex`). Always use design tokens for consistency across platforms
Applied to files:
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/editor/DevInEditorInput.ktmpp-ui/src/androidMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.android.ktmpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ktmpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.jvm.ktmpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.ktmpp-ui/src/iosMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ios.ktmpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentMessageList.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/idea/**/*.kt : For dialogs in IntelliJ plugins, use IntelliJ's `DialogWrapper` with `org.jetbrains.jewel.bridge.compose` instead of `androidx.compose.ui.window.Dialog`
Applied to files:
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/editor/DevInEditorInput.ktmpp-idea/src/main/resources/META-INF/plugin.xmlmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaDiffRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/codereview/IdeaAnalysisComponents.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/idea/**/*.kt : For popup/dropdown menus in IntelliJ plugins, use Jewel's `PopupMenu` instead of `androidx.compose.ui.window.Popup`
Applied to files:
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/editor/DevInEditorInput.ktmpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ktmpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaDiffRenderer.ktmpp-ui/src/iosMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ios.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/*.kt : For WASM platform, avoid using emoji and UTF-8 in code
Applied to files:
mpp-ui/src/wasmJsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.wasmJs.ktmpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.ktmpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentMessageList.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: For `mpp-idea` plugin tests, run with: `cd mpp-idea && ../gradlew test --tests "cc.unitmesh.devins.idea.renderer.JewelRendererTest"`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.ktmpp-idea/src/main/resources/META-INF/plugin.xmlmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaDiffRenderer.ktmpp-idea/build.gradle.kts
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Note that `IdeaAgentViewModelTest` requires IntelliJ Platform Test Framework; `JewelRendererTest` can run standalone with JUnit 5
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.ktmpp-idea/build.gradle.kts
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: For `mpp-idea` plugin development, use `cd mpp-idea && ../gradlew compileKotlin` instead of `./gradlew :mpp-idea:compileKotlin`
Applied to files:
mpp-idea/src/main/resources/META-INF/plugin.xmlmpp-idea/build.gradle.kts
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/idea/**/*.kt : For SwingPanel z-index issues with Compose popups, enable Jewel's custom popup renderer: `JewelFlags.useCustomPopupRenderer = true` in `IdeaAgentToolWindowFactory`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaDiffRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/codereview/IdeaAnalysisComponents.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/*.kt : Use `expect`/`actual` for platform-specific code (e.g., file I/O on JVM/JS/Wasm) in Kotlin Multiplatform projects
Applied to files:
mpp-idea/build.gradle.kts
🧬 Code graph analysis (3)
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/editor/DevInEditorInput.kt (6)
mpp-ui/src/androidMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.android.kt (1)
getUtf8FontFamily(39-40)mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.kt (1)
getUtf8FontFamily(22-23)mpp-ui/src/iosMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ios.kt (1)
getUtf8FontFamily(20-21)mpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.kt (1)
getUtf8FontFamily(23-24)mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.jvm.kt (1)
getUtf8FontFamily(38-39)mpp-ui/src/wasmJsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.wasmJs.kt (1)
getUtf8FontFamily(24-27)
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentMessageList.kt (6)
mpp-ui/src/androidMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.android.kt (1)
getUtf8FontFamily(39-40)mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.kt (1)
getUtf8FontFamily(22-23)mpp-ui/src/iosMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ios.kt (1)
getUtf8FontFamily(20-21)mpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.kt (1)
getUtf8FontFamily(23-24)mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.jvm.kt (1)
getUtf8FontFamily(38-39)mpp-ui/src/wasmJsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.wasmJs.kt (1)
getUtf8FontFamily(24-27)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaDiffActions.kt (1)
core/src/main/kotlin/cc/unitmesh/devti/sketch/ui/patch/DiffLangSketch.kt (1)
showSingleDiff(268-297)
⏰ 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: Build (241)
- GitHub Check: Build (223)
- GitHub Check: Test mpp-core (KMP)
🔇 Additional comments (24)
mpp-ui/build.gradle.kts (1)
699-700: Font path change is appropriate for WASM-specific resource layout.The change to
src/wasmJsMain/composeResources/fontis correct. Verification confirms no Kotlin source code across JVM, Android, iOS, or JS platforms references fonts, and no font files exist in the repository outside the build task. Fonts are downloaded at build time specifically for WASM UTF-8 rendering and are not needed by other platforms. This is not a breaking change.However, the build script contains emoji characters (✅, ❌, ℹ️) in the
DownloadWasmFontsTaskclass (lines 661, 663, 685, 687), which conflicts with the guideline to avoid emoji and UTF-8 characters in code for the WASM platform. Consider replacing emoji with ASCII alternatives in theseprintln()statements (e.g., use[OK],[FAIL],[INFO]instead).mpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.kt (1)
19-24: LGTM! Clean JS/Web implementation.The function correctly returns
FontFamily.Defaultfor the JS platform, relying on the browser's native UTF-8 font support. The@Composableannotation ensures API consistency across platforms.mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/editor/DevInEditorInput.kt (1)
42-42: LGTM! Excellent refactoring to unified font API.Replacing the conditional platform-specific font selection with
getUtf8FontFamily()simplifies the code and centralizes font handling. The function is correctly called within the Composable context.Also applies to: 486-486
mpp-ui/src/androidMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.android.kt (1)
35-40: LGTM! Correct Android implementation.Returning
FontFamily.Defaultis appropriate for Android, which has robust system font support for UTF-8. The implementation aligns with the cross-platform API design.mpp-ui/src/wasmJsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.wasmJs.kt (1)
20-27: LGTM! WASM-specific CJK font support is well-documented.The WASM implementation correctly uses Noto Sans SC for CJK character support. The ~18MB font bundle is documented and intentional. The
@Composableannotation is necessary here for resource access viaRes.font.mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentMessageList.kt (1)
25-25: LGTM! Clean removal of platform-specific conditional logic.Replacing the
Platform.isWasmcheck with the unifiedgetUtf8FontFamily()API simplifies the code and improves maintainability by centralizing platform-specific font handling.Also applies to: 278-278
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.kt (1)
17-23: LGTM! Well-designed cross-platform API.The
expectdeclaration correctly establishes the multiplatform contract. The@Composableannotation is necessary because the WASM implementation requires a Composable context for resource access. Documentation clearly explains platform-specific behavior.mpp-ui/src/iosMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ios.kt (1)
16-21: LGTM! Correct iOS implementation.Returning
FontFamily.Defaultis appropriate for iOS, leveraging the platform's robust system font support for UTF-8 characters.mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.jvm.kt (1)
34-39: LGTM! Correct JVM implementation.Returning
FontFamily.Defaultis appropriate for the JVM platform, which has robust system font support for UTF-8 characters.mpp-idea/src/main/resources/META-INF/plugin.xml (1)
4-8: LGTM - Plugin metadata updates are consistent.The rebranding from "AutoDev Compose UI" to "AutoDev Next" and updated contact information align with the PR's feature additions.
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaDiffActions.kt (4)
98-100: LGTM - Clean delegation to core module.Correctly uses
showSingleDiffwhich internally usesDialogWrapperfor the diff preview dialog, aligning with IntelliJ plugin best practices per coding guidelines.
106-127: Repair operates on currently selected editor.Similar to
rejectPatch, this usesselectedTextEditorwhich may not correspond to the file targeted by the patch. For multi-file patches, the behavior could be unexpected.
132-139: LGTM - Clean synchronous repair API.Good design taking
originalCodeas an explicit parameter rather than relying on editor state.
144-146: LGTM - Simple validation utility.mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/codereview/IdeaAnalysisComponents.kt (2)
150-155: LGTM - Named parameters improve readability.The switch to named parameters is a good practice. Note that
projectis not passed here, so diff blocks within these sections won't show action buttons, which appears intentional for this context.
163-168: Consistent parameter usage across all RenderResponse calls.Also applies to: 199-204
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt (2)
42-47: LGTM - Clean API extension with optional project parameter.The optional
projectparameter allows progressive enhancement without breaking existing callers. Good backward-compatible design.
67-76: Diff blocks correctly receive project context for action buttons.The selective passing of
projectonly toIdeaDiffRendereris appropriate since only diff blocks need project-aware actions.mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaDiffRenderer.kt (3)
289-315: LGTM - Well-structured action button with proper hover and enabled states.Good use of Jewel's
Tooltipcomponent and clean conditional styling based on interaction and enabled state.
78-120: Good UX - offering AI repair when diff parsing fails.The fallback UI with an AI repair option provides a graceful degradation path for malformed diff content.
55-58: UI state depends onacceptPatchsuccess flag reliability.The
patchAppliedstate is set based onIdeaDiffActions.acceptPatchreturn value. As noted in theIdeaDiffActionsreview, this success flag may not accurately reflect the actual patch application outcome.mpp-idea/build.gradle.kts (3)
126-126: Documentation comment improves clarity on exclusion strategy.The note clarifying that heavy dependencies are excluded globally is helpful for maintainers. This contextualizes why the mpp-core dependency block doesn't include redundant Compose/Kotlinx exclusions.
221-234: Sandbox exclusions are appropriate; no over-exclusion risk identified.The
**/*.ttfand**/*.otfpatterns inprepareSandboxare safe. These exclusions apply only to the plugin sandbox distribution (not project-wide compilation), and target Desktop/WASM-specific fonts from mpp-ui (FiraCode, Noto) that are unnecessary in the IDEA plugin. The IDEA plugin usesJewelTheme.defaultTextStyle(IntelliJ's built-in theme), not custom fonts. No font files exist in mpp-idea or mpp-core. Exclusions are consistent with other Desktop-specific resource filters (icons, resources) in the same task.
40-63: Global exclusions are safe and intentionally exclude mpp-core's non-patch features.The excluded dependencies (Tika, PDFBox, Jsoup, pty4j) are declared in
mpp-corefor document parsing, not for patch processing.DiffRepair.ktandPatchProcessor.ktuse only IntelliJ APIs—no excluded libraries. The global exclusion in mpp-idea (lines 40-63) is correct: it silences transitive deps from mpp-core's document-parsing features that the IDEA plugin doesn't need. The patch/diff workflows have no runtime dependencies on excluded libraries and will function correctly.
|
|
||
| var success = false | ||
| commandProcessor.executeCommand(project, { | ||
| commandProcessor.markCurrentCommandAsGlobal(project) | ||
|
|
||
| val matchedPatches = MatchPatchPaths(project).execute(filePatches, true) | ||
| val patchGroups = MultiMap<VirtualFile, AbstractFilePatchInProgress<*>>() | ||
| for (patchInProgress in matchedPatches) { | ||
| patchGroups.putValue(patchInProgress.base, patchInProgress) | ||
| } | ||
|
|
||
| val pathsFromGroups = ApplyPatchDefaultExecutor.pathsFromGroups(patchGroups) | ||
| val reader = PatchReader(patchContent) | ||
| reader.parseAllPatches() | ||
| val additionalInfo = reader.getAdditionalInfo(pathsFromGroups) | ||
|
|
||
| shelfExecutor.apply(filePatches, patchGroups, null, "AutoDev.diff", additionalInfo) | ||
| success = true | ||
| }, "ApplyPatch", null, UndoConfirmationPolicy.REQUEST_CONFIRMATION, false) | ||
|
|
||
| return success | ||
| } |
There was a problem hiding this comment.
Success flag doesn't reflect actual patch application result.
success = true is set unconditionally after shelfExecutor.apply() without verifying the actual outcome. The apply() method may fail silently or partially, leading to incorrect success reporting.
Consider capturing the result from the executor or wrapping in try-catch:
var success = false
commandProcessor.executeCommand(project, {
commandProcessor.markCurrentCommandAsGlobal(project)
val matchedPatches = MatchPatchPaths(project).execute(filePatches, true)
val patchGroups = MultiMap<VirtualFile, AbstractFilePatchInProgress<*>>()
for (patchInProgress in matchedPatches) {
patchGroups.putValue(patchInProgress.base, patchInProgress)
}
val pathsFromGroups = ApplyPatchDefaultExecutor.pathsFromGroups(patchGroups)
val reader = PatchReader(patchContent)
reader.parseAllPatches()
val additionalInfo = reader.getAdditionalInfo(pathsFromGroups)
- shelfExecutor.apply(filePatches, patchGroups, null, "AutoDev.diff", additionalInfo)
- success = true
+ try {
+ shelfExecutor.apply(filePatches, patchGroups, null, "AutoDev.diff", additionalInfo)
+ success = true
+ } catch (e: Exception) {
+ AutoDevNotifications.error(project, "Failed to apply patch: ${e.message}")
+ }
}, "ApplyPatch", null, UndoConfirmationPolicy.REQUEST_CONFIRMATION, false)Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaDiffActions.kt
around lines 56-77: the success flag is unconditionally set to true after
calling shelfExecutor.apply(), which can fail or partially apply patches; change
the code to determine success from the executor call (capture and inspect any
return value/result object) or wrap the apply() call in a try/catch and set
success = true only when the result indicates full success (and set success =
false on failure/exception), and ensure any exceptions are logged or propagated
appropriately so the method returns an accurate success value.
| fun rejectPatch(project: Project): Boolean { | ||
| val undoManager = UndoManager.getInstance(project) | ||
| val fileEditor = FileEditorManager.getInstance(project).selectedEditor ?: return false | ||
|
|
||
| if (undoManager.isUndoAvailable(fileEditor)) { | ||
| undoManager.undo(fileEditor) | ||
| return true | ||
| } | ||
| return false | ||
| } |
There was a problem hiding this comment.
Undo operates on currently selected editor, not necessarily the patched file.
If the user switches to a different file after applying a patch, rejectPatch will undo in the wrong editor. Consider tracking the affected file(s) from acceptPatch for more reliable undo behavior.
| val fileDiffs = remember(diffContent) { DiffParser.parse(diffContent) } | ||
| var isRepairing by remember { mutableStateOf(false) } | ||
| var patchApplied by remember { mutableStateOf(false) } | ||
|
|
There was a problem hiding this comment.
State may become stale when diffContent changes.
patchApplied and isRepairing are not keyed to diffContent. If the diff content changes (e.g., during streaming), these states won't reset, potentially showing incorrect applied/repairing status.
val fileDiffs = remember(diffContent) { DiffParser.parse(diffContent) }
- var isRepairing by remember { mutableStateOf(false) }
- var patchApplied by remember { mutableStateOf(false) }
+ var isRepairing by remember(diffContent) { mutableStateOf(false) }
+ var patchApplied by remember(diffContent) { mutableStateOf(false) }📝 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.
| val fileDiffs = remember(diffContent) { DiffParser.parse(diffContent) } | |
| var isRepairing by remember { mutableStateOf(false) } | |
| var patchApplied by remember { mutableStateOf(false) } | |
| val fileDiffs = remember(diffContent) { DiffParser.parse(diffContent) } | |
| var isRepairing by remember(diffContent) { mutableStateOf(false) } | |
| var patchApplied by remember(diffContent) { mutableStateOf(false) } |
🤖 Prompt for AI Agents
In
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaDiffRenderer.kt
around lines 43-46, the local UI states isRepairing and patchApplied are not
keyed to diffContent so they can become stale when diffContent changes; update
them to be remembered with diffContent as a key (e.g., remember(diffContent) {
mutableStateOf(false) }) or otherwise reset their values whenever diffContent
updates so the repairing/applied flags are cleared on a new diff.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaCodeActions.kt (1)
43-73: Consider logging insertion failures.Similar to
copyToClipboard, the exception handler silently returns false without logging. This makes it harder to diagnose issues with code insertion.Consider adding logging:
} catch (e: Exception) { + com.intellij.openapi.diagnostic.Logger.getInstance(IdeaCodeActions::class.java).warn("Failed to insert code at cursor", e) false }mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaCodeBlockRenderer.kt (1)
107-118: Consider recomputing insert availability.Line 108 caches
canInsertAtCursorbased on the project alone, but the result can change if the user switches editors or the document's write-protection changes. This might lead to a stale button state.If dynamic updates are important, consider using a derived state or removing the
remember:if (project != null) { - val canInsert = remember(project) { IdeaCodeActions.canInsertAtCursor(project) } + val canInsert = IdeaCodeActions.canInsertAtCursor(project) CodeActionButton(Note: This will call the function on every recomposition, which may have minor performance implications but ensures the button state reflects the current editor.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaCodeBlockRenderer.kt(3 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt(4 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaCodeActions.kt(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.kt
📄 CodeRabbit inference engine (AGENTS.md)
**/*.kt: Useexpect/actualfor platform-specific code (e.g., file I/O on JVM/JS/Wasm) in Kotlin Multiplatform projects
Check export first if some functions are not working well with CLI (TypeScript)
In Kotlin/JS @JsExport: AvoidFlow, usePromiseinstead
In Kotlin/JS @JsExport: Use concrete classes as return types and parameter types; avoid interface types
For WASM platform, avoid using emoji and UTF-8 in code
Files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaCodeActions.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaCodeBlockRenderer.kt
**/idea/**/*.kt
📄 CodeRabbit inference engine (AGENTS.md)
**/idea/**/*.kt: For SwingPanel z-index issues with Compose popups, enable Jewel's custom popup renderer:JewelFlags.useCustomPopupRenderer = trueinIdeaAgentToolWindowFactory
For popup/dropdown menus in IntelliJ plugins, use Jewel'sPopupMenuinstead ofandroidx.compose.ui.window.Popup
For dialogs in IntelliJ plugins, use IntelliJ'sDialogWrapperwithorg.jetbrains.jewel.bridge.composeinstead ofandroidx.compose.ui.window.Dialog
Files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaCodeActions.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaCodeBlockRenderer.kt
🧠 Learnings (7)
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: For `mpp-idea` plugin tests, run with: `cd mpp-idea && ../gradlew test --tests "cc.unitmesh.devins.idea.renderer.JewelRendererTest"`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Note that `IdeaAgentViewModelTest` requires IntelliJ Platform Test Framework; `JewelRendererTest` can run standalone with JUnit 5
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaCodeBlockRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/idea/**/*.kt : For SwingPanel z-index issues with Compose popups, enable Jewel's custom popup renderer: `JewelFlags.useCustomPopupRenderer = true` in `IdeaAgentToolWindowFactory`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaCodeBlockRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/compose/**/*.{kt,kts} : In Compose (Desktop/Android), use `AutoDevColors` from `cc.unitmesh.devins.ui.compose.theme` or `MaterialTheme.colorScheme`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaCodeBlockRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/idea/**/*.kt : For dialogs in IntelliJ plugins, use IntelliJ's `DialogWrapper` with `org.jetbrains.jewel.bridge.compose` instead of `androidx.compose.ui.window.Dialog`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaCodeBlockRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/idea/**/*.kt : For popup/dropdown menus in IntelliJ plugins, use Jewel's `PopupMenu` instead of `androidx.compose.ui.window.Popup`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaCodeBlockRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to {**/compose/**/*.kt,mpp-ui/src/jsMain/typescript/**/*.{ts,tsx}} : DO NOT hardcode colors (e.g., `Color(0xFF...)` or `#hex`). Always use design tokens for consistency across platforms
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaCodeBlockRenderer.kt
🔇 Additional comments (6)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt (1)
12-12: LGTM! Clean parameter threading.The addition of the optional
projectparameter and its propagation to child renderers is implemented correctly. This enables project-aware actions in downstream components without breaking existing usage.Also applies to: 46-46, 71-71, 129-129
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaCodeActions.kt (3)
78-81: LGTM!Clean helper function with appropriate null-safety checks.
86-102: LGTM! Good user feedback.The file saving logic correctly uses write actions and provides clear notifications to users. The mix of
java.io.Fileand VFS refresh is acceptable and properly synchronized.
107-134: LGTM! Comprehensive language mapping.Good coverage of common programming languages with appropriate file extensions.
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaCodeBlockRenderer.kt (2)
30-57: LGTM! Clean refactoring.The separation of toolbar and content rendering improves maintainability while preserving the visual styling.
134-164: LGTM! Proper use of design tokens.The button implementation correctly uses
AutoDevColorsfor theming and Jewel'sTooltipcomponent, aligning with the coding guidelines for IntelliJ plugins.
| fun copyToClipboard(code: String): Boolean { | ||
| return try { | ||
| val selection = StringSelection(code) | ||
| val clipboard = Toolkit.getDefaultToolkit().systemClipboard | ||
| clipboard.setContents(selection, null) | ||
| true | ||
| } catch (e: Exception) { | ||
| false | ||
| } | ||
| } |
There was a problem hiding this comment.
Log exceptions for better debuggability.
The catch block silently swallows all exceptions, making it difficult to diagnose clipboard failures. Consider logging the exception before returning false.
Apply this diff to add logging:
fun copyToClipboard(code: String): Boolean {
return try {
val selection = StringSelection(code)
val clipboard = Toolkit.getDefaultToolkit().systemClipboard
clipboard.setContents(selection, null)
true
} catch (e: Exception) {
+ // Log for debugging purposes
+ com.intellij.openapi.diagnostic.Logger.getInstance(IdeaCodeActions::class.java).warn("Failed to copy to clipboard", e)
false
}
}📝 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.
| fun copyToClipboard(code: String): Boolean { | |
| return try { | |
| val selection = StringSelection(code) | |
| val clipboard = Toolkit.getDefaultToolkit().systemClipboard | |
| clipboard.setContents(selection, null) | |
| true | |
| } catch (e: Exception) { | |
| false | |
| } | |
| } | |
| fun copyToClipboard(code: String): Boolean { | |
| return try { | |
| val selection = StringSelection(code) | |
| val clipboard = Toolkit.getDefaultToolkit().systemClipboard | |
| clipboard.setContents(selection, null) | |
| true | |
| } catch (e: Exception) { | |
| // Log for debugging purposes | |
| com.intellij.openapi.diagnostic.Logger.getInstance(IdeaCodeActions::class.java).warn("Failed to copy to clipboard", e) | |
| false | |
| } | |
| } |
🤖 Prompt for AI Agents
In
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaCodeActions.kt
around lines 28 to 37, the catch block for copyToClipboard silently swallows all
exceptions; update it to log the exception before returning false by
obtaining/using the IntelliJ Logger (com.intellij.openapi.diagnostic.Logger) or
an existing logger instance, call logger.error or logger.warn with a clear
message and include the caught exception (e), and ensure necessary import is
added; keep the current behavior of returning false after logging.
- Create IdeaPlanActions.kt with parsePlan/copyToClipboard/pinToToolWindow methods - Create IdeaPlanRenderer.kt with plan sections, steps, status indicators - Add plan language support to IdeaSketchRenderer - Reuses core module's MarkdownPlanParser, AgentStateService Phase 3 of #25
- Create IdeaTerminalActions.kt with checkDangerousCommand/executeCommand methods - Create IdeaTerminalRenderer.kt with command display, execute button, output panel - Add bash/shell/sh/zsh language support to IdeaSketchRenderer - Reuses core module's ShellSafetyCheck, ProcessExecutor Phase 4 of #25
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaPlanActions.kt (1)
56-65: Consider logging exceptions for better debuggability.Same issue as
copyPlanToClipboard()- exceptions are silently swallowed. Consider adding logging for clipboard access failures.
🧹 Nitpick comments (2)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaPlanRenderer.kt (1)
42-42: Reset thecopiedstate for better UX.The
copiedflag is set totruewhen the user clicks "Copy Plan" but never resets back tofalse, so the button permanently shows "Copied!" after the first click. Consider resetting the flag after a delay.Apply this diff to reset the flag after 2 seconds:
fun IdeaPlanRenderer( planContent: String, project: Project? = null, isComplete: Boolean = false, modifier: Modifier = Modifier ) { val planItems = remember(planContent) { IdeaPlanActions.parsePlan(planContent) } var isCompressed by remember { mutableStateOf(false) } var copied by remember { mutableStateOf(false) } + + LaunchedEffect(copied) { + if (copied) { + delay(2000) + copied = false + } + }mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaPlanActions.kt (1)
38-51: Consider logging exceptions for better debuggability.The method silently swallows all exceptions and returns
false. Consider logging the exception to help diagnose clipboard or service access failures during development or debugging.fun copyPlanToClipboard(project: Project): Boolean { return try { val agentStateService = project.getService(AgentStateService::class.java) val currentPlan = agentStateService.getPlan() val planString = formatPlanToMarkdown(currentPlan) val clipboard = Toolkit.getDefaultToolkit().systemClipboard val selection = StringSelection(planString) clipboard.setContents(selection, null) true } catch (e: Exception) { + logger.warn("Failed to copy plan to clipboard", e) false } }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaPlanRenderer.kt(1 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt(4 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaPlanActions.kt(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.kt
📄 CodeRabbit inference engine (AGENTS.md)
**/*.kt: Useexpect/actualfor platform-specific code (e.g., file I/O on JVM/JS/Wasm) in Kotlin Multiplatform projects
Check export first if some functions are not working well with CLI (TypeScript)
In Kotlin/JS @JsExport: AvoidFlow, usePromiseinstead
In Kotlin/JS @JsExport: Use concrete classes as return types and parameter types; avoid interface types
For WASM platform, avoid using emoji and UTF-8 in code
Files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaPlanActions.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaPlanRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
**/idea/**/*.kt
📄 CodeRabbit inference engine (AGENTS.md)
**/idea/**/*.kt: For SwingPanel z-index issues with Compose popups, enable Jewel's custom popup renderer:JewelFlags.useCustomPopupRenderer = trueinIdeaAgentToolWindowFactory
For popup/dropdown menus in IntelliJ plugins, use Jewel'sPopupMenuinstead ofandroidx.compose.ui.window.Popup
For dialogs in IntelliJ plugins, use IntelliJ'sDialogWrapperwithorg.jetbrains.jewel.bridge.composeinstead ofandroidx.compose.ui.window.Dialog
Files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaPlanActions.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaPlanRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
🧠 Learnings (5)
📓 Common learnings
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: For `mpp-idea` plugin tests, run with: `cd mpp-idea && ../gradlew test --tests "cc.unitmesh.devins.idea.renderer.JewelRendererTest"`
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/idea/**/*.kt : For SwingPanel z-index issues with Compose popups, enable Jewel's custom popup renderer: `JewelFlags.useCustomPopupRenderer = true` in `IdeaAgentToolWindowFactory`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaPlanRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/idea/**/*.kt : For dialogs in IntelliJ plugins, use IntelliJ's `DialogWrapper` with `org.jetbrains.jewel.bridge.compose` instead of `androidx.compose.ui.window.Dialog`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaPlanRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: For `mpp-idea` plugin tests, run with: `cd mpp-idea && ../gradlew test --tests "cc.unitmesh.devins.idea.renderer.JewelRendererTest"`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Note that `IdeaAgentViewModelTest` requires IntelliJ Platform Test Framework; `JewelRendererTest` can run standalone with JUnit 5
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
🧬 Code graph analysis (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaPlanRenderer.kt (1)
IdeaPlanRenderer(33-66)
🔇 Additional comments (3)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt (2)
46-47: LGTM: Project parameter addition is backward-compatible.The optional
projectparameter allows renderers to provide project-aware actions (Accept/Reject/View Diff) without breaking existing call sites.
78-88: LGTM: Plan block rendering integrated consistently.The new "plan" block type follows the same pattern as other specialized renderers, properly forwarding the
projectandisCompleteflags.mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaPlanRenderer.kt (1)
40-40: Error handling already exists in the parser.
MarkdownPlanParser.parse()delegates tointerpretPlan(), which wraps the entire parsing logic in a try-catch block (lines 228-236). Any exception during markdown parsing is caught, logged as a warning, and the method returns an empty list instead of propagating the exception. The renderer will not crash on malformed content.Likely an incorrect or invalid review comment.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (4)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaTerminalActions.kt (3)
36-71: Consider extracting duplicated safety check and result mapping logic.Both
executeCommandandexecuteCommandSyncduplicate the safety check and theExecutionResultconstruction logic. This violates DRY and increases maintenance burden.Consider extracting the common logic:
private fun createBlockedResult(reason: String) = ExecutionResult( exitCode = -1, output = "", error = "Command blocked for safety: $reason", isDangerous = true, dangerReason = reason ) private fun createResultFromExecution(result: ProcessExecutorResult) = ExecutionResult( exitCode = result.exitCode, output = result.stdOutput, error = result.errOutput, isDangerous = false, dangerReason = "" ) private fun createErrorResult(e: Exception) = ExecutionResult( exitCode = -1, output = "", error = "Execution error: ${e.message}", isDangerous = false, dangerReason = "" )Also applies to: 76-107
126-134: Useresult.isSuccessfor consistency with the data class definition.The notification logic uses
exitCode == 0directly, butExecutionResult.isSuccessis defined asexitCode == 0 && !isDangerous. Using the property ensures consistent success semantics.fun notifyResult(project: Project, result: ExecutionResult) { - if (result.exitCode == 0) { + if (result.isSuccess) { AutoDevNotifications.notify(project, "Command executed successfully") } else if (result.isDangerous) { AutoDevNotifications.warn(project, "Command blocked: ${result.dangerReason}") } else { AutoDevNotifications.error(project, "Command failed with exit code ${result.exitCode}") } }
112-121: Consider using IntelliJ'sCopyPasteManagerfor clipboard operations.Using
java.awt.Toolkitdirectly may fail in headless environments and bypasses IntelliJ's clipboard management. The platform providesCopyPasteManagerfor this purpose.+import com.intellij.openapi.ide.CopyPasteManager +import java.awt.datatransfer.StringSelection fun copyToClipboard(text: String): Boolean { return try { val selection = StringSelection(text) - val clipboard = Toolkit.getDefaultToolkit().systemClipboard - clipboard.setContents(selection, null) + CopyPasteManager.getInstance().setContents(selection) true } catch (e: Exception) { false } }This also removes the need for the
java.awt.Toolkitimport on line 10.mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaTerminalRenderer.kt (1)
157-169: Minor:Rowwith single child andSpaceBetweenhas no effect.The
Rowon lines 160-163 usesArrangement.SpaceBetweenbut contains only a singleTextchild, making the arrangement redundant.If no additional elements are planned, simplify:
-Row(Modifier.fillMaxWidth(), Arrangement.SpaceBetween, Alignment.CenterVertically) { - Text("Output (Exit: ${result.exitCode})", style = JewelTheme.defaultTextStyle.copy(fontSize = 10.sp, - color = if (result.isSuccess) AutoDevColors.Green.c400 else AutoDevColors.Red.c400)) -} +Text("Output (Exit: ${result.exitCode})", style = JewelTheme.defaultTextStyle.copy(fontSize = 10.sp, + color = if (result.isSuccess) AutoDevColors.Green.c400 else AutoDevColors.Red.c400))
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt(5 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaTerminalRenderer.kt(1 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaTerminalActions.kt(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.kt
📄 CodeRabbit inference engine (AGENTS.md)
**/*.kt: Useexpect/actualfor platform-specific code (e.g., file I/O on JVM/JS/Wasm) in Kotlin Multiplatform projects
Check export first if some functions are not working well with CLI (TypeScript)
In Kotlin/JS @JsExport: AvoidFlow, usePromiseinstead
In Kotlin/JS @JsExport: Use concrete classes as return types and parameter types; avoid interface types
For WASM platform, avoid using emoji and UTF-8 in code
Files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaTerminalRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaTerminalActions.kt
**/idea/**/*.kt
📄 CodeRabbit inference engine (AGENTS.md)
**/idea/**/*.kt: For SwingPanel z-index issues with Compose popups, enable Jewel's custom popup renderer:JewelFlags.useCustomPopupRenderer = trueinIdeaAgentToolWindowFactory
For popup/dropdown menus in IntelliJ plugins, use Jewel'sPopupMenuinstead ofandroidx.compose.ui.window.Popup
For dialogs in IntelliJ plugins, use IntelliJ'sDialogWrapperwithorg.jetbrains.jewel.bridge.composeinstead ofandroidx.compose.ui.window.Dialog
Files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaTerminalRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaTerminalActions.kt
🧠 Learnings (6)
📓 Common learnings
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: For `mpp-idea` plugin tests, run with: `cd mpp-idea && ../gradlew test --tests "cc.unitmesh.devins.idea.renderer.JewelRendererTest"`
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: For `mpp-idea` plugin tests, run with: `cd mpp-idea && ../gradlew test --tests "cc.unitmesh.devins.idea.renderer.JewelRendererTest"`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Note that `IdeaAgentViewModelTest` requires IntelliJ Platform Test Framework; `JewelRendererTest` can run standalone with JUnit 5
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/idea/**/*.kt : For SwingPanel z-index issues with Compose popups, enable Jewel's custom popup renderer: `JewelFlags.useCustomPopupRenderer = true` in `IdeaAgentToolWindowFactory`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaTerminalRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/idea/**/*.kt : For dialogs in IntelliJ plugins, use IntelliJ's `DialogWrapper` with `org.jetbrains.jewel.bridge.compose` instead of `androidx.compose.ui.window.Dialog`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaTerminalRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/idea/**/*.kt : For popup/dropdown menus in IntelliJ plugins, use Jewel's `PopupMenu` instead of `androidx.compose.ui.window.Popup`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaTerminalRenderer.kt
⏰ 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 (223)
- GitHub Check: Build (241)
🔇 Additional comments (10)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaTerminalActions.kt (1)
140-149: LGTM!The
ExecutionResultdata class is well-structured with appropriate computed properties forisSuccessanddisplayOutput. The design cleanly encapsulates execution state.mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaTerminalRenderer.kt (4)
31-85: LGTM!The main composable is well-structured with appropriate state management. Using
remember(command)for the safety check ensures it's only recomputed when the command changes, and tying the coroutine scope to the project lifecycle viaAutoDevCoroutineScope.scope(project)is correct.
89-124: LGTM!The toolbar correctly shows/hides the Execute button based on project availability and command safety. Status indicators provide clear visual feedback for execution states.
126-138: LGTM!The action button uses Jewel's
Tooltipcomponent correctly and provides appropriate hover feedback using interaction sources.
140-155: LGTM!Clear visual distinction for dangerous commands with the red warning banner. The monospace font for command display is appropriate for terminal content.
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt (5)
41-48: LGTM!The
projectparameter is added with anulldefault, ensuring backward compatibility. The KDoc clearly documents its purpose for enabling action buttons.
67-76: LGTM!Project parameter correctly forwarded to
IdeaDiffRendererfor enabling diff action buttons.
78-88: LGTM!Plan rendering integration follows the established pattern, correctly propagating
projectandisCompletestate.
101-111: LGTM!Terminal rendering correctly handles common shell language identifiers (
bash,shell,sh,zsh) and follows the established rendering pattern with proper project and completion state propagation.
148-158: LGTM!Code block rendering correctly receives the
projectparameter, enabling code actions (copy, insert, save) for all language types in the fallback case.
- Create IdeaDiagramActions.kt with copySourceToClipboard/saveDiagramToFile/validate methods - Create IdeaMermaidRenderer.kt with toolbar (copy/show code), validation warnings - Update IdeaSketchRenderer to use enhanced IdeaMermaidRenderer - Note: PlantUML excluded from mpp-idea due to size (~20MB) Phase 5 of #25
Introduce async shell execution with live terminal sessions. Shell commands now return a Pending result immediately, and session completion is monitored in the background. Renderers are updated to handle live terminal status and await session results.
There was a problem hiding this comment.
Pull request overview
This PR adds comprehensive business logic actions and enhanced UI renderers for IntelliJ IDEA, implementing support for Diff/Patch, Code, Plan, Terminal, and Diagram operations. It also includes platform-specific font handling improvements and build optimizations to reduce plugin size by excluding unnecessary dependencies.
Key changes include:
- New Action Classes: Five action classes (IdeaDiffActions, IdeaCodeActions, IdeaPlanActions, IdeaTerminalActions, IdeaDiagramActions) that encapsulate business logic and delegate to core module functionality
- Enhanced Renderers: New and updated Compose-based renderers with interactive toolbars and action buttons for improved user experience
- Font Handling: Platform-specific UTF-8 font support with WASM-specific Noto Sans SC font for CJK characters
- Build Optimizations: Global dependency exclusions (~100MB+ savings) and font file exclusions for cleaner IDEA plugin distribution
Reviewed changes
Copilot reviewed 23 out of 23 changed files in this pull request and generated 19 comments.
Show a summary per file
| File | Description |
|---|---|
mpp-ui/src/*/kotlin/.../CodeFont.*.kt |
Added platform-specific getUtf8FontFamily() implementations for proper font handling across JVM/JS/iOS/Android/WASM |
mpp-ui/src/commonMain/kotlin/.../DevInEditorInput.kt |
Refactored to use new getUtf8FontFamily() helper instead of inline font selection |
mpp-ui/src/commonMain/kotlin/.../AgentMessageList.kt |
Refactored to use new getUtf8FontFamily() helper for consistent font rendering |
mpp-ui/build.gradle.kts |
Updated font download task to target wasmJsMain instead of commonMain |
mpp-idea/src/main/kotlin/.../actions/IdeaDiffActions.kt |
New action class for patch operations (accept/reject/view/repair) with IntelliJ Platform integration |
mpp-idea/src/main/kotlin/.../actions/IdeaCodeActions.kt |
New action class for code operations (copy/insert/save) with editor integration |
mpp-idea/src/main/kotlin/.../actions/IdeaPlanActions.kt |
New action class for plan operations (parse/copy/pin/save) using MarkdownPlanParser |
mpp-idea/src/main/kotlin/.../actions/IdeaTerminalActions.kt |
New action class for terminal operations (execute/safety-check) using ProcessExecutor |
mpp-idea/src/main/kotlin/.../actions/IdeaDiagramActions.kt |
New action class for diagram operations (validate/copy/save) for Mermaid/PlantUML/Graphviz |
mpp-idea/src/main/kotlin/.../IdeaDiffRenderer.kt |
Enhanced with interactive toolbar containing Accept/Reject/View Diff/Repair buttons |
mpp-idea/src/main/kotlin/.../IdeaCodeBlockRenderer.kt |
Enhanced with toolbar containing Copy/Insert at Cursor/Save to File buttons |
mpp-idea/src/main/kotlin/.../IdeaPlanRenderer.kt |
New renderer for plan display with expand/collapse, status indicators, and toolbar actions |
mpp-idea/src/main/kotlin/.../IdeaTerminalRenderer.kt |
New renderer for terminal commands with execution, safety warnings, and output display |
mpp-idea/src/main/kotlin/.../IdeaMermaidRenderer.kt |
New enhanced Mermaid renderer with validation warnings and code toggle |
mpp-idea/src/main/kotlin/.../IdeaSketchRenderer.kt |
Updated to integrate new renderers for plan/terminal/mermaid language types |
mpp-idea/src/main/kotlin/.../IdeaAnalysisComponents.kt |
Formatting improvement for better code readability |
mpp-idea/build.gradle.kts |
Added global dependency exclusions (~100MB savings) and font file exclusions for plugin distribution |
mpp-idea/src/main/resources/META-INF/plugin.xml |
Updated plugin name and description for clarity |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| } | ||
|
|
||
| return try { | ||
| val executor = project.getService(ProcessExecutor::class.java) |
There was a problem hiding this comment.
The executeCommand method is missing proper error handling for service retrieval. If project.getService(ProcessExecutor::class.java) returns null, it will throw a NullPointerException. Consider adding a null check and returning an appropriate ExecutionResult with an error message.
| val executor = project.getService(ProcessExecutor::class.java) | |
| val executor = project.getService(ProcessExecutor::class.java) | |
| if (executor == null) { | |
| return ExecutionResult( | |
| exitCode = -1, | |
| output = "", | |
| error = "ProcessExecutor service is not available.", | |
| isDangerous = false, | |
| dangerReason = "" | |
| ) | |
| } |
| val codingPanel = toolWindow.contentManager.component.components | ||
| ?.filterIsInstance<AutoDevPlannerToolWindow>() | ||
| ?.firstOrNull() | ||
|
|
There was a problem hiding this comment.
The pinToToolWindow method has potential null safety issues. If toolWindow.contentManager.component.components is null or if no AutoDevPlannerToolWindow is found, the method silently fails. Consider adding error logging or notifications to inform the user when the operation fails.
| * Validate Mermaid diagram syntax (basic check) | ||
| */ | ||
| fun validateMermaidSyntax(code: String): Pair<Boolean, String> { | ||
| val trimmed = code.trim() | ||
| if (trimmed.isEmpty()) { | ||
| return Pair(false, "Empty diagram code") | ||
| } | ||
|
|
||
| val validStarts = listOf( | ||
| "graph", "flowchart", "sequenceDiagram", "classDiagram", | ||
| "stateDiagram", "erDiagram", "journey", "gantt", "pie", | ||
| "gitGraph", "mindmap", "timeline", "quadrantChart", | ||
| "requirementDiagram", "C4Context", "sankey" | ||
| ) | ||
|
|
||
| val hasValidStart = validStarts.any { | ||
| trimmed.startsWith(it, ignoreCase = true) | ||
| } | ||
|
|
||
| return if (hasValidStart) { | ||
| Pair(true, "") | ||
| } else { | ||
| Pair(false, "Unknown diagram type. Expected: ${validStarts.joinToString(", ")}") | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Validate PlantUML diagram syntax (basic check) | ||
| */ | ||
| fun validatePlantUmlSyntax(code: String): Pair<Boolean, String> { | ||
| val trimmed = code.trim() | ||
| if (trimmed.isEmpty()) { | ||
| return Pair(false, "Empty diagram code") | ||
| } | ||
|
|
||
| val hasStart = trimmed.contains("@startuml", ignoreCase = true) || | ||
| trimmed.contains("@startmindmap", ignoreCase = true) || | ||
| trimmed.contains("@startgantt", ignoreCase = true) || | ||
| trimmed.contains("@startwbs", ignoreCase = true) || | ||
| trimmed.contains("@startjson", ignoreCase = true) || | ||
| trimmed.contains("@startyaml", ignoreCase = true) | ||
|
|
||
| return if (hasStart) { | ||
| Pair(true, "") | ||
| } else { | ||
| Pair(false, "Missing @startuml or similar directive") | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Validate Graphviz DOT syntax (basic check) | ||
| */ | ||
| fun validateDotSyntax(code: String): Pair<Boolean, String> { | ||
| val trimmed = code.trim() | ||
| if (trimmed.isEmpty()) { | ||
| return Pair(false, "Empty diagram code") | ||
| } | ||
|
|
||
| val hasValidStart = trimmed.startsWith("digraph", ignoreCase = true) || | ||
| trimmed.startsWith("graph", ignoreCase = true) || | ||
| trimmed.startsWith("strict", ignoreCase = true) | ||
|
|
||
| return if (hasValidStart) { | ||
| Pair(true, "") | ||
| } else { | ||
| Pair(false, "Expected 'digraph', 'graph', or 'strict' keyword") | ||
| } | ||
| } |
There was a problem hiding this comment.
The validation methods in IdeaDiagramActions (validateMermaidSyntax, validatePlantUmlSyntax, validateDotSyntax) contain important business logic that could benefit from unit tests. Consider adding tests to verify the validation rules work correctly for various diagram types, similar to how ShellSafetyCheck has tests in the core module.
| * Check if a command is dangerous | ||
| * @return Pair of (isDangerous, reason) |
There was a problem hiding this comment.
[nitpick] The comment references the wrong method name. The method in ShellSafetyCheck is checkDangerousCommand(), not some other name. However, the implementation correctly calls ShellSafetyCheck.checkDangerousCommand(command) on line 27, so this is just a documentation issue. The comment on line 22-23 should be more specific about what this method does (it delegates to ShellSafetyCheck).
| * Check if a command is dangerous | |
| * @return Pair of (isDangerous, reason) | |
| * Delegates to [ShellSafetyCheck.checkDangerousCommand] to determine if a command is dangerous. | |
| * @param command The shell command to check. | |
| * @return Pair of (isDangerous, reason) as returned by [ShellSafetyCheck.checkDangerousCommand]. |
| */ | ||
| fun getCurrentPlan(project: Project): List<AgentTaskEntry> { | ||
| val agentStateService = project.getService(AgentStateService::class.java) | ||
| return agentStateService.getPlan() |
There was a problem hiding this comment.
The getCurrentPlan method is missing proper error handling for service retrieval. If project.getService(AgentStateService::class.java) returns null, it will throw a NullPointerException. Consider adding a null check and returning an empty list as a fallback.
| return agentStateService.getPlan() | |
| return agentStateService?.getPlan() ?: emptyList() |
| ) { | ||
| val fileDiffs = remember(diffContent) { DiffParser.parse(diffContent) } | ||
| var isRepairing by remember { mutableStateOf(false) } | ||
| var patchApplied by remember { mutableStateOf(false) } |
There was a problem hiding this comment.
The patchApplied state is set to true when a patch is successfully applied but is never reset when a new diff is received (via remember(diffContent)). If the same component is reused with different diffContent, this state will persist incorrectly. Consider using remember(diffContent) to reset this state when the content changes.
| var patchApplied by remember { mutableStateOf(false) } | |
| var patchApplied by remember(diffContent) { mutableStateOf(false) } |
| exclude(group = "org.jetbrains.kotlinx", module = "kotlinx-serialization-core-jvm") | ||
| exclude(group = "org.jetbrains.kotlinx", module = "kotlinx-io-core") | ||
| exclude(group = "org.jetbrains.kotlinx", module = "kotlinx-io-core-jvm") | ||
| // Note: Heavy dependencies (AWS, Tika, POI, PDFBox, PlantUML, Jsoup) are excluded globally above |
There was a problem hiding this comment.
[nitpick] The comment on line 126 refers to "excluded globally above", but the global exclusions were just added in this PR. This comment would be clearer if it explained why these specific dependencies were already excluded elsewhere, or if it simply said "Note: Additional heavy dependencies are excluded globally at the top of the dependencies block" to make the reference more precise.
| // Note: Heavy dependencies (AWS, Tika, POI, PDFBox, PlantUML, Jsoup) are excluded globally above | |
| // Note: Additional heavy dependencies (AWS, Tika, POI, PDFBox, PlantUML, Jsoup) are excluded globally at the top of the dependencies block |
| fun copyToClipboard(text: String): Boolean { | ||
| return try { | ||
| val selection = StringSelection(text) | ||
| val clipboard = Toolkit.getDefaultToolkit().systemClipboard | ||
| clipboard.setContents(selection, null) |
There was a problem hiding this comment.
The clipboard operations use Toolkit.getDefaultToolkit().systemClipboard which might not be available in headless environments or during testing. Consider using IntelliJ's CopyPasteManager.getInstance() instead, which is the platform-preferred way to handle clipboard operations and works better in all environments.
| enabled = executionState != TerminalState.RUNNING, onClick = onExecute | ||
| ) | ||
| } | ||
| TerminalActionButton(if (copied) "Copied!" else "Copy", |
There was a problem hiding this comment.
[nitpick] The TerminalToolbar composable has copied as a parameter but doesn't provide a way to reset it back to false after some time. This means once "Copied!" is shown, it will remain that way for the lifetime of the component. Consider adding a LaunchedEffect to reset the copied state after a delay (e.g., 2 seconds).
| fun copyToClipboard(content: String): Boolean { | ||
| return try { | ||
| val clipboard = Toolkit.getDefaultToolkit().systemClipboard | ||
| val selection = StringSelection(content) | ||
| clipboard.setContents(selection, null) |
There was a problem hiding this comment.
The clipboard operations use Toolkit.getDefaultToolkit().systemClipboard which might not be available in headless environments or during testing. Consider using IntelliJ's CopyPasteManager.getInstance() instead, which is the platform-preferred way to handle clipboard operations and works better in all environments.
Enable real-time shell command output in the IDEA timeline using live process monitoring. Adds a new UI bubble for live terminal sessions and updates shell execution to support async streaming and status reporting.
Adds a cancel button to terminate running shell processes in the live terminal timeline bubble. Also refines timeline logic to prevent duplicate shell command bubbles.
Introduce read-process, wait-process, and kill-process tools to manage long-running shell commands. ShellTool now supports background execution with session IDs, enabling users to read output, wait for completion, or terminate processes asynchronously.
Add support for capturing and sending the current output log to the AI when a live terminal process is cancelled by the user. This includes a new CancelEvent data class and updates to the cancellation flow in the UI and view model.
Problem: - When user clicks Cancel on LiveTerminal, the output was empty - This was because PtyShellExecutor.waitForSession was reading from the same inputStream as ProcessOutputCollector, causing conflicts Root Cause: - Two readers competing for the same PTY inputStream - ProcessOutputCollector in UI layer and waitForSession in core layer Solution: 1. Modified PtyShellExecutor.waitForSession to NOT read output - Only waits for process completion, no output reading - Avoids conflict with UI-layer output collectors 2. Enhanced ProcessOutputCollector to sync output to ShellSessionManager - Added sessionId parameter to ProcessOutputCollector - Syncs output chunks to ManagedSession.appendOutput() - Cancel event now gets actual output from collector buffer 3. Updated IdeaLiveTerminalBubble to use collector.getCurrentOutput() - More reliable than state-based output for cancel events 4. CLI renderer (CodingCli) already reads output independently - Not affected by waitForSession changes
There was a problem hiding this comment.
Actionable comments posted: 8
♻️ Duplicate comments (2)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.kt (1)
44-47: Resetcopiedstate after a delay for better UX.The
copiedstate is set totruebut never reset, so the button will permanently show "Copied!" after the first click. Add aLaunchedEffectto reset it.var copied by remember { mutableStateOf(false) } var showCode by remember { mutableStateOf(false) } + + LaunchedEffect(copied) { + if (copied) { + kotlinx.coroutines.delay(2000) + copied = false + } + }mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaDiagramActions.kt (1)
21-30: Consider using IntelliJ'sCopyPasteManagerfor clipboard operations.
Toolkit.getDefaultToolkit().systemClipboardmay not work in headless environments or during testing. IntelliJ'sCopyPasteManager.getInstance()is the platform-preferred approach.+import com.intellij.openapi.ide.CopyPasteManager + fun copySourceToClipboard(source: String): Boolean { return try { val selection = StringSelection(source) - val clipboard = Toolkit.getDefaultToolkit().systemClipboard - clipboard.setContents(selection, null) + CopyPasteManager.getInstance().setContents(selection) true } catch (e: Exception) { false } }
🧹 Nitpick comments (14)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.kt (1)
96-118: Unusedprojectparameter in MermaidToolbar.The
projectparameter is passed toMermaidToolbarbut not used within the function. Either remove it or wire it to an action (e.g.,saveDiagramToFile).@Composable private fun MermaidToolbar( - project: Project?, mermaidCode: String, copied: Boolean, showCode: Boolean, + mermaidCode: String, copied: Boolean, showCode: Boolean, onCopy: () -> Unit, onToggleCode: () -> Unit ) {mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaDiagramActions.kt (1)
60-62: Silent exception swallowing hides failures.When
saveDiagramToFilefails, the exception is caught andfalseis returned, but the actual error is lost. Consider logging the exception for debugging purposes.+import com.intellij.openapi.diagnostic.Logger + +private val LOG = Logger.getInstance(IdeaDiagramActions::class.java) + } catch (e: Exception) { + LOG.warn("Failed to save diagram to file", e) false }mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolOrchestrator.kt (2)
41-43:backgroundScopelacks lifecycle management and failure isolation.The
CoroutineScope(Dispatchers.Default)creates an unmanaged scope that is never cancelled. If theToolOrchestratoris discarded, monitoring coroutines may leak. Additionally, withoutSupervisorJob, an exception in one monitoring coroutine could cancel others.Consider using
SupervisorJob()for failure isolation and exposing aclose()method:- private val backgroundScope = CoroutineScope(Dispatchers.Default) + private val backgroundScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + /** + * Cancel all background monitoring tasks. + * Call when this orchestrator is no longer needed. + */ + fun close() { + backgroundScope.cancel() + }Also add the import:
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel
132-146: Safe cast and null check recommended for shell executor retrieval.Line 133 fetches the tool again and casts without null check. While unlikely to fail since
liveSessionwas created from this tool, it's defensive to verify.val result = if (liveSession != null) { - val shellExecutor = getShellExecutor(registry.getTool(toolName) as cc.unitmesh.agent.tool.impl.ShellTool) + val tool = registry.getTool(toolName) as? cc.unitmesh.agent.tool.impl.ShellTool + ?: return ToolExecutionResult.failure( + context.executionId, toolName, "Shell tool not found", + startTime, Clock.System.now().toEpochMilliseconds() + ) + val shellExecutor = getShellExecutor(tool)mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/executor/CodingAgentExecutor.kt (1)
21-31: Unused configuration fields:maxWaitTimeoutMsandcheckIntervalMs.Only
initialWaitTimeoutMsis used inhandlePendingResult. The other fields are declared but never referenced, which may confuse maintainers.Either remove unused fields or add a TODO comment indicating planned usage:
data class AsyncShellConfig( /** Initial wait timeout in milliseconds before notifying AI that process is still running */ val initialWaitTimeoutMs: Long = 60_000L, // 1 minute - /** Maximum total wait time in milliseconds */ - val maxWaitTimeoutMs: Long = 300_000L, // 5 minutes - /** Interval for checking process status after initial timeout */ - val checkIntervalMs: Long = 30_000L // 30 seconds + // TODO: Add maxWaitTimeoutMs and checkIntervalMs when implementing polling retry logic )mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/shell/ShellSessionManager.kt (3)
77-86: Exception safety inclearAll()- failing kill could leave sessions uncleaned.If
kill()throws for one session, the loop exits and remaining sessions aren't killed. Consider catching exceptions per-session.suspend fun clearAll() { mutex.withLock { - sessions.values.forEach { it.kill() } + sessions.values.forEach { session -> + try { + session.kill() + } catch (e: Exception) { + // Log and continue cleaning up remaining sessions + } + } sessions.clear() _activeSessions.value = emptyList() } }
130-136:markCompleted()has potential race condition.
_exitCodeand_endTimeare updated without synchronization while other methods may read them concurrently. Consider using atomic operations or the existing mutex.+ private val stateMutex = Mutex() + /** * Mark session as completed */ - fun markCompleted(exitCode: Int, endTime: Long = Platform.getCurrentTimestamp()) { - _exitCode = exitCode - _endTime = endTime + suspend fun markCompleted(exitCode: Int, endTime: Long = Platform.getCurrentTimestamp()) { + stateMutex.withLock { + _exitCode = exitCode + _endTime = endTime + } }Note: This changes the function signature to
suspend, which may require updates to callers.
141-150:kill()silently swallows exceptions.The catch block returns
falsebut doesn't log the exception, making debugging difficult when process termination fails.fun kill(): Boolean { val process = processHandle as? Process ?: return false return try { process.destroyForcibly() markCompleted(-1) true } catch (e: Exception) { + // Consider logging: logger.warn { "Failed to kill process: ${e.message}" } false } }mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.kt (3)
71-74: Cancelling stream readers may lose final output.After the process ends, only 50ms delay is given before cancelling stdout/stderr jobs. If there's buffered data, it may not be read. Consider joining the jobs or reading until EOF.
// Process ended - wait a bit for streams to flush - delay(50) - stdoutJob.cancel() - stderrJob.cancel() + // Wait for streams to complete (EOF) rather than cancelling + stdoutJob.join() + stderrJob.join()The
readStreamfunction already exits when it reads -1 (EOF), so joining should be safe and ensure all output is captured.
111-114: Suspend function called inside synchronized block may cause issues.
ShellSessionManager.getSession()is a suspend function being called within a non-suspend context inside the stream reader. While this specific call works because the enclosing function is suspend, mixingsynchronizedwith coroutines can lead to blocking issues.Move the ShellSessionManager sync outside the synchronized block:
synchronized(buffer) { if (isError) buffer.append("\u001B[31m") buffer.append(chunk) if (isError) buffer.append("\u001B[0m") } _state.update { it.copy(output = buffer.toString()) } // Sync to ShellSessionManager for cancel event handling - sessionId?.let { sid -> - ShellSessionManager.getSession(sid)?.appendOutput(chunk) - } + sessionId?.let { sid -> + try { + ShellSessionManager.getSession(sid)?.appendOutput(chunk) + } catch (e: Exception) { + // Ignore sync errors + } + }
324-346: Cancel button lacks accessibility indication.The cancel button uses
clickablewithoutindicationor semantic description, which may affect accessibility for screen readers and keyboard navigation.Consider adding semantics for accessibility:
Box( modifier = Modifier .align(Alignment.BottomEnd) .padding(4.dp) .background( AutoDevColors.Red.c600.copy(alpha = 0.9f), RoundedCornerShape(4.dp) ) - .clickable { handleCancel() } + .clickable( + onClick = { handleCancel() }, + onClickLabel = "Cancel running process" + ) .padding(horizontal = 8.dp, vertical = 4.dp) )mpp-ui/src/jvmMain/kotlin/cc/unitmesh/server/cli/CodingCli.kt (2)
163-171: Consider thread-safe map for concurrent session access.
activeSessionsis a plainmutableMapOf, but it may be accessed concurrently from coroutines running on different threads (e.g.,addLiveTerminal,updateLiveTerminalStatus, andawaitSessionResult). This could lead to data races.- private val activeSessions = mutableMapOf<String, SessionInfo>() + private val activeSessions = java.util.concurrent.ConcurrentHashMap<String, SessionInfo>()
316-357: Close stream readers to avoid resource leaks.The
BufferedReaderinstances for stdout and stderr are never explicitly closed. While the process termination may eventually release these, explicitly closing them ensures deterministic cleanup, especially if exceptions occur.private suspend fun awaitProcess( process: Process, session: SessionInfo, timeoutMs: Long ): cc.unitmesh.agent.tool.ToolResult { val startWait = System.currentTimeMillis() val checkIntervalMs = 100L val outputBuilder = StringBuilder() // Read output in background val stdoutReader = process.inputStream.bufferedReader() val stderrReader = process.errorStream.bufferedReader() - while (process.isAlive) { + try { + while (process.isAlive) { // ... existing loop body ... - } + } - // Read remaining output - stdoutReader.forEachLine { line -> - outputBuilder.appendLine(line) - println(" │ $line") - } - stderrReader.forEachLine { line -> - outputBuilder.appendLine("[stderr] $line") - println(" │ [stderr] $line") - } + // Read remaining output + stdoutReader.forEachLine { line -> + outputBuilder.appendLine(line) + println(" │ $line") + } + stderrReader.forEachLine { line -> + outputBuilder.appendLine("[stderr] $line") + println(" │ [stderr] $line") + } + } finally { + stdoutReader.close() + stderrReader.close() + }mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/impl/ProcessManagementTools.kt (1)
95-106: Inconsistent session cleanup between ReadProcess and WaitProcess.
ReadProcessInvocationdoes not remove completed sessions, whileWaitProcessInvocation(line 204) does. This inconsistency could cause session accumulation if users only useread-processto check completed processes. Consider adding cleanup for completed sessions here as well, or document thatread-processis non-destructive by design.If cleanup is intended:
} else { + // Clean up completed session + ShellSessionManager.removeSession(params.sessionId) + val exitCode = session.exitCode ?: -1 if (exitCode == 0) {Alternatively, if this is intentional (e.g., allowing multiple reads), add a comment clarifying the design choice.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (22)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/executor/CodingAgentExecutor.kt(5 hunks)mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolExecutionResult.kt(3 hunks)mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolOrchestrator.kt(5 hunks)mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/render/CodingAgentRenderer.kt(3 hunks)mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/Tool.kt(1 hunks)mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/impl/ProcessManagementTools.kt(1 hunks)mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/impl/ShellTool.kt(6 hunks)mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/schema/ToolResultFormatter.kt(2 hunks)mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/shell/ShellSessionManager.kt(1 hunks)mpp-core/src/jsMain/kotlin/cc/unitmesh/llm/JsExports.kt(1 hunks)mpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/DefaultShellExecutor.jvm.kt(2 hunks)mpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/PtyShellExecutor.kt(1 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.kt(1 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaTimelineContent.kt(4 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/JewelRenderer.kt(2 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.kt(1 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt(6 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaDiagramActions.kt(1 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt(2 hunks)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.kt(1 hunks)mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/ComposeRenderer.kt(1 hunks)mpp-ui/src/jvmMain/kotlin/cc/unitmesh/server/cli/CodingCli.kt(2 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.kt
📄 CodeRabbit inference engine (AGENTS.md)
**/*.kt: Useexpect/actualfor platform-specific code (e.g., file I/O on JVM/JS/Wasm) in Kotlin Multiplatform projects
Check export first if some functions are not working well with CLI (TypeScript)
In Kotlin/JS @JsExport: AvoidFlow, usePromiseinstead
In Kotlin/JS @JsExport: Use concrete classes as return types and parameter types; avoid interface types
For WASM platform, avoid using emoji and UTF-8 in code
Files:
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/schema/ToolResultFormatter.ktmpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/shell/ShellSessionManager.ktmpp-core/src/jsMain/kotlin/cc/unitmesh/llm/JsExports.ktmpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolExecutionResult.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.ktmpp-core/src/commonMain/kotlin/cc/unitmesh/agent/executor/CodingAgentExecutor.ktmpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolOrchestrator.ktmpp-core/src/commonMain/kotlin/cc/unitmesh/agent/render/CodingAgentRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.ktmpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/Tool.ktmpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/DefaultShellExecutor.jvm.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaDiagramActions.ktmpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/ComposeRenderer.ktmpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/PtyShellExecutor.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/JewelRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.ktmpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/impl/ProcessManagementTools.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaTimelineContent.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.ktmpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/impl/ShellTool.ktmpp-ui/src/jvmMain/kotlin/cc/unitmesh/server/cli/CodingCli.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
**/idea/**/*.kt
📄 CodeRabbit inference engine (AGENTS.md)
**/idea/**/*.kt: For SwingPanel z-index issues with Compose popups, enable Jewel's custom popup renderer:JewelFlags.useCustomPopupRenderer = trueinIdeaAgentToolWindowFactory
For popup/dropdown menus in IntelliJ plugins, use Jewel'sPopupMenuinstead ofandroidx.compose.ui.window.Popup
For dialogs in IntelliJ plugins, use IntelliJ'sDialogWrapperwithorg.jetbrains.jewel.bridge.composeinstead ofandroidx.compose.ui.window.Dialog
Files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaDiagramActions.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/JewelRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaTimelineContent.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
**/compose/**/*.{kt,kts}
📄 CodeRabbit inference engine (AGENTS.md)
In Compose (Desktop/Android), use
AutoDevColorsfromcc.unitmesh.devins.ui.compose.themeorMaterialTheme.colorScheme
Files:
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/ComposeRenderer.kt
{**/compose/**/*.kt,mpp-ui/src/jsMain/typescript/**/*.{ts,tsx}}
📄 CodeRabbit inference engine (AGENTS.md)
DO NOT hardcode colors (e.g.,
Color(0xFF...)or#hex). Always use design tokens for consistency across platforms
Files:
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/ComposeRenderer.kt
🧠 Learnings (8)
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/*.kt : In Kotlin/JS JsExport: Avoid `Flow`, use `Promise` instead
Applied to files:
mpp-core/src/jsMain/kotlin/cc/unitmesh/llm/JsExports.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/*.kt : In Kotlin/JS JsExport: Use concrete classes as return types and parameter types; avoid interface types
Applied to files:
mpp-core/src/jsMain/kotlin/cc/unitmesh/llm/JsExports.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/idea/**/*.kt : For SwingPanel z-index issues with Compose popups, enable Jewel's custom popup renderer: `JewelFlags.useCustomPopupRenderer = true` in `IdeaAgentToolWindowFactory`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/JewelRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Note that `IdeaAgentViewModelTest` requires IntelliJ Platform Test Framework; `JewelRendererTest` can run standalone with JUnit 5
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/JewelRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: For `mpp-idea` plugin tests, run with: `cd mpp-idea && ../gradlew test --tests "cc.unitmesh.devins.idea.renderer.JewelRendererTest"`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/JewelRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/idea/**/*.kt : For dialogs in IntelliJ plugins, use IntelliJ's `DialogWrapper` with `org.jetbrains.jewel.bridge.compose` instead of `androidx.compose.ui.window.Dialog`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/idea/**/*.kt : For popup/dropdown menus in IntelliJ plugins, use Jewel's `PopupMenu` instead of `androidx.compose.ui.window.Popup`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.ktmpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/compose/**/*.{kt,kts} : In Compose (Desktop/Android), use `AutoDevColors` from `cc.unitmesh.devins.ui.compose.theme` or `MaterialTheme.colorScheme`
Applied to files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
🧬 Code graph analysis (9)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.kt (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/terminal/IdeaAnsiTerminalRenderer.kt (1)
IdeaAnsiTerminalRenderer(42-65)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolOrchestrator.kt (2)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/logging/LoggingInitializer.kt (2)
getLogger(93-98)getLogger(100-105)mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/logging/AutoDevLogger.kt (1)
getLogger(38-42)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.kt (1)
mpp-core/src/commonMain/kotlin/cc/unitmesh/devins/test/AstFormatter.kt (1)
appendLine(206-209)
mpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/DefaultShellExecutor.jvm.kt (3)
mpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/PtyShellExecutor.kt (2)
validateCommand(184-200)prepareCommand(129-154)mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/shell/ShellExecutor.kt (2)
validateCommand(75-77)validateCommand(80-89)build.gradle.kts (1)
environment(47-47)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.kt (1)
mpp-viewer-web/src/commonMain/kotlin/cc/unitmesh/viewer/web/MermaidRenderer.kt (1)
MermaidRenderer(42-91)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/impl/ProcessManagementTools.kt (1)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/schema/ToolSchema.kt (3)
string(136-155)boolean(172-181)integer(157-170)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaTimelineContent.kt (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.kt (1)
IdeaLiveTerminalBubble(153-350)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/impl/ShellTool.kt (1)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/schema/ToolSchema.kt (2)
boolean(172-181)integer(157-170)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt (4)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaPlanRenderer.kt (1)
IdeaPlanRenderer(33-66)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaTerminalRenderer.kt (1)
IdeaTerminalRenderer(31-85)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.kt (1)
IdeaMermaidRenderer(31-94)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/markdown/JewelMarkdownRenderer.kt (1)
JewelMarkdownRenderer(46-59)
⏰ 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 (223)
- GitHub Check: Build (241)
🔇 Additional comments (49)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.kt (2)
31-42: LGTM on JCEF availability check.Early return when JCEF is not supported prevents runtime errors and provides a clean fallback message.
53-58: Unable to verify disposal handling — referenced code not found in repository.The file
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.ktand theMermaidRendererclass do not exist in the current repository. After comprehensive searches including directory traversal, class definition lookups, and pattern matching for related code (parentDisposable usage, DisposableEffect patterns, Composable functions), no matching code was found.mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaDiagramActions.kt (2)
86-95: Mermaid validation uses case-insensitive check against mixed-case list.The
validStartslist contains mixed case (e.g.,sequenceDiagram,C4Context), andstartsWithwithignoreCase = truehandles this correctly. However, for consistency and clarity, consider documenting this behavior or normalizing the list.
150-157: LGTM ongetDiagramTypeimplementation.Clean mapping from language identifiers to enum values with proper lowercase normalization.
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt (5)
41-47: LGTM on addingprojectparameter toRenderResponse.The optional
Projectparameter enables action buttons across renderers while maintaining backward compatibility with a default ofnull.
149-155: Fallback toJewelMarkdownRendererfor unknown code blocks.The fallback now uses
JewelMarkdownRendererinstead of a dedicated code block renderer. This may render code without syntax highlighting for unrecognized languages. Verify this is the intended behavior.
67-76: Consistent project wiring for diff renderer.The
IdeaDiffRenderernow receives the project context, enabling Accept/Reject/View Diff actions. The wiring pattern is consistent with other renderers.
78-88: Plan renderer integration looks correct.
IdeaPlanRendererreceivesproject,isComplete, and content. This aligns with the relevant code snippet showing its signature.
101-111: Terminal commands are safely gated behind explicit user action.Commands execute only when users click the "Execute" button in
TerminalToolbar(lines 60-69), never automatically during streaming. Execution is protected by project null-check and dangerous command detection before callingIdeaTerminalActions.executeCommand().Minor note: The
isCompleteparameter is accepted but unused inIdeaTerminalRenderer. Consider either using it to disable the execute button during streaming (consistent with other renderers likeIdeaDevInBlockRenderer), or removing it if execution should always be available.mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/JewelRenderer.kt (2)
141-150: LGTM!The approach correctly prevents duplicate timeline entries for Shell tools while preserving the current tool call context. The early return ensures that only
LiveTerminalItemwill be added viaaddLiveTerminal().
431-445: LGTM!The implementation correctly adds a
LiveTerminalItemto the timeline with all necessary session metadata.mpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/DefaultShellExecutor.jvm.kt (3)
347-357: LGTM on the live execution support flag.Returning
trueunconditionally is appropriate since both PTY and ProcessBuilder paths are available as fallbacks.
363-400: LGTM on the ProcessBuilder fallback path.The implementation correctly reuses existing helpers (
prepareCommand,augmentEnvironmentPath) and properly validates commands before execution.
405-425: LGTM on session completion handling.The dual-path logic (PTY vs Process) is clear, with proper timeout handling and cleanup. The cast validation with
ToolExceptionprovides a clear error for debugging.mpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/PtyShellExecutor.kt (1)
259-286: LGTM on the output handling delegation.The comments clearly document the architectural decision to let the UI layer handle output collection. This prevents conflicts with concurrent readers (e.g.,
ProcessOutputCollectorinIdeaLiveTerminalBubble).mpp-core/src/jsMain/kotlin/cc/unitmesh/llm/JsExports.kt (1)
800-805: LGTM on Pending variant mapping.The implementation correctly surfaces the pending state to JS consumers via
metadatawithsessionIdandisPendingflag. Usingsuccess = falseis appropriate since the operation hasn't completed yet. Based on learnings, the use of concreteJsToolResultclass (not an interface) aligns with Kotlin/JS export best practices.mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt (1)
166-170: LGTM on cancellation callback wiring.The
onProcessCancelcallback is cleanly integrated, following the existing pattern of delegating events to theviewModelfor handling.mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/schema/ToolResultFormatter.kt (1)
30-57: LGTM on pending state formatting.The implementation correctly differentiates between pending and completed states, providing appropriate context for each:
- Pending: Displays session metadata without output (since none exists yet)
- Completed: Shows output with optional error details
The safe cast on line 40 gracefully handles edge cases where the result type doesn't match expectations.
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.kt (1)
397-432: LGTM!The process cancellation handling is well-implemented. The function safely terminates the process using
destroyForcibly()(idempotent), captures relevant context (command, session ID, output), and renders structured metadata for the AI/LLM layer to understand the cancellation. The markdown-formatted output provides clear context for debugging.mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolExecutionResult.kt (2)
26-48: LGTM!The
isSuccess,isPending, andcontentproperties correctly handle the newToolResult.Pendingvariant. Treating pending as not-yet-successful is semantically correct for async execution flows.
109-136: LGTM!The
pending()factory method is well-designed for async tool execution. SettingendTime = startTime(resulting induration = 0) is appropriate for in-progress executions, and the automatic metadata enrichment withsessionIdandisAsyncprovides useful context for downstream consumers.mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/render/CodingAgentRenderer.kt (1)
32-74: LGTM!The new live terminal API methods are well-designed with sensible defaults. The no-op implementations for
addLiveTerminalandupdateLiveTerminalStatusmaintain backward compatibility, whileawaitSessionResultreturning an error for unsupported renderers is a safe fallback. The KDoc clearly documents the expected behavior and parameter semantics.mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaTimelineContent.kt (1)
22-90: LGTM!The cancellation callback is properly threaded through the component hierarchy from
IdeaTimelineContent→IdeaTimelineItemView→IdeaLiveTerminalBubble. TheLiveTerminalItemcase correctly wires theonProcessCancelcallback to enable user-initiated process termination.mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolOrchestrator.kt (3)
258-303: LGTM - Background monitoring implementation is well-structured.The async session monitoring handles both success and error cases appropriately, updates the renderer with final status, and logs errors with full exception context.
202-213: LGTM - Pending result propagation is correct.The pending result is properly converted to
ToolExecutionResult.pendingwith all necessary metadata preserved.
666-681: LGTM - Pending handling in helper functions is semantically correct.Treating
Pendingas not-yet-successful and having no error message is the appropriate behavior for async execution states.mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/executor/CodingAgentExecutor.kt (3)
218-227: LGTM - Pending result interception and handling.The pattern of intercepting
Pendingresults and delegating tohandlePendingResultis clean. Thevarusage is justified for the reassignment.
379-396: LGTM - AgentResult handling is appropriate defensive code.The comment "Unexpected, but handle it" correctly documents that this branch shouldn't normally execute, while still providing graceful handling.
357-377: The semantic mismatch concern is unfounded. The code intentionally returnsToolResult.SuccesswithToolExecutionState.Executingto allow the agent to continue making decisions while the process runs in the background—as documented in the inline comment on lines 353-354. Downstream consumers (DocumentAgentExecutor, CodeReviewAgentExecutor, CodingAgentExecutor) check only theresulttype, not both state and result simultaneously, so there are no consistency issues downstream.Likely an incorrect or invalid review comment.
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/Tool.kt (2)
80-97: LGTM -Pendingresult type is well-designed.The new
Pendingsubclass properly extendsToolResult, includes appropriate fields for async tracking, and is correctly marked@Serializable. Documentation is clear.
99-122: LGTM - Helper methods consistently handlePending.The
isPending()method and updates togetOutput(),getError(), andextractMetadata()follow established patterns and maintain exhaustivewhenexpressions.mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.kt (3)
134-139: LGTM -CancelEventprovides necessary context for cancellation handling.Including the
Processreference allows callers flexibility in how they handle termination (e.g., graceful vs forceful).
175-184: LGTM - Proper lifecycle management for ProcessOutputCollector.Using
LaunchedEffectfor starting andDisposableEffectfor cleanup ensures the collector is properly managed across recompositions and disposal.
241-245: Emoji usage in UI Text is acceptable for IntelliJ plugin (JVM-only).While coding guidelines mention avoiding emoji for WASM, this file is in
mpp-ideawhich targets only JVM/IntelliJ, so the 💻 and 📁 emoji are acceptable.mpp-ui/src/jvmMain/kotlin/cc/unitmesh/server/cli/CodingCli.kt (3)
200-229: LGTM!The live terminal lifecycle methods properly register and unregister sessions, with clear status output formatting including exit code and execution time.
231-248: LGTM!Good fallback strategy: first checks local
activeSessions, then delegates toShellSessionManagerfor externally managed sessions. Clear error handling for missing sessions.
250-304: LGTM!The managed session awaiting logic correctly polls, handles timeouts with
Pendingresult, and properly marks sessions as completed with appropriateSuccess/Errorresults based on exit code.mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/impl/ShellTool.kt (6)
39-49: LGTM!Clear documentation for the new
waitparameter explaining both modes, and sensible default oftruefor backward compatibility with synchronous behavior.
80-91: LGTM!Schema properties are well-defined with appropriate bounds (
minimum: 1000,maximum: 600000for timeoutMs) preventing unreasonable values.
171-186: LGTM!Clean execution mode triage: background mode → wait-with-timeout → synchronous fallback. The smart cast to
LiveShellExecutorwith capability check ensures graceful degradation.
192-220: LGTM!Background execution correctly registers the session with
ShellSessionManagerand returns aPendingresult with clear instructions for follow-up interaction tools.
301-327: LGTM!Synchronous fallback preserves full metadata including stdout/stderr content, execution time, and shell info. Good backward compatibility for platforms without live execution support.
264-296: No action required: timeout contract is correctly implemented.The
LiveShellExecutor.waitForSession()implementations (bothPtyShellExecutorandDefaultShellExecutor.jvm) properly throwToolExceptionwitherrorType == ToolErrorType.TIMEOUTon timeout, confirming the assumed contract is followed. Both platforms usewithTimeoutOrNull()orprocess.waitFor()with explicit timeout checks, and correctly throw the expected exception when timeout occurs. The timeout handling in ShellTool.kt (lines 264-296) is therefore valid.mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/impl/ProcessManagementTools.kt (6)
1-12: LGTM!Clean imports following established patterns. Good use of
Platformfor multiplatform timestamp access.
25-49: LGTM!Schema is well-defined with appropriate descriptions and bounds for
maxWaitSeconds.
141-160: LGTM!Schema mirrors ShellTool's timeout bounds (1000-600000ms), maintaining consistency across the tooling surface.
162-218: LGTM!Wait logic is clean with proper polling, timeout handling returning
Pending, and session cleanup on completion. Good truncation of partial output to 1000 chars for timeout messages.
264-310: LGTM!Kill implementation handles both running and already-completed processes gracefully, with appropriate metadata and cleanup.
110-129: LGTM!All three tool classes follow consistent patterns with proper parameter validation ensuring
sessionIdis not blank before creating invocations.Also applies to: 220-239, 312-331
| val stillRunningMessage = buildString { | ||
| appendLine("⏳ Process is still running after ${elapsedSeconds}s") | ||
| appendLine("Command: $command") | ||
| appendLine("Session ID: $sessionId") | ||
| appendLine() | ||
| appendLine("The process is executing in the background. You can:") | ||
| appendLine("1. Continue with other tasks while waiting") | ||
| appendLine("2. Check the terminal output in the UI for real-time progress") | ||
| appendLine("3. The result will be available when the process completes") | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# Check for WASM platform configurations
find . -name "build.gradle.kts" -o -name "build.gradle" | head -5 | xargs grep -l "wasmJs\|wasmWasi" 2>/dev/null || echo "No WASM config found in gradle files"Repository: phodal/auto-dev-sketch
Length of output: 126
🏁 Script executed:
# Search for platform-specific shell implementations
rg "expect|actual" --type=kt -A 2 | grep -i "shell\|command\|exec" | head -20Repository: phodal/auto-dev-sketch
Length of output: 92
🏁 Script executed:
# Check if there are wasmMain/wasmJs source directories
fd -type d -name "wasmMain" -o -name "wasmJs" -o -name "wasmWasi"Repository: phodal/auto-dev-sketch
Length of output: 236
🏁 Script executed:
# Search for CodingAgentExecutor usage and platform markers
rg "CodingAgentExecutor" --type=kt -B 2 -A 2 | head -30Repository: phodal/auto-dev-sketch
Length of output: 92
🏁 Script executed:
# Check build.gradle.kts for WASM targets
cat ./mpp-core/build.gradle.kts | grep -i "wasm\|target" | head -20Repository: phodal/auto-dev-sketch
Length of output: 989
🏁 Script executed:
# Search for expect/actual declarations for shell
rg "expect|actual" --max-count=50 | grep -i "shell\|command"Repository: phodal/auto-dev-sketch
Length of output: 8729
🏁 Script executed:
# Find all Kotlin files related to shell execution
fd "Shell" -e ktRepository: phodal/auto-dev-sketch
Length of output: 2047
🏁 Script executed:
# Check the CodingAgentExecutor file structure and platform specificity
cat -n ./mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/executor/CodingAgentExecutor.kt | head -30Repository: phodal/auto-dev-sketch
Length of output: 1583
🏁 Script executed:
# Look for platform-specific directories
find ./mpp-core/src -type d | grep -E "(commonMain|commonTest|jvm|js|wasm)" | sortRepository: phodal/auto-dev-sketch
Length of output: 11573
🏁 Script executed:
# Check CodingAgentExecutor for platform guards around line 343-352
cat -n ./mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/executor/CodingAgentExecutor.kt | sed -n '330,365p'Repository: phodal/auto-dev-sketch
Length of output: 2298
🏁 Script executed:
# Search for @OptIn or expect/actual declarations related to CodingAgentExecutor
rg "CodingAgentExecutor" -A 3 -B 3 | head -50Repository: phodal/auto-dev-sketch
Length of output: 3163
🏁 Script executed:
# Check if this executor is used in wasmJsMain
find ./mpp-core/src/wasmJsMain -name "*.kt" -exec grep -l "CodingAgentExecutor" {} \;Repository: phodal/auto-dev-sketch
Length of output: 48
Remove emoji from WASM-compiled code.
Replace the ⏳ emoji with a text alternative (e.g., [hourglass] or ...) to comply with WASM platform requirements. This code is in commonMain and compiles to all platforms including wasmJs, so UTF-8/emoji should be avoided per coding guidelines.
Suggested change at line 344:
appendLine("[hourglass] Process is still running after ${elapsedSeconds}s")
🤖 Prompt for AI Agents
In
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/executor/CodingAgentExecutor.kt
around lines 343 to 352, remove the Unicode emoji in the status message and
replace it with a plain-text alternative (e.g., "[hourglass]" or "...") so the
commonMain code remains WASM-safe; update the appendLine call to use the text
alternative and ensure no other emoji remain in this build-path string.
| // ========== Live Terminal Support ========== | ||
|
|
||
| // Channel map for awaiting session results | ||
| private val sessionResultChannels = mutableMapOf<String, kotlinx.coroutines.channels.Channel<cc.unitmesh.agent.tool.ToolResult>>() |
There was a problem hiding this comment.
Replace with thread-safe map and add cleanup mechanism.
The mutableMapOf is accessed concurrently from multiple coroutines (lines 469, 489, 526, 533) without synchronization, causing race conditions. Additionally, channels for abandoned sessions are never cleaned up.
Apply this diff to use a concurrent map:
- private val sessionResultChannels = mutableMapOf<String, kotlinx.coroutines.channels.Channel<cc.unitmesh.agent.tool.ToolResult>>()
+ private val sessionResultChannels = java.util.concurrent.ConcurrentHashMap<String, kotlinx.coroutines.channels.Channel<cc.unitmesh.agent.tool.ToolResult>>()For cleanup, consider adding a timeout-based cleanup mechanism in addLiveTerminal() or implement a background job that removes channels for sessions older than a threshold.
📝 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 val sessionResultChannels = mutableMapOf<String, kotlinx.coroutines.channels.Channel<cc.unitmesh.agent.tool.ToolResult>>() | |
| private val sessionResultChannels = java.util.concurrent.ConcurrentHashMap<String, kotlinx.coroutines.channels.Channel<cc.unitmesh.agent.tool.ToolResult>>() |
| override fun updateLiveTerminalStatus( | ||
| sessionId: String, | ||
| exitCode: Int, | ||
| executionTimeMs: Long, | ||
| output: String? | ||
| ) { | ||
| // Find and update the LiveTerminalItem in the timeline | ||
| _timeline.update { currentTimeline -> | ||
| currentTimeline.map { item -> | ||
| if (item is TimelineItem.LiveTerminalItem && item.sessionId == sessionId) { | ||
| item.copy(exitCode = exitCode, executionTimeMs = executionTimeMs) | ||
| } else { | ||
| item | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Also notify any waiting coroutines via the session result channel | ||
| sessionResultChannels[sessionId]?.let { channel -> | ||
| val result = if (exitCode == 0) { | ||
| cc.unitmesh.agent.tool.ToolResult.Success( | ||
| content = output ?: "", | ||
| metadata = mapOf( | ||
| "exit_code" to exitCode.toString(), | ||
| "execution_time_ms" to executionTimeMs.toString() | ||
| ) | ||
| ) | ||
| } else { | ||
| cc.unitmesh.agent.tool.ToolResult.Error( | ||
| message = "Command failed with exit code: $exitCode", | ||
| metadata = mapOf( | ||
| "exit_code" to exitCode.toString(), | ||
| "execution_time_ms" to executionTimeMs.toString(), | ||
| "output" to (output ?: "") | ||
| ) | ||
| ) | ||
| } | ||
| channel.trySend(result) | ||
| sessionResultChannels.remove(sessionId) | ||
| } | ||
| } |
There was a problem hiding this comment.
Store output in LiveTerminalItem and handle channel send failures.
Two issues identified:
-
Data inconsistency: The
outputparameter is used inToolResult(lines 472, 484) but NOT stored in theLiveTerminalItem(line 461). This means the timeline UI and agent results will be inconsistent. -
Silent failure:
trySend(result)at line 488 can fail without notification, causing the waiting coroutine to timeout unnecessarily.
Apply this diff to fix both issues:
_timeline.update { currentTimeline ->
currentTimeline.map { item ->
if (item is TimelineItem.LiveTerminalItem && item.sessionId == sessionId) {
- item.copy(exitCode = exitCode, executionTimeMs = executionTimeMs)
+ item.copy(exitCode = exitCode, executionTimeMs = executionTimeMs, output = output)
} else {
item
}
}
}
// Also notify any waiting coroutines via the session result channel
sessionResultChannels[sessionId]?.let { channel ->
val result = if (exitCode == 0) {
cc.unitmesh.agent.tool.ToolResult.Success(
content = output ?: "",
metadata = mapOf(
"exit_code" to exitCode.toString(),
"execution_time_ms" to executionTimeMs.toString()
)
)
} else {
cc.unitmesh.agent.tool.ToolResult.Error(
message = "Command failed with exit code: $exitCode",
metadata = mapOf(
"exit_code" to exitCode.toString(),
"execution_time_ms" to executionTimeMs.toString(),
"output" to (output ?: "")
)
)
}
- channel.trySend(result)
+ val sendResult = channel.trySend(result)
+ if (!sendResult.isSuccess) {
+ // Log or handle channel send failure
+ println("Warning: Failed to send result for session $sessionId: ${sendResult.exceptionOrNull()}")
+ }
sessionResultChannels.remove(sessionId)
}| override suspend fun awaitSessionResult(sessionId: String, timeoutMs: Long): cc.unitmesh.agent.tool.ToolResult { | ||
| // Check if the session is already completed | ||
| val existingItem = _timeline.value.find { | ||
| it is TimelineItem.LiveTerminalItem && it.sessionId == sessionId | ||
| } as? TimelineItem.LiveTerminalItem | ||
|
|
||
| if (existingItem?.exitCode != null) { | ||
| // Session already completed | ||
| return if (existingItem.exitCode == 0) { | ||
| cc.unitmesh.agent.tool.ToolResult.Success( | ||
| content = "", | ||
| metadata = mapOf( | ||
| "exit_code" to existingItem.exitCode.toString(), | ||
| "execution_time_ms" to (existingItem.executionTimeMs ?: 0L).toString() | ||
| ) | ||
| ) | ||
| } else { | ||
| cc.unitmesh.agent.tool.ToolResult.Error( | ||
| message = "Command failed with exit code: ${existingItem.exitCode}", | ||
| metadata = mapOf( | ||
| "exit_code" to existingItem.exitCode.toString(), | ||
| "execution_time_ms" to (existingItem.executionTimeMs ?: 0L).toString() | ||
| ) | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| // Create a channel to wait for the result | ||
| val channel = kotlinx.coroutines.channels.Channel<cc.unitmesh.agent.tool.ToolResult>(1) | ||
| sessionResultChannels[sessionId] = channel | ||
|
|
||
| return try { | ||
| kotlinx.coroutines.withTimeout(timeoutMs) { | ||
| channel.receive() | ||
| } | ||
| } catch (e: kotlinx.coroutines.TimeoutCancellationException) { | ||
| sessionResultChannels.remove(sessionId) | ||
| cc.unitmesh.agent.tool.ToolResult.Error("Session timed out after ${timeoutMs}ms") | ||
| } | ||
| } |
There was a problem hiding this comment.
Fix race condition between completion check and channel creation.
There's a TOCTOU (time-of-check to time-of-use) race condition:
- Line 503 checks if
exitCode != null(not completed) updateLiveTerminalStatus()could run here and complete the session- Line 526 creates a channel that will never receive a result
This causes the coroutine to wait until timeout even when the session is already complete.
Apply this diff to fix the race condition:
override suspend fun awaitSessionResult(sessionId: String, timeoutMs: Long): cc.unitmesh.agent.tool.ToolResult {
+ // Create channel BEFORE checking completion to avoid race
+ val channel = kotlinx.coroutines.channels.Channel<cc.unitmesh.agent.tool.ToolResult>(1)
+ sessionResultChannels[sessionId] = channel
+
// Check if the session is already completed
val existingItem = _timeline.value.find {
it is TimelineItem.LiveTerminalItem && it.sessionId == sessionId
} as? TimelineItem.LiveTerminalItem
if (existingItem?.exitCode != null) {
+ // Clean up channel since we don't need it
+ sessionResultChannels.remove(sessionId)
+ channel.close()
+
// Session already completed
return if (existingItem.exitCode == 0) {
cc.unitmesh.agent.tool.ToolResult.Success(
content = "",
metadata = mapOf(
"exit_code" to existingItem.exitCode.toString(),
"execution_time_ms" to (existingItem.executionTimeMs ?: 0L).toString()
)
)
} else {
cc.unitmesh.agent.tool.ToolResult.Error(
message = "Command failed with exit code: ${existingItem.exitCode}",
metadata = mapOf(
"exit_code" to existingItem.exitCode.toString(),
"execution_time_ms" to (existingItem.executionTimeMs ?: 0L).toString()
)
)
}
}
- // Create a channel to wait for the result
- val channel = kotlinx.coroutines.channels.Channel<cc.unitmesh.agent.tool.ToolResult>(1)
- sessionResultChannels[sessionId] = channel
-
return try {
kotlinx.coroutines.withTimeout(timeoutMs) {
channel.receive()
}
} catch (e: kotlinx.coroutines.TimeoutCancellationException) {
sessionResultChannels.remove(sessionId)
+ channel.close()
cc.unitmesh.agent.tool.ToolResult.Error("Session timed out after ${timeoutMs}ms")
}
}| fun saveDiagramToPath(bytes: ByteArray, filePath: String): Boolean { | ||
| return try { | ||
| File(filePath).writeBytes(bytes) | ||
| true | ||
| } catch (e: Exception) { | ||
| false | ||
| } | ||
| } |
There was a problem hiding this comment.
saveDiagramToPath lacks path validation and parent directory creation.
If the parent directory doesn't exist, File(filePath).writeBytes(bytes) will fail. Consider creating parent directories or validating the path.
fun saveDiagramToPath(bytes: ByteArray, filePath: String): Boolean {
return try {
- File(filePath).writeBytes(bytes)
+ val file = File(filePath)
+ file.parentFile?.mkdirs()
+ file.writeBytes(bytes)
true
} catch (e: Exception) {
false
}
}🤖 Prompt for AI Agents
In
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaDiagramActions.kt
around lines 68 to 75, the saveDiagramToPath function doesn't validate the
provided path or ensure parent directories exist before writeBytes, causing
failures when parents are missing; update the function to validate the filePath,
create any missing parent directories (e.g., obtain File(filePath).parentFile
and call mkdirs() when non-null), then attempt to write the bytes and return
success/failure, and preserve or improve error handling (log or rethrow as
appropriate) for clear diagnostics.
| // Also notify any waiting coroutines via the session result channel | ||
| sessionResultChannels[sessionId]?.let { channel -> | ||
| val result = if (exitCode == 0) { | ||
| cc.unitmesh.agent.tool.ToolResult.Success( | ||
| content = output ?: "", | ||
| metadata = mapOf( | ||
| "exit_code" to exitCode.toString(), | ||
| "execution_time_ms" to executionTimeMs.toString() | ||
| ) | ||
| ) | ||
| } else { | ||
| cc.unitmesh.agent.tool.ToolResult.Error( | ||
| message = "Command failed with exit code: $exitCode", | ||
| metadata = mapOf( | ||
| "exit_code" to exitCode.toString(), | ||
| "execution_time_ms" to executionTimeMs.toString(), | ||
| "output" to (output ?: "") | ||
| ) | ||
| ) | ||
| } | ||
| channel.trySend(result) | ||
| sessionResultChannels.remove(sessionId) | ||
| } |
There was a problem hiding this comment.
Channel is not closed after use, potential resource leak.
When trySend completes and the channel is removed from the map (line 491), the channel should be closed to release resources.
sessionResultChannels[sessionId]?.let { channel ->
val result = if (exitCode == 0) {
// ... build Success
} else {
// ... build Error
}
channel.trySend(result)
+ channel.close()
sessionResultChannels.remove(sessionId)
}🤖 Prompt for AI Agents
In
mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/ComposeRenderer.kt
around lines 470 to 492, the session result channel is being trySend and then
removed from the sessionResultChannels map but never closed, causing a potential
resource leak; after invoking channel.trySend(result) close the channel (e.g.,
channel.close()) to release resources (optionally passing a cause or null)
before removing it from the map so the channel is properly terminated.
| private val sessionResultChannels = mutableMapOf<String, kotlinx.coroutines.channels.Channel<cc.unitmesh.agent.tool.ToolResult>>() | ||
|
|
||
| /** | ||
| * Await the result of an async shell session. | ||
| * Used when the Agent needs to wait for a shell command to complete before proceeding. | ||
| */ | ||
| override suspend fun awaitSessionResult(sessionId: String, timeoutMs: Long): cc.unitmesh.agent.tool.ToolResult { | ||
| // Check if the session is already completed | ||
| val existingItem = _timeline.find { | ||
| it is TimelineItem.LiveTerminalItem && it.sessionId == sessionId | ||
| } as? TimelineItem.LiveTerminalItem | ||
|
|
||
| if (existingItem?.exitCode != null) { | ||
| // Session already completed | ||
| return if (existingItem.exitCode == 0) { | ||
| cc.unitmesh.agent.tool.ToolResult.Success( | ||
| content = "", | ||
| metadata = mapOf( | ||
| "exit_code" to existingItem.exitCode.toString(), | ||
| "execution_time_ms" to (existingItem.executionTimeMs ?: 0L).toString() | ||
| ) | ||
| ) | ||
| } else { | ||
| cc.unitmesh.agent.tool.ToolResult.Error( | ||
| message = "Command failed with exit code: ${existingItem.exitCode}", | ||
| metadata = mapOf( | ||
| "exit_code" to existingItem.exitCode.toString(), | ||
| "execution_time_ms" to (existingItem.executionTimeMs ?: 0L).toString() | ||
| ) | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| // Create a channel to wait for the result | ||
| val channel = kotlinx.coroutines.channels.Channel<cc.unitmesh.agent.tool.ToolResult>(1) | ||
| sessionResultChannels[sessionId] = channel | ||
|
|
||
| return try { | ||
| kotlinx.coroutines.withTimeout(timeoutMs) { | ||
| channel.receive() | ||
| } | ||
| } catch (e: kotlinx.coroutines.TimeoutCancellationException) { | ||
| sessionResultChannels.remove(sessionId) | ||
| cc.unitmesh.agent.tool.ToolResult.Error("Session timed out after ${timeoutMs}ms") | ||
| } | ||
| } |
There was a problem hiding this comment.
Race condition between status check and channel registration can cause indefinite wait.
There's a TOCTOU race between checking existingItem?.exitCode != null (line 508) and registering the channel (line 531):
awaitSessionResultchecks exitCode → nullupdateLiveTerminalStatusruns, updates exitCode, doesn't find channelawaitSessionResultregisters channel, waits forever
Consider using atomic check-and-register with synchronization:
+ private val sessionResultLock = Any()
+
override suspend fun awaitSessionResult(sessionId: String, timeoutMs: Long): cc.unitmesh.agent.tool.ToolResult {
- // Check if the session is already completed
- val existingItem = _timeline.find {
- it is TimelineItem.LiveTerminalItem && it.sessionId == sessionId
- } as? TimelineItem.LiveTerminalItem
-
- if (existingItem?.exitCode != null) {
- // Session already completed
- return if (existingItem.exitCode == 0) {
- // ... existing code
- }
- }
-
- // Create a channel to wait for the result
- val channel = kotlinx.coroutines.channels.Channel<cc.unitmesh.agent.tool.ToolResult>(1)
- sessionResultChannels[sessionId] = channel
+ val channel = kotlinx.coroutines.channels.Channel<cc.unitmesh.agent.tool.ToolResult>(1)
+
+ synchronized(sessionResultLock) {
+ // Check if already completed while holding lock
+ val existingItem = _timeline.find {
+ it is TimelineItem.LiveTerminalItem && it.sessionId == sessionId
+ } as? TimelineItem.LiveTerminalItem
+
+ if (existingItem?.exitCode != null) {
+ channel.close()
+ return if (existingItem.exitCode == 0) {
+ cc.unitmesh.agent.tool.ToolResult.Success(/* ... */)
+ } else {
+ cc.unitmesh.agent.tool.ToolResult.Error(/* ... */)
+ }
+ }
+ sessionResultChannels[sessionId] = channel
+ }
return try {
kotlinx.coroutines.withTimeout(timeoutMs) {
channel.receive()
}
} catch (e: kotlinx.coroutines.TimeoutCancellationException) {
- sessionResultChannels.remove(sessionId)
+ synchronized(sessionResultLock) { sessionResultChannels.remove(sessionId) }
+ channel.close()
cc.unitmesh.agent.tool.ToolResult.Error("Session timed out after ${timeoutMs}ms")
+ } finally {
+ channel.close()
}
}Also update updateLiveTerminalStatus to use the same lock when accessing sessionResultChannels.
Committable suggestion skipped: line range outside the PR's diff.
Problem: - ShellSessionManager.kt in commonMain used JVM-specific Process class - This caused WASM build to fail with 'Unresolved reference: Process' Solution: 1. Changed LiveShellSession from data class to regular class 2. Added isAliveChecker and killHandler callback parameters to LiveShellSession 3. Updated ManagedSession to use callback-based process handlers 4. PtyShellExecutor now passes platform-specific handlers when creating session 5. ShellTool sets handlers on ManagedSession after registration This allows the shell session management to work across all platforms (JVM, JS, WASM) while still supporting platform-specific process operations.
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
mpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/PtyShellExecutor.kt (1)
253-283: Timeout inwaitForSessionleavesLiveShellSessionincompleteIn
waitForSession, whenexitCodeisnull(timeout), you destroy the process and throw aToolException, but you never update theLiveShellSessionstate. Any UI or client observingsession.isCompleted/session.exitCodewill continue to see a “running, no exit code” session even though the process has been killed.Given that you already pass a
killHandlerintoLiveShellSession, you can both reuse that and keep the lifecycle consistent by:
- delegating termination to
session.kill(), and- letting
kill()mark the session as completed with a sentinel exit code (e.g.-1, consistent withManagedSession.kill()), as suggested in theLiveShellSessionreview.Minimal change in the timeout branch:
- if (exitCode == null) { - ptyHandle.destroyForcibly() - ptyHandle.waitFor(3000, TimeUnit.MILLISECONDS) - throw ToolException("Command timed out after ${timeoutMs}ms", ToolErrorType.TIMEOUT) - } + if (exitCode == null) { + // Use the session's kill handler so lifecycle state stays in sync + session.kill() + ptyHandle.waitFor(3000, TimeUnit.MILLISECONDS) + throw ToolException("Command timed out after ${timeoutMs}ms", ToolErrorType.TIMEOUT) + }Combined with updating
LiveShellSession.kill()to callmarkCompleted(-1), this ensures timeouts and explicit cancels both leave the session in a completed state that clients can reliably observe.
🧹 Nitpick comments (7)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/impl/ShellTool.kt (3)
39-50: AligntimeoutMsruntime validation with schema bounds
ShellSchemaconstrainstimeoutMsto[1000, 600000], butvalidateParametersonly checksparams.timeoutMs <= 0. Calls with very small (<1000) or very large (>600000) timeouts will be accepted and only indirectly constrained bycontext.timeout. Consider enforcing the same min/max invalidateParametersso the behavior matches the declared schema and avoids unexpectedly tiny or excessively long waits.Also applies to: 80-91
171-225: Defensively clean up live sessions on non-timeout failuresIn
executeWithTimeout, the session is registered before thetry, and onlyToolExceptionwitherrorType == ToolErrorType.TIMEOUTis handled specially. IfwaitForSession(or later operations) can ever throw other exceptions, the session will stay registered and the process may continue running without any cleanup.It would be safer to add best-effort teardown for the non-timeout path (kill if still alive +
ShellSessionManager.removeSession(session.sessionId)), e.g. in anelsebranch of thecatchor viafinally, while preserving the current behavior for timeouts.- } catch (e: ToolException) { - if (e.errorType == ToolErrorType.TIMEOUT) { + } catch (e: ToolException) { + if (e.errorType == ToolErrorType.TIMEOUT) { // Timeout - process still running val output = managedSession.getOutput() val metadata = mapOf( "command" to params.command, "session_id" to session.sessionId, "working_directory" to (config.workingDirectory ?: ""), "mode" to "timeout", "partial_output" to output.take(1000) ) ToolResult.Pending( sessionId = session.sessionId, toolName = "shell", command = params.command, message = """Process still running after ${config.timeoutMs}ms timeout. ... metadata = metadata ) - } else { - throw e - } + } else { + // Best-effort cleanup on non-timeout failures + try { + if (session.isAlive()) { + session.kill() + } + } finally { + ShellSessionManager.removeSession(session.sessionId) + } + throw e + } }Same idea could be applied to
executeBackgroundif anything afterstartLiveExecutioncan fail.Also applies to: 230-306
311-327: Cap stdout/stderr stored in metadata to avoid oversized payloads
executeSynchronousnow includes fullstdoutandstderrstrings inmetadata. For long-running or very chatty commands, this can bloatToolResultsize and any downstream logging/serialization. Consider capping these fields (e.g., first N characters with a truncation marker) and leaving the full formatted output only in the primarymessageor in a separate retrieval path.Also applies to: 328-335
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/shell/LiveShellSession.kt (2)
70-83: Alignkill()with completion state to avoid inconsistent session lifecycleRight now
kill()invokes the handler but does not updateisCompleted/exitCode, so callers observingisCompletedorexitCodecan see “running + no exit code” even after the process has been killed (unless something else later callsmarkCompleted). That’s also inconsistent withManagedSession.kill()which marks exit code-1.Consider marking the session as completed inside
kill()when you terminate the process:/** * Kill the process */ fun kill() { - killHandler?.invoke() + killHandler?.invoke() + if (!_isCompleted.value) { + markCompleted(-1) + } }This keeps
isAlive(),isCompleted, andexitCodein sync after explicit kills and aligns semantics withManagedSession.kill().
85-91: Clarify or reworkwaitForCompletioncontract
waitForCompletionalways throwsUnsupportedOperationException, yet the KDoc says it’s “expected to be overridden or handled platform‑specifically”. SinceLiveShellSessionis notopenincommonMain, overriding on platforms is not possible.Either:
- drop this API and rely solely on
LiveShellExecutor.waitForSession, or- make this an
expect/actualor otherwise provide a real implementation on supported platforms, and adjust the KDoc accordingly.Right now it’s easy for callers to misuse this and hit an unexpected exception.
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/shell/ShellSessionManager.kt (2)
21-23: Avoid doing potentially heavy work while holding the manager mutexIn both
getActiveSessionsandclearAllyou run per‑session operations underShellSessionManager’s mutex:
getActiveSessions()callsit.isRunning()insidemutex.withLock { ... };isRunning()in turn hits the platform‑specificisAliveChecker.clearAll()callsit.kill()for every session while holding the same mutex.If the liveness/kill handlers are slow or blocking, this serializes all session operations behind a single lock and can hurt responsiveness.
Pattern that keeps the critical section small:
suspend fun getActiveSessions(): List<ManagedSession> { val snapshot: List<ManagedSession> = mutex.withLock { sessions.values.toList() } return snapshot.filter { it.isRunning() } } suspend fun clearAll() { val snapshot: List<ManagedSession> = mutex.withLock { val values = sessions.values.toList() sessions.clear() _activeSessions.value = emptyList() values } snapshot.forEach { it.kill() } }This preserves correctness but avoids doing IO / process ops while holding the global manager lock.
Also applies to: 60-63, 80-85
21-23: Clarify semantics ofactiveSessionsvsgetActiveSessions
activeSessions(StateFlow<List<String>>) is updated withsessions.keys.toList(), i.e., all registered sessions (including completed ones), whereasgetActiveSessions()filters byisRunning()and returns only running sessions.That split can be useful, but the naming is a bit confusing and easy to misinterpret as both meaning “running sessions”. Consider either:
- documenting explicitly that
activeSessionsis “registered session IDs (may include completed)”, or- renaming the flow (e.g.
registeredSessions) if you intend to expose both views.This will make downstream UI/state consumers less error‑prone.
Also applies to: 66-73, 92-128
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/impl/ShellTool.kt(6 hunks)mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/shell/LiveShellSession.kt(2 hunks)mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/shell/ShellSessionManager.kt(1 hunks)mpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/PtyShellExecutor.kt(2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.kt
📄 CodeRabbit inference engine (AGENTS.md)
**/*.kt: Useexpect/actualfor platform-specific code (e.g., file I/O on JVM/JS/Wasm) in Kotlin Multiplatform projects
Check export first if some functions are not working well with CLI (TypeScript)
In Kotlin/JS @JsExport: AvoidFlow, usePromiseinstead
In Kotlin/JS @JsExport: Use concrete classes as return types and parameter types; avoid interface types
For WASM platform, avoid using emoji and UTF-8 in code
Files:
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/shell/LiveShellSession.ktmpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/impl/ShellTool.ktmpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/shell/ShellSessionManager.ktmpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/PtyShellExecutor.kt
🧠 Learnings (1)
📚 Learning: 2025-12-02T00:20:34.480Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-02T00:20:34.480Z
Learning: Applies to **/*.kt : Use `expect`/`actual` for platform-specific code (e.g., file I/O on JVM/JS/Wasm) in Kotlin Multiplatform projects
Applied to files:
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/shell/ShellSessionManager.kt
🧬 Code graph analysis (2)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/impl/ShellTool.kt (1)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/schema/ToolSchema.kt (2)
boolean(172-181)integer(157-170)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/shell/ShellSessionManager.kt (1)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/shell/LiveShellSession.kt (1)
markCompleted(65-68)
⏰ 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: Build (241)
- GitHub Check: Build (223)
- GitHub Check: Test mpp-core (KMP)
🔇 Additional comments (2)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/shell/LiveShellSession.kt (1)
12-31: Constructor wiring for PTY handle and callbacks looks cleanThe refactor to carry a generic
ptyHandleplus platform-providedisAliveChecker/killHandlerkeepscommonMainplatform‑agnostic while still exposing enough hooks for JVM/Wasm/JS implementations. No issues here from a KMP perspective.mpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/PtyShellExecutor.kt (1)
208-251: Live session construction and callback wiring look good
startLiveExecutioncorrectly:
- validates the command with existing safety checks,
- sets up PTY env and login env,
- starts the
PtyProcess, and- wires
isAliveChecker/killHandleronLiveShellSessionback to the underlyingProcess.That keeps the common session API decoupled while still giving JVM full control over the lifecycle. No changes needed here.
…ring Problem: - When shell process completes, ToolOrchestrator.startSessionMonitoring was getting output from LiveShellSession.getStdout() which was empty - This is because PtyShellExecutor.waitForSession no longer reads output (to avoid conflict with UI's ProcessOutputCollector) Solution: - Get output from ShellSessionManager.getSession().getOutput() first - This output is synced by UI's ProcessOutputCollector in real-time - Fall back to LiveShellSession.getStdout() if not available Now when a shell command completes (or is cancelled), the output collected by the UI will be properly sent to the AI.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolOrchestrator.kt (1)
132-143: Redundant executor fetch; consider caching.
getShellExecutoris called again at line 133 despite already having fetched and validated it earlier (lines 87-91). This is redundant and the unchecked cast at line 143 assumes the executor type hasn't changed between calls.Consider caching the executor from the initial check:
liveSession = shellExecutor.startLiveExecution(command, shellConfig) logger.debug { "Live session started: ${liveSession.sessionId}" } + // Cache the executor for later use + cachedLiveExecutor = shellExecutorThen reuse it instead of re-fetching:
val result = if (liveSession != null) { - val shellExecutor = getShellExecutor(registry.getTool(toolName) as cc.unitmesh.agent.tool.impl.ShellTool) + val shellExecutor = cachedLiveExecutor!!
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolOrchestrator.kt(5 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.kt
📄 CodeRabbit inference engine (AGENTS.md)
**/*.kt: Useexpect/actualfor platform-specific code (e.g., file I/O on JVM/JS/Wasm) in Kotlin Multiplatform projects
Check export first if some functions are not working well with CLI (TypeScript)
In Kotlin/JS @JsExport: AvoidFlow, usePromiseinstead
In Kotlin/JS @JsExport: Use concrete classes as return types and parameter types; avoid interface types
For WASM platform, avoid using emoji and UTF-8 in code
Files:
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolOrchestrator.kt
⏰ 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 (223)
- GitHub Check: Build (241)
🔇 Additional comments (2)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolOrchestrator.kt (2)
202-213: LGTM!Proper early return for Pending results, correctly bypassing synchronous state calculation and preserving metadata.
668-683: LGTM!Proper handling of
ToolResult.Pendingstate in both helper functions. Pending correctly returnsfalsefor success check and empty string for error message.
| * | ||
| * @param asyncShellExecution If true, shell commands will execute asynchronously and return | ||
| * a Pending result immediately. The UI can display live terminal output | ||
| * and the result will be updated when the command completes. | ||
| * If false (default), shell commands will block until completion. | ||
| */ | ||
| class ToolOrchestrator( | ||
| private val registry: ToolRegistry, | ||
| private val policyEngine: PolicyEngine, | ||
| private val renderer: CodingAgentRenderer, | ||
| private val mcpConfigService: McpToolConfigService? = null | ||
| private val mcpConfigService: McpToolConfigService? = null, | ||
| private val asyncShellExecution: Boolean = true |
There was a problem hiding this comment.
Documentation contradicts default value.
The KDoc states "If false (default)" at line 31, but the actual default is asyncShellExecution: Boolean = true at line 38.
* @param asyncShellExecution If true, shell commands will execute asynchronously and return
* a Pending result immediately. The UI can display live terminal output
* and the result will be updated when the command completes.
- * If false (default), shell commands will block until completion.
+ * If false, shell commands will block until completion.
+ * Defaults to true for responsive UI.
*/📝 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.
| * | |
| * @param asyncShellExecution If true, shell commands will execute asynchronously and return | |
| * a Pending result immediately. The UI can display live terminal output | |
| * and the result will be updated when the command completes. | |
| * If false (default), shell commands will block until completion. | |
| */ | |
| class ToolOrchestrator( | |
| private val registry: ToolRegistry, | |
| private val policyEngine: PolicyEngine, | |
| private val renderer: CodingAgentRenderer, | |
| private val mcpConfigService: McpToolConfigService? = null | |
| private val mcpConfigService: McpToolConfigService? = null, | |
| private val asyncShellExecution: Boolean = true | |
| * | |
| * @param asyncShellExecution If true, shell commands will execute asynchronously and return | |
| * a Pending result immediately. The UI can display live terminal output | |
| * and the result will be updated when the command completes. | |
| * If false, shell commands will block until completion. | |
| * Defaults to true for responsive UI. | |
| */ | |
| class ToolOrchestrator( | |
| private val registry: ToolRegistry, | |
| private val policyEngine: PolicyEngine, | |
| private val renderer: CodingAgentRenderer, | |
| private val mcpConfigService: McpToolConfigService? = null, | |
| private val asyncShellExecution: Boolean = true |
🤖 Prompt for AI Agents
In
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolOrchestrator.kt
around lines 27 to 38, the KDoc states "If false (default)" but the constructor
sets asyncShellExecution: Boolean = true; update either the KDoc or the default
to make them consistent: change the KDoc to indicate "If true (default)" if
async behavior should be the default, or change the constructor default to =
false if synchronous behavior should be the documented default; ensure the
chosen behavior is consistent across docs and code and update any related tests
or usages if you flip the default.
| // Coroutine scope for background tasks (async shell monitoring) | ||
| private val backgroundScope = CoroutineScope(Dispatchers.Default) |
There was a problem hiding this comment.
Unmanaged CoroutineScope may leak resources.
backgroundScope is created but never cancelled. Background coroutines will continue running even after the orchestrator is no longer needed, potentially causing memory leaks and orphaned tasks.
Consider:
- Implementing
Closeable/AutoCloseablewith aclose()method that cancels the scope - Or accepting a
CoroutineScopefrom the caller for structured concurrency
- // Coroutine scope for background tasks (async shell monitoring)
- private val backgroundScope = CoroutineScope(Dispatchers.Default)
+ // Coroutine scope for background tasks (async shell monitoring)
+ private val backgroundScope = CoroutineScope(Dispatchers.Default + SupervisorJob())
+
+ /**
+ * Cancel all background tasks and release resources.
+ * Should be called when the orchestrator is no longer needed.
+ */
+ fun close() {
+ backgroundScope.coroutineContext.cancelChildren()
+ }You'll also need to add the import:
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelChildren🤖 Prompt for AI Agents
In
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolOrchestrator.kt
around lines 42-43, the created backgroundScope =
CoroutineScope(Dispatchers.Default) is never cancelled and can leak; change the
class to either accept a CoroutineScope from the caller or manage its own scope
with a SupervisorJob and cancellation: create the scope as
CoroutineScope(SupervisorJob() + Dispatchers.Default), implement
Closeable/AutoCloseable (or provide a close()/shutdown() method) that calls
backgroundScope.coroutineContext[Job]?.cancel() or
backgroundScope.cancelChildren()/backgroundScope.cancel(), and ensure callers
call close(); also add the recommended imports (kotlinx.coroutines.SupervisorJob
and kotlinx.coroutines.cancelChildren) where applicable.
| // Update renderer with final status | ||
| renderer.updateLiveTerminalStatus( | ||
| sessionId = session.sessionId, | ||
| exitCode = exitCode, | ||
| executionTimeMs = executionTimeMs, | ||
| output = output | ||
| ) | ||
|
|
||
| logger.debug { "Updated renderer with session completion: ${session.sessionId}" } | ||
| } catch (e: Exception) { | ||
| logger.error(e) { "Error monitoring session ${session.sessionId}: ${e.message}" } | ||
|
|
||
| // Update renderer with error status | ||
| renderer.updateLiveTerminalStatus( | ||
| sessionId = session.sessionId, | ||
| exitCode = -1, | ||
| executionTimeMs = Clock.System.now().toEpochMilliseconds() - startTime, | ||
| output = "Error: ${e.message}" | ||
| ) |
There was a problem hiding this comment.
Wrap renderer update in try-catch to prevent silent failures.
If renderer.updateLiveTerminalStatus throws an exception in the success path (lines 285-290), it will crash the coroutine without being caught by the outer try-catch, as the catch block only handles errors from waitForSession and output collection.
// Update renderer with final status
+ try {
renderer.updateLiveTerminalStatus(
sessionId = session.sessionId,
exitCode = exitCode,
executionTimeMs = executionTimeMs,
output = output
)
+ } catch (e: Exception) {
+ logger.error(e) { "Failed to update renderer for session ${session.sessionId}" }
+ }
logger.debug { "Updated renderer with session completion: ${session.sessionId}" }🤖 Prompt for AI Agents
In
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolOrchestrator.kt
around lines 284 to 302, the call to renderer.updateLiveTerminalStatus in the
success path can throw and is not covered by the surrounding catch; wrap the
success-path renderer.updateLiveTerminalStatus call in its own try-catch so any
exception from the renderer is logged and does not crash the coroutine, and in
the renderer catch log the error and attempt a safe fallback update (or skip)
with a guarded/output-safe message and ensure execution continues to the
existing logger.debug and overall flow.
Problem: - PTY process was not configured properly, causing output stream to close prematurely or not be readable by ProcessOutputCollector - Missing critical PTY configuration options Solution: - Add setInitialColumns(240) and setInitialRows(80) for proper terminal size - Add setUnixOpenTtyToPreserveOutputAfterTermination(true) to keep output stream open after process completes - This matches the configuration used in ProcessExecutor.createInteractiveProcess Now the ProcessOutputCollector should be able to read output from PTY process.
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
mpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/PtyShellExecutor.kt(2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.kt
📄 CodeRabbit inference engine (AGENTS.md)
**/*.kt: Useexpect/actualfor platform-specific code (e.g., file I/O on JVM/JS/Wasm) in Kotlin Multiplatform projects
Check export first if some functions are not working well with CLI (TypeScript)
In Kotlin/JS @JsExport: AvoidFlow, usePromiseinstead
In Kotlin/JS @JsExport: Use concrete classes as return types and parameter types; avoid interface types
For WASM platform, avoid using emoji and UTF-8 in code
Files:
mpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/PtyShellExecutor.kt
⏰ 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 (223)
- GitHub Check: Build (241)
🔇 Additional comments (2)
mpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/PtyShellExecutor.kt (2)
245-253: LGTM! Clean lifecycle hook design.The addition of
isAliveCheckerandkillHandlerlambdas to theLiveShellSessionconstructor provides good encapsulation for platform-specific process lifecycle management, enabling explicit liveness checks and forcible termination.
235-237: Consider making terminal dimensions configurable rather than hardcoded.The 240x80 dimensions at lines 235-236 are hardcoded. Consider passing these values from
ShellExecutionConfigto allow terminal size customization for different use cases.Note:
setUnixOpenTtyToPreserveOutputAfterTermination(true)is platform-appropriate—pty4j internally handles platform differences (Unix vs. Windows implementations) transparently, so no cross-platform concerns exist here.Likely an incorrect or invalid review comment.
| // Note: We do NOT read output here to avoid conflicts with UI-layer output collectors | ||
| // (e.g., ProcessOutputCollector in IdeaLiveTerminalBubble). | ||
| // The UI layer is responsible for reading and displaying output in real-time. | ||
| // For CLI usage, the renderer's awaitSessionResult should handle output reading. | ||
|
|
||
| val exitCode = withTimeoutOrNull(timeoutMs) { | ||
| while (ptyHandle.isAlive) { | ||
| yield() | ||
| delay(100) | ||
| } | ||
| ptyHandle.exitValue() | ||
| } | ||
|
|
||
| if (exitCode == null) { | ||
| outputJob.cancel() | ||
| ptyHandle.destroyForcibly() | ||
| ptyHandle.waitFor(3000, TimeUnit.MILLISECONDS) | ||
| throw ToolException("Command timed out after ${timeoutMs}ms", ToolErrorType.TIMEOUT) | ||
| } | ||
|
|
||
| // 等待输出读取完成 | ||
| outputJob.join() | ||
|
|
||
|
|
||
| session.markCompleted(exitCode) | ||
| exitCode |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check PtyShellExecutor implementation and output handling
# First, find the file and examine its complete structure
find . -name "PtyShellExecutor.kt" -type f
# Look for the waitForSession method implementation
rg -n -A20 'suspend fun waitForSession' --type kotlin | head -100
# Check if there's output reading in this method
rg -n -C10 'readOutput|collectOutput|drainOutput|ProcessOutputCollector' --type kotlin | head -150Repository: phodal/auto-dev-sketch
Length of output: 19881
🏁 Script executed:
#!/bin/bash
# Search for LiveShellExecutor and LiveShellSession definitions
rg -n 'interface LiveShellExecutor|class.*LiveShellExecutor' --type kotlin
rg -n 'interface LiveShellSession|class.*LiveShellSession' --type kotlin -A15
# Look for output consumption patterns
rg -n 'awaitSessionResult|collectOutput|onOutput' --type kotlin -B2 -A5Repository: phodal/auto-dev-sketch
Length of output: 9297
🏁 Script executed:
#!/bin/bash
# Check for ProcessOutputCollector and IdeaLiveTerminalBubble
rg -n 'ProcessOutputCollector|IdeaLiveTerminalBubble' --type kotlin -B3 -A8
# Look for any output buffer or process stream handling
rg -n 'ProcessBuilder|ProcessIO|inputStream|outputStream' --type kotlin -B2 -A4 | head -100Repository: phodal/auto-dev-sketch
Length of output: 21563
🏁 Script executed:
#!/bin/bash
# Search for timeout and process termination handling to see if output is consumed
rg -n 'destroyForcibly|waitFor|ptyHandle' --type kotlin -B3 -A5 | head -150
# Look for IdeaLiveTerminalBubble mentions in comments to understand the architecture
rg -n 'IdeaLiveTerminalBubble|UI.*layer|renderer' --type kotlin -B2 -A3Repository: phodal/auto-dev-sketch
Length of output: 50379
🏁 Script executed:
#!/bin/bash
# Check if ProcessOutputCollector is guaranteed to start and protected from races
# Find where ProcessOutputCollector is instantiated
rg -n 'ProcessOutputCollector\(' --type kotlin -B3 -A3
# Check if there's any synchronization or guarantees
rg -n 'start\(\)|launch|async' mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.kt -B2 -A5 | head -80
# Look for any output draining or fallback mechanisms
rg -n 'drainOutput|consumeOutput|fallback' --type kotlinRepository: phodal/auto-dev-sketch
Length of output: 25273
🏁 Script executed:
#!/bin/bash
# Check the complete ProcessOutputCollector.start() implementation
sed -n '44,120p' mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.kt
# Check CLI implementation to see if output reading is guaranteed
sed -n '305,330p' mpp-ui/src/jvmMain/kotlin/cc/unitmesh/server/cli/CodingCli.ktRepository: phodal/auto-dev-sketch
Length of output: 3766
Output handling delegation creates race condition risk but coverage exists.
The removal of output reading from waitForSession intentionally delegates responsibility to callers. Output IS consumed, but through asynchronous mechanisms that may not start before a process fills its output buffers:
- UI path:
ProcessOutputCollectorreads streams viaLaunchedEffect, creating a vulnerable window between process launch and collector startup - CLI path:
CodingCli.awaitSessionResultreads output in background, but only if explicitly called - Fallback:
ShellSessionManagerpersists output synced by the collector, but depends on the collector having started
Actual risks:
- Process output buffer overflow if
ProcessOutputCollector.start()hasn't launched before large output is produced - No runtime validation that output collection started successfully
- If collector startup fails or is delayed, output loss and process blocking are possible
Recommendations:
- Document the output consumption contract in
LiveShellSessionKDoc explicitly - Add safeguards in
PtyShellExecutor.waitForSessionto drain output if no external collector is active after a timeout - Consider adding debug logging to detect when output collection is not started within expected time
🤖 Prompt for AI Agents
mpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/PtyShellExecutor.kt
around lines 266-286: the current waitForSession removes inline output reading
and relies on external collectors, which can cause process-blocking if
collectors aren't started; update LiveShellSession KDoc to document the
responsibility and startup contract for output consumption, and modify
waitForSession to (1) detect whether an external output collector has started
within a short grace period after process launch (e.g., via a session flag or a
collector-registered callback), (2) if no collector registers in time, start a
local drain of stdout/stderr asynchronously to prevent buffer fill (and mark
this as a fallback), and (3) add debug logs when the collector is absent, when
fallback draining starts, and when collector registration occurs; ensure the
fallback drain is non-blocking, cancels if a collector later registers, and
preserve existing timeout/exit behavior.
Problem: - ProcessOutputCollector was trying to read both inputStream and errorStream - PTY processes combine stdout and stderr into a single stream (inputStream) - Reading both streams simultaneously caused race conditions and missing output - errorStream for PTY is empty/EOF, causing stderrJob to exit immediately Solution: - Remove separate stderr reader - only read from process.inputStream - PTY combines all output into inputStream, matching PtyShellExecutor behavior - Remove isError parameter from readStream() since PTY doesn't separate streams This matches the pattern used in PtyShellExecutor.executeWithPty() which only reads inputStream and sets stderr to empty string.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (3)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.kt (3)
93-126: Consider adding a buffer size limit for very long outputs.The
buffer(StringBuilder) grows unbounded as output accumulates. For long-running processes with verbose output, this could lead to memory issues.Consider implementing a maximum buffer size with truncation (e.g., keep last N characters or lines) or a circular buffer, especially if this will be used for background jobs that run for extended periods.
240-240: Note: emoji usage is acceptable here but may limit code reuse.The emojis (💻 and 📁) are fine for the
mpp-ideamodule (JVM/IntelliJ), but per coding guidelines, WASM platforms should avoid emojis and UTF-8. If this code is ever shared with or extracted to a WASM-compatible module, consider using text alternatives or icon components.Also applies to: 282-282
189-210: Consider attempting graceful shutdown before forceful termination.Line 206 uses
destroyForcibly()for the default cancel behavior. Consider tryingdestroy()first to allow the process a chance to clean up gracefully, then falling back todestroyForcibly()if needed:} else { // Default: just destroy the process - p.destroyForcibly() + p.destroy() + // Give it a moment to terminate gracefully + scope.launch { + delay(500) + if (p.isAlive) { + p.destroyForcibly() + } + } }That said, for typical shell commands, the forceful approach is simpler and acceptable.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.kt(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.kt
📄 CodeRabbit inference engine (AGENTS.md)
**/*.kt: Useexpect/actualfor platform-specific code (e.g., file I/O on JVM/JS/Wasm) in Kotlin Multiplatform projects
Check export first if some functions are not working well with CLI (TypeScript)
In Kotlin/JS @JsExport: AvoidFlow, usePromiseinstead
In Kotlin/JS @JsExport: Use concrete classes as return types and parameter types; avoid interface types
For WASM platform, avoid using emoji and UTF-8 in code
Files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.kt
**/idea/**/*.kt
📄 CodeRabbit inference engine (AGENTS.md)
**/idea/**/*.kt: For SwingPanel z-index issues with Compose popups, enable Jewel's custom popup renderer:JewelFlags.useCustomPopupRenderer = trueinIdeaAgentToolWindowFactory
For popup/dropdown menus in IntelliJ plugins, use Jewel'sPopupMenuinstead ofandroidx.compose.ui.window.Popup
For dialogs in IntelliJ plugins, use IntelliJ'sDialogWrapperwithorg.jetbrains.jewel.bridge.composeinstead ofandroidx.compose.ui.window.Dialog
Files:
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.kt
🧬 Code graph analysis (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.kt (2)
exts/devins-lang/src/main/kotlin/cc/unitmesh/devti/language/task/ChatCompletionTask.kt (1)
onCancel(106-110)mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/terminal/IdeaAnsiTerminalRenderer.kt (1)
IdeaAnsiTerminalRenderer(42-65)
⏰ 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 (223)
- GitHub Check: Build (241)
🔇 Additional comments (5)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.kt (5)
32-36: LGTM!Clean data class design for representing process output state.
44-53: LGTM!The StateFlow pattern is correctly applied for reactive state updates, and the architecture cleanly separates internal mutable state from the public API.
59-91: Note the timing heuristic and PTY-only design.The 50ms delay (line 72) to flush streams after process completion is pragmatic but may not capture all output in edge cases. This is likely acceptable for UI purposes but worth documenting.
Additionally, the PTY-only design (reading only
inputStream) is a deliberate constraint per the comment, but non-PTY processes would missstderr. Consider documenting this limitation in the class KDoc if this class might be used more broadly.
131-136: LGTM!Clean cancel event structure with all necessary context for handling cancellation and communicating with the AI.
157-186: LGTM!Compose lifecycle management is correctly implemented with proper
rememberkeys,LaunchedEffectfor initialization, andDisposableEffectfor cleanup. The fallback state handling is robust.
Summary
Add business logic actions for Diff/Patch, Code, Plan, Terminal, and Diagram operations in mpp-idea, reusing core module's functionality.
Changes
Phase 1: IdeaDiffActions
New Files:
IdeaDiffActions.kt- Methods:acceptPatch(),rejectPatch(),viewDiff(),repairPatch()Modified Files:
IdeaDiffRenderer.kt: Added toolbar with 4 action buttons (Accept/Reject/View Diff/Repair)Phase 2: IdeaCodeActions
New Files:
IdeaCodeActions.kt- Methods:copyToClipboard(),insertAtCursor(),saveToFile()Modified Files:
IdeaCodeBlockRenderer.kt: Added toolbar with 3 action buttons (Copy/Insert/Save)Phase 3: IdeaPlanActions
New Files:
IdeaPlanActions.kt- Methods:parsePlan(),copyToClipboard(),pinToToolWindow(),savePlanToService()IdeaPlanRenderer.kt- Plan sections with status indicators, expand/collapse, compress modeModified Files:
IdeaSketchRenderer.kt: Addedplanlanguage supportPhase 4: IdeaTerminalActions
New Files:
IdeaTerminalActions.kt- Methods:checkDangerousCommand(),executeCommand(),copyToClipboard()IdeaTerminalRenderer.kt- Command display, execute button, output panel, safety warningsModified Files:
IdeaSketchRenderer.kt: Addedbash/shell/sh/zshlanguage supportPhase 5: IdeaDiagramActions
New Files:
IdeaDiagramActions.kt- Methods:copySourceToClipboard(),saveDiagramToFile(),validateMermaidSyntax()IdeaMermaidRenderer.kt- Enhanced Mermaid with toolbar (copy/show code), validation warningsModified Files:
IdeaSketchRenderer.kt: Use enhancedIdeaMermaidRendererNote: PlantUML excluded from mpp-idea due to size (~20MB)
Phase 6: Shell Tool Improvements (Augment-style)
New Files:
ShellSessionManager.kt- Centralized session management with thread-safe operationsProcessManagementTools.kt-read-process,wait-process,kill-processtoolsModified Files:
ShellTool.kt: Addedwaitparameter for async/sync execution modesPtyShellExecutor.kt: Fixed output reading conflict with UI layerIdeaLiveTerminalBubble.kt: Added Cancel button with output captureCodingCli.kt: Implemented async shell execution supportKey Features:
wait=true(default): Wait for completion up to timeoutwait=false: Run in background, return sessionId immediatelyArchitecture
Related Issue
Closes #25
Files Created
Test Results
All shell execution scenarios tested successfully:
Summary by CodeRabbit
New Features
Chores
✏️ Tip: You can customize this high-level summary in your review settings.