Skip to content

refactor(ui): split message part rendering#620

Merged
Astro-Han merged 3 commits into
devfrom
codex/i601-message-part-split
May 14, 2026
Merged

refactor(ui): split message part rendering#620
Astro-Han merged 3 commits into
devfrom
codex/i601-message-part-split

Conversation

@Astro-Han
Copy link
Copy Markdown
Owner

@Astro-Han Astro-Han commented May 14, 2026

Summary

Split packages/ui/src/components/message-part.tsx into focused message-part modules while keeping message-part.tsx as the public facade.

Moved the tool-info switch behind toolInfoForInput() in packages/ui/src/components/tool-info.ts, and added source guards for registration coverage, facade import boundaries, registry independence, hidden tools, default-open behavior, and deferred heavy tool bodies.

Why

#601 Area A calls out message-part.tsx as too large to audit safely. This PR is the structural slice only: make the renderer easier to inspect without changing message, tool, streaming, grouping, or public import behavior.

Related Issue

Part of #601.

Human Review Status

Pending. A human should make the final merge decision after reviewing the final diff and verification evidence.

Review Focus

  • Confirm this remains a pure refactor with no intended behavior change.
  • Check the side-effect registration barrels cover every original part and tool renderer.
  • Check AssistantParts still preserves grouping, staging, Index each, keys, and default open behavior.
  • Check heavy tool bodies still pass defer at the same BasicTool layer.
  • Check internal modules do not import back through the message-part.tsx facade.

Risk Notes

Medium structural risk because missing a side-effect import would not necessarily fail typecheck. Mitigated with message-part-registry.test.ts coverage for part/tool registrations, hidden tools, partDefaultOpen, defer, facade import boundaries, and registry independence.

No dependency, schema, permission, generated-file, or platform behavior changes intended.

Review follow-up also tightened defensive guards around clipboard failure, safe WebFetch hrefs, write-tool missing metadata, empty write content, and session path matching. These are hardening changes with no intended visible UI change.

A later CI follow-up stabilized shared app test mocks so Linux CI does not leak partial module mocks across concurrent test files.

Known baseline issue: the local E2E command below still has two failures, and both reproduced unchanged on the current dev checkout. They are recorded as baseline failures, not introduced by this branch.

How To Verify

Install: bun install --frozen-lockfile passed in this worktree
Diff check: git diff --cached --check && git diff --check passed
UI typecheck: bun --cwd packages/ui typecheck passed
App typecheck: cd packages/app && bun typecheck passed
Opencode typecheck: cd packages/opencode && bun typecheck passed
Focused UI tests: bun --cwd packages/ui test src/components/message-part-registry.test.ts src/components/message-part-stale.test.ts test/components/message-part-rename.test.ts src/components/basic-tool-trigger.test.ts src/components/apply-patch-file.test.ts src/components/markdown-stream.test.ts passed, 27 pass
App unit CI entry: cd packages/app && bun run test:ci passed, 1066 pass
Local E2E: cd packages/app && bun test:e2e:local -- e2e/session/session-scroll-position.spec.ts e2e/session/session-renderer-diagnostics.spec.ts e2e/session/session-child-navigation.spec.ts ran, 6 passed and 2 failed
Baseline E2E comparison: the same two failing E2E tests reproduced on dev with the same failure points
Perf E2E: cd packages/app && bun test:e2e:local:perf passed, 5 passed and 1 skipped
Electron smoke: bun run dev:desktop launched; desktop shell, new-session composer, and model picker opened without renderer crash; no live prompt was sent
Reviewer subagent: Requesting Code Review flow completed; no Critical or Important findings, one Minor guard gap fixed
Review threads: received review comments were replied to and resolved; reviewThreads.isResolved re-query returned 0 unresolved threads
Review follow-up tests: targeted app mock-isolation files passed, 42 pass

Screenshots or Recordings

Not included. This is a pure structural refactor with no intended visible UI change. Electron smoke was still completed for the desktop shell and composer.

Checklist

  • Human review status is stated above as pending, approved, or not required
  • I linked the related issue, or stated why there is no issue
  • This PR has type, primary area, and priority labels, or I requested maintainer labeling
  • I described the review focus and any meaningful risks
  • I listed the relevant verification steps and the key result for each
  • I did not introduce unrelated refactors, dependencies, generated files, or file changes beyond the stated scope
  • I manually checked visible UI or copy changes when needed, with screenshots or recordings
  • I considered macOS and Windows impact for platform, packaging, updater, signing, paths, shell, or permissions changes
  • I called out docs, release notes, dependencies, permissions, credentials, deletion behavior, generated content, or local file changes when relevant
  • I reviewed the final diff for unrelated changes and suspicious dependency changes
  • I am targeting dev, and my PR title and commit messages use Conventional Commits in English

Summary by CodeRabbit

  • New Features
    • Many new message-part UI components and tool renderers (agent/task, context groups, tool cards, diff/file viewers, diagnostics, paced Markdown, highlighted text, image previews, copy actions).
    • Centralized part/tool registry and simpler message-part entry that improves component composition and reuse.
  • Improvements
    • Enhanced assistant/user message rendering (grouping, streaming, copy/revert UX, tool summaries).
  • Tests
    • Expanded and hardened tests covering message-part rendering and guards.

Review Change Stack

@Astro-Han Astro-Han added P2 Medium priority app Application behavior and product flows ui Design system and user interface task Maintainer or agent execution task tech-debt Internal cleanup and maintainability debt labels May 14, 2026
Copy link
Copy Markdown

@github-actions github-actions Bot left a comment

Choose a reason for hiding this comment

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

Suggested priority: P2 (includes user-path files (packages/app/src/no-mode-picker.test.ts)).

P1/P0 are reserved for maintainer confirmation. Please relabel manually if this is a release blocker, security issue, data-loss risk, or updater/runtime failure.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 14, 2026

Warning

Rate limit exceeded

@Astro-Han has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 37 minutes and 3 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: f58b5afa-c6ac-41b1-9469-17986ed0bad2

📥 Commits

Reviewing files that changed from the base of the PR and between 864780a and a602886.

📒 Files selected for processing (44)
  • packages/app/src/components/file-tree.test.ts
  • packages/app/src/no-mode-picker.test.ts
  • packages/app/src/pages/session/session-side-panel.test.tsx
  • packages/app/src/pages/session/use-session-followups.test.ts
  • packages/ui/src/components/message-part-registry.test.ts
  • packages/ui/src/components/message-part-stale.test.ts
  • packages/ui/src/components/message-part.tsx
  • packages/ui/src/components/message-part/agent-tone.ts
  • packages/ui/src/components/message-part/assistant-message-display.tsx
  • packages/ui/src/components/message-part/assistant-parts.tsx
  • packages/ui/src/components/message-part/context-tool-group.tsx
  • packages/ui/src/components/message-part/context-tool-helpers.ts
  • packages/ui/src/components/message-part/grouping.ts
  • packages/ui/src/components/message-part/highlighted-text.tsx
  • packages/ui/src/components/message-part/markdown-render.tsx
  • packages/ui/src/components/message-part/message-router.tsx
  • packages/ui/src/components/message-part/parts/compaction-and-divider.tsx
  • packages/ui/src/components/message-part/parts/index.ts
  • packages/ui/src/components/message-part/parts/reasoning.tsx
  • packages/ui/src/components/message-part/parts/text.tsx
  • packages/ui/src/components/message-part/parts/tool.tsx
  • packages/ui/src/components/message-part/registry.ts
  • packages/ui/src/components/message-part/session-link.ts
  • packages/ui/src/components/message-part/shared-utils.ts
  • packages/ui/src/components/message-part/tools/_diagnostics.tsx
  • packages/ui/src/components/message-part/tools/_file-accordion.tsx
  • packages/ui/src/components/message-part/tools/agent.tsx
  • packages/ui/src/components/message-part/tools/apply-patch.tsx
  • packages/ui/src/components/message-part/tools/bash.tsx
  • packages/ui/src/components/message-part/tools/edit.tsx
  • packages/ui/src/components/message-part/tools/glob.tsx
  • packages/ui/src/components/message-part/tools/grep.tsx
  • packages/ui/src/components/message-part/tools/index.ts
  • packages/ui/src/components/message-part/tools/list.tsx
  • packages/ui/src/components/message-part/tools/question.tsx
  • packages/ui/src/components/message-part/tools/read.tsx
  • packages/ui/src/components/message-part/tools/skill.tsx
  • packages/ui/src/components/message-part/tools/todowrite.tsx
  • packages/ui/src/components/message-part/tools/webfetch.tsx
  • packages/ui/src/components/message-part/tools/websearch.tsx
  • packages/ui/src/components/message-part/tools/worktree.tsx
  • packages/ui/src/components/message-part/tools/write.tsx
  • packages/ui/src/components/message-part/user-message.tsx
  • packages/ui/src/components/tool-info.ts
📝 Walkthrough

Walkthrough

Modularizes the message-part UI: introduces a registry, grouping/filtering helpers, paced markdown/highlight rendering, new part and tool components, diagnostics/file UI helpers, and tests updated to assert aggregated source-level properties and agent-pill removal.

Changes

Message-part UI modularization and registry system

Layer / File(s) Summary
Core registry and shared utilities
packages/ui/src/components/message-part/registry.ts, packages/ui/src/components/message-part/shared-utils.ts, packages/ui/src/components/message-part/agent-tone.ts
Adds PART_MAPPING, registerPartComponent, registerTool, ToolRegistry, and shared helpers/sets used by parts and tools.
Grouping & context helpers
packages/ui/src/components/message-part/grouping.ts, packages/ui/src/components/message-part/context-tool-helpers.ts
Adds PartRef/PartGroup types, grouping logic (groupParts), visibility (renderable), and context tool trigger/detail helpers.
Tool-info refactor
packages/ui/src/components/tool-info.ts
Extracts toolInfoForInput(...) and delegates buildToolInfo to it.
Text & markdown helpers
packages/ui/src/components/message-part/markdown-render.tsx, packages/ui/src/components/message-part/highlighted-text.tsx
Implements paced markdown, link/path helpers, MessageMarkdown/PacedMarkdown, and HighlightedText segmentation.
Message display & routing
packages/ui/src/components/message-part/user-message.tsx, assistant-message-display.tsx, assistant-parts.tsx, message-router.tsx
Adds user and assistant message renderers, grouped-part rendering, and a router that dispatches parts to registered renderers.
Part renderers
packages/ui/src/components/message-part/parts/*
Registers text, reasoning, tool, and compaction part renderers and provides parts barrel.
Tool helpers
packages/ui/src/components/message-part/tools/_diagnostics.tsx, .../_file-accordion.tsx
Adds diagnostics extraction/display and a file-accordion UI used by multiple tools.
Tool implementations
packages/ui/src/components/message-part/tools/*
Registers many tool renderers (agent/task, bash, apply_patch, edit, read, list, glob, grep, webfetch, websearch, question, skill, todowrite, worktree, write) with their UI and behaviors.
Tools index barrel
packages/ui/src/components/message-part/tools/index.ts
Aggregates tool modules so registration side-effects run.
Facade refactor
packages/ui/src/components/message-part.tsx
Replaces the large monolith with a thin re-export + delegation to toolInfoForInput.
Tests updated
packages/app/src/no-mode-picker.test.ts, packages/ui/src/components/message-part-registry.test.ts, packages/ui/src/components/message-part-stale.test.ts
Tests now aggregate all message-part source files for assertions; adds hardening checks and the agent-pill regression assertion.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

Suggested labels

enhancement

🐰 I hopped through files with joy and cheer,
Monoliths divided, the registry near.
Parts and tools now neatly aligned,
A modular garden, well-designed.
Cheers for tests that guard what’s dear!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 title clearly summarizes the main change: refactoring the message-part rendering by splitting a large component into focused modules.
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 follows the template structure with all required sections present and complete: Summary, Why, Related Issue, Human Review Status, Review Focus, Risk Notes, How to Verify, Screenshots or Recordings, and a thorough Checklist.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/i601-message-part-split

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.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 9

🧹 Nitpick comments (6)
packages/ui/src/components/message-part/registry.ts (2)

32-34: 💤 Low value

Consider guarding against double-registration in development.

registerPartComponent silently overwrites if called twice with the same type. For a structural refactor, adding a dev-mode warning would catch accidental duplicate registrations.

🛡️ Optional guard to detect double-registration
 export function registerPartComponent(type: string, component: PartComponent) {
+  if (import.meta.env.DEV && PART_MAPPING[type]) {
+    console.warn(`[registry] Part type "${type}" is already registered`)
+  }
   PART_MAPPING[type] = component
 }
🤖 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 `@packages/ui/src/components/message-part/registry.ts` around lines 32 - 34,
Update registerPartComponent to detect and warn on duplicate registrations in
development: check PART_MAPPING[type] before assigning and, if a different
component is already registered and process.env.NODE_ENV !== 'production' (or
import a DEV flag), log a console.warn or use the project's logger that includes
the conflicting type and the existing vs new component identifiers; then still
allow overwrite (or optionally skip assignment) depending on desired behavior.
Reference: registerPartComponent and PART_MAPPING.

58-65: 💤 Low value

Optional: Simplify tool state structure.

The tool state stores { name, render? } but getTool only returns render. The stored name field is never read. You could simplify state to Record<string, ToolComponent | undefined> to match the pattern in PART_MAPPING.

♻️ Optional simplification
-const state: Record<
-  string,
-  {
-    name: string
-    render?: ToolComponent
-  }
-> = {}
+const state: Record<string, ToolComponent | undefined> = {}

 export function registerTool(input: { name: string; render?: ToolComponent }) {
-  state[input.name] = input
+  state[input.name] = input.render
   return input
 }

 export function getTool(name: string) {
-  return state[name]?.render
+  return state[name]
 }
🤖 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 `@packages/ui/src/components/message-part/registry.ts` around lines 58 - 65,
The state currently stores objects with { name, render? } but getTool only
returns the render, so simplify state to Record<string, ToolComponent |
undefined> and update registerTool to assign input.render directly to
state[input.name]; adjust any references to state shape accordingly (notably
registerTool and getTool) so they match the PART_MAPPING pattern and remove the
unused name field.
packages/ui/src/components/message-part/message-router.tsx (1)

11-21: ⚡ Quick win

Consider using type predicates instead of as assertions for better type narrowing.

The as type assertions on lines 12 and 16 work because MessageType is a discriminated union from the SDK, but type predicates would provide proper type narrowing without bypassing TypeScript checks. Other parts of the codebase (e.g., timeline-playground.stories.tsx) use this pattern:

(m): m is UserMessage => m.role === "user"

This approach is more idiomatic and eliminates reliance on manual type assertions.

🤖 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 `@packages/ui/src/components/message-part/message-router.tsx` around lines 11 -
21, The code uses `as` assertions to cast props.message to
UserMessage/AssistantMessage in message-router.tsx (used by UserMessageDisplay
and AssistantMessageDisplay); replace those casts with proper type predicate
functions (e.g., isUserMessage(m): m is UserMessage and isAssistantMessage(m): m
is AssistantMessage) that check m.role === "user" / "assistant", use those
predicates in the Show conditions to let TypeScript narrow the type, and remove
the `as` assertions from the UserMessageDisplay and AssistantMessageDisplay
props so the components receive correctly narrowed types without bypassing the
compiler.
packages/ui/src/components/message-part/tools/question.tsx (1)

11-12: ⚡ Quick win

Consider adding runtime validation for type casts.

Lines 11-12 cast props.input.questions and props.metadata.answers to QuestionInfo[] and QuestionAnswer[] without runtime validation. If the data doesn't match the expected shape, this could cause runtime errors when accessing properties like q.question (line 39).

While TypeScript casts provide compile-time type checking, they don't guarantee runtime safety when dealing with external data. Consider adding validation or type guards if these values come from untrusted sources.

🛡️ Proposed defensive validation
- const questions = createMemo(() => (props.input.questions ?? []) as QuestionInfo[])
- const answers = createMemo(() => (props.metadata.answers ?? []) as QuestionAnswer[])
+ const questions = createMemo(() => {
+   const value = props.input.questions ?? []
+   if (!Array.isArray(value)) return []
+   return value as QuestionInfo[]
+ })
+ const answers = createMemo(() => {
+   const value = props.metadata?.answers ?? []
+   if (!Array.isArray(value)) return []
+   return value as QuestionAnswer[]
+ })

This adds basic array validation before casting. For stricter validation, consider using a schema validator like Zod.

🤖 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 `@packages/ui/src/components/message-part/tools/question.tsx` around lines 11 -
12, The current casts in createMemo for questions and answers assume
props.input.questions and props.metadata.answers match
QuestionInfo[]/QuestionAnswer[] at runtime; add defensive runtime checks (e.g.,
Array.isArray and simple item shape/type guards or a utility
isQuestionInfo/isQuestionAnswer) before casting and fall back to [] if
validation fails so accesses like q.question in the component are safe; update
the createMemo calls that initialize questions and answers to use these
validators (or a small helper validateArray<T>(value, predicate)) to ensure only
properly-shaped objects are returned.
packages/ui/src/components/message-part/tools/edit.tsx (1)

40-43: 💤 Low value

Use consistent optional chaining for path handling.

Lines 40 and 42 show inconsistent null handling:

  • Line 40 uses optional chaining: props.input.filePath?.includes("/")
  • Line 42 uses non-null assertion: props.input.filePath!

While the conditional check ensures filePath is truthy at line 42, using optional chaining is more defensive and consistent with the pattern established at line 40.

♻️ Proposed consistency improvement
  <Show when={!pending() && props.input.filePath?.includes("/")}>
    <div data-slot="message-part-path">
-     <span data-slot="message-part-directory">{getDirectory(props.input.filePath!)}</span>
+     <span data-slot="message-part-directory">{getDirectory(props.input.filePath)}</span>
    </div>
  </Show>

Note: This assumes getDirectory handles string input safely. The Show condition already guarantees filePath is a non-empty string.

🤖 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 `@packages/ui/src/components/message-part/tools/edit.tsx` around lines 40 - 43,
The code uses a non-null assertion when calling getDirectory but optional
chaining in the conditional; replace the non-null assertion with consistent
optional handling by calling getDirectory(props.input.filePath) (or
getDirectory(props.input.filePath ?? '') if you prefer a fallback) inside the
Show block and keep the existing Show condition and pending() check; update
occurrences around the Show component, pending(), props.input.filePath and
getDirectory usage to remove the trailing "!" for consistency.
packages/ui/src/components/tool-info.ts (1)

67-73: 💤 Low value

Default parameters precede a required one — defaults are effectively unreachable.

input and metadata have defaults, but the required i18n follows them. Callers can never omit input/metadata to fall back to {} (they'd have to pass undefined explicitly), so the defaults add noise without value and the parameter list invites positional mistakes. Consider reordering required params first, or making i18n part of an options object.

♻️ Suggested signature
 export function toolInfoForInput(
   tool: string,
+  i18n: UiI18n,
   input: Record<string, any> = {},
   metadata: Record<string, any> = {},
-  i18n: UiI18n,
   options: { unknownSubtitle?: string } = {},
 ): ToolInfo {
🤖 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 `@packages/ui/src/components/tool-info.ts` around lines 67 - 73, The function
signature for toolInfoForInput places optional params (input, metadata) before
the required i18n, making their defaults effectively unreachable; fix by
reordering required params before defaults or by collapsing i18n into an options
object. For example, change the signature of toolInfoForInput so i18n: UiI18n
appears immediately after tool (or replace the last options param with an
options object that includes i18n and unknownSubtitle), then update all call
sites to pass i18n in the new position or as part of the options; adjust the
function body to read i18n from its new location and keep input and metadata
defaulting to {}.
🤖 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 `@packages/ui/src/components/message-part.tsx`:
- Around line 27-29: getToolInfo currently calls toolInfoForInput without the
options object, causing unknown tools to get subtitle: undefined whereas
buildToolInfo sets subtitle: ""; update getToolInfo to forward the same options
used by buildToolInfo by passing an options object including unknownSubtitle
(e.g., unknownSubtitle: "") when calling toolInfoForInput; reference the
getToolInfo function and ensure it calls toolInfoForInput(tool, input, metadata,
useI18n(), { unknownSubtitle: "" }) so behavior matches buildToolInfo.

In `@packages/ui/src/components/message-part/markdown-render.tsx`:
- Around line 145-148: The function relativizeProjectPath leaves a leading path
separator because it slices using directory.length instead of the full prefix
length; update the slice to remove the entire prefix by using prefix.length
(i.e., after computing separator and prefix and verifying
path.startsWith(prefix), return path.slice(prefix.length)) so the leading
separator is stripped correctly.

In `@packages/ui/src/components/message-part/message-router.tsx`:
- Around line 26-41: CompactionPartDisplay currently has a signature that
accepts no parameters while PART_MAPPING and the PartComponent type expect
Component<MessagePartProps>; update CompactionPartDisplay to accept the props
shape (e.g., (props: MessagePartProps) or function CompactionPartDisplay(props:
MessagePartProps)) and use props as needed (or ignore them) so its type matches
PartComponent, ensuring compatibility with PART_MAPPING and the Part function
that forwards part, message, hideDetails, defaultOpen, showAssistantCopyPartID,
and turnDurationMs.

In `@packages/ui/src/components/message-part/parts/text.tsx`:
- Around line 78-84: The handleCopy function currently calls
navigator.clipboard.writeText(content) without error handling; wrap that await
call in a try/catch so clipboard failures don't bubble up — on success keep the
existing setCopied(true) and timeout to reset, and on error handle gracefully
(e.g., log or show a fallback notification and ensure setCopied(false) or no
visual success state is set). Specifically update handleCopy to try { await
navigator.clipboard.writeText(content); setCopied(true); setTimeout(...); }
catch (err) { /* handle/log error and avoid showing copied state */ } to ensure
robust behavior when clipboard access is denied.

In `@packages/ui/src/components/message-part/session-link.ts`:
- Around line 22-24: The current logic uses path.indexOf("/session") which
matches substrings and can create malformed links; instead, treat the path as
segments by splitting on "/" (use the existing path and id variables), find the
first segment equal to "session" (not just containing it), and rebuild the URL
by joining segments up to that segment then appending "session" and the id;
update the code that computes idx and the returned string so it uses
segment-aware matching (e.g., operate on path.split("/"), check segments ===
"session", compute the slice accordingly) to ensure correct route matching.

In `@packages/ui/src/components/message-part/tools/bash.tsx`:
- Around line 57-63: The handleCopy function currently awaits
navigator.clipboard.writeText(content) without error handling; wrap that call in
try/catch inside handleCopy (and only call it if navigator.clipboard and
writeText exist) to catch permission or API errors, setCopied true on success,
and on failure fall back to a safe alternative (e.g., create a temporary
textarea and use document.execCommand('copy')) or surface an error
state/notification so unhandled promise rejections are avoided; reference
handleCopy, navigator.clipboard.writeText, setCopied, and the temporary timeout
reset when implementing the fix.

In `@packages/ui/src/components/message-part/tools/webfetch.tsx`:
- Around line 13-17: The code currently returns props.input.url directly via
createMemo (the url variable) which allows unsafe protocols; update the
createMemo that computes url to parse and validate the input: if value is not a
string return ""; otherwise try new URL(value) and only return the string if its
protocol is "http:" or "https:" (reject "javascript:", "data:", etc. by
returning ""); ensure the same protocol check is applied to the other createMemo
usage covering lines ~29-39 so any href rendered only uses the validated url
variable derived from props.input.url.

In `@packages/ui/src/components/message-part/tools/write.tsx`:
- Line 19: The current createMemo calls
getDiagnostics(props.metadata.diagnostics, props.input.filePath) but
dereferences props.metadata and will throw if metadata is null/undefined; update
the memo to guard metadata (e.g. use optional chaining or a default) before
accessing diagnostics—call getDiagnostics(props.metadata?.diagnostics ?? [],
props.input.filePath) or pass undefined when metadata is absent so createMemo
and getDiagnostics handle missing metadata safely; change the expression around
createMemo and getDiagnostics accordingly.
- Line 50: The Show condition hides the accordion when props.input.content is an
empty string because it checks truthiness; update the condition that currently
uses "props.input.content && path()" to explicitly test for null/undefined
instead (e.g., check props.input.content != null) so empty-string content still
renders while still gating on path() — locate the Show around the MessagePart
write UI where props.input.content and path() are used and replace the truthy
check with a nullish check.

---

Nitpick comments:
In `@packages/ui/src/components/message-part/message-router.tsx`:
- Around line 11-21: The code uses `as` assertions to cast props.message to
UserMessage/AssistantMessage in message-router.tsx (used by UserMessageDisplay
and AssistantMessageDisplay); replace those casts with proper type predicate
functions (e.g., isUserMessage(m): m is UserMessage and isAssistantMessage(m): m
is AssistantMessage) that check m.role === "user" / "assistant", use those
predicates in the Show conditions to let TypeScript narrow the type, and remove
the `as` assertions from the UserMessageDisplay and AssistantMessageDisplay
props so the components receive correctly narrowed types without bypassing the
compiler.

In `@packages/ui/src/components/message-part/registry.ts`:
- Around line 32-34: Update registerPartComponent to detect and warn on
duplicate registrations in development: check PART_MAPPING[type] before
assigning and, if a different component is already registered and
process.env.NODE_ENV !== 'production' (or import a DEV flag), log a console.warn
or use the project's logger that includes the conflicting type and the existing
vs new component identifiers; then still allow overwrite (or optionally skip
assignment) depending on desired behavior. Reference: registerPartComponent and
PART_MAPPING.
- Around line 58-65: The state currently stores objects with { name, render? }
but getTool only returns the render, so simplify state to Record<string,
ToolComponent | undefined> and update registerTool to assign input.render
directly to state[input.name]; adjust any references to state shape accordingly
(notably registerTool and getTool) so they match the PART_MAPPING pattern and
remove the unused name field.

In `@packages/ui/src/components/message-part/tools/edit.tsx`:
- Around line 40-43: The code uses a non-null assertion when calling
getDirectory but optional chaining in the conditional; replace the non-null
assertion with consistent optional handling by calling
getDirectory(props.input.filePath) (or getDirectory(props.input.filePath ?? '')
if you prefer a fallback) inside the Show block and keep the existing Show
condition and pending() check; update occurrences around the Show component,
pending(), props.input.filePath and getDirectory usage to remove the trailing
"!" for consistency.

In `@packages/ui/src/components/message-part/tools/question.tsx`:
- Around line 11-12: The current casts in createMemo for questions and answers
assume props.input.questions and props.metadata.answers match
QuestionInfo[]/QuestionAnswer[] at runtime; add defensive runtime checks (e.g.,
Array.isArray and simple item shape/type guards or a utility
isQuestionInfo/isQuestionAnswer) before casting and fall back to [] if
validation fails so accesses like q.question in the component are safe; update
the createMemo calls that initialize questions and answers to use these
validators (or a small helper validateArray<T>(value, predicate)) to ensure only
properly-shaped objects are returned.

In `@packages/ui/src/components/tool-info.ts`:
- Around line 67-73: The function signature for toolInfoForInput places optional
params (input, metadata) before the required i18n, making their defaults
effectively unreachable; fix by reordering required params before defaults or by
collapsing i18n into an options object. For example, change the signature of
toolInfoForInput so i18n: UiI18n appears immediately after tool (or replace the
last options param with an options object that includes i18n and
unknownSubtitle), then update all call sites to pass i18n in the new position or
as part of the options; adjust the function body to read i18n from its new
location and keep input and metadata defaulting to {}.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 771f8dd5-974d-4e84-a4aa-80a03f4e593d

📥 Commits

Reviewing files that changed from the base of the PR and between 864780a and b1536f0.

📒 Files selected for processing (41)
  • packages/app/src/no-mode-picker.test.ts
  • packages/ui/src/components/message-part-registry.test.ts
  • packages/ui/src/components/message-part-stale.test.ts
  • packages/ui/src/components/message-part.tsx
  • packages/ui/src/components/message-part/agent-tone.ts
  • packages/ui/src/components/message-part/assistant-message-display.tsx
  • packages/ui/src/components/message-part/assistant-parts.tsx
  • packages/ui/src/components/message-part/context-tool-group.tsx
  • packages/ui/src/components/message-part/context-tool-helpers.ts
  • packages/ui/src/components/message-part/grouping.ts
  • packages/ui/src/components/message-part/highlighted-text.tsx
  • packages/ui/src/components/message-part/markdown-render.tsx
  • packages/ui/src/components/message-part/message-router.tsx
  • packages/ui/src/components/message-part/parts/compaction-and-divider.tsx
  • packages/ui/src/components/message-part/parts/index.ts
  • packages/ui/src/components/message-part/parts/reasoning.tsx
  • packages/ui/src/components/message-part/parts/text.tsx
  • packages/ui/src/components/message-part/parts/tool.tsx
  • packages/ui/src/components/message-part/registry.ts
  • packages/ui/src/components/message-part/session-link.ts
  • packages/ui/src/components/message-part/shared-utils.ts
  • packages/ui/src/components/message-part/tools/_diagnostics.tsx
  • packages/ui/src/components/message-part/tools/_file-accordion.tsx
  • packages/ui/src/components/message-part/tools/agent.tsx
  • packages/ui/src/components/message-part/tools/apply-patch.tsx
  • packages/ui/src/components/message-part/tools/bash.tsx
  • packages/ui/src/components/message-part/tools/edit.tsx
  • packages/ui/src/components/message-part/tools/glob.tsx
  • packages/ui/src/components/message-part/tools/grep.tsx
  • packages/ui/src/components/message-part/tools/index.ts
  • packages/ui/src/components/message-part/tools/list.tsx
  • packages/ui/src/components/message-part/tools/question.tsx
  • packages/ui/src/components/message-part/tools/read.tsx
  • packages/ui/src/components/message-part/tools/skill.tsx
  • packages/ui/src/components/message-part/tools/todowrite.tsx
  • packages/ui/src/components/message-part/tools/webfetch.tsx
  • packages/ui/src/components/message-part/tools/websearch.tsx
  • packages/ui/src/components/message-part/tools/worktree.tsx
  • packages/ui/src/components/message-part/tools/write.tsx
  • packages/ui/src/components/message-part/user-message.tsx
  • packages/ui/src/components/tool-info.ts

Comment thread packages/ui/src/components/message-part.tsx
Comment thread packages/ui/src/components/message-part/markdown-render.tsx Outdated
Comment thread packages/ui/src/components/message-part/message-router.tsx
Comment thread packages/ui/src/components/message-part/parts/text.tsx
Comment thread packages/ui/src/components/message-part/session-link.ts Outdated
Comment thread packages/ui/src/components/message-part/tools/bash.tsx
Comment thread packages/ui/src/components/message-part/tools/webfetch.tsx
Comment thread packages/ui/src/components/message-part/tools/write.tsx Outdated
Comment thread packages/ui/src/components/message-part/tools/write.tsx Outdated
@github-actions
Copy link
Copy Markdown

github-actions Bot commented May 14, 2026

Perf delta summary

Comparator: pass

Profile / Scenario interaction median interaction worst long task max tbt frame gap p95 frame gap max jank count cls status
default / homepage-cold 40 -> 32 (-8) 56 -> 88 (+32) 66 -> 64 (-2) 16 -> 14 (-2) 16.8 -> 16.8 (0) 166.6 -> 83.4 (-83.2) 3 -> 3 (0) 0 -> 0 (0) pass
default / session-streaming-long 48 -> 48 (0) 72 -> 64 (-8) 116 -> 0 (-116) 66 -> 0 (-66) 33.3 -> 16.8 (-16.5) 100 -> 33.4 (-66.6) 1 -> 0 (-1) 0 -> 0 (0) pass
default / tool-call-expand 24 -> 16 (-8) 24 -> 24 (0) 0 -> 0 (0) 0 -> 0 (0) 16.8 -> 16.8 (0) 16.8 -> 16.8 (0) 0 -> 0 (0) 0 -> 0 (0) pass
default / terminal-side-panel-open 48 -> 40 (-8) 64 -> 48 (-16) 0 -> 0 (0) 0 -> 0 (0) 33.4 -> 16.8 (-16.6) 33.4 -> 16.8 (-16.6) 0 -> 0 (0) 0 -> 0 (0) pass
default / session-scroll-reading 32 -> 32 (0) 40 -> 40 (0) 0 -> 0 (0) 0 -> 0 (0) 16.8 -> 16.8 (0) 16.8 -> 16.8 (0) 0 -> 0 (0) 0.505 -> 0.505 (0) warn: cls
low-end / session-timeline-recompute 120 -> 128 (+8) 136 -> 128 (-8) 105 -> 111 (+6) 155 -> 151 (-4) 83.4 -> 83.4 (0) 150 -> 166.7 (+16.7) 3 -> 3 (0) 0.081 -> 0.081 (0) pass

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 refactors the monolithic message-part.tsx component into a modular structure within a new message-part/ directory, separating concerns for different message parts and tools. The changes include extracting rendering logic into dedicated components and updating the test suite to accommodate the new file structure. Feedback suggests replacing window.location.assign with the application's router for navigation to prevent unnecessary full page reloads.

Comment thread packages/ui/src/components/message-part/tools/agent.tsx
@Astro-Han
Copy link
Copy Markdown
Owner Author

@coderabbitai full review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 14, 2026

✅ Actions performed

Full review triggered.

@Astro-Han Astro-Han merged commit 25d9ee4 into dev May 14, 2026
26 checks passed
@Astro-Han Astro-Han deleted the codex/i601-message-part-split branch May 14, 2026 13:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app Application behavior and product flows P2 Medium priority task Maintainer or agent execution task tech-debt Internal cleanup and maintainability debt ui Design system and user interface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant