Skip to content

feat(mpp-idea): add IdeaDiffActions, IdeaCodeActions, IdeaPlanActions, IdeaTerminalActions, IdeaDiagramActions - #26

Merged
phodal merged 16 commits into
masterfrom
feat/idea-diff-actions
Dec 2, 2025
Merged

phodal merged 16 commits into
masterfrom
feat/idea-diff-actions

Conversation

@phodal

@phodal phodal commented Dec 2, 2025 •

Copy link
Copy Markdown
Member

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 mode

Modified Files:

  • IdeaSketchRenderer.kt: Added plan language support

Phase 4: IdeaTerminalActions

New Files:

  • IdeaTerminalActions.kt - Methods: checkDangerousCommand(), executeCommand(), copyToClipboard()
  • IdeaTerminalRenderer.kt - Command display, execute button, output panel, safety warnings

Modified Files:

  • IdeaSketchRenderer.kt: Added bash/shell/sh/zsh language support

Phase 5: IdeaDiagramActions

New Files:

  • IdeaDiagramActions.kt - Methods: copySourceToClipboard(), saveDiagramToFile(), validateMermaidSyntax()
  • IdeaMermaidRenderer.kt - Enhanced Mermaid with toolbar (copy/show code), validation warnings

Modified Files:

  • IdeaSketchRenderer.kt: Use enhanced IdeaMermaidRenderer

Note: 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 operations
  • ProcessManagementTools.kt - read-process, wait-process, kill-process tools

Modified Files:

  • ShellTool.kt: Added wait parameter for async/sync execution modes
  • PtyShellExecutor.kt: Fixed output reading conflict with UI layer
  • IdeaLiveTerminalBubble.kt: Added Cancel button with output capture
  • CodingCli.kt: Implemented async shell execution support

Key Features:

  • wait=true (default): Wait for completion up to timeout
  • wait=false: Run in background, return sessionId immediately
  • Cancel button captures and sends current output to AI
  • Session management for background process interaction

Architecture

Compose UI Layer                          Business Logic Layer
────────────────────────────────────────────────────────────────────────────────
IdeaDiffRenderer         →  IdeaDiffActions       →  PatchProcessor, DiffRepair
IdeaCodeBlockRenderer    →  IdeaCodeActions       →  Clipboard, InsertUtil
IdeaPlanRenderer         →  IdeaPlanActions       →  MarkdownPlanParser, AgentStateService
IdeaTerminalRenderer     →  IdeaTerminalActions   →  ShellSafetyCheck, ProcessExecutor
IdeaMermaidRenderer      →  IdeaDiagramActions    →  Validation, Export
IdeaLiveTerminalBubble   →  ShellSessionManager   →  ProcessOutputCollector

Related Issue

Closes #25

Files Created

mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/
├── IdeaPlanRenderer.kt
├── IdeaTerminalRenderer.kt
├── IdeaMermaidRenderer.kt
└── actions/
    ├── IdeaDiffActions.kt
    ├── IdeaCodeActions.kt
    ├── IdeaPlanActions.kt
    ├── IdeaTerminalActions.kt
    └── IdeaDiagramActions.kt

mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/
├── shell/ShellSessionManager.kt
└── impl/ProcessManagementTools.kt

Test Results

All shell execution scenarios tested successfully:

  • ✅ Normal command execution (sleep 5): Success
  • ✅ Timeout handling (sleep 120 with timeout): Exit code 137 (SIGKILL)
  • ✅ Failed command (exit 1): Exit code 1
  • ✅ Command with output: Output captured correctly
  • ✅ Cancel button: Now captures and sends current output to AI

Summary by CodeRabbit

  • New Features

    • Rich diff UI with view/accept/reject and AI repair actions
    • Code block toolbar: copy/insert/save
    • Live terminal: streaming output, background sessions, await/cancel support
    • Terminal runner: safe async/background execution and result reporting
    • Plans: expandable/compressed view, copy/pin actions
    • Mermaid diagrams: preview, validation and export
    • Diagram & code utilities: copy, save and basic validation
    • UTF‑8 font fallbacks across platforms
  • Chores

    • Slimmed plugin distribution by excluding large deps/assets and fonts
    • Updated plugin name, vendor contact, and description

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

* 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
@coderabbitai

coderabbitai Bot commented Dec 2, 2025 •

Copy link
Copy Markdown

Note

Other AI code review bot(s) detected

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

Walkthrough

Makes 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

Cohort / File(s) Change Summary
Build config & sandbox
\mpp-idea/build.gradle.kts`, `mpp-ui/build.gradle.kts``
Global dependency exclusions for heavy transitive libs; PrepareSandboxTask excludes large font/asset files; WASM font download path adjusted.
Sketch renderer API & wiring
IdeaSketchRenderer
\mpp-idea/src/main/kotlin/.../IdeaSketchRenderer.kt``
RenderResponse gains project: Project? param and forwards it to diff/plan/terminal/mermaid renderers; markdown fallback adjusted.
Diff UI & actions
IdeaDiffRenderer, IdeaDiffActions
\mpp-idea/src/main/kotlin/.../IdeaDiffRenderer.kt`, `.../actions/IdeaDiffActions.kt``
Diff renderer becomes project-aware, adds toolbar (accept/reject/view/repair); IdeaDiffActions implements parsing, accept/reject/apply, preview and AI repair integration.
Code block toolbar & actions
IdeaCodeBlockRenderer, IdeaCodeActions
\mpp-idea/src/main/kotlin/.../IdeaCodeBlockRenderer.kt`, `.../actions/IdeaCodeActions.kt``
Code block renderer adds header toolbar and project-aware actions; IdeaCodeActions adds copy/insert/save utilities tied to editor/clipboard/file dialog.
Plan UI & actions
IdeaPlanRenderer, IdeaPlanActions
\mpp-idea/src/main/kotlin/.../IdeaPlanRenderer.kt`, `.../actions/IdeaPlanActions.kt``
New plan renderer composable (toolbar, compress/expand, sections); IdeaPlanActions centralizes parse/format/copy/pin/save/get-current-plan.
Terminal UI & actions
IdeaTerminalRenderer, IdeaTerminalActions
\mpp-idea/src/main/kotlin/.../IdeaTerminalRenderer.kt`, `.../actions/IdeaTerminalActions.kt``
New terminal renderer with execution UI and danger checks; IdeaTerminalActions adds sync/async execution, safety checks, clipboard and notification helpers plus ExecutionResult model.
Mermaid & diagram actions
IdeaMermaidRenderer, IdeaDiagramActions
\mpp-idea/src/main/kotlin/.../IdeaMermaidRenderer.kt`, `.../actions/IdeaDiagramActions.kt``
Mermaid renderer with toolbar, validation and JCEF rendering; IdeaDiagramActions adds copy/save/validate and diagram type detection.
Live terminal UI & timeline
LiveTerminalBubble, Timeline wiring
\mpp-idea/src/main/kotlin/.../IdeaLiveTerminalBubble.kt`, `.../IdeaTimelineContent.kt`, `.../IdeaTimelineItemView.kt``
New live-terminal bubble, ProcessOutputCollector, CancelEvent; timeline components accept onProcessCancel and render live terminal with cancel handling.
ViewModel & toolwindow wiring
IdeaAgentApp, IdeaAgentViewModel, Analysis components
\mpp-idea/src/main/kotlin/.../IdeaAgentApp.kt`, `.../IdeaAgentViewModel.kt`, `.../codereview/IdeaAnalysisComponents.kt``
Timeline wired to ViewModel.handleProcessCancel; RenderResponse call sites use named params; new handler terminates processes and posts cancellation result.
Renderer/CLI session coordination
JewelRenderer / ComposeRenderer / CodingCli
\mpp-idea/src/main/kotlin/.../JewelRenderer.kt`, `mpp-ui/src/commonMain/.../ComposeRenderer.kt`, `mpp-ui/src/jvmMain/.../CodingCli.kt``
Added per-session channels and overrides: addLiveTerminal, updateLiveTerminalStatus, awaitSessionResult; renderers/CLI register live sessions, update timeline, and coordinate awaiting results.
Core: ToolResult & orchestration (async shell)
ToolResult, ToolExecutionResult, ToolOrchestrator, CodingAgentExecutor
\mpp-core/src/commonMain/kotlin/.../Tool.kt`, `.../ToolExecutionResult.kt`, `.../ToolOrchestrator.kt`, `.../CodingAgentExecutor.kt``
Added ToolResult.Pending with metadata and helpers; ToolExecutionResult.pending factory; orchestrator/executor support async shell execution with background monitoring and configurable async timeouts.
Core: shell tools & process tools
ShellTool, ProcessManagementTools, ShellSessionManager
\mpp-core/src/commonMain/kotlin/.../ShellTool.kt`, `.../ProcessManagementTools.kt`, `.../ShellSessionManager.kt``
Shell tool supports live/background mode (wait flag, timeoutMs); added Read/Wait/Kill process tools; new ShellSessionManager and ManagedSession for session lifecycle and buffered output.
Core: executors & PTY handling
DefaultShellExecutor, PtyShellExecutor
\mpp-core/src/jvmMain/kotlin/.../DefaultShellExecutor.jvm.kt`, `.../PtyShellExecutor.kt``
DefaultShellExecutor now implements LiveShellExecutor (startLiveExecution, waitForSession, supportsLiveExecution); PTY executor updated to provide liveness and kill hooks.
JS/jvm exports & formatting
JsExports, ToolResultFormatter
\mpp-core/src/jsMain/.../JsExports.kt`, `.../ToolResultFormatter.kt``
JS bridge exports ToolResult.Pending as pending; formatter distinguishes PENDING status and emits session metadata.
UTF‑8 font API & platform impls
CodeFont (expect/actual)
\mpp-ui/src/commonMain/.../CodeFont.kt`, `mpp-ui/src/{androidMain,iosMain,jvmMain,jsMain,wasmJsMain}/.../CodeFont.*.kt``
Added @Composable expect fun getUtf8FontFamily() and platform actual implementations (WASM uses NotoSansSC resource; others return default).
Font usage consolidation
AgentMessageList, DevInEditorInput
\mpp-ui/src/commonMain/.../AgentMessageList.kt`, `.../DevInEditorInput.kt``
Replaced platform branch font logic with getUtf8FontFamily() and removed resource-specific imports.
Plugin metadata
\mpp-idea/src/main/resources/META-INF/plugin.xml``
Plugin <name> changed to "AutoDev Next"; vendor email and description updated.

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)
Loading
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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Files needing extra attention:
    • mpp-idea/.../actions/IdeaDiffActions.kt — patch parsing, path matching, ApplyPatchDefaultExecutor, Undo handling.
    • Core shell/live execution stack: ShellTool.kt, ShellSessionManager.kt, DefaultShellExecutor.jvm.kt, ProcessManagementTools.kt — concurrency, liveness, timeouts, cleanup.
    • Renderer/session coordination: JewelRenderer.kt, ComposeRenderer.kt, CodingCli.kt — channel lifecycle and await semantics.
    • UI components integrating project APIs: IdeaDiffRenderer.kt, IdeaCodeBlockRenderer.kt, IdeaTerminalRenderer.kt, IdeaPlanRenderer.kt — Compose + IntelliJ API interactions.

Possibly related PRs

Poem

🐇 I hopped where terminals hum and glow,

Toolbars clicked and patches flow,
Fonts align in every land,
Sessions sprint and yield their hand,
A tiny rabbit cheers — code grows so.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 47.65% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title directly matches the primary changes: adding five new action classes (IdeaDiffActions, IdeaCodeActions, IdeaPlanActions, IdeaTerminalActions, IdeaDiagramActions) and related UI enhancements.
Linked Issues check ✅ Passed All coding requirements from issue #25 are met: Phase 1-5 completed with action classes, renderer implementations, core logic reuse (DiffRepair, MarkdownPlanParser, ShellSafetyCheck), and shell execution improvements.
Out of Scope Changes check ✅ Passed All changes are scoped to the stated objectives: action classes, renderer updates, shell session management, process management tools, and plugin metadata updates align with PR objectives and issue #25 phases.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/idea-diff-actions

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

@augmentcode augmentcode Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review completed. 3 suggestions posted.

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

val additionalInfo = reader.getAdditionalInfo(pathsFromGroups)

shelfExecutor.apply(filePatches, patchGroups, null, "AutoDev.diff", additionalInfo)
success = true

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 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 unused diffContent parameter.

The diffContent parameter is passed to DiffToolbar but 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9f9b009 and a603073.

📒 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: Use expect/actual for 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: Avoid Flow, use Promise instead
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.kt
  • mpp-ui/src/androidMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.android.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.kt
  • mpp-ui/src/wasmJsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.wasmJs.kt
  • mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.jvm.kt
  • mpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaDiffRenderer.kt
  • mpp-ui/src/iosMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ios.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/AgentMessageList.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/codereview/IdeaAnalysisComponents.kt
  • mpp-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 AutoDevColors from cc.unitmesh.devins.ui.compose.theme or MaterialTheme.colorScheme

Files:

  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/editor/DevInEditorInput.kt
  • mpp-ui/src/androidMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.android.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.kt
  • mpp-ui/src/wasmJsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.wasmJs.kt
  • mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.jvm.kt
  • mpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.kt
  • mpp-ui/src/iosMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ios.kt
  • mpp-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.kt
  • mpp-ui/src/androidMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.android.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.kt
  • mpp-ui/src/wasmJsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.wasmJs.kt
  • mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.jvm.kt
  • mpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.kt
  • mpp-ui/src/iosMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ios.kt
  • mpp-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 = true in IdeaAgentToolWindowFactory
For popup/dropdown menus in IntelliJ plugins, use Jewel's PopupMenu instead of androidx.compose.ui.window.Popup
For dialogs in IntelliJ plugins, use IntelliJ's DialogWrapper with org.jetbrains.jewel.bridge.compose instead of androidx.compose.ui.window.Dialog

Files:

  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaDiffRenderer.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/codereview/IdeaAnalysisComponents.kt
  • mpp-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.kt
  • mpp-ui/src/androidMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.android.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.kt
  • mpp-ui/src/wasmJsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.wasmJs.kt
  • mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.jvm.kt
  • mpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.kt
  • mpp-idea/src/main/resources/META-INF/plugin.xml
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaDiffRenderer.kt
  • mpp-ui/src/iosMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ios.kt
  • mpp-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.kt
  • mpp-ui/src/androidMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.android.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.kt
  • mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.jvm.kt
  • mpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.kt
  • mpp-ui/src/iosMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.ios.kt
  • mpp-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.kt
  • mpp-idea/src/main/resources/META-INF/plugin.xml
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaDiffRenderer.kt
  • mpp-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.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.kt
  • mpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaDiffRenderer.kt
  • mpp-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.kt
  • mpp-ui/src/jsMain/kotlin/cc/unitmesh/devins/ui/compose/sketch/CodeFont.js.kt
  • mpp-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.kt
  • mpp-idea/src/main/resources/META-INF/plugin.xml
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaDiffRenderer.kt
  • mpp-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.kt
  • mpp-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.xml
  • mpp-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.kt
  • mpp-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/font is 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 DownloadWasmFontsTask class (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 these println() 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.Default for the JS platform, relying on the browser's native UTF-8 font support. The @Composable annotation 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.Default is 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 @Composable annotation is necessary here for resource access via Res.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.isWasm check with the unified getUtf8FontFamily() 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 expect declaration correctly establishes the multiplatform contract. The @Composable annotation 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.Default is 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.Default is 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 showSingleDiff which internally uses DialogWrapper for 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 uses selectedTextEditor which 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 originalCode as 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 project is 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 project parameter 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 project only to IdeaDiffRenderer is 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 Tooltip component 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 on acceptPatch success flag reliability.

The patchApplied state is set based on IdeaDiffActions.acceptPatch return value. As noted in the IdeaDiffActions review, 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 **/*.ttf and **/*.otf patterns in prepareSandbox are 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 uses JewelTheme.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-core for document parsing, not for patch processing. DiffRepair.kt and PatchProcessor.kt use 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.

Comment on lines +56 to +77

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
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

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.

Comment on lines +83 to +92
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
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

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.

Comment on lines 43 to 46
val fileDiffs = remember(diffContent) { DiffParser.parse(diffContent) }
var isRepairing by remember { mutableStateOf(false) }
var patchApplied by remember { mutableStateOf(false) }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

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.

Suggested change
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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 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 canInsertAtCursor based 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

📥 Commits

Reviewing files that changed from the base of the PR and between a603073 and a47d39b.

📒 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: Use expect/actual for 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: Avoid Flow, use Promise instead
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.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaCodeActions.kt
  • mpp-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 = true in IdeaAgentToolWindowFactory
For popup/dropdown menus in IntelliJ plugins, use Jewel's PopupMenu instead of androidx.compose.ui.window.Popup
For dialogs in IntelliJ plugins, use IntelliJ's DialogWrapper with org.jetbrains.jewel.bridge.compose instead of androidx.compose.ui.window.Dialog

Files:

  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaCodeActions.kt
  • mpp-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.kt
  • 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 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 project parameter 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.File and 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 AutoDevColors for theming and Jewel's Tooltip component, aligning with the coding guidelines for IntelliJ plugins.

Comment on lines +28 to +37
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
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

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.

Suggested change
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
@phodal phodal changed the title feat(mpp-idea): add IdeaDiffActions for diff/patch operations feat(mpp-idea): add IdeaDiffActions, IdeaCodeActions, IdeaPlanActions for sketch operations Dec 2, 2025
- 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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 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 the copied state for better UX.

The copied flag is set to true when the user clicks "Copy Plan" but never resets back to false, 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

📥 Commits

Reviewing files that changed from the base of the PR and between a47d39b and 56dabc6.

📒 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: Use expect/actual for 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: Avoid Flow, use Promise instead
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.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaPlanRenderer.kt
  • mpp-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 = true in IdeaAgentToolWindowFactory
For popup/dropdown menus in IntelliJ plugins, use Jewel's PopupMenu instead of androidx.compose.ui.window.Popup
For dialogs in IntelliJ plugins, use IntelliJ's DialogWrapper with org.jetbrains.jewel.bridge.compose instead of androidx.compose.ui.window.Dialog

Files:

  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaPlanActions.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaPlanRenderer.kt
  • mpp-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 project parameter 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 project and isComplete flags.

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 to interpretPlan(), 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 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 executeCommand and executeCommandSync duplicate the safety check and the ExecutionResult construction 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: Use result.isSuccess for consistency with the data class definition.

The notification logic uses exitCode == 0 directly, but ExecutionResult.isSuccess is defined as exitCode == 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's CopyPasteManager for clipboard operations.

Using java.awt.Toolkit directly may fail in headless environments and bypasses IntelliJ's clipboard management. The platform provides CopyPasteManager for 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.Toolkit import on line 10.

mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaTerminalRenderer.kt (1)

157-169: Minor: Row with single child and SpaceBetween has no effect.

The Row on lines 160-163 uses Arrangement.SpaceBetween but contains only a single Text child, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 56dabc6 and 2850cd2.

📒 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: Use expect/actual for 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: Avoid Flow, use Promise instead
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.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaTerminalRenderer.kt
  • mpp-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 = true in IdeaAgentToolWindowFactory
For popup/dropdown menus in IntelliJ plugins, use Jewel's PopupMenu instead of androidx.compose.ui.window.Popup
For dialogs in IntelliJ plugins, use IntelliJ's DialogWrapper with org.jetbrains.jewel.bridge.compose instead of androidx.compose.ui.window.Dialog

Files:

  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaSketchRenderer.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaTerminalRenderer.kt
  • mpp-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 ExecutionResult data class is well-structured with appropriate computed properties for isSuccess and displayOutput. 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 via AutoDevCoroutineScope.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 Tooltip component 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 project parameter is added with a null default, ensuring backward compatibility. The KDoc clearly documents its purpose for enabling action buttons.


67-76: LGTM!

Project parameter correctly forwarded to IdeaDiffRenderer for enabling diff action buttons.


78-88: LGTM!

Plan rendering integration follows the established pattern, correctly propagating project and isComplete state.


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 project parameter, 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
@phodal phodal changed the title feat(mpp-idea): add IdeaDiffActions, IdeaCodeActions, IdeaPlanActions for sketch operations feat(mpp-idea): add IdeaDiffActions, IdeaCodeActions, IdeaPlanActions, IdeaTerminalActions, IdeaDiagramActions Dec 2, 2025
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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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)

Copilot AI Dec 2, 2025

Copy link

Choose a reason for hiding this comment

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

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.

Suggested change
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 = ""
)
}

Copilot uses AI. Check for mistakes.
Comment on lines +75 to +78
val codingPanel = toolWindow.contentManager.component.components
?.filterIsInstance<AutoDevPlannerToolWindow>()
?.firstOrNull()

Copilot AI Dec 2, 2025

Copy link

Choose a reason for hiding this comment

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

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.

Copilot uses AI. Check for mistakes.
Comment on lines +78 to +145
* 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")
}
}

Copilot AI Dec 2, 2025

Copy link

Choose a reason for hiding this comment

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

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.

Copilot uses AI. Check for mistakes.
Comment on lines +22 to +23
* Check if a command is dangerous
* @return Pair of (isDangerous, reason)

Copilot AI Dec 2, 2025

Copy link

Choose a reason for hiding this comment

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

[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).

Suggested change
* 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].

Copilot uses AI. Check for mistakes.
*/
fun getCurrentPlan(project: Project): List<AgentTaskEntry> {
val agentStateService = project.getService(AgentStateService::class.java)
return agentStateService.getPlan()

Copilot AI Dec 2, 2025

Copy link

Choose a reason for hiding this comment

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

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.

Suggested change
return agentStateService.getPlan()
return agentStateService?.getPlan() ?: emptyList()

Copilot uses AI. Check for mistakes.
) {
val fileDiffs = remember(diffContent) { DiffParser.parse(diffContent) }
var isRepairing by remember { mutableStateOf(false) }
var patchApplied by remember { mutableStateOf(false) }

Copilot AI Dec 2, 2025

Copy link

Choose a reason for hiding this comment

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

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.

Suggested change
var patchApplied by remember { mutableStateOf(false) }
var patchApplied by remember(diffContent) { mutableStateOf(false) }

Copilot uses AI. Check for mistakes.
Comment thread mpp-idea/build.gradle.kts
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

Copilot AI Dec 2, 2025

Copy link

Choose a reason for hiding this comment

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

[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.

Suggested change
// 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

Copilot uses AI. Check for mistakes.
Comment on lines +112 to +116
fun copyToClipboard(text: String): Boolean {
return try {
val selection = StringSelection(text)
val clipboard = Toolkit.getDefaultToolkit().systemClipboard
clipboard.setContents(selection, null)

Copilot AI Dec 2, 2025

Copy link

Choose a reason for hiding this comment

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

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.

Copilot uses AI. Check for mistakes.
enabled = executionState != TerminalState.RUNNING, onClick = onExecute
)
}
TerminalActionButton(if (copied) "Copied!" else "Copy",

Copilot AI Dec 2, 2025

Copy link

Choose a reason for hiding this comment

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

[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).

Copilot uses AI. Check for mistakes.
Comment on lines +56 to +60
fun copyToClipboard(content: String): Boolean {
return try {
val clipboard = Toolkit.getDefaultToolkit().systemClipboard
val selection = StringSelection(content)
clipboard.setContents(selection, null)

Copilot AI Dec 2, 2025

Copy link

Choose a reason for hiding this comment

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

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.

Copilot uses AI. Check for mistakes.
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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 8

♻️ Duplicate comments (2)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.kt (1)

44-47: Reset copied state after a delay for better UX.

The copied state is set to true but never reset, so the button will permanently show "Copied!" after the first click. Add a LaunchedEffect to 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's CopyPasteManager for clipboard operations.

Toolkit.getDefaultToolkit().systemClipboard may not work in headless environments or during testing. IntelliJ's CopyPasteManager.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: Unused project parameter in MermaidToolbar.

The project parameter is passed to MermaidToolbar but 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 saveDiagramToFile fails, the exception is caught and false is 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: backgroundScope lacks lifecycle management and failure isolation.

The CoroutineScope(Dispatchers.Default) creates an unmanaged scope that is never cancelled. If the ToolOrchestrator is discarded, monitoring coroutines may leak. Additionally, without SupervisorJob, an exception in one monitoring coroutine could cancel others.

Consider using SupervisorJob() for failure isolation and exposing a close() 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 liveSession was 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: maxWaitTimeoutMs and checkIntervalMs.

Only initialWaitTimeoutMs is used in handlePendingResult. 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 in clearAll() - 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.

_exitCode and _endTime are 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 false but 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 readStream function 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, mixing synchronized with 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 clickable without indication or 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.

activeSessions is a plain mutableMapOf, but it may be accessed concurrently from coroutines running on different threads (e.g., addLiveTerminal, updateLiveTerminalStatus, and awaitSessionResult). 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 BufferedReader instances 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.

ReadProcessInvocation does not remove completed sessions, while WaitProcessInvocation (line 204) does. This inconsistency could cause session accumulation if users only use read-process to check completed processes. Consider adding cleanup for completed sessions here as well, or document that read-process is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2850cd2 and 0263ba0.

📒 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: Use expect/actual for 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: Avoid Flow, use Promise instead
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.kt
  • mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/shell/ShellSessionManager.kt
  • mpp-core/src/jsMain/kotlin/cc/unitmesh/llm/JsExports.kt
  • mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolExecutionResult.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.kt
  • mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/executor/CodingAgentExecutor.kt
  • mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolOrchestrator.kt
  • mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/render/CodingAgentRenderer.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.kt
  • mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/Tool.kt
  • mpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/DefaultShellExecutor.jvm.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaDiagramActions.kt
  • mpp-ui/src/commonMain/kotlin/cc/unitmesh/devins/ui/compose/agent/ComposeRenderer.kt
  • mpp-core/src/jvmMain/kotlin/cc/unitmesh/agent/tool/shell/PtyShellExecutor.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/JewelRenderer.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.kt
  • mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/impl/ProcessManagementTools.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaTimelineContent.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt
  • mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/impl/ShellTool.kt
  • mpp-ui/src/jvmMain/kotlin/cc/unitmesh/server/cli/CodingCli.kt
  • mpp-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 = true in IdeaAgentToolWindowFactory
For popup/dropdown menus in IntelliJ plugins, use Jewel's PopupMenu instead of androidx.compose.ui.window.Popup
For dialogs in IntelliJ plugins, use IntelliJ's DialogWrapper with org.jetbrains.jewel.bridge.compose instead of androidx.compose.ui.window.Dialog

Files:

  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/actions/IdeaDiagramActions.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/JewelRenderer.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaTimelineContent.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt
  • mpp-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 AutoDevColors from cc.unitmesh.devins.ui.compose.theme or MaterialTheme.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.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt
  • 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/JewelRenderer.kt
  • 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: 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.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/sketch/IdeaMermaidRenderer.kt
  • 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 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.kt
  • 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 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.kt
  • 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 **/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.kt and the MermaidRenderer class 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 validStarts list contains mixed case (e.g., sequenceDiagram, C4Context), and startsWith with ignoreCase = true handles this correctly. However, for consistency and clarity, consider documenting this behavior or normalizing the list.


150-157: LGTM on getDiagramType implementation.

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 adding project parameter to RenderResponse.

The optional Project parameter enables action buttons across renderers while maintaining backward compatibility with a default of null.


149-155: Fallback to JewelMarkdownRenderer for unknown code blocks.

The fallback now uses JewelMarkdownRenderer instead 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 IdeaDiffRenderer now 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.

IdeaPlanRenderer receives project, 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 calling IdeaTerminalActions.executeCommand().

Minor note: The isComplete parameter is accepted but unused in IdeaTerminalRenderer. Consider either using it to disable the execute button during streaming (consistent with other renderers like IdeaDevInBlockRenderer), 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 LiveTerminalItem will be added via addLiveTerminal().


431-445: LGTM!

The implementation correctly adds a LiveTerminalItem to 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 true unconditionally 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 ToolException provides 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., ProcessOutputCollector in IdeaLiveTerminalBubble).

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 metadata with sessionId and isPending flag. Using success = false is appropriate since the operation hasn't completed yet. Based on learnings, the use of concrete JsToolResult class (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 onProcessCancel callback is cleanly integrated, following the existing pattern of delegating events to the viewModel for 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, and content properties correctly handle the new ToolResult.Pending variant. 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. Setting endTime = startTime (resulting in duration = 0) is appropriate for in-progress executions, and the automatic metadata enrichment with sessionId and isAsync provides 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 addLiveTerminal and updateLiveTerminalStatus maintain backward compatibility, while awaitSessionResult returning 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. The LiveTerminalItem case correctly wires the onProcessCancel callback 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.pending with all necessary metadata preserved.


666-681: LGTM - Pending handling in helper functions is semantically correct.

Treating Pending as 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 Pending results and delegating to handlePendingResult is clean. The var usage 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 returns ToolResult.Success with ToolExecutionState.Executing to 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 the result type, 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 - Pending result type is well-designed.

The new Pending subclass properly extends ToolResult, includes appropriate fields for async tracking, and is correctly marked @Serializable. Documentation is clear.


99-122: LGTM - Helper methods consistently handle Pending.

The isPending() method and updates to getOutput(), getError(), and extractMetadata() follow established patterns and maintain exhaustive when expressions.

mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/components/timeline/IdeaLiveTerminalBubble.kt (3)

134-139: LGTM - CancelEvent provides necessary context for cancellation handling.

Including the Process reference allows callers flexibility in how they handle termination (e.g., graceful vs forceful).


175-184: LGTM - Proper lifecycle management for ProcessOutputCollector.

Using LaunchedEffect for starting and DisposableEffect for 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-idea which 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 to ShellSessionManager for externally managed sessions. Clear error handling for missing sessions.


250-304: LGTM!

The managed session awaiting logic correctly polls, handles timeouts with Pending result, and properly marks sessions as completed with appropriate Success/Error results 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 wait parameter explaining both modes, and sensible default of true for backward compatibility with synchronous behavior.


80-91: LGTM!

Schema properties are well-defined with appropriate bounds (minimum: 1000, maximum: 600000 for timeoutMs) preventing unreasonable values.


171-186: LGTM!

Clean execution mode triage: background mode → wait-with-timeout → synchronous fallback. The smart cast to LiveShellExecutor with capability check ensures graceful degradation.


192-220: LGTM!

Background execution correctly registers the session with ShellSessionManager and returns a Pending result 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 (both PtyShellExecutor and DefaultShellExecutor.jvm) properly throw ToolException with errorType == ToolErrorType.TIMEOUT on timeout, confirming the assumed contract is followed. Both platforms use withTimeoutOrNull() or process.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 Platform for 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 sessionId is not blank before creating invocations.

Also applies to: 220-239, 312-331

Comment on lines +343 to +352
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")
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 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 -20

Repository: 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 -30

Repository: 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 -20

Repository: 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 kt

Repository: 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 -30

Repository: 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)" | sort

Repository: 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 -50

Repository: 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>>()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

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.

Suggested change
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>>()

Comment on lines +451 to +491
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)
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Store output in LiveTerminalItem and handle channel send failures.

Two issues identified:

  1. Data inconsistency: The output parameter is used in ToolResult (lines 472, 484) but NOT stored in the LiveTerminalItem (line 461). This means the timeline UI and agent results will be inconsistent.

  2. 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)
         }

Comment on lines +497 to +536
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")
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Fix race condition between completion check and channel creation.

There's a TOCTOU (time-of-check to time-of-use) race condition:

  1. Line 503 checks if exitCode != null (not completed)
  2. updateLiveTerminalStatus() could run here and complete the session
  3. 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")
         }
     }

Comment on lines +68 to +75
fun saveDiagramToPath(bytes: ByteArray, filePath: String): Boolean {
return try {
File(filePath).writeBytes(bytes)
true
} catch (e: Exception) {
false
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

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.

Comment on lines +470 to +492
// 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)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

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.

Comment on lines +496 to +541
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")
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

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):

  1. awaitSessionResult checks exitCode → null
  2. updateLiveTerminalStatus runs, updates exitCode, doesn't find channel
  3. awaitSessionResult registers 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 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 in waitForSession leaves LiveShellSession incomplete

In waitForSession, when exitCode is null (timeout), you destroy the process and throw a ToolException, but you never update the LiveShellSession state. Any UI or client observing session.isCompleted / session.exitCode will continue to see a “running, no exit code” session even though the process has been killed.

Given that you already pass a killHandler into LiveShellSession, 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 with ManagedSession.kill()), as suggested in the LiveShellSession review.

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 call markCompleted(-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: Align timeoutMs runtime validation with schema bounds

ShellSchema constrains timeoutMs to [1000, 600000], but validateParameters only checks params.timeoutMs <= 0. Calls with very small (<1000) or very large (>600000) timeouts will be accepted and only indirectly constrained by context.timeout. Consider enforcing the same min/max in validateParameters so 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 failures

In executeWithTimeout, the session is registered before the try, and only ToolException with errorType == ToolErrorType.TIMEOUT is handled specially. If waitForSession (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 an else branch of the catch or via finally, 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 executeBackground if anything after startLiveExecution can fail.

Also applies to: 230-306


311-327: Cap stdout/stderr stored in metadata to avoid oversized payloads

executeSynchronous now includes full stdout and stderr strings in metadata. For long-running or very chatty commands, this can bloat ToolResult size 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 primary message or 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: Align kill() with completion state to avoid inconsistent session lifecycle

Right now kill() invokes the handler but does not update isCompleted / exitCode, so callers observing isCompleted or exitCode can see “running + no exit code” even after the process has been killed (unless something else later calls markCompleted). That’s also inconsistent with ManagedSession.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, and exitCode in sync after explicit kills and aligns semantics with ManagedSession.kill().


85-91: Clarify or rework waitForCompletion contract

waitForCompletion always throws UnsupportedOperationException, yet the KDoc says it’s “expected to be overridden or handled platform‑specifically”. Since LiveShellSession is not open in commonMain, overriding on platforms is not possible.

Either:

  • drop this API and rely solely on LiveShellExecutor.waitForSession, or
  • make this an expect/actual or 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 mutex

In both getActiveSessions and clearAll you run per‑session operations under ShellSessionManager’s mutex:

  • getActiveSessions() calls it.isRunning() inside mutex.withLock { ... }; isRunning() in turn hits the platform‑specific isAliveChecker.
  • clearAll() calls it.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 of activeSessions vs getActiveSessions

activeSessions (StateFlow<List<String>>) is updated with sessions.keys.toList(), i.e., all registered sessions (including completed ones), whereas getActiveSessions() filters by isRunning() 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 activeSessions is “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

📥 Commits

Reviewing files that changed from the base of the PR and between 0263ba0 and 9b64871.

📒 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: Use expect/actual for 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: Avoid Flow, use Promise instead
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.kt
  • mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/impl/ShellTool.kt
  • mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/tool/shell/ShellSessionManager.kt
  • mpp-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 clean

The refactor to carry a generic ptyHandle plus platform-provided isAliveChecker/killHandler keeps commonMain platform‑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

startLiveExecution correctly:

  • validates the command with existing safety checks,
  • sets up PTY env and login env,
  • starts the PtyProcess, and
  • wires isAliveChecker / killHandler on LiveShellSession back to the underlying Process.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
mpp-core/src/commonMain/kotlin/cc/unitmesh/agent/orchestrator/ToolOrchestrator.kt (1)

132-143: Redundant executor fetch; consider caching.

getShellExecutor is 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 = shellExecutor

Then 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9b64871 and 8a7212a.

📒 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: Use expect/actual for 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: Avoid Flow, use Promise instead
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.Pending state in both helper functions. Pending correctly returns false for success check and empty string for error message.

Comment on lines +27 to +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.
*/
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

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.

Suggested change
*
* @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.

Comment on lines +42 to +43
// Coroutine scope for background tasks (async shell monitoring)
private val backgroundScope = CoroutineScope(Dispatchers.Default)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

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:

  1. Implementing Closeable/AutoCloseable with a close() method that cancels the scope
  2. Or accepting a CoroutineScope from 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.

Comment on lines +284 to +302
// 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}"
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8a7212a and e63950f.

📒 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: Use expect/actual for 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: Avoid Flow, use Promise instead
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 isAliveChecker and killHandler lambdas to the LiveShellSession constructor 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 ShellExecutionConfig to 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.

Comment on lines +266 to 286
// 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 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 -150

Repository: 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 -A5

Repository: 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 -100

Repository: 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 -A3

Repository: 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 kotlin

Repository: 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.kt

Repository: 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: ProcessOutputCollector reads streams via LaunchedEffect, creating a vulnerable window between process launch and collector startup
  • CLI path: CodingCli.awaitSessionResult reads output in background, but only if explicitly called
  • Fallback: ShellSessionManager persists output synced by the collector, but depends on the collector having started

Actual risks:

  1. Process output buffer overflow if ProcessOutputCollector.start() hasn't launched before large output is produced
  2. No runtime validation that output collection started successfully
  3. If collector startup fails or is delayed, output loss and process blocking are possible

Recommendations:

  • Document the output consumption contract in LiveShellSession KDoc explicitly
  • Add safeguards in PtyShellExecutor.waitForSession to 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 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-idea module (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 trying destroy() first to allow the process a chance to clean up gracefully, then falling back to destroyForcibly() 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

📥 Commits

Reviewing files that changed from the base of the PR and between e63950f and 4a09c8f.

📒 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: Use expect/actual for 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: Avoid Flow, use Promise instead
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 = true in IdeaAgentToolWindowFactory
For popup/dropdown menus in IntelliJ plugins, use Jewel's PopupMenu instead of androidx.compose.ui.window.Popup
For dialogs in IntelliJ plugins, use IntelliJ's DialogWrapper with org.jetbrains.jewel.bridge.compose instead of androidx.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 miss stderr. 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 remember keys, LaunchedEffect for initialization, and DisposableEffect for cleanup. The fallback state handling is robust.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[mpp-idea] Refactor IdeaSketchRenderer to reuse LangSketch business logic from core module

2 participants