Skip to content

Implement Markdown support and message parts refactoring#21

Merged
MrOrz merged 15 commits intomasterfrom
feature/markdown-support-16087018265232926545
Apr 21, 2026
Merged

Implement Markdown support and message parts refactoring#21
MrOrz merged 15 commits intomasterfrom
feature/markdown-support-16087018265232926545

Conversation

@MrOrz
Copy link
Copy Markdown
Member

@MrOrz MrOrz commented Mar 15, 2026

Overview

This PR adds Markdown rendering for chat messages and overhauls how ADK stream events are mapped to UI state.

The root problem: ADK streams events that interleave text chunks with tool call parts. The previous model stored a single text string per message, which could not represent this interleaved structure nor preserve ordering. This PR replaces it with a parts[]-based model that mirrors ADK's own Content type, then wires it up to a streaming state machine that handles partial text accumulation correctly.

Fixes #12


Key Changes

1. Type Refactoring — ChatMessage now extends AdkContent (adk.ts)

ChatMessage no longer has its own role/parts fields. Instead it extends AdkContent (from the generated OpenAPI types) and adds only UI-specific fields:

export interface ChatMessage extends AdkContent {
  id: string
  author?: string
  isStreaming?: boolean
  timestamp?: Date
}

This makes ChatMessage a strict superset of what ADK returns, so constructing one from an ADK event is a simple spread — no lossy mapping.

2. Streaming State Machine — applyEventToState (chatCache.ts)

The core change. Every incoming ADK SSE event is classified into one of four branches:

Branch Condition Action
User message event.content.role === 'user' Append new user ChatMessage
New agent turn Last message is not streaming (or different author) Append new model ChatMessage
Streaming end Last is streaming, but this event is partial: false Mark last message isStreaming: false, drop event content (ADK repeats the full text on the final event)
Streaming chunk Last is streaming and event is also partial: true Merge parts into last message, concatenating consecutive text parts

The text-concatenation logic (updatedParts) preserves interleaved structure: a tool call followed by another text chunk results in separate parts, not a collapsed string.

applyEventToState is a pure function (no side effects) — the impure processEventIntoCache is a thin wrapper that calls queryClient.setQueryData. This also enables reuse in convertAdkSessionToChatState for history loading.

startChatStream no longer pre-inserts an empty placeholder ChatMessage before the stream begins. The isStreaming: true flag on ChatSessionState is sufficient to drive the loading indicator (see §3); the first real event from ADK creates the model message.

3. Loading Indicator & Message Filtering in ChatArea.tsx

The streaming "正在思考中" indicator was moved from individual AgentMessage components up to ChatArea. It is now driven by the session-level isStreaming flag rather than per-message isStreaming, and is rendered once below the message list while a stream is active:

{isStreaming && (
  <p className="flex items-center gap-2 text-gray-500">
    正在思考中
    <span className="typing-indicator ml-1">...</span>
  </p>
)}

This avoids the indicator appearing inside a partially-rendered message bubble, and correctly handles the case where a stream starts before any event has arrived (since there's no placeholder message anymore).

ADK also sometimes emits events with role: 'user' that are actually internal (e.g. function responses). These are suppressed:

if (msg.role === 'user') {
  return msg.author === 'user'
    ? <UserMessage key={msg.id} message={msg} />
    : null  // function response → render nothing
}

4. Markdown Rendering — AgentMessage.tsx & UserMessage.tsx

Both components now iterate message.parts[] and render each text part through ReactMarkdown with remark-gfm. Tool call parts (functionCall) are rendered as inline badges showing the tool name + icon.

Tailwind CSS v4 plugin syntax (one line in styles.css):

@plugin "@tailwindcss/typography";

5. Removed Dead Code

  • draftResponse field removed from ChatSessionState — it was being accumulated from writer partial events but never read anywhere.
  • User-message dedup logic removed — investigation showed ADK does not actually send duplicate user messages, so the defensive code was unnecessary noise.
  • Placeholder model message pre-insertion removed from startChatStream — the empty { role: 'model', parts: [] } message inserted before streaming began is no longer needed since the loading indicator is now session-level.

6. Dev Tooling

Added React Query Devtools to visualize the TanStack Query cache during development. Visible only in dev mode via the floating button.


Reviewer Guide

Suggested reading order:

  1. src/lib/adk.ts — understand the new ChatMessage type
  2. src/lib/chatCache.ts, applyEventToState (~line 174) — the streaming state machine is the heart of this PR
  3. src/components/AgentMessage.tsx — see how parts[] maps to rendered UI
  4. src/components/ChatArea.tsx — message filtering + session-level loading indicator
  5. src/components/UserMessage.tsx — simpler; same parts[] pattern
  6. src/hooks/useChat.ts — confirm draftResponse is cleanly gone
  7. package.json / styles.css — dependency additions

Key invariant to verify: When event.partial === false, applyEventToState intentionally discards the event's content (branch 3 above). The reasoning is that ADK sends the complete accumulated text on the final event, but since we've already been appending chunks incrementally, we'd double-count it. The docs: commit (a517073) was added specifically to document this assumption.


PR originally created by Jules for task 16087018265232926545. Subsequent fixes and refactoring by @MrOrz.

- Installed `react-markdown`, `remark-gfm`, and `@tailwindcss/typography`.
- Refactored `ChatMessage` type to extend `AdkContent` and use `parts` array as the source of truth.
- Updated state management logic in `src/lib/chatCache.ts` to map ADK events to message parts and handle streaming text.
- Implemented Markdown rendering in `AgentMessage.tsx` and `UserMessage.tsx` with proper styling using Tailwind CSS Typography.
- Configured Tailwind CSS v4 to correctly load the typography plugin.
- Verified visual changes and build integrity.

Co-authored-by: MrOrz <108608+MrOrz@users.noreply.github.com>
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@google-labs-jules google-labs-jules Bot mentioned this pull request Mar 15, 2026
@github-actions github-actions Bot temporarily deployed to pr-21 March 15, 2026 07:09 Destroyed
@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the chat interface by introducing Markdown rendering capabilities and a more robust message data model. The core change involves refactoring ChatMessage to use a parts array, which allows for the accurate and ordered display of both text and tool calls, especially during streaming. This refactoring improves the user experience by providing richer message formatting and ensuring that complex agent responses, including interleaved text and tool executions, are presented coherently.

Highlights

  • Markdown Support: Integrated react-markdown and remark-gfm for rendering Markdown in chat messages, enhancing text formatting capabilities.
  • Message Data Model Refactoring: ChatMessage now utilizes a parts array to represent interleaved text and tool calls, ensuring their correct sequential rendering.
  • Enhanced Streaming Logic: Updated applyEventToState to accurately handle streaming updates for both text (appending to the last text part) and tool calls within the new parts array structure.
  • UI Integration: Chat message components (AgentMessage, UserMessage) were adapted to render content from the parts array, leveraging the new Markdown capabilities and Tailwind CSS typography.
  • Styling: The @tailwindcss/typography plugin was added to enable rich, readable styling for Markdown content.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • package.json
    • Added @tailwindcss/typography for styling Markdown content.
    • Added react-markdown for rendering Markdown.
    • Added remark-gfm for GitHub Flavored Markdown support.
  • pnpm-lock.yaml
    • Updated lockfile to include new dependencies and their transitive dependencies for Markdown rendering and styling.
  • src/components/AgentMessage.tsx
    • Imported useMemo, ReactMarkdown, and remarkGfm.
    • Computed fullText from message.parts for feedback and clipboard actions.
    • Replaced direct message.text rendering with an iteration over message.parts, applying ReactMarkdown for text content and rendering tool badges for function calls.
    • Adjusted feedback button visibility and styling to use fullText and occupy full width.
  • src/components/UserMessage.tsx
    • Imported ReactMarkdown and remarkGfm.
    • Updated message rendering to iterate over message.parts and apply ReactMarkdown for text content.
  • src/lib/adk.ts
    • Modified ChatMessage interface to extend AdkContent, removing direct text and toolCalls properties.
    • Removed the ToolCall interface as its functionality is now integrated into AdkContent.parts.
  • src/lib/chatCache.ts
    • Removed ToolCall import.
    • Updated startChatStream to initialize streaming messages with an empty parts array.
    • Modified sendChatMessage to encapsulate user input text within a parts array.
    • Refactored applyEventToState to process event.content.parts directly, handling streaming text by appending to the last text part and integrating tool calls as distinct parts, ensuring correct message construction and deduplication based on parts content.
  • src/styles.css
    • Added @plugin "@tailwindcss/typography"; to enable Tailwind CSS typography styles.
Activity
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces Markdown support for chat messages and refactors the message data model to use parts, which is a great improvement for handling complex message structures. The implementation is mostly solid, but I've found a few critical issues in the new state update logic (applyEventToState) and in the UI component (AgentMessage) where missing null or undefined checks could lead to runtime errors. I've provided suggestions to fix these. Once these are addressed, this will be a great enhancement.

Comment thread src/components/AgentMessage.tsx Outdated
Comment thread src/lib/chatCache.ts Outdated
Comment thread src/lib/chatCache.ts Outdated
@MrOrz MrOrz marked this pull request as ready for review March 15, 2026 09:13
@MrOrz MrOrz marked this pull request as draft March 15, 2026 09:27
- Refactor `ChatMessage` type to extend `AdkContent` and use `parts` array.
- Update `applyEventToState` to preserve order of text and tool calls during streaming.
- Integrate `react-markdown` and `remark-gfm` for rendering message content.
- Apply `prose` styling from `@tailwindcss/typography`.
- Add null check for `lastPart` in streaming logic to prevent `TypeError`.

Co-authored-by: MrOrz <108608+MrOrz@users.noreply.github.com>
@github-actions github-actions Bot temporarily deployed to pr-21 March 15, 2026 09:27 Destroyed
@cofacts cofacts deleted a comment from claude Bot Mar 16, 2026
@cofacts cofacts deleted a comment from claude Bot Mar 17, 2026
MrOrz and others added 8 commits April 21, 2026 01:14
draftResponse was being accumulated from writer partial events
but never read anywhere in the codebase. Remove it along with
the dead accumulation logic.

Co-authored-by: Antigravity <antigravity@google.com>
because there is no duplication there
@github-actions github-actions Bot temporarily deployed to pr-21 April 20, 2026 18:00 Destroyed
MrOrz added 2 commits April 21, 2026 02:18
Separatly process 3 scenarios
1. Last message is not streaming --> append new event
2. Last message is streaming, but event stops streaming --> ADK repeating after stream ends, drop event
3. Last message is streaming and this event is also partial --> append content to last event
@github-actions github-actions Bot temporarily deployed to pr-21 April 20, 2026 18:26 Destroyed
- Use optional chaining ?.includes() in AgentMessage.tsx to prevent
  TypeError when tool.name is null/undefined
- Use optional chaining on `last` in chatCache.ts to prevent TypeError
  when messages array is empty

Co-authored-by: Antigravity <antigravity@google.com>
@github-actions github-actions Bot temporarily deployed to pr-21 April 20, 2026 18:35 Destroyed
@github-actions github-actions Bot temporarily deployed to pr-21 April 20, 2026 18:39 Destroyed
@MrOrz MrOrz marked this pull request as ready for review April 20, 2026 18:50
@github-actions github-actions Bot temporarily deployed to pr-21 April 20, 2026 19:23 Destroyed
@MrOrz MrOrz self-assigned this Apr 20, 2026
@MrOrz MrOrz merged commit a25f3b6 into master Apr 21, 2026
3 checks passed
@MrOrz MrOrz deleted the feature/markdown-support-16087018265232926545 branch April 21, 2026 14:08
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.

Markdown support

3 participants