Files
Saxon Fletcher d0135231fb chore(studio): improve assistant feed performance (#50888)
## Problem

Assistant conversations with multiple query and Edge Function blocks
repeatedly render expensive content while streaming. Scrolling past the
feed boundary can also move the surrounding layout.

## Solution

Memoize unchanged messages, blocks, and code highlighting; batch
streaming UI updates; and skip off-screen query layout while keeping
block state mounted. Preserve streamed status updates and contain
scrolling in the message viewport. The changes are shared by Next and
TanStack.

## Review instructions

1. Compare the base branch and this branch using the same saved
conversation containing 10–20 query, result/chart, and Edge Function
blocks. Keep the browser, viewport, and conversation identical.
2. In Chrome DevTools, record Performance with 4× CPU throttling while
streaming a follow-up, typing in the composer, and scrolling through the
feed. Compare scripting/layout time and long tasks. React DevTools
Profiler should show unchanged completed blocks avoiding renders during
subsequent text updates.
3. Scroll away from query blocks and return. Confirm results, display
settings, selections, and controls retain their state. Run a read-only
query such as `select 1` and check its results still update.
4. Confirm “Thinking…” finishes, Stop retains the latest streamed text,
and approval/skip, copy, edit, and branch actions still work. Repeated
scrolling at the feed boundary must leave the outer layout/composer
stationary; jump-to-latest and following new messages should still work.
5. Repeat in both runtimes: `STUDIO_FRAMEWORK=next pnpm dev:studio` and
`STUDIO_FRAMEWORK=tanstack pnpm dev:studio`. Also check the assistant
sidebar, which shares the feed.

## Validation

- 170 assistant/Explorer tests and one shared CodeBlock test passed;
formatting and Studio lint passed (two existing warnings).
- Browser checks covered both route entry points, viewport
state/geometry, and scroll behavior.
- Review fixes: 23 focused tests, lint, formatting, and full Studio
typechecking passed. Full production builds were not verified.

## Checklist

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [x] No docs content changed; docs authoring skills are not applicable.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Performance**
* Improved responsiveness in the AI assistant by reducing unnecessary
updates while messages stream and conversation history is displayed.
* Optimized query previews, message rendering, and code blocks to keep
the interface smoother during use.
* **Bug Fixes**
* Improved handling of message edits and deletions during generation,
and preserved the latest response when generation is stopped.
* Improved conversation scrolling behavior while keeping conversation
content and scroll areas working as expected.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-09-25 18:09:34 +10:00

173 lines
5.6 KiB
TypeScript

import { UIMessage as VercelMessage } from '@ai-sdk/react'
import { memo, useMemo, useState } from 'react'
import { toast } from 'sonner'
import { cn, copyToClipboard } from 'ui'
import { DeleteMessageConfirmModal } from './DeleteMessageConfirmModal'
import { MessageActions } from './Message.Actions'
import type { AddToolApprovalResponse, MessageInfo } from './Message.Context'
import { MessageProvider, useMessageActionsContext, useMessageInfoContext } from './Message.Context'
import { MessageDisplay } from './Message.Display'
function AssistantMessage({ message }: { message: VercelMessage }) {
const { onBranch, onCancelEdit, onRate } = useMessageActionsContext()
const { id, variant, state, isLastMessage, readOnly, rating, isLoading } = useMessageInfoContext()
const handleRate = (newRating: 'positive' | 'negative', reason?: string) => {
onRate?.(id, newRating, reason)
}
const handleCopy = (onSuccess: () => void) => {
const response = message.parts
.filter((x) => x.type === 'text')
.map((x) => x.text)
.join('\n')
copyToClipboard(response, onSuccess)
}
return (
<MessageDisplay.Container
className={cn(
variant === 'warning' && 'bg-warning-200',
state === 'predecessor-editing' && 'opacity-50 transition-opacity cursor-pointer'
)}
onClick={state === 'predecessor-editing' ? onCancelEdit : undefined}
>
<MessageDisplay.MainArea>
<MessageDisplay.Content message={message} />
</MessageDisplay.MainArea>
{!readOnly && onRate && !isLoading && (
<MessageActions alwaysShow={isLastMessage}>
<MessageActions.Copy onClick={handleCopy} />
<MessageActions.ThumbsUp
onClick={() => handleRate('positive')}
isActive={rating === 'positive'}
disabled={!!rating}
/>
<MessageActions.ThumbsDown
onClick={(reason) => handleRate('negative', reason)}
isActive={rating === 'negative'}
disabled={!!rating}
/>
<MessageActions.Branch onClick={() => onBranch(id)} />
</MessageActions>
)}
</MessageDisplay.Container>
)
}
function UserMessage({ message }: { message: VercelMessage }) {
const { id, variant, state } = useMessageInfoContext()
const { onCancelEdit, onEdit, onDelete } = useMessageActionsContext()
const [showDeleteConfirmModal, setShowDeleteConfirmModal] = useState(false)
return (
<>
<MessageDisplay.Container
className={cn(
'mt-6 text-foreground',
variant === 'warning' && 'bg-warning-200',
state === 'predecessor-editing' && 'opacity-50 transition-opacity cursor-pointer'
)}
onClick={state === 'predecessor-editing' ? onCancelEdit : undefined}
>
<MessageDisplay.MainArea className="w-full max-w-3xl mx-auto">
<MessageDisplay.ProfileImage />
<MessageDisplay.Content message={message} />
</MessageDisplay.MainArea>
<MessageActions>
<MessageActions.Edit
onClick={state === 'idle' ? () => onEdit(id) : onCancelEdit}
tooltip={state === 'idle' ? 'Edit message' : 'Cancel editing'}
/>
<MessageActions.Delete onClick={() => setShowDeleteConfirmModal(true)} />
</MessageActions>
</MessageDisplay.Container>
<DeleteMessageConfirmModal
visible={showDeleteConfirmModal}
onConfirm={() => {
onDelete(id)
setShowDeleteConfirmModal(false)
toast.success('Message deleted successfully')
}}
onCancel={() => setShowDeleteConfirmModal(false)}
/>
</>
)
}
interface MessageProps {
id: string
message: VercelMessage
isLoading: boolean
readOnly?: boolean
variant?: 'default' | 'warning'
addToolApprovalResponse?: AddToolApprovalResponse
onDelete: (id: string) => void
onEdit: (id: string) => void
onBranch: (id: string) => void
isAfterEditedMessage: boolean
isBeingEdited: boolean
onCancelEdit: () => void
isLastMessage?: boolean
onRate?: (id: string, rating: 'positive' | 'negative', reason?: string) => void
rating?: 'positive' | 'negative' | null
}
export const Message = memo(function Message(props: MessageProps) {
const message = props.message
const { role } = message
const isUserMessage = role === 'user'
let messageState: MessageInfo['state'] = 'idle'
if (props.isBeingEdited) messageState = 'editing'
else if (props.isAfterEditedMessage) messageState = 'predecessor-editing'
const messageInfo = useMemo<MessageInfo>(
() => ({
id: props.id,
isLoading: props.isLoading,
readOnly: props.readOnly,
variant: props.variant,
isUserMessage,
state: messageState,
isLastMessage: props.isLastMessage,
rating: props.rating,
}),
[
props.id,
props.isLoading,
props.readOnly,
props.variant,
isUserMessage,
messageState,
props.isLastMessage,
props.rating,
]
)
const messageActions = useMemo(
() => ({
addToolApprovalResponse: props.addToolApprovalResponse,
onDelete: props.onDelete,
onEdit: props.onEdit,
onBranch: props.onBranch,
onCancelEdit: props.onCancelEdit,
onRate: props.onRate,
}),
[
props.addToolApprovalResponse,
props.onDelete,
props.onEdit,
props.onBranch,
props.onCancelEdit,
props.onRate,
]
)
return (
<MessageProvider messageInfo={messageInfo} messageActions={messageActions}>
{isUserMessage ? <UserMessage message={message} /> : <AssistantMessage message={message} />}
</MessageProvider>
)
})