Skip to content

An AI-powered search engine with a generative UI

refactor: improve reasoning auto-collapse logic in chat messages

Yoshiki Miura84fd25a75224
diff --git a/components/chat-messages.tsx b/components/chat-messages.tsx
index b2b14e4a..c4859723 100644
--- a/components/chat-messages.tsx
+++ b/components/chat-messages.tsx
@@ -3,7 +3,7 @@
import { cn } from '@/lib/utils'
import { UseChatHelpers } from '@ai-sdk/react'
import { UIMessage } from 'ai'
-import { useEffect, useState } from 'react'
+import { useState } from 'react'
import { DefaultSkeleton } from './default-skeleton'
import { RenderMessage } from './render-message'
@@ -36,50 +36,42 @@ export function ChatMessages({
onUpdateMessage,
reload
}: ChatMessagesProps) {
- const [openStates, setOpenStates] = useState<Record<string, boolean>>({})
- const manualToolCallId = 'manual-tool-call'
+ // Track user-modified states (when user explicitly opens/closes)
+ const [userModifiedStates, setUserModifiedStates] = useState<
+ Record<string, boolean>
+ >({})
const isLoading = status === 'submitted' || status === 'streaming'
- useEffect(() => {
- // Open manual tool call when the last section is a user message
- if (sections.length > 0) {
- const lastSection = sections[sections.length - 1]
- if (lastSection.userMessage.role === 'user') {
- setOpenStates({ [manualToolCallId]: true })
- }
- }
- }, [sections])
-
if (!sections.length) return null
- // Get all messages as a flattened array
- const allMessages = sections.flatMap(section => [
- section.userMessage,
- ...section.assistantMessages
- ])
-
- const lastUserIndex =
- allMessages.length -
- 1 -
- [...allMessages].reverse().findIndex(msg => msg.role === 'user')
-
// Check if loading indicator should be shown
const showLoading =
isLoading &&
sections.length > 0 &&
sections[sections.length - 1].assistantMessages.length === 0
- const getIsOpen = (id: string) => {
- if (id.includes('call')) {
- return openStates[id] ?? true
+ const getIsOpen = (id: string, partType?: string, hasNextPart?: boolean) => {
+ // If user has explicitly modified this state, use that
+ if (userModifiedStates.hasOwnProperty(id)) {
+ return userModifiedStates[id]
}
- const baseId = id.endsWith('-related') ? id.slice(0, -8) : id
- const index = allMessages.findIndex(msg => msg.id === baseId)
- return openStates[id] ?? index >= lastUserIndex
+
+ // For tool-invocations, default to open
+ if (partType === 'tool-invocation') {
+ return true
+ }
+
+ // For reasoning, auto-collapse if there's a next part in the same message
+ if (partType === 'reasoning') {
+ return !hasNextPart
+ }
+
+ // For other types (like text), default to open
+ return true
}
const handleOpenChange = (id: string, open: boolean) => {
- setOpenStates(prev => ({
+ setUserModifiedStates(prev => ({
...prev,
[id]: open
}))
@@ -121,6 +113,7 @@ export function ChatMessages({
addToolResult={addToolResult}
onUpdateMessage={onUpdateMessage}
reload={reload}
+ sectionIndex={sectionIndex}
/>
{showLoading && <DefaultSkeleton />}
</div>
@@ -139,6 +132,7 @@ export function ChatMessages({
addToolResult={addToolResult}
onUpdateMessage={onUpdateMessage}
reload={reload}
+ sectionIndex={sectionIndex}
/>
</div>
))}
diff --git a/components/render-message.tsx b/components/render-message.tsx
index 26c1899b..544ffe6d 100644
--- a/components/render-message.tsx
+++ b/components/render-message.tsx
@@ -8,7 +8,7 @@ import { UserTextSection } from './user-text-section'
interface RenderMessageProps {
message: UIMessage
messageId: string
- getIsOpen: (id: string) => boolean
+ getIsOpen: (id: string, partType?: string, hasNextPart?: boolean) => boolean
onOpenChange: (id: string, open: boolean) => void
onQuerySelect: (query: string) => void
chatId?: string
@@ -16,6 +16,7 @@ interface RenderMessageProps {
addToolResult?: (params: { toolCallId: string; result: any }) => void
onUpdateMessage?: (messageId: string, newContent: string) => Promise<void>
reload?: (messageId: string) => Promise<void | string | null | undefined>
+ sectionIndex: number
}
export function RenderMessage({
@@ -28,7 +29,8 @@ export function RenderMessage({
status,
addToolResult,
onUpdateMessage,
- reload
+ reload,
+ sectionIndex
}: RenderMessageProps) {
if (message.role === 'user') {
return (
@@ -73,13 +75,20 @@ export function RenderMessage({
part.type === 'text' &&
textParts.indexOf(part) === textParts.length - 1
+ // Check if there's a next part in this message
+ const hasNextPart = message.parts && index < message.parts.length - 1
+
switch (part.type) {
case 'tool-invocation':
return (
<ToolSection
key={`${messageId}-tool-${index}`}
tool={part.toolInvocation}
- isOpen={getIsOpen(part.toolInvocation.toolCallId)}
+ isOpen={getIsOpen(
+ part.toolInvocation.toolCallId,
+ part.type,
+ hasNextPart
+ )}
onOpenChange={open =>
onOpenChange(part.toolInvocation.toolCallId, open)
}
@@ -94,7 +103,7 @@ export function RenderMessage({
<AnswerSection
key={`${messageId}-text-${index}`}
content={part.text}
- isOpen={getIsOpen(messageId)}
+ isOpen={getIsOpen(messageId, 'text', hasNextPart)}
onOpenChange={open => onOpenChange(messageId, open)}
chatId={chatId}
showActions={isLastTextPart}
@@ -111,7 +120,7 @@ export function RenderMessage({
reasoning: part.text,
isDone: index !== (message.parts?.length ?? 0) - 1
}}
- isOpen={getIsOpen(messageId)}
+ isOpen={getIsOpen(messageId, 'reasoning', hasNextPart)}
onOpenChange={open => onOpenChange(messageId, open)}
/>
)