Skip to content

feat(desktop): group assistant turns in chat with a collapsible step view - #5056

Closed
giovannivarela wants to merge 2 commits into
ParadevAI:mainfrom
giovannivarela:feat/desktop-chat-turn-grouping
Closed

giovannivarela wants to merge 2 commits into
ParadevAI:mainfrom
giovannivarela:feat/desktop-chat-turn-grouping

Conversation

@giovannivarela

@giovannivarela giovannivarela commented Jun 2, 2026 •

Copy link
Copy Markdown

Description

Renders an assistant turn as a single collapsible group instead of a flat
stream of parts. The header summarises the turn ("3 tool calls · 1 subagent ·
1 message") with a status dot and timestamp, and the final answer stays visible
even when the intermediate steps are collapsed.

  • AssistantTurnGroup — a collapsible turn card (header + steps + always-visible
    final answer). A finished turn collapses to its summary + answer; live, errored,
    or approval-pending turns stay open. Open state is controlled so a turn that
    streamed in open auto-collapses when it finishes (manual toggles are respected).
  • summarizeAssistantTurn / formatTurnSummary (unit-tested) count
    reasoning/tool/subagent/message parts and derive turn status from tool errors
    and the message stopReason/errorMessage.
  • Intermediate text and thinking render as collapsible item rows (TurnTextItem),
    reusing ToolCallRow for visual consistency.
  • Subagent card — a contained card with a TASK badge, the sub-agent model +
    run duration (parsed from <subagent-meta>), and an "Execution Trace · N tool
    calls" of its inner tools.
  • Required actions stay visible — a pending plan approval renders outside the
    collapsible group (with an amber "awaiting approval" header indicator), so
    collapsing a turn can never hide an action the user must take.
  • Status is exposed as screen-reader text alongside the dot; the assistant is
    labelled generically (works for any provider).

Applied to both the v2-workspace and legacy chat panes. Pure render-layer change —
reuses the existing per-tool ToolCallBlock viewers, no backend or data changes.

Related Issues

Closes #5188

Type of Change

  • New feature

Testing

  • bun test across the chat area (64 tests, incl. new unit + render tests) — pass
  • bun run typecheck (desktop + ui) — pass
  • bun run lint — pass
  • Manually verified in the desktop app: turn grouping/collapse, final-answer
    visibility while collapsed, subagent Execution Trace, error/streaming status
    states, and the pending-approval-stays-visible behaviour.

Screenshots

1. Completed turn — collapses to a one-line summary + the final answer
Captura de Tela 2026-06-02 às 18 10 42

2. Expanded — intermediate steps render as item rows (reasoning · output · tools)
Captura de Tela 2026-06-02 às 18 11 38

3. Subagent card — TASK badge, model · duration, and the Execution Trace
Captura de Tela 2026-06-02 às 18 12 05

4. Pending plan approval — rendered outside the group with an amber status
Captura de Tela 2026-06-02 às 18 12 37

5. …and it stays visible when the turn is collapsed (required action is never hidden)
Captura de Tela 2026-06-02 às 18 12 53

Additional Notes

Token/cost metrics are intentionally omitted — they are not available client-side
without exposing per-message usage from the harness, so nothing here relies on
estimated values.

…view

Render an assistant turn as a single collapsible group instead of a flat
stream of parts. The header summarises the turn ("3 tool calls · 1 subagent
· 1 message") with a status dot and timestamp, and the final answer stays
visible even when the intermediate steps are collapsed.

- Add AssistantTurnGroup: a collapsible turn card (header + steps + always-
  visible final answer). A finished turn collapses to its summary + answer;
  live, errored, or approval-pending turns stay open so nothing is hidden.
- Add summarizeAssistantTurn/formatTurnSummary helpers (unit-tested) that
  count reasoning/tool/subagent/message parts and derive turn status from
  tool errors and the message stopReason/errorMessage.
- Render intermediate text and thinking as collapsible item rows
  (TurnTextItem), reusing ToolCallRow for visual consistency.
- Subagent card: add a TASK badge, an "Execution Trace · N tool calls"
  header, and surface the subagent model + run duration already parsed
  from the <subagent-meta> tag.

Applied to both the v2-workspace and legacy chat panes. Pure render-layer
change — reuses the existing per-tool ToolCallBlock viewers, no backend or
data changes.
@capy-ai

capy-ai Bot commented Jun 2, 2026

Copy link
Copy Markdown

Capy auto-review is paused for this organization because the monthly auto-review limit has been reached. Increase the limit or turn it off in billing settings to resume automatic reviews.

@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR adds turn-summary types and helpers, implements summarizeAssistantTurn/formatTurnSummary with tests, introduces AssistantTurnGroup and TurnTextItem UI components, enhances SubagentToolCall headers/duration display, and integrates turn-based grouping into two AssistantMessage renderers splitting collapsible steps from always-visible final output.

Changes

Assistant Turn Grouping Feature

Layer / File(s) Summary
Turn summary contracts and barrel export
apps/desktop/src/renderer/components/Chat/ChatInterface/utils/group-assistant-turn/group-assistant-turn.ts, .../index.ts
Defines TurnStatus and AssistantTurnSummary and adds a barrel export.
Turn summarization implementation
apps/desktop/src/renderer/components/Chat/ChatInterface/utils/group-assistant-turn/group-assistant-turn.ts
Implements summarizeAssistantTurn() to compute thinking/tool/subagent/output/image counts, fold tool_result into tool_call counts, derive status, set lastTextIndex and hasSteps; adds formatTurnSummary() for one-line summaries.
Turn summarization unit tests
apps/desktop/src/renderer/components/Chat/ChatInterface/utils/group-assistant-turn/group-assistant-turn.test.ts
Tests counting, deduplication, subagent separation, status derivation for errors/streaming, hasSteps/lastTextIndex behavior, and formatted summary output.
AssistantTurnGroup component and tests
apps/desktop/src/renderer/components/Chat/ChatInterface/components/AssistantTurnGroup/AssistantTurnGroup.tsx, .../index.ts, .../AssistantTurnGroup.test.tsx
Adds a collapsible AssistantTurnGroup with status-dot styling/labels, formatClock, controlled open state reset behavior, renders steps inside collapsible content and lastOutput always visible; tests verify collapsed final output, status-dot variants, pendingAction amber state, and step visibility.
TurnTextItem component and export
apps/desktop/src/renderer/components/Chat/ChatInterface/components/TurnTextItem/TurnTextItem.tsx, .../index.ts
New component rendering intermediate thinking/output rows with preview; supports static thinking blocks and streaming text rendering with a fixed Mermaid theme.
SubagentToolCall header and duration
apps/desktop/src/renderer/components/Chat/ChatInterface/components/ToolCallBlock/components/SubagentToolCall/SubagentToolCall.tsx
Imports TerminalIcon, adds formatDuration(ms) with validation and human-readable units, updates header to show Task badge + Agent title, computes headerExtra with modelId and duration, and inserts an Execution Trace row.
AssistantMessage integration (v2-workspace)
apps/desktop/src/renderer/routes/.../AssistantMessage/AssistantMessage.tsx
Refactors rendering to compute turnSummary, split content into stepNodes/lastOutputNodes/pendingActionNodes, route parts into collapsible steps or final output, and render AssistantTurnGroup or fragment/shimmer based on state.
AssistantMessage integration (main workspace)
apps/desktop/src/renderer/screens/.../AssistantMessage/AssistantMessage.tsx
Parallel refactor in main workspace mirroring v2-workspace integration: turnSummary-driven splitting and conditional AssistantTurnGroup rendering, with pending actions rendered outside the collapsible body.

Sequence Diagram(s)

sequenceDiagram
  participant Renderer as AssistantMessage Renderer
  participant Summarizer as summarizeAssistantTurn
  participant Grouper as AssistantTurnGroup
  participant StepUI as TurnTextItem/ToolCallBlock
  Renderer->>Summarizer: analyze message parts
  Summarizer-->>Renderer: AssistantTurnSummary (counts, status, lastTextIndex)
  Renderer->>Renderer: split into stepNodes + lastOutputNodes + pendingActionNodes
  Renderer->>Grouper: pass summary, status, steps, lastOutput, defaultOpen
  Grouper->>StepUI: render steps (thinking, outputs, tool calls)
  Grouper-->>Renderer: collapsible group UI with always-visible final output
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A rabbit hops through code so fine,
Steps fold away and final answers shine,
Summaries count, the status dot gleams,
Grouped turns whisper structured dreams,
Hooray — the UI hops in neat streams!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The pull request title clearly and specifically describes the main change: grouping assistant turns in chat with collapsible step views, which is the primary focus of the entire changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The pull request description is comprehensive and detailed, following the template structure with all major sections completed.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@ghost

ghost commented Jun 2, 2026 •

Copy link
Copy Markdown

Ready to review this PR? Stage has broken it down into 5 individual chapters for you:

Title
1 Implement assistant turn summarization logic
2 Create collapsible turn group and text item components
3 Enhance subagent tool call visualization
4 Integrate turn grouping into v2 workspace chat
5 Integrate turn grouping into legacy chat pane
Open in Stage

Chapters generated by Stage for commit 227063b on Jun 2, 2026 8:43pm UTC.

@greptile-apps

greptile-apps Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR introduces turn-level grouping for assistant messages, bundling intermediate tool calls, thinking blocks, and narration into a single collapsible card (AssistantTurnGroup) while keeping the final answer always visible. The summarizeAssistantTurn / formatTurnSummary helpers compute the one-line header label and overall turn status; TurnTextItem wraps intermediate text as ToolCallRow-style items; and SubagentToolCall gains a TASK badge, model/duration metadata, and an Execution Trace header.

  • PendingPlanApprovalMessage is placed inside stepNodes (via getInlineToolStateNodes), which lives inside the collapsible content. A user who manually collapses the group loses sight of a required approve/reject action with no indicator that anything is waiting — this is a regression from the previous flat render.
  • AssistantTurnGroup uses defaultOpen (Radix uncontrolled), so turns that stream in open do not auto-collapse when streaming ends; and the status dot correctly distinguishes in-progress / error / complete but shows green even when plan approval is pending.
  • summarizeAssistantTurn is called unconditionally on every render without useMemo, re-scanning all parts each cycle.

Confidence Score: 3/5

Not safe to merge as-is: the plan-approval card can be hidden by collapsing the turn group, blocking a required user action with no visual indicator.

The plan-approval message (PendingPlanApprovalMessage) is now placed inside the collapsible step list rather than outside it. Because defaultOpen is an uncontrolled initial value, a user who manually collapses the group will see a green "complete" dot and no indication that a plan is waiting for approval — the approve/reject controls are simply gone. This is a behaviour regression from the flat render this PR replaces. The remainder of the changes — the grouping helpers, TurnTextItem, SubagentToolCall enhancements, and tests — are solid; the issue is narrowly scoped to how inline tool-state nodes are routed.

Both AssistantMessage.tsx files (v2-workspace and legacy pane) where getInlineToolStateNodes routes PendingPlanApprovalMessage into stepNodes.

Important Files Changed

Filename Overview
apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/WorkspaceChatInterface/components/ChatMessageList/components/AssistantMessage/AssistantMessage.tsx Major rework: parts routed into stepNodes/lastOutputNodes for turn grouping; PendingPlanApprovalMessage ends up inside collapsible stepNodes where it can be hidden, and summarizeAssistantTurn is un-memoized.
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/ChatPane/ChatPaneInterface/components/ChatMessageList/components/AssistantMessage/AssistantMessage.tsx Legacy pane counterpart with identical changes and the same plan-approval visibility and memoization issues.
apps/desktop/src/renderer/components/Chat/ChatInterface/utils/group-assistant-turn/group-assistant-turn.ts New utility: summarizes turn parts into counts and status; imageCount is tracked but excluded from hasSteps, creating an inconsistency with formatTurnSummary.
apps/desktop/src/renderer/components/Chat/ChatInterface/components/AssistantTurnGroup/AssistantTurnGroup.tsx New collapsible turn-group card; uses uncontrolled defaultOpen so streaming→complete transitions don't auto-collapse; status dot shows green even when plan approval is pending.
apps/desktop/src/renderer/components/Chat/ChatInterface/components/ToolCallBlock/components/SubagentToolCall/SubagentToolCall.tsx Adds TASK badge, model+duration meta bits, and Execution Trace header to subagent cards; formatDuration handles all edge cases correctly.
apps/desktop/src/renderer/components/Chat/ChatInterface/components/TurnTextItem/TurnTextItem.tsx New component rendering intermediate text and thinking as ToolCallRow items; clean and straightforward.
apps/desktop/src/renderer/components/Chat/ChatInterface/utils/group-assistant-turn/group-assistant-turn.test.ts Good unit coverage for summarizeAssistantTurn and formatTurnSummary, including deduplication, subagent splitting, error/streaming status, and pluralization.
apps/desktop/src/renderer/components/Chat/ChatInterface/components/AssistantTurnGroup/AssistantTurnGroup.test.tsx Render tests verify lastOutput visibility when collapsed, status-dot class names, and step content when open; adequate coverage for the component's key contracts.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["message.content parts"] --> B["summarizeAssistantTurn()\n(pre-pass: counts + lastTextIndex)"]
    B --> C{hasSteps?}
    B --> D["turnSummary.lastTextIndex"]

    A --> E["Render loop (partIndex 0..n)"]
    D --> E

    E --> F{part.type}
    F -->|text & partIndex == lastTextIndex| G["lastOutputNodes\n(always visible)"]
    F -->|text & intermediate| H["stepNodes ← TurnTextItem kind=output"]
    F -->|thinking| I["stepNodes ← TurnTextItem kind=thinking"]
    F -->|tool_call / tool_result| J["stepNodes ← ToolCallBlock"]
    F -->|image / file| K["stepNodes ← ImageHoverPreview / AttachmentChip"]
    J --> L["getInlineToolStateNodes()\n⚠ PendingPlanApprovalMessage → stepNodes"]

    C -->|true| M["AssistantTurnGroup\nsteps=stepNodes\nlastOutput=lastOutputNodes"]
    C -->|false| N["Plain render: stepNodes + lastOutputNodes"]

    M --> O["Collapsible (defaultOpen)"]
    O -->|open| P["steps visible"]
    O -->|collapsed| Q["steps hidden ⚠\nincl. PendingPlanApprovalMessage"]
    M --> R["lastOutput always visible"]
Loading

Comments Outside Diff (2)

  1. apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/WorkspaceChatInterface/components/ChatMessageList/components/AssistantMessage/AssistantMessage.tsx, line 150-173 (link)

    P1 Plan-approval UI hidden inside collapsible steps

    PendingPlanApprovalMessage is pushed into stepNodes via getInlineToolStateNodes, which means it lives inside the CollapsibleContent of AssistantTurnGroup. defaultOpen is set to true when pendingPlanApproval is truthy, but defaultOpen is an uncontrolled initial value — once the user collapses the group (e.g., accidentally clicking the header), the approval card disappears with no visual indicator that required action is pending. The status dot also shows green (complete), signalling "done" while the turn is actually waiting for user input. The approval message should be placed in lastOutputNodes (outside the collapsible) so it is always visible alongside the plan text, matching the behaviour of the previous flat render.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/WorkspaceChatInterface/components/ChatMessageList/components/AssistantMessage/AssistantMessage.tsx
    Line: 150-173
    
    Comment:
    **Plan-approval UI hidden inside collapsible steps**
    
    `PendingPlanApprovalMessage` is pushed into `stepNodes` via `getInlineToolStateNodes`, which means it lives inside the `CollapsibleContent` of `AssistantTurnGroup`. `defaultOpen` is set to `true` when `pendingPlanApproval` is truthy, but `defaultOpen` is an uncontrolled initial value — once the user collapses the group (e.g., accidentally clicking the header), the approval card disappears with no visual indicator that required action is pending. The status dot also shows green (`complete`), signalling "done" while the turn is actually waiting for user input. The approval message should be placed in `lastOutputNodes` (outside the collapsible) so it is always visible alongside the plan text, matching the behaviour of the previous flat render.
    
    How can I resolve this? If you propose a fix, please make it concise.

    Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

  2. apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/ChatPane/ChatPaneInterface/components/ChatMessageList/components/AssistantMessage/AssistantMessage.tsx, line 150-173 (link)

    P1 Plan-approval UI hidden inside collapsible steps (legacy pane)

    Same issue as in the v2-workspace AssistantMessage: PendingPlanApprovalMessage is pushed into stepNodes via getInlineToolStateNodes and therefore lives inside the CollapsibleContent. Once a user collapses the group, the approval card is hidden with no indication that input is required. The message should be routed to lastOutputNodes so it stays visible regardless of collapse state.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/ChatPane/ChatPaneInterface/components/ChatMessageList/components/AssistantMessage/AssistantMessage.tsx
    Line: 150-173
    
    Comment:
    **Plan-approval UI hidden inside collapsible steps (legacy pane)**
    
    Same issue as in the v2-workspace `AssistantMessage`: `PendingPlanApprovalMessage` is pushed into `stepNodes` via `getInlineToolStateNodes` and therefore lives inside the `CollapsibleContent`. Once a user collapses the group, the approval card is hidden with no indication that input is required. The message should be routed to `lastOutputNodes` so it stays visible regardless of collapse state.
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
Fix the following 6 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 6
apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/WorkspaceChatInterface/components/ChatMessageList/components/AssistantMessage/AssistantMessage.tsx:150-173
**Plan-approval UI hidden inside collapsible steps**

`PendingPlanApprovalMessage` is pushed into `stepNodes` via `getInlineToolStateNodes`, which means it lives inside the `CollapsibleContent` of `AssistantTurnGroup`. `defaultOpen` is set to `true` when `pendingPlanApproval` is truthy, but `defaultOpen` is an uncontrolled initial value — once the user collapses the group (e.g., accidentally clicking the header), the approval card disappears with no visual indicator that required action is pending. The status dot also shows green (`complete`), signalling "done" while the turn is actually waiting for user input. The approval message should be placed in `lastOutputNodes` (outside the collapsible) so it is always visible alongside the plan text, matching the behaviour of the previous flat render.

### Issue 2 of 6
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/ChatPane/ChatPaneInterface/components/ChatMessageList/components/AssistantMessage/AssistantMessage.tsx:150-173
**Plan-approval UI hidden inside collapsible steps (legacy pane)**

Same issue as in the v2-workspace `AssistantMessage`: `PendingPlanApprovalMessage` is pushed into `stepNodes` via `getInlineToolStateNodes` and therefore lives inside the `CollapsibleContent`. Once a user collapses the group, the approval card is hidden with no indication that input is required. The message should be routed to `lastOutputNodes` so it stays visible regardless of collapse state.

### Issue 3 of 6
apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/WorkspaceChatInterface/components/ChatMessageList/components/AssistantMessage/AssistantMessage.tsx:132-135
`summarizeAssistantTurn` iterates every part on every render with no memoization. For long agentic conversations the scan is O(n) per render cycle. Wrapping in `useMemo` keyed on `message.content`, `isStreaming`, and `errored` limits recomputation to when the message actually changes.

```suggestion
	const turnSummary = useMemo(
		() => summarizeAssistantTurn(message.content, { isStreaming, errored }),
		// eslint-disable-next-line react-hooks/exhaustive-deps
		[message.content, isStreaming, errored],
	);
```

### Issue 4 of 6
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/ChatPane/ChatPaneInterface/components/ChatMessageList/components/AssistantMessage/AssistantMessage.tsx:133-136
Same missing `useMemo` as in the v2-workspace `AssistantMessage` — `summarizeAssistantTurn` re-scans all parts on every render.

```suggestion
	const turnSummary = useMemo(
		() => summarizeAssistantTurn(message.content, { isStreaming, errored }),
		// eslint-disable-next-line react-hooks/exhaustive-deps
		[message.content, isStreaming, errored],
	);
```

### Issue 5 of 6
apps/desktop/src/renderer/components/Chat/ChatInterface/components/AssistantTurnGroup/AssistantTurnGroup.tsx:58
**`defaultOpen` is uncontrolled — live turns don't auto-collapse on completion**

`defaultOpen` is Radix UI's uncontrolled initial value: changing it on a re-render after mount has no effect. A turn that starts streaming (mounting with `defaultOpen=true`) stays open after streaming ends even though the `defaultOpen` logic now evaluates to `false`. Users must manually collapse finished turns from the current session, while turns restored from history correctly start collapsed. If the design intent is that completed turns should collapse automatically, this needs either a controlled `open` + `onOpenChange` pair with a local `useState`, or a `key` that changes when the turn transitions from live to complete to force remounting.

### Issue 6 of 6
apps/desktop/src/renderer/components/Chat/ChatInterface/utils/group-assistant-turn/group-assistant-turn.ts:117
**`imageCount` included in summary label but excluded from `hasSteps`**

`formatTurnSummary` appends "N images" when `imageCount > 0`, but `hasSteps` is `toolCount > 0 || subagentCount > 0 || thinkingCount > 0` — images are not included. For a turn whose only non-text content is images, `hasSteps` is `false`, `AssistantTurnGroup` is never rendered, and the "N images" segment from `formatTurnSummary` is silently unused. Either add `imageCount > 0` to the `hasSteps` expression, or drop the image segment from `formatTurnSummary`.

Reviews (1): Last reviewed commit: "feat(desktop): group assistant turns in ..." | Re-trigger Greptile

Comment on lines +132 to +135
const turnSummary = summarizeAssistantTurn(message.content, {
isStreaming,
errored,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 summarizeAssistantTurn iterates every part on every render with no memoization. For long agentic conversations the scan is O(n) per render cycle. Wrapping in useMemo keyed on message.content, isStreaming, and errored limits recomputation to when the message actually changes.

Suggested change
const turnSummary = summarizeAssistantTurn(message.content, {
isStreaming,
errored,
});
const turnSummary = useMemo(
() => summarizeAssistantTurn(message.content, { isStreaming, errored }),
// eslint-disable-next-line react-hooks/exhaustive-deps
[message.content, isStreaming, errored],
);
Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/WorkspaceChatInterface/components/ChatMessageList/components/AssistantMessage/AssistantMessage.tsx
Line: 132-135

Comment:
`summarizeAssistantTurn` iterates every part on every render with no memoization. For long agentic conversations the scan is O(n) per render cycle. Wrapping in `useMemo` keyed on `message.content`, `isStreaming`, and `errored` limits recomputation to when the message actually changes.

```suggestion
	const turnSummary = useMemo(
		() => summarizeAssistantTurn(message.content, { isStreaming, errored }),
		// eslint-disable-next-line react-hooks/exhaustive-deps
		[message.content, isStreaming, errored],
	);
```

How can I resolve this? If you propose a fix, please make it concise.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +133 to +136
const turnSummary = summarizeAssistantTurn(message.content, {
isStreaming,
errored,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Same missing useMemo as in the v2-workspace AssistantMessage — summarizeAssistantTurn re-scans all parts on every render.

Suggested change
const turnSummary = summarizeAssistantTurn(message.content, {
isStreaming,
errored,
});
const turnSummary = useMemo(
() => summarizeAssistantTurn(message.content, { isStreaming, errored }),
// eslint-disable-next-line react-hooks/exhaustive-deps
[message.content, isStreaming, errored],
);
Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/ChatPane/ChatPaneInterface/components/ChatMessageList/components/AssistantMessage/AssistantMessage.tsx
Line: 133-136

Comment:
Same missing `useMemo` as in the v2-workspace `AssistantMessage` — `summarizeAssistantTurn` re-scans all parts on every render.

```suggestion
	const turnSummary = useMemo(
		() => summarizeAssistantTurn(message.content, { isStreaming, errored }),
		// eslint-disable-next-line react-hooks/exhaustive-deps
		[message.content, isStreaming, errored],
	);
```

How can I resolve this? If you propose a fix, please make it concise.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

const clock = formatClock(timestamp);
return (
<div className="flex flex-col gap-1.5">
<Collapsible defaultOpen={defaultOpen} className="not-prose group/turn">

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 defaultOpen is uncontrolled — live turns don't auto-collapse on completion

defaultOpen is Radix UI's uncontrolled initial value: changing it on a re-render after mount has no effect. A turn that starts streaming (mounting with defaultOpen=true) stays open after streaming ends even though the defaultOpen logic now evaluates to false. Users must manually collapse finished turns from the current session, while turns restored from history correctly start collapsed. If the design intent is that completed turns should collapse automatically, this needs either a controlled open + onOpenChange pair with a local useState, or a key that changes when the turn transitions from live to complete to force remounting.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/renderer/components/Chat/ChatInterface/components/AssistantTurnGroup/AssistantTurnGroup.tsx
Line: 58

Comment:
**`defaultOpen` is uncontrolled — live turns don't auto-collapse on completion**

`defaultOpen` is Radix UI's uncontrolled initial value: changing it on a re-render after mount has no effect. A turn that starts streaming (mounting with `defaultOpen=true`) stays open after streaming ends even though the `defaultOpen` logic now evaluates to `false`. Users must manually collapse finished turns from the current session, while turns restored from history correctly start collapsed. If the design intent is that completed turns should collapse automatically, this needs either a controlled `open` + `onOpenChange` pair with a local `useState`, or a `key` that changes when the turn transitions from live to complete to force remounting.

How can I resolve this? If you propose a fix, please make it concise.

imageCount,
status,
lastTextIndex,
hasSteps: toolCount > 0 || subagentCount > 0 || thinkingCount > 0,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 imageCount included in summary label but excluded from hasSteps

formatTurnSummary appends "N images" when imageCount > 0, but hasSteps is toolCount > 0 || subagentCount > 0 || thinkingCount > 0 — images are not included. For a turn whose only non-text content is images, hasSteps is false, AssistantTurnGroup is never rendered, and the "N images" segment from formatTurnSummary is silently unused. Either add imageCount > 0 to the hasSteps expression, or drop the image segment from formatTurnSummary.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/renderer/components/Chat/ChatInterface/utils/group-assistant-turn/group-assistant-turn.ts
Line: 117

Comment:
**`imageCount` included in summary label but excluded from `hasSteps`**

`formatTurnSummary` appends "N images" when `imageCount > 0`, but `hasSteps` is `toolCount > 0 || subagentCount > 0 || thinkingCount > 0` — images are not included. For a turn whose only non-text content is images, `hasSteps` is `false`, `AssistantTurnGroup` is never rendered, and the "N images" segment from `formatTurnSummary` is silently unused. Either add `imageCount > 0` to the `hasSteps` expression, or drop the image segment from `formatTurnSummary`.

How can I resolve this? If you propose a fix, please make it concise.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (1)
apps/desktop/src/renderer/components/Chat/ChatInterface/utils/group-assistant-turn/group-assistant-turn.test.ts (1)

10-18: ⚡ Quick win

Stop using as never for the test fixtures.

These casts opt the suite out of validating the public input shape, so the tests can keep passing even if summarizeAssistantTurn's contract drifts. Prefer a local alias like type TurnParts = Parameters<typeof summarizeAssistantTurn>[0] and type the arrays directly.

Suggested cleanup
 import {
 	type AssistantTurnSummary,
 	formatTurnSummary,
 	summarizeAssistantTurn,
 } from "./group-assistant-turn";
+
+type TurnParts = Parameters<typeof summarizeAssistantTurn>[0];
 
 describe("summarizeAssistantTurn", () => {
 	it("counts tools, thinking, and intermediate outputs", () => {
-		const summary = summarizeAssistantTurn([
+		const parts: TurnParts = [
 			{ type: "thinking" },
 			{ type: "text" }, // intermediate narration
 			{ type: "tool_call", id: "a" },
 			{ type: "tool_result", id: "a" },
 			{ type: "tool_call", id: "b" },
 			{ type: "tool_result", id: "b" },
 			{ type: "text" }, // final answer
-		] as never);
+		];
+		const summary = summarizeAssistantTurn(parts);

As per coding guidelines, **/*.{ts,tsx}: Avoid any type unless necessary; maintain type safety in TypeScript files.

Also applies to: 29-32, 37-39, 44-49, 55-58, 64-67, 75-78, 85-85

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/desktop/src/renderer/components/Chat/ChatInterface/utils/group-assistant-turn/group-assistant-turn.test.ts`
around lines 10 - 18, Replace the unsafe "as never" casts in the test fixtures
with a proper typed alias so the test input shape is validated: add a local type
alias like TurnParts = Parameters<typeof summarizeAssistantTurn>[0] and use
TurnParts for the arrays passed to summarizeAssistantTurn (e.g., type the array
literals as TurnParts), then remove all "as never" occurrences in this file and
the other listed ranges so the compiler checks the public input contract of
summarizeAssistantTurn.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@apps/desktop/src/renderer/components/Chat/ChatInterface/components/AssistantTurnGroup/AssistantTurnGroup.tsx`:
- Around line 82-88: The status dot rendered in AssistantTurnGroup currently
encodes status only via color (STATUS_DOT_CLASS[status]) which is inaccessible;
update the span (or add a sibling visually-hidden element) to expose the status
as text for assistive tech by mapping the existing status values (e.g.,
"complete", "error", "in_progress") to human-readable strings and providing them
via aria-label or screen-reader-only text, keep the visual dot unchanged and
ensure decorative attributes (aria-hidden) are used correctly so the text is
announced while visual-only styling remains intact.

In
`@apps/desktop/src/renderer/components/Chat/ChatInterface/components/ToolCallBlock/components/SubagentToolCall/SubagentToolCall.tsx`:
- Around line 27-35: The formatDuration function can produce "1m 60s" by
rounding the remainder seconds; fix formatDuration by first rounding total
seconds (const totalSeconds = Math.round(ms / 1000)), then compute minutes with
Math.floor(totalSeconds / 60) and seconds with totalSeconds % 60, and return the
string accordingly (preserving the existing sub-second and small-value
behavior), keeping the initial finite/negative checks intact.

In
`@apps/desktop/src/renderer/components/Chat/ChatInterface/components/TurnTextItem/TurnTextItem.tsx`:
- Around line 29-32: The thinking text is rendered in a plain div and inherits
global user-select: none, making it not copyable; update the JSX in TurnTextItem
(the branch using isThinking) to add an explicit selectable class (e.g. the
Tailwind utility "select-text" or your project's equivalent like "selectable" or
"selectable-text") to the div's className so the reasoning text becomes copyable
while keeping existing styles (whitespace-pre-wrap py-1 pl-3
text-muted-foreground text-xs).

In
`@apps/desktop/src/renderer/components/Chat/ChatInterface/utils/group-assistant-turn/group-assistant-turn.ts`:
- Around line 109-117: The hasSteps flag currently ignores intermediate
non-final text because it is only set from toolCount, subagentCount, and
thinkingCount; include outputCount in the condition so intermediate text counts
as a step (update the hasSteps expression used in group-assistant-turn.ts to
something that also checks outputCount > 0, keeping the other counts the same
and leaving lastTextIndex/outputCount logic unchanged).

In
`@apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/`$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/WorkspaceChatInterface/components/ChatMessageList/components/AssistantMessage/AssistantMessage.tsx:
- Around line 368-403: Add the same early-return guard as the main workspace:
inside the AssistantMessage component, after computing hasAnyNode and before
rendering, return null when there is no content to show by checking if
(!hasAnyNode && !isStreaming && !footer); this prevents rendering an empty
Message container for non‑streaming, empty messages — update the
AssistantMessage function to perform that check and return null early.

---

Nitpick comments:
In
`@apps/desktop/src/renderer/components/Chat/ChatInterface/utils/group-assistant-turn/group-assistant-turn.test.ts`:
- Around line 10-18: Replace the unsafe "as never" casts in the test fixtures
with a proper typed alias so the test input shape is validated: add a local type
alias like TurnParts = Parameters<typeof summarizeAssistantTurn>[0] and use
TurnParts for the arrays passed to summarizeAssistantTurn (e.g., type the array
literals as TurnParts), then remove all "as never" occurrences in this file and
the other listed ranges so the compiler checks the public input contract of
summarizeAssistantTurn.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3e18b5b0-9d4d-4174-93a4-f2ef28aad50f

📥 Commits

Reviewing files that changed from the base of the PR and between 3647b17 and 7a0f76a.

📒 Files selected for processing (11)
  • apps/desktop/src/renderer/components/Chat/ChatInterface/components/AssistantTurnGroup/AssistantTurnGroup.test.tsx
  • apps/desktop/src/renderer/components/Chat/ChatInterface/components/AssistantTurnGroup/AssistantTurnGroup.tsx
  • apps/desktop/src/renderer/components/Chat/ChatInterface/components/AssistantTurnGroup/index.ts
  • apps/desktop/src/renderer/components/Chat/ChatInterface/components/ToolCallBlock/components/SubagentToolCall/SubagentToolCall.tsx
  • apps/desktop/src/renderer/components/Chat/ChatInterface/components/TurnTextItem/TurnTextItem.tsx
  • apps/desktop/src/renderer/components/Chat/ChatInterface/components/TurnTextItem/index.ts
  • apps/desktop/src/renderer/components/Chat/ChatInterface/utils/group-assistant-turn/group-assistant-turn.test.ts
  • apps/desktop/src/renderer/components/Chat/ChatInterface/utils/group-assistant-turn/group-assistant-turn.ts
  • apps/desktop/src/renderer/components/Chat/ChatInterface/utils/group-assistant-turn/index.ts
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/WorkspaceChatInterface/components/ChatMessageList/components/AssistantMessage/AssistantMessage.tsx
  • apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabView/ChatPane/ChatPaneInterface/components/ChatMessageList/components/AssistantMessage/AssistantMessage.tsx

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

7 issues found across 11 files

Architecture diagram
sequenceDiagram
    participant UI as Chat UI
    participant AM as AssistantMessage (Renderer)
    participant Summarize as summarizeAssistantTurn (Helper)
    participant Format as formatTurnSummary (Helper)
    participant ATG as AssistantTurnGroup (Component)
    participant TTI as TurnTextItem (Component)
    participant TCB as ToolCallBlock (Existing)
    participant STC as SubagentToolCall (Component)

    Note over UI,STC: Runtime Flow: Rendering an Assistant Turn

    UI->>AM: Render assistant message with content parts and streaming state
    
    AM->>Summarize: summarizeAssistantTurn(message.content, { isStreaming, errored })
    Summarize-->>AM: AssistantTurnSummary (counts, lastTextIndex, status)
    
    AM->>Format: formatTurnSummary(summary)
    Format-->>AM: Human-readable summary string (e.g., "3 tool calls · 1 subagent")
    
    alt Turn has steps (tools, thinking, or subagents)
        AM->>ATG: Render with summary, status, timestamp, defaultOpen, steps, lastOutput
        
        alt Turn is live, error, or has pending approval
            Note over AM,ATG: defaultOpen = true (expanded)
        else Turn is complete
            Note over AM,ATG: defaultOpen = false (collapsed, steps hidden)
        end
        
        ATG->>ATG: Render collapsible header with Chevron, BotIcon, summary, clock, status dot
        
        alt Steps are expanded
            ATG->>TTI: Render intermediate text parts (kind: "output" or "thinking")
            ATG->>TCB: Render tool calls and results (existing blocks)
            TCB->>STC: Render subagent details with TASK badge and execution trace
            Note over STC: NEW: Shows model, duration, tool call count
        end
        
        ATG->>ATG: Always render lastOutput (final answer) outside collapsible
        
    else No steps (plain Q&A)
        AM->>AM: Render stepNodes + lastOutputNodes directly (no grouping)
    end
    
    alt No content at all and streaming
        AM->>AM: Show "Thinking..." shimmer
    end
    
    Note over AM,STC: Key boundary: Pure render-layer change, no backend modifications
    
    Note over Summarize: Turn status derivation:<br/>- streaming → in_progress<br/>- tool error or stopReason=error → error<br/>- otherwise → complete
    
    Note over STC: Subagent metadata parsed from<br/>existing <subagent-meta> tag content
Loading

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

- Memoize summarizeAssistantTurn; include intermediate output text in
  hasSteps; drop the unused image segment from the summary label.
- Add the empty-message early return to the v2 AssistantMessage (parity
  with the legacy pane).
- AssistantTurnGroup: controlled open state so finished turns auto-collapse
  while respecting a manual toggle; expose turn status as screen-reader text
  alongside the dot; label the assistant generically instead of a fixed
  provider name.
- SubagentToolCall: render the spawned agent as a contained card; fix the
  minute-boundary rollover in duration formatting.
- Make thinking-block text selectable.
- Render pending plan approval OUTSIDE the collapsible group so collapsing a
  turn can never hide a required action; surface an amber "awaiting approval"
  header indicator instead of a misleading complete state.
@Kitenite

Copy link
Copy Markdown
Member

Closing: main already ships this. 8f2753b (#6461) deleted the old Chat tree for chat-v3; all touched files gone. Thanks for the PR; if you think the shipped version misses a case, open an issue and link this.

@Kitenite Kitenite closed this Aug 22, 2026
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.

[feat] Group assistant turns in chat with a collapsible step view

2 participants