Skip to content

refactor(mpp-idea): extract IdeaAgentApp components and align with mpp-ui patterns - #11

Merged
phodal merged 5 commits into
masterfrom
refactor/idea-agent-app-components
Nov 30, 2025
Merged

phodal merged 5 commits into
masterfrom
refactor/idea-agent-app-components

Conversation

@phodal

@phodal phodal commented Nov 30, 2025 •

Copy link
Copy Markdown
Member

Summary

Refactor IdeaAgentApp.kt by extracting components into separate files and aligning UI patterns with mpp-ui.

Changes

Component Extraction

Main file simplified: IdeaAgentApp.kt from 780 lines to 276 lines

New component files:

File Components
timeline/IdeaTimelineContent.kt IdeaTimelineContent, IdeaTimelineItemView, IdeaEmptyStateMessage
timeline/IdeaMessageBubble.kt IdeaMessageBubble, IdeaStreamingMessageBubble
timeline/IdeaToolCallBubble.kt IdeaToolCallBubble, IdeaCurrentToolCallItem
timeline/IdeaErrorBubble.kt IdeaErrorBubble
timeline/IdeaTaskCompleteBubble.kt IdeaTaskCompleteBubble
timeline/IdeaTerminalOutputBubble.kt IdeaTerminalOutputBubble
header/IdeaAgentTabsHeader.kt IdeaAgentTabsHeader, IdeaAgentTab
status/IdeaToolLoadingStatusBar.kt IdeaToolLoadingStatusBar, IdeaToolStatusChip

ToolCallBubble Enhancements (aligned with mpp-ui ToolItem)

  • Expand/collapse animation using AnimatedVisibility
  • Copy to clipboard functionality for params and output
  • Status icons (executing, success, failed) with design system colors
  • Execution time display
  • Show Full toggle for long params/output
  • IdeaCurrentToolCallItem for executing tool indicator with badge

New Icons Added

  • PlayArrow - for executing status
  • ExpandLess / ExpandMore - for expand/collapse
  • ContentCopy - for clipboard copy

Alignment with mpp-ui

  • Component structure matches mpp-ui/compose/agent/ patterns
  • Uses same TimelineItem data structure approach
  • Uses AutoDevColors design system for color consistency
  • UI components adapted for Jewel (IntelliJ) theme while maintaining same logic

Testing

  • Build passes: cd mpp-idea && ../gradlew compileKotlin

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

Summary by CodeRabbit

  • New Features
    • Agent type tabs for quick navigation (Coding, Code Review, Knowledge, Remote) plus new-chat and settings actions.
    • New set of UI icons for play/stop/expand/copy/terminal actions.
    • Enhanced timeline: styled message bubbles, error bubbles, task-complete badges, tool-call views, and collapsible terminal output with copy and auto-scroll.
    • Loading status bar showing SubAgents and tool availability.

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

- Extract timeline components: IdeaTimelineContent, IdeaMessageBubble, IdeaToolCallBubble, IdeaErrorBubble, IdeaTaskCompleteBubble, IdeaTerminalOutputBubble
- Extract header component: IdeaAgentTabsHeader
- Extract status component: IdeaToolLoadingStatusBar
- Reduce IdeaAgentApp.kt from 780 lines to 276 lines
- Align component structure with mpp-ui patterns
- Add AnimatedVisibility for expand/collapse animation
- Add copy to clipboard functionality for params and output
- Add status icons (executing, success, failed) with colors
- Add execution time display
- Add 'Show Full' toggle for long params/output
- Add IdeaCurrentToolCallItem for executing tool indicator
- Add new icons: PlayArrow, ExpandLess, ExpandMore, ContentCopy

Aligns with mpp-ui ToolItem/ToolResultItem patterns
@coderabbitai

coderabbitai Bot commented Nov 30, 2025 •

Copy link
Copy Markdown

Walkthrough

Extracts inline UI composables from IdeaAgentApp into external components prefixed with "Idea", adds multiple timeline bubble components and status/header UI, and introduces new icon definitions (with duplicated declarations present).

Changes

Cohort / File(s) Summary
Main UI Refactor
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt
Replaces in-file composables with external Idea-prefixed components (IdeaAgentTabsHeader, IdeaTimelineContent, IdeaEmptyStateMessage, IdeaDevInInputArea, IdeaToolLoadingStatusBar) and updates rendering paths while preserving state and callbacks.
Header Navigation
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/header/IdeaAgentTabsHeader.kt
New composable IdeaAgentTabsHeader and child IdeaAgentTab for agent-type tabs and right-aligned actions (New Chat, Settings).
Status Bar
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/status/IdeaToolLoadingStatusBar.kt
New IdeaToolLoadingStatusBar composable with IdeaToolStatusChip to show SubAgents and MCP Tools counts, loading state, and trailing status message.
Timeline Container & Dispatcher
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTimelineContent.kt
New IdeaTimelineContent, IdeaTimelineItemView, and IdeaEmptyStateMessage to render timeline list or empty state and dispatch timeline item variants to bubble components.
Timeline Item Renderers
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaErrorBubble.kt, .../IdeaMessageBubble.kt, .../IdeaTaskCompleteBubble.kt, .../IdeaTerminalOutputBubble.kt, .../IdeaToolCallBubble.kt
Adds specialized timeline bubbles: IdeaErrorBubble, IdeaMessageBubble/IdeaStreamingMessageBubble, IdeaTaskCompleteBubble, IdeaTerminalOutputBubble (expandable, copyable terminal output), and IdeaToolCallBubble (tool call UI with formatting and copy).
Icon Definitions
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaComposeIcons.kt
Adds six ImageVector icons (PlayArrow, ExpandLess, ExpandMore, ContentCopy, Terminal, Stop). Declarations were duplicated consecutively in the file.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Check duplicate icon declarations in IdeaComposeIcons.kt and consolidate if unintentional.
  • Review state, LaunchedEffect and auto-scroll behavior in IdeaTerminalOutputBubble.kt.
  • Verify clipboard usage and formatting logic in IdeaToolCallBubble.kt.
  • Confirm correct wiring and callback propagation in IdeaAgentApp.kt after component extraction.

Possibly related PRs

Poem

🐰 I hopped through code with nimble feet,

Split the bubbles, made things neat,
Tabs and icons now take the stage,
Terminal whispers from the cage,
The plugin shuffles—fresh and sweet. ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 34.21% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main refactoring work: extracting IdeaAgentApp components into separate files and aligning patterns with mpp-ui, which is the core objective.
✨ 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 refactor/idea-agent-app-components

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

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

)
} else if (!toolStatus.isLoading && toolStatus.mcpServersLoaded > 0) {
Text(
text = "+ All tools ready",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The status message shows a "+" prefix; consider restoring the intended checkmark or removing the prefix to avoid confusion in the UI. It currently reads "+ All tools ready".

🤖 Was this useful? React with 👍 or 👎

/**
* Copy text to system clipboard (JVM implementation)
*/
private fun copyToClipboard(text: String) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

For clipboard operations in IntelliJ plugins, consider using CopyPasteManager instead of AWT Toolkit to align with platform APIs and avoid potential issues in sandboxed/remote contexts. This also helps ensure EDT-safe interactions.

🤖 Was this useful? React with 👍 or 👎

@coderabbitai

coderabbitai Bot commented Nov 30, 2025

Copy link
Copy Markdown

Note

Unit test generation is an Early Access feature. Expect some limitations and changes as we gather feedback and continue to improve it.


Generating unit tests... This may take up to 20 minutes.

@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-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt (1)

77-99: ViewModel disposal timing in DisposableEffect doesn’t match the comment’s intent

The comment says “Dispose ViewModels when leaving their tabs”, but with:

DisposableEffect(currentAgentType) {
    onDispose {
        if (currentAgentType != AgentType.CODE_REVIEW) {
            codeReviewViewModel?.dispose()
            codeReviewViewModel = null
        }
        if (currentAgentType != AgentType.KNOWLEDGE) {
            knowledgeViewModel?.dispose()
            knowledgeViewModel = null
        }
    }
}

currentAgentType inside onDispose is the type captured when that effect instance was created. When you navigate from CODE_REVIEW to another tab, the onDispose belonging to the CODE_REVIEW key runs with currentAgentType == AgentType.CODE_REVIEW, so the first if is false and the code review VM is kept alive until you later leave the next tab. The same pattern applies to the knowledge VM.

If you want creation and disposal strictly tied to entering/leaving each tab, you can fold both into the LaunchedEffect(currentAgentType) and drop DisposableEffect, e.g.:

-    LaunchedEffect(currentAgentType) {
-        if (currentAgentType == AgentType.CODE_REVIEW && codeReviewViewModel == null) {
-            codeReviewViewModel = IdeaCodeReviewViewModel(project, coroutineScope)
-        }
-        if (currentAgentType == AgentType.KNOWLEDGE && knowledgeViewModel == null) {
-            knowledgeViewModel = IdeaKnowledgeViewModel(project, coroutineScope)
-        }
-    }
-
-    // Dispose ViewModels when leaving their tabs
-    DisposableEffect(currentAgentType) {
-        onDispose {
-            if (currentAgentType != AgentType.CODE_REVIEW) {
-                codeReviewViewModel?.dispose()
-                codeReviewViewModel = null
-            }
-            if (currentAgentType != AgentType.KNOWLEDGE) {
-                knowledgeViewModel?.dispose()
-                knowledgeViewModel = null
-            }
-        }
-    }
+    LaunchedEffect(currentAgentType) {
+        if (currentAgentType == AgentType.CODE_REVIEW) {
+            if (codeReviewViewModel == null) {
+                codeReviewViewModel = IdeaCodeReviewViewModel(project, coroutineScope)
+            }
+        } else {
+            codeReviewViewModel?.dispose()
+            codeReviewViewModel = null
+        }
+
+        if (currentAgentType == AgentType.KNOWLEDGE) {
+            if (knowledgeViewModel == null) {
+                knowledgeViewModel = IdeaKnowledgeViewModel(project, coroutineScope)
+            }
+        } else {
+            knowledgeViewModel?.dispose()
+            knowledgeViewModel = null
+        }
+    }

This keeps the behavior simple: entering a tab ensures its VM exists, and switching away ensures it’s disposed immediately.

🧹 Nitpick comments (7)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTaskCompleteBubble.kt (1)

21-59: Consider pluralizing the iterations label

The success/failure styling looks solid; one small UX nit is "${item.iterations} iterations" which reads oddly for 1. You could optionally pluralize:

-                Text(
-                    text = "${item.message} (${item.iterations} iterations)",
+                val iterationsLabel = if (item.iterations == 1) "iteration" else "iterations"
+                Text(
+                    text = "${item.message} (${item.iterations} $iterationsLabel)",
                     style = JewelTheme.defaultTextStyle.copy(
                         fontWeight = FontWeight.Bold
                     )
                 )
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTerminalOutputBubble.kt (1)

20-79: Terminal output bubble is solid; consider monospace for body text

The command/exit/time header and truncation behavior look good. For the output Text, using a monospace font would make CLI output and tables easier to scan:

// inside the Text at lines 70–75
style = JewelTheme.defaultTextStyle.copy(
    fontSize = 12.sp,
    // import androidx.compose.ui.text.font.FontFamily
    fontFamily = FontFamily.Monospace,
    color = AutoDevColors.Neutral.c300
)

Purely a readability improvement; current implementation is functionally fine.

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

25-106: Tab header behavior: AgentType coverage and button background

Two things to double‑check here:

  1. The tab list only includes CODING, CODE_REVIEW, KNOWLEDGE, and REMOTE (Line 46), while IdeaAgentApp still has dedicated branches for AgentType.LOCAL_CHAT. If LOCAL_CHAT is meant to be user‑switchable rather than only entered programmatically, you may want to surface it as a tab as well or document how users reach it.

  2. In IdeaAgentTab, applying Modifier.background(backgroundColor) directly to an OutlinedButton (Lines 91–97) hard‑codes a background over whatever visual states Jewel would normally render (hover/pressed/disabled). If Jewel exposes a colors/style API for buttons, wiring the selected state through that would avoid potentially masking built‑in interaction feedback.

Styling and use of JewelTheme/AutoDevColors otherwise look consistent with the rest of the UI. Based on learnings, this aligns with the design system usage.

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

41-294: Check auto‑expand behavior when tool success transitions from null to false

The overall bubble (status icon, summary, expandable params/output, copy buttons) is nicely put together. One subtle state issue to be aware of:

var expanded by remember { mutableStateOf(item.success == false) }
var showFullOutput by remember { mutableStateOf(item.success == false) }

If your TimelineItem.ToolCallItem instances keep the same id and are updated from “executing” (success == null) to “failed” (success == false), these remember blocks won’t reinitialize, so the bubble may stay collapsed and showFullOutput may remain false even for errors, contrary to the “Auto-expand on error” intent.

If you want the UI to auto‑expand whenever an existing item turns into an error (rather than only for items first composed with success == false), consider keying the state off item.success:

var expanded by remember(item.success) { mutableStateOf(item.success == false) }
var showFullOutput by remember(item.success) { mutableStateOf(item.success == false) }

This preserves per‑item state but re-syncs default expansion with status transitions. If your renderer always inserts a fresh error item instead of mutating existing ones, current code is fine and this is not needed.


296-399: Clipboard helper and output formatter are reasonable for mpp‑idea

copyToClipboard using java.awt.Toolkit and swallowing exceptions is pragmatic for the IntelliJ plugin context, and formatToolOutput’s lightweight heuristics for JSON/tables/long lines are safe (string replaces only; no parsing). If you ever decide to reuse these bubbles in non‑IDEA frontends, this would be a good spot to introduce expect/actual and push the clipboard/output formatting into a shared utility, but for mpp‑idea‑only usage the current implementation is fine.

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

28-32: Reconsider remember(mcpPreloadingStatus) as the only key for toolStatus.

If viewModel.getToolLoadingStatus() depends on more than just mcpPreloadingStatus (e.g., sub‑agent enablement, MCP counts), keying remember only on mcpPreloadingStatus can leave toolStatus stale across recompositions.

Two lighter options:

  • If getToolLoadingStatus() is cheap and side‑effect free, drop remember entirely:
  • val toolStatus = remember(mcpPreloadingStatus) { viewModel.getToolLoadingStatus() }
  • val toolStatus = viewModel.getToolLoadingStatus()
- Or, better long‑term, expose `toolStatus` as a `StateFlow`/`SnapshotState` from the viewModel and `collectAsState()`/read it here so Compose tracks the actual dependencies.

---

`90-123`: **Avoid magic `-1` sentinel for unknown `total` in `IdeaToolStatusChip`.**

Using `total < 0` → `"..."` is a hidden contract between caller and chip. Making `total` nullable is more self‑documenting and type‑safe:

```diff
-    total: Int,
+    total: Int?,
@@
-    val totalDisplay = if (total < 0) "..." else total.toString()
+    val totalDisplay = total?.toString() ?: "..."

Call site:

-            total = if (toolStatus.isLoading) -1 else toolStatus.mcpToolsTotal,
+            total = if (toolStatus.isLoading) null else toolStatus.mcpToolsTotal,

This keeps the UI behavior while removing the magic value.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 507a6bd and dfe4521.

📒 Files selected for processing (10)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt (7 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaComposeIcons.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/header/IdeaAgentTabsHeader.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/status/IdeaToolLoadingStatusBar.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaErrorBubble.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaMessageBubble.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTaskCompleteBubble.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTerminalOutputBubble.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTimelineContent.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaToolCallBubble.kt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.kt

📄 CodeRabbit inference engine (AGENTS.md)

Use expect/actual for platform-specific code in KMP projects (e.g., file I/O on JVM/JS/Wasm)

Files:

  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/status/IdeaToolLoadingStatusBar.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTerminalOutputBubble.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaComposeIcons.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTimelineContent.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaToolCallBubble.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaErrorBubble.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/header/IdeaAgentTabsHeader.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTaskCompleteBubble.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaMessageBubble.kt
🧠 Learnings (1)
📚 Learning: 2025-11-30T02:30:49.805Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-11-30T02:30:49.805Z
Learning: Applies to **/src/{androidMain,desktopMain}/**/*.kt : For 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/toolwindow/status/IdeaToolLoadingStatusBar.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/header/IdeaAgentTabsHeader.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt
🧬 Code graph analysis (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/header/IdeaAgentTabsHeader.kt (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.kt (1)
  • onAgentTypeChange (182-184)
⏰ 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). (2)
  • GitHub Check: Build (241)
  • GitHub Check: Build (223)
🔇 Additional comments (6)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaComposeIcons.kt (1)

333-446: New icon vectors are consistent and correct

PlayArrow, ExpandLess, ExpandMore, and ContentCopy follow the existing pattern for vector icons (24×24 dp, matching viewport, black fill) and the path data looks valid and within bounds. No functional or stylistic issues from this addition.

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

19-53: Error bubble implementation looks clean and consistent

The composable is small, self-contained, and uses AutoDevColors + JewelTheme appropriately; I don’t see functional or styling issues here.

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

17-71: Message and streaming bubbles are wired correctly

Role-based alignment, width constraints, and use of JewelTheme all look good; the streaming variant’s cursor indicator is straightforward and side‑effect free.

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

20-94: Timeline container and dispatcher look correct

Empty‑state handling, keyed LazyColumn, and the dispatcher mapping each TimelineItem variant to the appropriate Idea*Bubble are all consistent and match the intended mpp‑ui pattern.

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

107-167: New Idea components are wired correctly into the main app*

IdeaAgentTabsHeader, IdeaTimelineContent, IdeaEmptyStateMessage, IdeaDevInInputArea, and IdeaToolLoadingStatusBar are all passed the expected state and callbacks, and the when (currentAgentType) branches still cover all existing agent modes (including LOCAL_CHAT) consistently. The refactor reads as a straightforward structural cleanup without behavioral regressions.

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

46-47: Theming choice for status colors looks consistent with guidelines.

The use of AutoDevColors.Blue/Green alongside JewelTheme.globalColors.text.info gives clear semantic status signaling and aligns with the AutoDevColors guidance for Compose theming in this codebase.

Based on learnings, this matches the preferred theming approach.

Also applies to: 55-59, 75-79

@coderabbitai

coderabbitai Bot commented Nov 30, 2025

Copy link
Copy Markdown

✅ UTG Post-Process Complete

No new issues were detected in the generated code and all check runs have completed. The unit test generation process has completed successfully.

@coderabbitai

coderabbitai Bot commented Nov 30, 2025

Copy link
Copy Markdown

Creating a PR to put the unit tests in...

The changes have been created in this pull request: View PR

- Add IdeaShellExecutor service for command execution using PtyCommandLine
- Add IdeaUIWriter for streaming output updates with state callbacks
- Enhance IdeaTerminalOutputBubble with execute/stop, expand/collapse, copy
- Add Terminal and Stop icons to IdeaComposeIcons
- Pass project through timeline components for shell access
- Add status badges (Ready, Running, Success, Failed, Terminated)
- Add execution time display and 'Show Full Output' toggle

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 9

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

73-81: The "+" prefix in "All tools ready" may be unintended.

The status message shows "+ All tools ready" which looks like it might have been intended to be a checkmark (✓) or similar indicator. This was already flagged in a previous review.

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

369-376: Use IntelliJ's CopyPasteManager instead of AWT Toolkit.

This was already flagged in a previous review. CopyPasteManager is preferred for IntelliJ plugins.

🧹 Nitpick comments (9)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTaskCompleteBubble.kt (1)

50-55: Consider handling singular/plural for iteration count.

The text will display "1 iterations" when item.iterations == 1, which is grammatically incorrect.

                 Text(
-                    text = "${item.message} (${item.iterations} iterations)",
+                    text = "${item.message} (${item.iterations} ${if (item.iterations == 1) "iteration" else "iterations"})",
                     style = JewelTheme.defaultTextStyle.copy(
                         fontWeight = FontWeight.Bold
                     )
                 )
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaErrorBubble.kt (1)

19-52: Solid error bubble implementation; only an optional accessibility/i18n tweak

The composable is clean, follows the design system (AutoDevColors + JewelTheme), constrains width appropriately, and lays out icon + text in a readable way. No functional issues spotted.

One optional refinement: contentDescription = "Error" on Line 40 hard‑codes an English string and doesn’t convey the actual error. Depending on how you handle accessibility elsewhere, you could consider either:

  • Using the message itself for a more descriptive announcement, or
  • Treating the icon as decorative with contentDescription = null and letting the Text carry the semantics.

Both are minor and non‑blocking; the current implementation is otherwise good to ship.

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

50-71: Consider making the cursor animated for better UX.

The static "|" cursor works but doesn't convey the streaming state as effectively as a blinking cursor would. This is a minor enhancement opportunity.

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

46-52: Hardcoded agent type list may become stale.

The list of agent types is hardcoded. If AgentType enum changes, this list won't automatically update. Consider deriving from the enum or accepting the list as a parameter.

-            listOf(AgentType.CODING, AgentType.CODE_REVIEW, AgentType.KNOWLEDGE, AgentType.REMOTE).forEach { type ->
+            // Consider parameterizing or deriving from AgentType.entries
+            val displayedTypes = listOf(AgentType.CODING, AgentType.CODE_REVIEW, AgentType.KNOWLEDGE, AgentType.REMOTE)
+            displayedTypes.forEach { type ->
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTimelineContent.kt (1)

55-80: Consider passing project consistently to all item views.

project is passed to IdeaTerminalOutputBubble but not to IdeaToolCallBubble. For consistency and future extensibility (e.g., if tool calls need project context), consider passing it uniformly.

         is JewelRenderer.TimelineItem.ToolCallItem -> {
-            IdeaToolCallBubble(item)
+            IdeaToolCallBubble(item, project)
         }
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTerminalOutputBubble.kt (2)

124-127: Consider using IntelliJ's CopyPasteManager for clipboard operations.

Using Toolkit.getDefaultToolkit().systemClipboard works but CopyPasteManager is the IntelliJ platform-preferred approach, ensuring EDT safety and compatibility with remote/sandboxed environments.

+import com.intellij.openapi.ide.CopyPasteManager
+import java.awt.datatransfer.StringSelection

                     onCopy = {
-                        val clipboard = Toolkit.getDefaultToolkit().systemClipboard
-                        clipboard.setContents(StringSelection(currentOutput), null)
+                        CopyPasteManager.getInstance().setContents(StringSelection(currentOutput))
                     }

136-147: Hardcoded color could use design system.

Color(0xFF1E1E1E) is hardcoded. Consider using AutoDevColors.Neutral.c900 or similar from the design system for consistency.

                     Column(
                         modifier = Modifier
                             .fillMaxWidth()
-                            .background(Color(0xFF1E1E1E))
+                            .background(AutoDevColors.Neutral.c950) // or appropriate neutral color
                             .padding(12.dp)
                     ) {
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaToolCallBubble.kt (1)

300-364: Static "..." doesn't convey progress effectively.

The IdeaCurrentToolCallItem uses static "..." text as a spinner indicator. Consider using an actual animated indicator or at least a more descriptive static text like "⏳" or an animated CircularProgressIndicator if available in Jewel.

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

184-275: Consider extracting IdeaDevInInputArea to a separate file.

While making the function private is valid, this 90+ line composable with significant logic (SwingPanel integration, editor management, disposal handling) would benefit from being in its own file (e.g., input/IdeaDevInInputArea.kt) for better modularity and consistency with the other extracted components.

This refactor would align with the PR's stated goal of component extraction and make the codebase more maintainable.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 507a6bd and fc681c1.

📒 Files selected for processing (12)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/services/IdeaShellExecutor.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/services/IdeaUIWriter.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt (6 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaComposeIcons.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/header/IdeaAgentTabsHeader.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/status/IdeaToolLoadingStatusBar.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaErrorBubble.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaMessageBubble.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTaskCompleteBubble.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTerminalOutputBubble.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTimelineContent.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaToolCallBubble.kt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.kt

📄 CodeRabbit inference engine (AGENTS.md)

Use expect/actual for platform-specific code in KMP projects (e.g., file I/O on JVM/JS/Wasm)

Files:

  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaMessageBubble.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/header/IdeaAgentTabsHeader.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTaskCompleteBubble.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaToolCallBubble.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/services/IdeaUIWriter.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTimelineContent.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/status/IdeaToolLoadingStatusBar.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTerminalOutputBubble.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaComposeIcons.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaErrorBubble.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/services/IdeaShellExecutor.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt
🧠 Learnings (1)
📚 Learning: 2025-11-30T02:30:49.805Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-11-30T02:30:49.805Z
Learning: Applies to **/src/{androidMain,desktopMain}/**/*.kt : For 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/toolwindow/timeline/IdeaMessageBubble.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt
🧬 Code graph analysis (3)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/header/IdeaAgentTabsHeader.kt (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentViewModel.kt (1)
  • onAgentTypeChange (182-184)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTimelineContent.kt (5)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaMessageBubble.kt (2)
  • IdeaStreamingMessageBubble (50-71)
  • IdeaMessageBubble (17-45)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaToolCallBubble.kt (1)
  • IdeaToolCallBubble (40-294)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaErrorBubble.kt (1)
  • IdeaErrorBubble (19-53)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTaskCompleteBubble.kt (1)
  • IdeaTaskCompleteBubble (21-59)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTerminalOutputBubble.kt (1)
  • IdeaTerminalOutputBubble (41-189)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTerminalOutputBubble.kt (2)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt (1)
  • onStop (227-229)
core/src/main/kotlin/cc/unitmesh/devti/mcp/ui/McpToolDetailDialog.kt (1)
  • onExecute (127-148)
⏰ 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). (2)
  • GitHub Check: Build (241)
  • GitHub Check: Build (223)
🔇 Additional comments (10)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaComposeIcons.kt (1)

332-514: LGTM!

The new icon definitions follow the established pattern in this file with consistent sizing (24dp), viewport configuration, and lazy initialization. The icons are well-documented and appropriately named.

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

17-45: LGTM!

The message bubble component properly uses Jewel theming for IntelliJ IDEA integration, with appropriate role-based alignment and styling. The max width constraint prevents overly wide bubbles.

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

91-106: Background modifier on OutlinedButton may not render as expected.

The .background() modifier is applied to the OutlinedButton externally, but Compose buttons typically have their own internal background. The background may be obscured by the button's surface. Consider using Modifier.then() or a wrapping Box if the background isn't visible.

Verify that the selected tab background color is actually visible in the UI.

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

21-50: LGTM!

The timeline content properly handles empty state, uses stable keys for LazyColumn items, and correctly shows streaming output at the bottom. The component structure is clean and follows Compose best practices.

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

23-83: LGTM!

The status bar component properly observes ViewModel state and uses remember with the correct key for derived state. The layout with spacer for right-alignment is appropriate.

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

80-117: Execution lifecycle looks correct.

The execution flow properly manages state transitions, handles success/failure, and supports cancellation. Good use of rememberCoroutineScope for structured concurrency within the composable.

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

40-147: LGTM!

The tool call bubble component has a well-structured UI with appropriate state management for expand/collapse, show more/less toggles, and status indicators. The auto-expand on error is good UX.

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

17-22: LGTM! Component imports align with the extraction strategy.

The new imports for extracted components (IdeaAgentTabsHeader, IdeaToolLoadingStatusBar, IdeaEmptyStateMessage, IdeaTimelineContent) are correctly structured and follow the established package organization pattern.


107-112: LGTM! Header component extraction is clean.

The extracted IdeaAgentTabsHeader component maintains the same parameters and callbacks as the original inline implementation, ensuring feature parity.


124-129: The project parameter is correctly required and used in IdeaTimelineContent.

The project parameter (line 26, optional with Project? = null default) is properly passed to IdeaTimelineItemView (line 39), which conditionally passes it further to IdeaTerminalOutputBubble for terminal output rendering. The parameter is correctly threaded through the composition hierarchy where needed.

Comment on lines +39 to +159
@Service(Service.Level.PROJECT)
class IdeaShellExecutor(private val project: Project) {

/**
* Execute shell command with streaming output support.
*
* @param shellScript The shell command to execute
* @param stdWriter Writer for stdout
* @param errWriter Writer for stderr
* @param dispatcher Coroutine dispatcher for execution
* @return Exit code of the process
*/
suspend fun exec(
shellScript: String,
stdWriter: Writer,
errWriter: Writer,
dispatcher: CoroutineDispatcher
): Int = withContext(dispatcher) {
val process = createProcess(shellScript)

val exitCode = async { process.awaitExit() }
val errOutput = async { consumeProcessOutput(process.errorStream, errWriter, process, dispatcher) }
val stdOutput = async { consumeProcessOutput(process.inputStream, stdWriter, process, dispatcher) }

stdOutput.await()
errOutput.await()
exitCode.await()
}

/**
* Execute shell command and return result.
*/
suspend fun executeCommand(command: String, dispatcher: CoroutineDispatcher): ShellExecutorResult {
val stdWriter = StringWriter()
val errWriter = StringWriter()

val exitCode = exec(command, stdWriter, errWriter, dispatcher)
return ShellExecutorResult(
exitCode = exitCode,
stdOutput = stdWriter.toString(),
errOutput = errWriter.toString()
)
}

private fun createProcess(shellScript: String): Process {
val basedir = project.basePath
val commandLine = PtyCommandLine()
commandLine.withConsoleMode(false)
commandLine.withUnixOpenTtyToPreserveOutputAfterTermination(true)
commandLine.withInitialColumns(240)
commandLine.withInitialRows(80)
commandLine.withEnvironment("TERM", "dumb")
commandLine.withEnvironment("BASH_SILENCE_DEPRECATION_WARNING", "1")
commandLine.withEnvironment("GIT_PAGER", "cat")

// Set JAVA_HOME if available
try {
getJdkVersion()?.let { javaHomePath ->
commandLine.withEnvironment("JAVA_HOME", javaHomePath)
}
} catch (e: Exception) {
// Ignore JAVA_HOME errors
}

val shell = detectShell()
val commands: List<String> = listOf(shell, "--noprofile", "--norc", "-c", formatCommand(shellScript))

if (basedir != null) {
commandLine.withWorkDirectory(basedir)
}

return commandLine.startProcessWithPty(commands)
}

private fun formatCommand(command: String): String {
return "{ $command; } 2>&1"
}

private fun detectShell(): String {
val shells = listOf("/bin/zsh", "/bin/bash", "/bin/sh")
return shells.find { File(it).exists() } ?: "bash"
}

private fun getJdkVersion(): String? {
return try {
val sdk = ProjectRootManager.getInstance(project).projectSdk
sdk?.homePath
} catch (e: Exception) {
null
}
}

private suspend fun consumeProcessOutput(
source: InputStream?,
outputWriter: Writer,
process: Process,
dispatcher: CoroutineDispatcher
) = withContext(dispatcher) {
if (source == null) return@withContext

var isFirstLine = true
BufferedReader(InputStreamReader(source, Charsets.UTF_8.name())).use { reader ->
do {
val line = reader.readLine()
if (Strings.isNotEmpty(line)) {
if (!isFirstLine) outputWriter.append(System.lineSeparator())
isFirstLine = false
outputWriter.append(line)
} else {
yield()
}
ensureActive()
} while (process.isAlive || line != null)
}
}

companion object {
@JvmStatic
fun getInstance(project: Project): IdeaShellExecutor = project.service()
}
}

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

Platform-specific implementation violates KMP guidelines.

This implementation uses Unix-specific shell execution (PtyCommandLine, hardcoded shell paths at lines 118-119, Unix shell options at line 104) without the expect/actual pattern required for KMP projects. The service won't work on Windows or other platforms.

As per coding guidelines: Use expect/actual for platform-specific code in KMP projects.

Consider restructuring:

  1. Define an expect class ShellExecutor in common code
  2. Provide actual implementations for each platform (JVM/JS/Wasm)
  3. Move this Unix-specific logic to the JVM actual implementation

Comment on lines +51 to +66
suspend fun exec(
shellScript: String,
stdWriter: Writer,
errWriter: Writer,
dispatcher: CoroutineDispatcher
): Int = withContext(dispatcher) {
val process = createProcess(shellScript)

val exitCode = async { process.awaitExit() }
val errOutput = async { consumeProcessOutput(process.errorStream, errWriter, process, dispatcher) }
val stdOutput = async { consumeProcessOutput(process.inputStream, stdWriter, process, dispatcher) }

stdOutput.await()
errOutput.await()
exitCode.await()
}

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

Add process cleanup on coroutine cancellation.

If the coroutine is cancelled during execution, the spawned process will continue running as a zombie. The process should be explicitly destroyed when the coroutine scope is cancelled.

Apply this diff to add cleanup:

     suspend fun exec(
         shellScript: String,
         stdWriter: Writer,
         errWriter: Writer,
         dispatcher: CoroutineDispatcher
     ): Int = withContext(dispatcher) {
         val process = createProcess(shellScript)
         
-        val exitCode = async { process.awaitExit() }
-        val errOutput = async { consumeProcessOutput(process.errorStream, errWriter, process, dispatcher) }
-        val stdOutput = async { consumeProcessOutput(process.inputStream, stdWriter, process, dispatcher) }
-        
-        stdOutput.await()
-        errOutput.await()
-        exitCode.await()
+        try {
+            val exitCode = async { process.awaitExit() }
+            val errOutput = async { consumeProcessOutput(process.errorStream, errWriter, process, dispatcher) }
+            val stdOutput = async { consumeProcessOutput(process.inputStream, stdWriter, process, dispatcher) }
+            
+            stdOutput.await()
+            errOutput.await()
+            exitCode.await()
+        } finally {
+            if (process.isAlive) {
+                process.destroy()
+            }
+        }
     }

Comment on lines +83 to +111
private fun createProcess(shellScript: String): Process {
val basedir = project.basePath
val commandLine = PtyCommandLine()
commandLine.withConsoleMode(false)
commandLine.withUnixOpenTtyToPreserveOutputAfterTermination(true)
commandLine.withInitialColumns(240)
commandLine.withInitialRows(80)
commandLine.withEnvironment("TERM", "dumb")
commandLine.withEnvironment("BASH_SILENCE_DEPRECATION_WARNING", "1")
commandLine.withEnvironment("GIT_PAGER", "cat")

// Set JAVA_HOME if available
try {
getJdkVersion()?.let { javaHomePath ->
commandLine.withEnvironment("JAVA_HOME", javaHomePath)
}
} catch (e: Exception) {
// Ignore JAVA_HOME errors
}

val shell = detectShell()
val commands: List<String> = listOf(shell, "--noprofile", "--norc", "-c", formatCommand(shellScript))

if (basedir != null) {
commandLine.withWorkDirectory(basedir)
}

return commandLine.startProcessWithPty(commands)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# First, check the full IdeaShellExecutor.kt file to see the public methods
wc -l mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/services/IdeaShellExecutor.kt

Repository: phodal/auto-dev-sketch

Length of output: 148


🏁 Script executed:

#!/bin/bash
# Check for exec and executeCommand method definitions
rg -n 'fun (exec|executeCommand)' mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/services/IdeaShellExecutor.kt

Repository: phodal/auto-dev-sketch

Length of output: 197


🏁 Script executed:

#!/bin/bash
# Find all call sites of IdeaShellExecutor methods
rg -n 'IdeaShellExecutor.*\.(exec|executeCommand)' --type kotlin

Repository: phodal/auto-dev-sketch

Length of output: 48


🏁 Script executed:

#!/bin/bash
# Check the timeline toolwindow components for input handling
rg -n 'shellScript|executeCommand' mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/ --type kotlin

Repository: phodal/auto-dev-sketch

Length of output: 48


🏁 Script executed:

#!/bin/bash
# Read the full IdeaShellExecutor.kt file
cat -n mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/services/IdeaShellExecutor.kt

Repository: phodal/auto-dev-sketch

Length of output: 6256


🏁 Script executed:

#!/bin/bash
# Look for interface definitions or base classes
rg -n 'interface.*ShellExecutor|class.*ShellExecutor' --type kotlin

Repository: phodal/auto-dev-sketch

Length of output: 5447


🏁 Script executed:

#!/bin/bash
# Search more broadly for method calls with different patterns
rg -n '\.exec\(|\.executeCommand\(' --type kotlin

Repository: phodal/auto-dev-sketch

Length of output: 1163


🏁 Script executed:

#!/bin/bash
# Look at IdeaTerminalOutputBubble.kt to see where the shell script comes from
cat -n mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTerminalOutputBubble.kt | sed -n '85,110p'

Repository: phodal/auto-dev-sketch

Length of output: 1719


🏁 Script executed:

#!/bin/bash
# Look at TerminalExecuteAction.kt to see how sketch.getViewText() is used
cat -n exts/ext-terminal/src/main/kotlin/cc/unitmesh/terminal/sketch/TerminalExecuteAction.kt | sed -n '75,95p'

Repository: phodal/auto-dev-sketch

Length of output: 1250


🏁 Script executed:

#!/antml/bash
# Check what sketch.getViewText() is and if there's input validation
rg -n 'getViewText\(\)' --type kotlin -A 2 -B 2

Repository: phodal/auto-dev-sketch

Length of output: 11045


🏁 Script executed:

#!/bin/bash
# Check if there's any sanitization in IdeaTerminalOutputBubble - look for the full context
wc -l mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTerminalOutputBubble.kt

Repository: phodal/auto-dev-sketch

Length of output: 166


🏁 Script executed:

#!/bin/bash
# Check the data source for item.command in IdeaTerminalOutputBubble
rg -n 'item\.command' mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/ --type kotlin -B 5 -A 2

Repository: phodal/auto-dev-sketch

Length of output: 2471


🏁 Script executed:

#!/bin/bash
# Check TerminalSketchProvider content property and how it's set
rg -n 'var content|val content' exts/ext-terminal/src/main/kotlin/cc/unitmesh/terminal/sketch/TerminalSketchProvider.kt -A 2 -B 2

Repository: phodal/auto-dev-sketch

Length of output: 600


🏁 Script executed:

#!/bin/bash
# Look for updateViewText implementation and how content is updated
rg -n 'updateViewText|override fun updateViewText' exts/ext-terminal/src/main/kotlin/cc/unitmesh/terminal/sketch/ --type kotlin -A 3

Repository: phodal/auto-dev-sketch

Length of output: 4059


🏁 Script executed:

#!/antml/bash
# Find the data model/class for 'item' in IdeaTerminalOutputBubble
rg -n '@Composable.*IdeaTerminalOutputBubble|fun IdeaTerminalOutputBubble' mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/ --type kotlin -B 5 -A 1

Repository: phodal/auto-dev-sketch

Length of output: 1074


🏁 Script executed:

#!/bin/bash
# Search for the item parameter and its type in the composable
cat -n mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTerminalOutputBubble.kt | head -100

Repository: phodal/auto-dev-sketch

Length of output: 5248


🏁 Script executed:

#!/bin/bash
# Find the TerminalOutputItem definition
rg -n 'class TerminalOutputItem|data class TerminalOutputItem|TerminalOutputItem.*=' --type kotlin -A 3

Repository: phodal/auto-dev-sketch

Length of output: 1006


🏁 Script executed:

#!/bin/bash
# Search for where TerminalOutputItem is created/instantiated
rg -n 'TerminalOutputItem(' --type kotlin -B 2 -A 2

Repository: phodal/auto-dev-sketch

Length of output: 154


🏁 Script executed:

#!/bin/bash
# Search for where TerminalOutputItem is instantiated
rg -n 'TerminalOutputItem\(' --type kotlin -B 3 -A 3

Repository: phodal/auto-dev-sketch

Length of output: 9588


🏁 Script executed:

#!/bin/bash
# Find where addOnCommandExecution is called
rg -n 'addOnCommandExecution' --type kotlin -B 3 -A 1

Repository: phodal/auto-dev-sketch

Length of output: 48


🏁 Script executed:

#!/bin/bash
# Look at the addOnCommandExecution function definition in JewelRenderer.kt
rg -n 'fun addOnCommandExecution' mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/JewelRenderer.kt -A 15

Repository: phodal/auto-dev-sketch

Length of output: 48


🏁 Script executed:

#!/bin/bash
# Look at JewelRenderer.kt around line 315 to find the function context
cat -n mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/JewelRenderer.kt | sed -n '295,345p'

Repository: phodal/auto-dev-sketch

Length of output: 2711


🏁 Script executed:

#!/bin/bash
# Search for the function signature containing this code
cat -n mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/JewelRenderer.kt | sed -n '200,320p'

Repository: phodal/auto-dev-sketch

Length of output: 5199


🏁 Script executed:

#!/bin/bash
# Look at formatToolCallDisplay to understand what details contains
rg -n 'fun formatToolCallDisplay' mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/renderer/ --type kotlin -A 10

Repository: phodal/auto-dev-sketch

Length of output: 1489


Confirm shell command injection vulnerability and add input validation at call sites.

The shellScript parameter is passed directly to the shell via formatCommand() without sanitization. Commands originate from LLM tool calls (JewelRenderer.kt:310) extracted with only removePrefix(). Although commands are passed as a list to startProcessWithPty(), the -c flag causes the shell to interpret metacharacters, enabling injection attacks.

Sanitize or validate shell command input at the source (LLM tool call parameters) or use a safer execution method that avoids shell interpretation entirely.

🤖 Prompt for AI Agents
In
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/services/IdeaShellExecutor.kt
around lines 83 to 111, the shellScript argument is passed through
formatCommand() into a shell invoked with "-c", allowing shell metacharacter
interpretation and command injection; fix by removing reliance on invoking a
shell with "-c" for untrusted input (use a direct process invocation API that
accepts the command and arguments without a shell, or construct
ProcessBuilder/PtyCommandLine with the executable and argument list rather than
a single concatenated string), and/or validate/sanitize inputs at the source
(JewelRenderer.kt:310) by whitelisting allowed commands/arguments or
rejecting/escaping metacharacters; ensure any JAVA_HOME or path handling remains
intact and update call sites to pass a safe-broken-out argv list instead of a
raw shellScript.

Comment on lines +117 to +120
private fun detectShell(): String {
val shells = listOf("/bin/zsh", "/bin/bash", "/bin/sh")
return shells.find { File(it).exists() } ?: "bash"
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Improve shell detection fallback handling.

The fallback to "bash" (Line 119) when no shell is found might fail if bash isn't in PATH. Consider throwing a descriptive exception or using an absolute path check.

Apply this diff:

     private fun detectShell(): String {
         val shells = listOf("/bin/zsh", "/bin/bash", "/bin/sh")
-        return shells.find { File(it).exists() } ?: "bash"
+        return shells.find { File(it).exists() } 
+            ?: throw IllegalStateException("No compatible shell found in: ${shells.joinToString()}")
     }
🤖 Prompt for AI Agents
In
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/services/IdeaShellExecutor.kt
around lines 117 to 120, the detectShell() function currently falls back to the
string "bash" which may not exist on PATH; change the logic to either return an
absolute path to a known shell or throw a descriptive exception: check the
standard absolute locations first, and if none exist, throw an
IllegalStateException (or a custom exception) with a clear message listing the
paths checked and suggesting to install/configure a shell, instead of silently
returning "bash".

Comment on lines +131 to +153
private suspend fun consumeProcessOutput(
source: InputStream?,
outputWriter: Writer,
process: Process,
dispatcher: CoroutineDispatcher
) = withContext(dispatcher) {
if (source == null) return@withContext

var isFirstLine = true
BufferedReader(InputStreamReader(source, Charsets.UTF_8.name())).use { reader ->
do {
val line = reader.readLine()
if (Strings.isNotEmpty(line)) {
if (!isFirstLine) outputWriter.append(System.lineSeparator())
isFirstLine = false
outputWriter.append(line)
} else {
yield()
}
ensureActive()
} while (process.isAlive || line != null)
}
}

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

Flush the output writer to prevent data loss.

The outputWriter is never flushed in consumeProcessOutput, which can result in buffered output being lost, especially during streaming scenarios where partial output needs to be visible immediately.

Apply this diff to flush the writer after each line:

                 if (Strings.isNotEmpty(line)) {
                     if (!isFirstLine) outputWriter.append(System.lineSeparator())
                     isFirstLine = false
                     outputWriter.append(line)
+                    outputWriter.flush()
                 } else {
                     yield()
                 }
📝 Committable suggestion

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

Suggested change
private suspend fun consumeProcessOutput(
source: InputStream?,
outputWriter: Writer,
process: Process,
dispatcher: CoroutineDispatcher
) = withContext(dispatcher) {
if (source == null) return@withContext
var isFirstLine = true
BufferedReader(InputStreamReader(source, Charsets.UTF_8.name())).use { reader ->
do {
val line = reader.readLine()
if (Strings.isNotEmpty(line)) {
if (!isFirstLine) outputWriter.append(System.lineSeparator())
isFirstLine = false
outputWriter.append(line)
} else {
yield()
}
ensureActive()
} while (process.isAlive || line != null)
}
}
private suspend fun consumeProcessOutput(
source: InputStream?,
outputWriter: Writer,
process: Process,
dispatcher: CoroutineDispatcher
) = withContext(dispatcher) {
if (source == null) return@withContext
var isFirstLine = true
BufferedReader(InputStreamReader(source, Charsets.UTF_8.name())).use { reader ->
do {
val line = reader.readLine()
if (Strings.isNotEmpty(line)) {
if (!isFirstLine) outputWriter.append(System.lineSeparator())
isFirstLine = false
outputWriter.append(line)
outputWriter.flush()
} else {
yield()
}
ensureActive()
} while (process.isAlive || line != null)
}
}
🤖 Prompt for AI Agents
In
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/services/IdeaShellExecutor.kt
around lines 131 to 153, the outputWriter isn't flushed which can cause buffered
data loss; after appending each line (after writing the line and any line
separator) call outputWriter.flush() so partial output is emitted promptly,
keeping the flush inside the same withContext block and after the append
operations (i.e., flush every time you append a line).

Comment on lines +17 to +23
private val stringWriter = StringWriter()
private var isExecuting = false

override fun write(cbuf: CharArray, off: Int, len: Int) {
stringWriter.write(cbuf, off, len)
updateUI()
}

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

Potential race condition on StringWriter access.

StringWriter is not thread-safe. write() may be called from a background thread while updateUI() reads stringWriter.toString() on the EDT via invokeLater. Consider synchronizing access or using a thread-safe buffer.

 class IdeaUIWriter(
     private val onTextUpdate: (String, Boolean) -> Unit,
     private val onStateUpdate: (IdeaTerminalExecutionState, String?) -> Unit
 ) : Writer() {
     private val stringWriter = StringWriter()
     private var isExecuting = false
+    private val lock = Any()

-    override fun write(cbuf: CharArray, off: Int, len: Int) {
-        stringWriter.write(cbuf, off, len)
-        updateUI()
+    override fun write(cbuf: CharArray, off: Int, len: Int) {
+        synchronized(lock) {
+            stringWriter.write(cbuf, off, len)
+        }
+        updateUI()
     }

And similarly guard updateUI():

private fun updateUI() {
    val currentText = synchronized(lock) { stringWriter.toString() }
    ApplicationManager.getApplication().invokeLater {
        onTextUpdate(currentText, !isExecuting)
    }
}
🤖 Prompt for AI Agents
In mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/services/IdeaUIWriter.kt
around lines 17 to 23, StringWriter is accessed from multiple threads causing a
race; make access thread-safe by adding a private final lock object and
synchronizing all reads and writes to stringWriter (and reads of isExecuting) on
that lock, ensure write() wraps stringWriter.write(...) and any isExecuting
updates in synchronized(lock), and change updateUI() to capture a snapshot of
stringWriter.toString() and the current isExecuting flag inside
synchronized(lock) then call ApplicationManager.getApplication().invokeLater
with the captured values so the EDT only reads immutable local data.

- Full width layout instead of max 700dp
- Scrollable output area with 4 lines visible (~120dp)
- Auto-scroll to bottom when output changes
- Remove execute/re-run functionality (display only)
- Remove IdeaShellExecutor and IdeaUIWriter services
- Simplified header with command, status badge, and copy button
@phodal

phodal commented Nov 30, 2025

Copy link
Copy Markdown
Member Author

augment review

@augmentcode augmentcode Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review completed. 1 suggestion posted.

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

expanded = expanded,
onExpandToggle = { expanded = !expanded },
onCopy = {
val clipboard = Toolkit.getDefaultToolkit().systemClipboard

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Consider using IntelliJ's CopyPasteManager for clipboard operations instead of AWT Toolkit to better align with platform APIs and avoid potential issues in sandboxed/remote contexts; this also helps ensure EDT-safe interactions (also applies to other clipboard usages in this PR). (Guideline: edt_violations)

🤖 Was this useful? React with 👍 or 👎

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt (1)

213-234: Stale closure: isProcessing captured in factory won't update.

The factory lambda in SwingPanel executes only once. The isProcessing parameter captured in the IdeaInputListener callback (line 219) will always hold its initial value and won't reflect state changes during recomposition.

This means the guard !isProcessing may allow submissions while already processing.

Consider using rememberUpdatedState to keep a stable reference that always points to the current value:

+    val currentIsProcessing by rememberUpdatedState(isProcessing)
+    val currentOnSend by rememberUpdatedState(onSend)
+
     // DevIn Editor via SwingPanel
     SwingPanel(
         ...
         factory = {
             val input = IdeaDevInInput(...).apply {
                 addInputListener(object : IdeaInputListener {
                     ...
                     override fun onSubmit(text: String, trigger: IdeaInputTrigger) {
-                        if (text.isNotBlank() && !isProcessing) {
-                            onSend(text)
+                        if (text.isNotBlank() && !currentIsProcessing) {
+                            currentOnSend(text)
                             ...
                         }
                     }
                     ...
                 })
             }
             ...
         },
🧹 Nitpick comments (4)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt (2)

88-99: DisposableEffect cleanup logic appears inverted.

The onDispose block runs when the effect key (currentAgentType) changes or when leaving composition. At that point, currentAgentType already holds the new value, so the conditions currentAgentType != AgentType.CODE_REVIEW will be evaluated against the new tab, not the previous one.

This means if you switch from CODE_REVIEW to CODING, currentAgentType is now CODING, the condition currentAgentType != AgentType.CODE_REVIEW is true, and the ViewModel gets disposed - which is correct. However, if you switch from CODING to CODE_REVIEW, currentAgentType is CODE_REVIEW, the condition is false, and nothing is disposed - also correct.

The logic works but is confusing. Consider using rememberUpdatedState or restructuring to make intent clearer:

-    // Dispose ViewModels when leaving their tabs
-    DisposableEffect(currentAgentType) {
-        onDispose {
-            if (currentAgentType != AgentType.CODE_REVIEW) {
-                codeReviewViewModel?.dispose()
-                codeReviewViewModel = null
-            }
-            if (currentAgentType != AgentType.KNOWLEDGE) {
-                knowledgeViewModel?.dispose()
-                knowledgeViewModel = null
-            }
-        }
-    }
+    // Dispose ViewModels when switching away from their tabs
+    val previousAgentType = remember { mutableStateOf(currentAgentType) }
+    LaunchedEffect(currentAgentType) {
+        val previous = previousAgentType.value
+        if (previous == AgentType.CODE_REVIEW && currentAgentType != AgentType.CODE_REVIEW) {
+            codeReviewViewModel?.dispose()
+            codeReviewViewModel = null
+        }
+        if (previous == AgentType.KNOWLEDGE && currentAgentType != AgentType.KNOWLEDGE) {
+            knowledgeViewModel?.dispose()
+            knowledgeViewModel = null
+        }
+        previousAgentType.value = currentAgentType
+    }

154-154: Reminder: Address TODO for token counting integration.

The token counting integration from the renderer is marked as TODO. This feature would provide useful feedback to users about their prompt size.

Would you like me to help implement the token counting integration, or should I open an issue to track this task?

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

78-78: Replace hardcoded color with design system token.

Line 78 uses a hardcoded Color(0xFF1E1E1E) while the rest of the component correctly uses AutoDevColors. This breaks consistency with the design system.

-                        .background(Color(0xFF1E1E1E))
+                        .background(AutoDevColors.Neutral.c950)

If c950 doesn't exist in the palette, consider using AutoDevColors.Neutral.c900 or defining a semantic token for terminal backgrounds. Based on learnings, use AutoDevColors from cc.unitmesh.devins.ui.compose.theme for Compose Desktop.


44-46: Auto-scroll may target 0 on initial composition.

scrollState.maxValue is 0 before the content is laid out. On initial render, this will scroll to position 0 (no-op). This is generally acceptable since the effect re-triggers when item.output changes, but it means the initial display won't auto-scroll to bottom if content exceeds the viewport.

Consider adding a small delay or using snapshotFlow to wait for layout:

     LaunchedEffect(item.output) {
-        scrollState.animateScrollTo(scrollState.maxValue)
+        // Small yield to allow layout to complete
+        kotlinx.coroutines.yield()
+        if (scrollState.maxValue > 0) {
+            scrollState.animateScrollTo(scrollState.maxValue)
+        }
     }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fc681c1 and 5fb1d1e.

📒 Files selected for processing (3)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt (7 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTerminalOutputBubble.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTimelineContent.kt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.kt

📄 CodeRabbit inference engine (AGENTS.md)

Use expect/actual for platform-specific code in KMP projects (e.g., file I/O on JVM/JS/Wasm)

Files:

  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTerminalOutputBubble.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTimelineContent.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt
🧠 Learnings (1)
📚 Learning: 2025-11-30T02:30:49.805Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-11-30T02:30:49.805Z
Learning: Applies to **/src/{androidMain,desktopMain}/**/*.kt : For 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/toolwindow/IdeaAgentApp.kt
🧬 Code graph analysis (1)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt (3)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/header/IdeaAgentTabsHeader.kt (1)
  • IdeaAgentTabsHeader (24-73)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTimelineContent.kt (2)
  • IdeaTimelineContent (20-48)
  • IdeaEmptyStateMessage (80-94)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/status/IdeaToolLoadingStatusBar.kt (1)
  • IdeaToolLoadingStatusBar (23-83)
🔇 Additional comments (7)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/IdeaAgentApp.kt (1)

107-128: Clean component extraction - LGTM!

The refactoring successfully delegates to the extracted components (IdeaAgentTabsHeader, IdeaTimelineContent, IdeaEmptyStateMessage). The main UI wiring is now concise and readable, following the mpp-ui alignment goal.

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

62-65: AWT clipboard usage is appropriate for this IntelliJ-specific module.

Since this file is in mpp-idea (the IntelliJ plugin module), using java.awt.Toolkit for clipboard access is correct. The coding guideline about expect/actual for platform-specific code applies to shared KMP modules, not platform-specific implementations like this.


112-194: Well-structured header component with proper separation of concerns.

The TerminalHeader composable cleanly encapsulates the header logic with expand/collapse toggle, command display, status badge, and copy action. The use of MutableInteractionSource with indication = null for a clean clickable area is appropriate.


199-231: Clean status badge implementation.

The destructuring pattern for (bgColor, textColor, text) based on exit code is readable and maintainable. Proper use of AutoDevColors for semantic coloring (green for success, red for failure).

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

20-48: Clean timeline container implementation - LGTM!

The IdeaTimelineContent composable properly handles:

  • Empty state with a friendly message
  • Keyed items for efficient recomposition
  • Streaming output appended at the end
  • Consistent spacing and padding

The structure aligns well with the mpp-ui AgentMessageList pattern as noted in the documentation.


80-94: Simple and effective empty state component.

The IdeaEmptyStateMessage uses proper centering and Jewel theming. Consider whether this should accept additional parameters (like an icon) for future flexibility, but for now this is sufficient.


54-75: The when expression is already exhaustive and covers all TimelineItem variants.

All five variants of the JewelRenderer.TimelineItem sealed class are handled: MessageItem, ToolCallItem, ErrorItem, TaskCompleteItem, and TerminalOutputItem. No additional variants exist, and Kotlin's exhaustiveness checking ensures this will be enforced at compile time if new variants are added in the future.

- Replace '+' with '✓' checkmark in IdeaToolLoadingStatusBar
- Use IntelliJ CopyPasteManager instead of AWT Toolkit for clipboard
- Add RoundedCornerShape to IdeaTaskCompleteBubble background
- Simplify formatToolOutput to avoid breaking valid JSON/tables

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (4)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTaskCompleteBubble.kt (2)

27-61: Previous issue resolved; consider extracting magic numbers for consistency.

The rounded corner shape issue from the previous review has been correctly addressed. The component now renders properly with rounded corners.

As an optional improvement, consider extracting the hard-coded alpha and spacing values as constants to improve maintainability and ensure consistency across the timeline components:

+private const val BUBBLE_ALPHA = 0.2f
+private val BUBBLE_CORNER_RADIUS = 16.dp
+private val BUBBLE_HORIZONTAL_PADDING = 16.dp
+private val BUBBLE_VERTICAL_PADDING = 8.dp
+private val CONTENT_SPACING = 6.dp
+private val ICON_SIZE = 16.dp
+
 @Composable
 fun IdeaTaskCompleteBubble(
     item: JewelRenderer.TimelineItem.TaskCompleteItem,
     modifier: Modifier = Modifier
 ) {
     Row(
         modifier = modifier.fillMaxWidth(),
         horizontalArrangement = Arrangement.Center
     ) {
         Box(
             modifier = Modifier
                 .background(
                     color = if (item.success)
-                        AutoDevColors.Green.c400.copy(alpha = 0.2f)
+                        AutoDevColors.Green.c400.copy(alpha = BUBBLE_ALPHA)
                     else
-                        AutoDevColors.Red.c400.copy(alpha = 0.2f),
+                        AutoDevColors.Red.c400.copy(alpha = BUBBLE_ALPHA),
-                    shape = RoundedCornerShape(16.dp)
+                    shape = RoundedCornerShape(BUBBLE_CORNER_RADIUS)
                 )
-                .padding(horizontal = 16.dp, vertical = 8.dp)
+                .padding(horizontal = BUBBLE_HORIZONTAL_PADDING, vertical = BUBBLE_VERTICAL_PADDING)
         ) {
             Row(
-                horizontalArrangement = Arrangement.spacedBy(6.dp),
+                horizontalArrangement = Arrangement.spacedBy(CONTENT_SPACING),
                 verticalAlignment = Alignment.CenterVertically
             ) {
                 Icon(
                     imageVector = if (item.success) IdeaComposeIcons.CheckCircle else IdeaComposeIcons.Error,
                     contentDescription = if (item.success) "Success" else "Failed",
-                    modifier = Modifier.size(16.dp),
+                    modifier = Modifier.size(ICON_SIZE),
                     tint = if (item.success) AutoDevColors.Green.c400 else AutoDevColors.Red.c400
                 )

34-50: Consider reducing conditional duplication.

The item.success check is repeated four times to derive different properties. You could optionally reduce duplication by extracting these into local variables:

val (backgroundColor, icon, iconDescription, iconTint) = if (item.success) {
    quadruple(
        AutoDevColors.Green.c400.copy(alpha = 0.2f),
        IdeaComposeIcons.CheckCircle,
        "Success",
        AutoDevColors.Green.c400
    )
} else {
    quadruple(
        AutoDevColors.Red.c400.copy(alpha = 0.2f),
        IdeaComposeIcons.Error,
        "Failed",
        AutoDevColors.Red.c400
    )
}

Or more simply with individual val statements:

val isSuccess = item.success
val backgroundColor = if (isSuccess) 
    AutoDevColors.Green.c400.copy(alpha = 0.2f) 
else 
    AutoDevColors.Red.c400.copy(alpha = 0.2f)
val icon = if (isSuccess) IdeaComposeIcons.CheckCircle else IdeaComposeIcons.Error
val iconDescription = if (isSuccess) "Success" else "Failed"
val iconTint = if (isSuccess) AutoDevColors.Green.c400 else AutoDevColors.Red.c400

This would make the composable body more declarative and easier to scan.

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

112-114: Refactor: avoid sentinel value for loading state.

Using -1 as a sentinel for "loading" (line 53 passes -1 when isLoading is true) is a code smell. Since isLoading is already a parameter, use it directly to decide the display:

-    val totalDisplay = if (total < 0) "..." else total.toString()
+    val totalDisplay = if (isLoading) "..." else total.toString()
     Text(
         text = "$label ($count/$totalDisplay)",

Then at line 53, pass the actual total instead of -1:

         IdeaToolStatusChip(
             label = "MCP Tools",
             count = toolStatus.mcpToolsEnabled,
-            total = if (toolStatus.isLoading) -1 else toolStatus.mcpToolsTotal,
+            total = toolStatus.mcpToolsTotal,
             isLoading = toolStatus.isLoading,
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTerminalOutputBubble.kt (1)

43-46: Consider using scrollTo instead of animateScrollTo for large outputs

For very long or frequently updating outputs, animating every auto-scroll can introduce jank. A snap scroll is cheaper and still keeps the view pinned to the bottom:

-    LaunchedEffect(item.output) {
-        scrollState.animateScrollTo(scrollState.maxValue)
-    }
+    LaunchedEffect(item.output) {
+        scrollState.scrollTo(scrollState.maxValue)
+    }

You can keep the animation if you prefer the affordance, but this is a small perf win when terminal output is large.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5fb1d1e and 0340be0.

📒 Files selected for processing (4)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/status/IdeaToolLoadingStatusBar.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTaskCompleteBubble.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTerminalOutputBubble.kt (1 hunks)
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaToolCallBubble.kt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.kt

📄 CodeRabbit inference engine (AGENTS.md)

Use expect/actual for platform-specific code in KMP projects (e.g., file I/O on JVM/JS/Wasm)

Files:

  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTaskCompleteBubble.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/status/IdeaToolLoadingStatusBar.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTerminalOutputBubble.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaToolCallBubble.kt
🧠 Learnings (1)
📚 Learning: 2025-11-30T02:30:49.805Z
Learnt from: CR
Repo: phodal/auto-dev-sketch PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-11-30T02:30:49.805Z
Learning: Applies to **/src/{androidMain,desktopMain}/**/*.kt : For 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/toolwindow/timeline/IdeaTaskCompleteBubble.kt
  • mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/status/IdeaToolLoadingStatusBar.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). (2)
  • GitHub Check: Build (223)
  • GitHub Check: Build (241)
🔇 Additional comments (7)
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaTaskCompleteBubble.kt (2)

1-16: LGTM! Imports and package structure are correct.

The imports properly reference the design system (AutoDevColors) and Jewel theme components as per the project's coding guidelines.


18-26: LGTM! Well-documented composable with proper signature.

The documentation clearly explains the component's purpose and its relationship to the mpp-ui pattern.

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

20-83: Good: proper use of AutoDevColors and design system.

The status bar correctly uses AutoDevColors for semantic colors (Blue for SubAgents, Green for success states) and JewelTheme.globalColors for theme-consistent UI elements, aligning with project design standards.

Based on learnings, AutoDevColors should be used for Compose Desktop/Android components.

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

40-294: LGTM with well-designed UX!

The component handles expand/collapse, status indicators, copy-to-clipboard, and execution time display effectively. The auto-expand on error (line 46, 48) and truncation logic for params/output provide good UX.


300-364: Simple and effective executing indicator.

The component provides a clear visual indicator for currently executing tools with the "EXECUTING" badge and appropriate styling.


369-375: Correct use of IntelliJ platform API.

The function properly uses CopyPasteManager for clipboard operations, which is the recommended approach for IntelliJ plugins and avoids potential issues with AWT Toolkit in sandboxed or remote contexts.

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

35-230: Well-factored terminal bubble; header/status/copy UX looks solid

The composable structure (header + animated, scrollable body), status badge, and use of Jewel/AutoDevColors + CopyPasteManager are cohesive and align well with the described mpp‑idea patterns. No functional issues stand out in this file.

Comment on lines +28 to +31
val mcpPreloadingMessage by viewModel.mcpPreloadingMessage.collectAsState()
val mcpPreloadingStatus by viewModel.mcpPreloadingStatus.collectAsState()
// Recompute when preloading status changes to make it reactive
val toolStatus = remember(mcpPreloadingStatus) { viewModel.getToolLoadingStatus() }

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

Fix reactivity issue: tool status may not update.

The remember(mcpPreloadingStatus) call only recomputes when mcpPreloadingStatus changes. If getToolLoadingStatus() internally reads from other StateFlows (e.g., tool counts, server states), those changes won't trigger recomposition, leaving toolStatus stale.

Solution: Expose tool loading status as a StateFlow from the ViewModel and collect it here:

-    val mcpPreloadingStatus by viewModel.mcpPreloadingStatus.collectAsState()
-    // Recompute when preloading status changes to make it reactive
-    val toolStatus = remember(mcpPreloadingStatus) { viewModel.getToolLoadingStatus() }
+    val toolStatus by viewModel.toolLoadingStatus.collectAsState()

Then in IdeaAgentViewModel, add:

val toolLoadingStatus: StateFlow<ToolLoadingStatus> = combine(
    mcpPreloadingStatus,
    // Add other relevant StateFlows here
) { ... ->
    getToolLoadingStatus()
}.stateIn(viewModelScope, SharingStarted.Lazily, getToolLoadingStatus())
🤖 Prompt for AI Agents
In
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/status/IdeaToolLoadingStatusBar.kt
around lines 28-31, toolStatus is derived via remember(mcpPreloadingStatus) {
viewModel.getToolLoadingStatus() } which only updates when mcpPreloadingStatus
changes and can become stale if getToolLoadingStatus() depends on other
StateFlows; instead expose a StateFlow<ToolLoadingStatus> from the ViewModel
(e.g., toolLoadingStatus) that combines all relevant StateFlows
(mcpPreloadingStatus plus tool counts, server states, etc.) and use
collectAsState() here to drive UI recomposition so toolStatus updates reactively
whenever any underlying state changes.

Comment on lines +381 to +388
private fun formatToolOutput(output: String): String {
return when {
output.contains("|") -> output // Table format
output.contains("\n") -> output // Already formatted
output.length > 100 -> "${output.take(100)}..." // Truncate long single-line output
else -> output
}
}

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

Consider removing the truncation in formatToolOutput.

The function truncates single-line output to 100 characters at line 385, but displayOutput (line 57) already handles truncation to 200 characters. This creates double truncation: when showFullOutput is false, users see only 100 characters instead of the intended 200 for single-line output without newlines or pipes.

Apply this diff to remove the redundant truncation:

 private fun formatToolOutput(output: String): String {
     return when {
         output.contains("|") -> output // Table format
         output.contains("\n") -> output // Already formatted
-        output.length > 100 -> "${output.take(100)}..." // Truncate long single-line output
         else -> output
     }
 }
🤖 Prompt for AI Agents
In
mpp-idea/src/main/kotlin/cc/unitmesh/devins/idea/toolwindow/timeline/IdeaToolCallBubble.kt
around lines 381 to 388, the formatToolOutput function applies an extra
truncation for single-line outputs (output.length > 100) which conflicts with
displayOutput's 200-char truncation; remove the redundant truncation branch so
the function only returns the original output for single-line, non-table cases
(keep the checks for '|' and '\n' but delete the length > 100 case), ensuring
single-line outputs are no longer shortened to 100 chars.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant