🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(playground): scroll to and focus new message on Add message (LFE-6864) (#14811)
Nikita Kabardin1ef1cf5eb9af
diff --git a/web/src/components/ChatMessages/ChatMessageComponent.tsx b/web/src/components/ChatMessages/ChatMessageComponent.tsxindex 025ee3234d..6d532621a7 100644--- a/web/src/components/ChatMessages/ChatMessageComponent.tsx+++ b/web/src/components/ChatMessages/ChatMessageComponent.tsx@@ -38,6 +38,11 @@ import {useOptionalMessageSearchPageId,} from "./MessageSearch";+export type MessageRowRefs = {+ rowRef: RefObject<HTMLDivElement | null>;+ editorRef: RefObject<ReactCodeMirrorRef | null>;+};+type ChatMessageProps = Pick<MessagesContext,| "deleteMessage"@@ -45,7 +50,13 @@ type ChatMessageProps = Pick<| "availableRoles"| "toolCallIds"| "replaceMessage"-> & { message: ChatMessageWithId; index: number };+> & {+ message: ChatMessageWithId;+ index: number;+ // Lets the parent ChatMessages track this row's DOM + editor refs so it can+ // scroll to and focus a freshly added message (LFE-6864).+ registerRow?: (id: string, refs: MessageRowRefs | null) => void;+};const ROLES: ChatMessageRole[] = [ChatMessageRole.User,@@ -94,6 +105,7 @@ export const ChatMessageComponent: React.FC<ChatMessageProps> = ({availableRoles,index: _index,toolCallIds,+ registerRow,}) => {const [roleIndex, setRoleIndex] = useState(1);const playgroundContext = useOptionalPlaygroundContext();@@ -243,7 +255,21 @@ export const ChatMessageComponent: React.FC<ChatMessageProps> = ({unregisterMessageTarget,]);+ // Keep the parent ChatMessages registry in sync so it can scroll to and+ // focus this row when it is the newly added message (LFE-6864). The actual+ // registration happens in handleEditorMount once CodeMirror has mounted and+ // editorRef.current is populated — registering here on first render would+ // store a null editor (CodeMirror mounts async). This effect only handles+ // unregistering the row when it unmounts.+ useEffect(() => {+ return () => {+ registerRow?.(message.id, null);+ };+ }, [message.id, registerRow]);+const handleEditorMount = useCallback(() => {+ registerRow?.(message.id, { rowRef, editorRef });+if (!pageId || !registerMessageTarget) {return;}@@ -252,7 +278,7 @@ export const ChatMessageComponent: React.FC<ChatMessageProps> = ({rowRef,editorRef,});- }, [message.id, pageId, registerMessageTarget]);+ }, [message.id, pageId, registerMessageTarget, registerRow]);return (<Carddiff --git a/web/src/components/ChatMessages/index.tsx b/web/src/components/ChatMessages/index.tsxindex a7d4085df8..3687a23892 100644--- a/web/src/components/ChatMessages/index.tsx+++ b/web/src/components/ChatMessages/index.tsx@@ -1,5 +1,5 @@import { ChevronDownIcon, PlusCircleIcon } from "lucide-react";-import { useEffect, useRef } from "react";+import { useCallback, useEffect, useRef } from "react";import { Button } from "@/src/components/ui/button";import {@@ -20,7 +20,10 @@ import {type ChatMessageWithId,} from "@langfuse/shared";-import { ChatMessageComponent } from "./ChatMessageComponent";+import {+ ChatMessageComponent,+ type MessageRowRefs,+} from "./ChatMessageComponent";import type { MessagesContext } from "./types";import {@@ -40,21 +43,76 @@ import {verticalListSortingStrategy,} from "@dnd-kit/sortable";import { isString } from "@/src/utils/types";+import { useOptionalPlaygroundContext } from "@/src/features/playground/page/context";type ChatMessagesProps = MessagesContext;export const ChatMessages: React.FC<ChatMessagesProps> = (props) => {const { messages } = props;- const scrollAreaRef = useRef<HTMLDivElement | null>(null);- const prevMessageCount = useRef(0);+ const playgroundContext = useOptionalPlaygroundContext();+ const registerScrollToMessage = playgroundContext?.registerScrollToMessage;- // Scroll to bottom when new messages are added- useEffect(() => {- if (prevMessageCount.current < messages.length && scrollAreaRef.current) {- const scrollElement = scrollAreaRef.current;- scrollElement.scrollTop = scrollElement.scrollHeight;+ // Registry of the DOM row + editor refs for each message, keyed by id.+ // Populated by each ChatMessageComponent so that after a new message is+ // appended we can scroll it into view and focus its editor (LFE-6864).+ const rowRefsById = useRef(new Map<string, MessageRowRefs>());++ const registerRow = useCallback((id: string, refs: MessageRowRefs | null) => {+ if (refs) {+ rowRefsById.current.set(id, refs);+ } else {+ rowRefsById.current.delete(id);}- prevMessageCount.current = messages.length;- }, [scrollAreaRef, messages.length]);+ }, []);++ // Scroll the newly added message into view and (by default) focus its editor+ // so the user can type immediately (LFE-6864). Both the row and its CodeMirror+ // editor mount asynchronously, and when the message is added from the dropdown+ // menu the menu's own focus teardown competes with ours over several frames.+ // So rather than guess a fixed delay, retry over a short bounded window until+ // the editor is mounted and actually holds focus (or we give up).+ //+ // Pass focus=false to scroll only, without stealing focus into the new editor+ // — used by programmatic append sites (e.g. GenerationOutput's "Add to+ // messages") where yanking the caret into a fresh editor would be jarring.+ const scrollToMessage = useCallback((id: string, focus = true) => {+ let attempts = 0;+ const maxAttempts = 20; // ~20 animation frames (< ~350ms)++ const attempt = () => {+ const refs = rowRefsById.current.get(id);+ const view = refs?.editorRef.current?.view;++ if (view) {+ refs?.rowRef.current?.scrollIntoView({+ behavior: "smooth",+ block: "nearest",+ });+ if (!focus) return;+ view.focus();+ // The dropdown menu can pull focus back for a frame after closing, so+ // keep retrying until the editor is the active element.+ if (view.hasFocus) return;+ }++ if (attempts++ < maxAttempts) {+ requestAnimationFrame(attempt);+ }+ };++ requestAnimationFrame(attempt);+ }, []);++ // Expose scrollToMessage to the playground context so append sites other than+ // AddMessageButton (e.g. GenerationOutput's "Add to messages") can scroll the+ // newly appended message into view too (LFE-6864). No-op outside the+ // playground (e.g. the New Prompt chat editor), where the context is absent.+ useEffect(() => {+ if (!registerScrollToMessage) return;+ registerScrollToMessage(scrollToMessage);+ return () => {+ registerScrollToMessage(null);+ };+ }, [registerScrollToMessage, scrollToMessage]);const sensors = useSensors(useSensor(MouseSensor, {}),@@ -87,7 +145,7 @@ export const ChatMessages: React.FC<ChatMessagesProps> = (props) => {sensors={sensors}><div className="flex h-full flex-col">- <div className="flex-1 overflow-auto scroll-smooth" ref={scrollAreaRef}>+ <div className="flex-1 overflow-auto scroll-smooth"><div className="flex-1 space-y-2"><SortableContextitems={props.messages.map((message) => message.id)}@@ -104,12 +162,13 @@ export const ChatMessages: React.FC<ChatMessagesProps> = (props) => {replaceMessage={props.replaceMessage}availableRoles={props.availableRoles}toolCallIds={props.toolCallIds}+ registerRow={registerRow}/>);})}</SortableContext><div className="mb-4 py-3">- <AddMessageButton {...props} />+ <AddMessageButton {...props} scrollToMessage={scrollToMessage} /></div></div></div>@@ -118,11 +177,24 @@ export const ChatMessages: React.FC<ChatMessagesProps> = (props) => {);};-type AddMessageButtonProps = Pick<MessagesContext, "messages" | "addMessage">;+type AddMessageButtonProps = Pick<+ MessagesContext,+ "messages" | "addMessage"+> & {+ scrollToMessage: (id: string) => void;+};const AddMessageButton: React.FC<AddMessageButtonProps> = ({messages,addMessage,+ scrollToMessage,}) => {+ // Tracks whether the role dropdown is closing because a menu item was+ // selected (vs. Escape / click-outside). Only then do we suppress Radix's+ // focus-return to the trigger, so our scrollToMessage can focus the new+ // editor. On dismissal we let Radix return focus to the trigger button per+ // the WAI-ARIA menu button pattern (LFE-6864).+ const selectedViaItemRef = useRef(false);+// Skip placeholder messages when determining last rolesconst lastMessageWithRole = messages.slice()@@ -138,53 +210,57 @@ const AddMessageButton: React.FC<AddMessageButtonProps> = ({: ChatMessageRole.User;const addRegularMessage = () => {- if (nextMessageRole === ChatMessageRole.User) {- addMessage({- role: nextMessageRole,- content: "",- type: ChatMessageType.User,- });- } else {- addMessage({- role: nextMessageRole,- content: "",- type: ChatMessageType.AssistantText,- });- }+ const newMessage =+ nextMessageRole === ChatMessageRole.User+ ? addMessage({+ role: nextMessageRole,+ content: "",+ type: ChatMessageType.User,+ })+ : addMessage({+ role: nextMessageRole,+ content: "",+ type: ChatMessageType.AssistantText,+ });+ scrollToMessage(newMessage.id);};const addMessageWithRole = (role: ChatMessageRole) => {+ // A menu item was selected: keep focus on the editor we're about to focus+ // rather than letting Radix return it to the trigger on close.+ selectedViaItemRef.current = true;+ let newMessage: ChatMessageWithId;switch (role) {case ChatMessageRole.User:- addMessage({+ newMessage = addMessage({role: ChatMessageRole.User,content: "",type: ChatMessageType.User,});break;case ChatMessageRole.Assistant:- addMessage({+ newMessage = addMessage({role: ChatMessageRole.Assistant,content: "",type: ChatMessageType.AssistantText,});break;case ChatMessageRole.System:- addMessage({+ newMessage = addMessage({role: ChatMessageRole.System,content: "",type: ChatMessageType.System,});break;case ChatMessageRole.Developer:- addMessage({+ newMessage = addMessage({role: ChatMessageRole.Developer,content: "",type: ChatMessageType.Developer,});break;case ChatMessageRole.Tool:- addMessage({+ newMessage = addMessage({role: ChatMessageRole.Tool,content: "",type: ChatMessageType.ToolResult,@@ -193,14 +269,17 @@ const AddMessageButton: React.FC<AddMessageButtonProps> = ({break;default:addRegularMessage();+ return;}+ scrollToMessage(newMessage.id);};const addPlaceholderMessage = () => {- addMessage({+ const newMessage = addMessage({type: ChatMessageType.Placeholder,name: "",});+ scrollToMessage(newMessage.id);};return (@@ -225,7 +304,22 @@ const AddMessageButton: React.FC<AddMessageButtonProps> = ({<ChevronDownIcon size={14} /></Button></DropdownMenuTrigger>- <DropdownMenuContent align="end">+ <DropdownMenuContent+ align="end"+ // When a menu item was selected, let the newly added message's+ // editor keep focus: without this, Radix restores focus to the+ // trigger button on close, stealing it back from the editor we+ // focus after appending. On Escape / click-outside we leave Radix's+ // default focus-return to the trigger intact so keyboard users+ // aren't dropped onto <body> (WAI-ARIA menu button pattern,+ // LFE-6864).+ onCloseAutoFocus={(event) => {+ if (selectedViaItemRef.current) {+ event.preventDefault();+ selectedViaItemRef.current = false;+ }+ }}+ ><DropdownMenuItemonClick={() => addMessageWithRole(ChatMessageRole.User)}>diff --git a/web/src/features/playground/page/components/GenerationOutput.tsx b/web/src/features/playground/page/components/GenerationOutput.tsxindex 889eb81818..b716e968a8 100644--- a/web/src/features/playground/page/components/GenerationOutput.tsx+++ b/web/src/features/playground/page/components/GenerationOutput.tsx@@ -12,8 +12,14 @@ export const GenerationOutput = () => {const [isAdded, setIsAdded] = useState(false);const [isJson, setIsJson] = useState(false);const scrollAreaRef = useRef<HTMLDivElement | null>(null);- const { output, outputReasoning, outputJson, addMessage, outputToolCalls } =- usePlaygroundContext();+ const {+ output,+ outputReasoning,+ outputJson,+ addMessage,+ outputToolCalls,+ scrollToMessage,+ } = usePlaygroundContext();const handleCopy = () => {setIsCopied(true);@@ -24,20 +30,25 @@ export const GenerationOutput = () => {const handleAddAssistantMessage = () => {setIsAdded(true);- if (outputToolCalls.length > 0) {- addMessage({- type: ChatMessageType.AssistantToolCall,- role: ChatMessageRole.Assistant,- content: output,- toolCalls: outputToolCalls,- });- } else {- addMessage({- type: ChatMessageType.AssistantText,- role: ChatMessageRole.Assistant,- content: output,- });- }+ const newMessage =+ outputToolCalls.length > 0+ ? addMessage({+ type: ChatMessageType.AssistantToolCall,+ role: ChatMessageRole.Assistant,+ content: output,+ toolCalls: outputToolCalls,+ })+ : addMessage({+ type: ChatMessageType.AssistantText,+ role: ChatMessageRole.Assistant,+ content: output,+ });+ // Scroll the appended row into view without stealing focus: this is a+ // programmatic add from the Output panel, so unlike the Add-message button+ // path (focus=true) we shouldn't yank the caret into the new editor. For a+ // tool-call add, addMessage returns the last appended row (the final+ // ToolResult placeholder), so we reveal the newest content (LFE-6864).+ scrollToMessage(newMessage.id, false);setTimeout(() => setIsAdded(false), 1000);};diff --git a/web/src/features/playground/page/context/index.tsx b/web/src/features/playground/page/context/index.tsxindex 0f883b87aa..cbc3960138 100644--- a/web/src/features/playground/page/context/index.tsx+++ b/web/src/features/playground/page/context/index.tsx@@ -74,6 +74,17 @@ type PlaygroundContextType = {handleSubmit: (streaming?: boolean) => Promise<void>;isStreaming: boolean;++ // Scroll-into-view for a freshly appended message (LFE-6864). ChatMessages+ // owns the row/editor registry and registers its scroll helper here; append+ // sites outside AddMessageButton (e.g. GenerationOutput's "Add to messages")+ // call scrollToMessage so the new row lands in view rather than below the+ // fold. Pass focus=false to scroll without stealing focus into the new+ // editor (the default true keeps the Add-message button focusing behavior).+ scrollToMessage: (id: string, focus?: boolean) => void;+ registerScrollToMessage: (+ fn: ((id: string, focus?: boolean) => void) | null,+ ) => void;} & ModelParamsContext &MessagesContext;@@ -138,6 +149,22 @@ export const PlaygroundProvider: React.FC<PlaygroundProviderProps> = ({} = useModelParams(windowId);const { registerWindow, unregisterWindow } = useWindowCoordination();+ // ChatMessages registers its scroll-into-view helper here so sibling append+ // sites (e.g. GenerationOutput) can scroll a newly added message into view+ // (LFE-6864).+ const scrollToMessageRef = useRef<+ ((id: string, focus?: boolean) => void) | null+ >(null);+ const registerScrollToMessage = useCallback(+ (fn: ((id: string, focus?: boolean) => void) | null) => {+ scrollToMessageRef.current = fn;+ },+ [],+ );+ const scrollToMessage = useCallback((id: string, focus = true) => {+ scrollToMessageRef.current?.(id, focus);+ }, []);+const toolCallIds = messages.reduce((acc, m) => {if (m.type === ChatMessageType.AssistantToolCall) {acc.push(...m.toolCalls.map((tc) => tc.id));@@ -269,7 +296,12 @@ export const PlaygroundProvider: React.FC<PlaygroundProviderProps> = ({...toolResultMessages,]);- return toolCallMessage;+ // Return the last appended row so callers scroll to the newest content:+ // for a tool-call add we append the tool-call row plus one ToolResult+ // placeholder per tool call, and the final placeholder is what should+ // land in view (LFE-6864). Falls back to the tool-call row when there+ // are no tool calls.+ return toolResultMessages.at(-1) ?? toolCallMessage;} else if (message.type === ChatMessageType.Placeholder) {const placeholderMessage = {...message,@@ -712,6 +744,8 @@ export const PlaygroundProvider: React.FC<PlaygroundProviderProps> = ({outputToolCalls,handleSubmit,isStreaming,+ scrollToMessage,+ registerScrollToMessage,availableProviders,availableModels,