⏸ refactor: Improve UX for Parallel Streams (Multi-Convo) (#11096)
Some checks are pending
Docker Dev Branch Images Build / build (Dockerfile, lc-dev, node) (push) Waiting to run
Docker Dev Branch Images Build / build (Dockerfile.multi, lc-dev-api, api-build) (push) Waiting to run

* 🌊 feat: Implement multi-conversation feature with added conversation context and payload adjustments

* refactor: Replace isSubmittingFamily with isSubmitting across message components for consistency

* feat: Add loadAddedAgent and processAddedConvo for multi-conversation agent execution

* refactor: Update ContentRender usage to conditionally render PlaceholderRow based on isLast and isSubmitting

* WIP: first pass, sibling index

* feat: Enhance multi-conversation support with agent tracking and display improvements

* refactor: Introduce isEphemeralAgentId utility and update related logic for agent handling

* refactor: Implement createDualMessageContent utility for sibling message display and enhance useStepHandler for added conversations

* refactor: duplicate tools for added agent if ephemeral and primary agent is also ephemeral

* chore: remove deprecated multimessage rendering

* refactor: enhance dual message content creation and agent handling for parallel rendering

* refactor: streamline message rendering and submission handling by removing unused state and optimizing conditional logic

* refactor: adjust content handling in parallel mode to utilize existing content for improved agent display

* refactor: update @librechat/agents dependency to version 3.0.53

* refactor: update @langchain/core and @librechat/agents dependencies to latest versions

* refactor: remove deprecated @langchain/core dependency from package.json

* chore: remove unused SearchToolConfig and GetSourcesParams types from web.ts

* refactor: remove unused message properties from Message component

* refactor: enhance parallel content handling with groupId support in ContentParts and useStepHandler

* refactor: implement parallel content styling in Message, MessageRender, and ContentRender components. use explicit model name

* refactor: improve agent ID handling in createDualMessageContent for dual message display

* refactor: simplify title generation in AddedConvo by removing unused sender and preset logic

* refactor: replace string interpolation with cn utility for className in HoverButtons component

* refactor: enhance agent ID handling by adding suffix management for parallel agents and updating related components

* refactor: enhance column ordering in ContentParts by sorting agents with suffix management

* refactor: update @librechat/agents dependency to version 3.0.55

* feat: implement parallel content rendering with metadata support

- Added `ParallelContentRenderer` and `ParallelColumns` components for rendering messages in parallel based on groupId and agentId.
- Introduced `contentMetadataMap` to store metadata for each content part, allowing efficient parallel content detection.
- Updated `Message` and `ContentRender` components to utilize the new metadata structure for rendering.
- Modified `useStepHandler` to manage content indices and metadata during message processing.
- Enhanced `IJobStore` interface and its implementations to support storing and retrieving content metadata.
- Updated data schemas to include `contentMetadataMap` for messages, enabling multi-agent and parallel execution scenarios.

* refactor: update @librechat/agents dependency to version 3.0.56

* refactor: remove unused EPHEMERAL_AGENT_ID constant and simplify agent ID check

* refactor: enhance multi-agent message processing and primary agent determination

* refactor: implement branch message functionality for parallel responses

* refactor: integrate added conversation retrieval into message editing and regeneration processes

* refactor: remove unused isCard and isMultiMessage props from MessageRender and ContentRender components

* refactor: update @librechat/agents dependency to version 3.0.60

* refactor: replace usage of EPHEMERAL_AGENT_ID constant with isEphemeralAgentId function for improved clarity and consistency

* refactor: standardize agent ID format in tests for consistency

* chore: move addedConvo property to the correct position in payload construction

* refactor: rename agent_id values in loadAgent tests for clarity

* chore: reorder props in ContentParts component for improved readability

* refactor: rename variable 'content' to 'result' for clarity in RedisJobStore tests

* refactor: streamline useMessageActions by removing duplicate handleFeedback assignment

* chore: revert placeholder rendering logic MessageRender and ContentRender components to original

* refactor: implement useContentMetadata hook for optimized content metadata handling

* refactor: remove contentMetadataMap and related logic from the codebase and revert back to agentId/groupId in content parts

- Eliminated contentMetadataMap from various components and services, simplifying the handling of message content.
- Updated functions to directly access agentId and groupId from content parts instead of relying on a separate metadata map.
- Adjusted related hooks and components to reflect the removal of contentMetadataMap, ensuring consistent handling of message content.
- Updated tests and documentation to align with the new structure of message content handling.

* refactor: remove logging from groupParallelContent function to clean up output

* refactor: remove model parameter from TBranchMessageRequest type for simplification

* refactor: enhance branch message creation by stripping metadata for standalone content

* chore: streamline branch message creation by simplifying content filtering and removing unnecessary metadata checks

* refactor: include attachments in branch message creation for improved content handling

* refactor: streamline agent content processing by consolidating primary agent identification and filtering logic

* refactor: simplify multi-agent message processing by creating a dedicated mapping method and enhancing content filtering

* refactor: remove unused parameter from loadEphemeralAgent function for cleaner code

* refactor: update groupId handling in metadata to only set when provided by the server
This commit is contained in:
Danny Avila 2025-12-25 01:43:54 -05:00 committed by GitHub
parent 9b6e7cabc9
commit 439bc98682
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
74 changed files with 2174 additions and 957 deletions

View file

@ -1,4 +1,4 @@
import { memo, useMemo } from 'react';
import { memo, useMemo, useCallback } from 'react';
import { ContentTypes } from 'librechat-data-provider';
import type {
TMessageContentParts,
@ -7,10 +7,11 @@ import type {
Agents,
} from 'librechat-data-provider';
import { MessageContext, SearchContext } from '~/Providers';
import { ParallelContentRenderer, type PartWithIndex } from './ParallelContent';
import { mapAttachments } from '~/utils';
import { EditTextPart, EmptyText } from './Parts';
import MemoryArtifacts from './MemoryArtifacts';
import Sources from '~/components/Web/Sources';
import { mapAttachments } from '~/utils/map';
import Container from './Container';
import Part from './Part';
@ -33,120 +34,159 @@ type ContentPartsProps = {
| undefined;
};
const ContentParts = memo(
({
content,
messageId,
conversationId,
attachments,
searchResults,
isCreatedByUser,
isLast,
isSubmitting,
isLatestMessage,
edit,
enterEdit,
siblingIdx,
setSiblingIdx,
}: ContentPartsProps) => {
const attachmentMap = useMemo(() => mapAttachments(attachments ?? []), [attachments]);
/**
* ContentParts renders message content parts, handling both sequential and parallel layouts.
*
* For 90% of messages (single-agent, no parallel execution), this renders sequentially.
* For multi-agent parallel execution, it uses ParallelContentRenderer to show columns.
*/
const ContentParts = memo(function ContentParts({
edit,
isLast,
content,
messageId,
enterEdit,
siblingIdx,
attachments,
isSubmitting,
setSiblingIdx,
searchResults,
conversationId,
isCreatedByUser,
isLatestMessage,
}: ContentPartsProps) {
const attachmentMap = useMemo(() => mapAttachments(attachments ?? []), [attachments]);
const effectiveIsSubmitting = isLatestMessage ? isSubmitting : false;
const effectiveIsSubmitting = isLatestMessage ? isSubmitting : false;
/**
* Render a single content part with proper context.
*/
const renderPart = useCallback(
(part: TMessageContentParts, idx: number, isLastPart: boolean) => {
const toolCallId = (part?.[ContentTypes.TOOL_CALL] as Agents.ToolCall | undefined)?.id ?? '';
const partAttachments = attachmentMap[toolCallId];
if (!content) {
return null;
}
if (edit === true && enterEdit && setSiblingIdx) {
return (
<>
{content.map((part, idx) => {
if (!part) {
return null;
}
const isTextPart =
part?.type === ContentTypes.TEXT ||
typeof (part as unknown as Agents.MessageContentText)?.text !== 'string';
const isThinkPart =
part?.type === ContentTypes.THINK ||
typeof (part as unknown as Agents.ReasoningDeltaUpdate)?.think !== 'string';
if (!isTextPart && !isThinkPart) {
return null;
}
const isToolCall =
part.type === ContentTypes.TOOL_CALL || part['tool_call_ids'] != null;
if (isToolCall) {
return null;
}
return (
<EditTextPart
index={idx}
part={part as Agents.MessageContentText | Agents.ReasoningDeltaUpdate}
messageId={messageId}
isSubmitting={isSubmitting}
enterEdit={enterEdit}
siblingIdx={siblingIdx ?? null}
setSiblingIdx={setSiblingIdx}
key={`edit-${messageId}-${idx}`}
/>
);
})}
</>
<MessageContext.Provider
key={`provider-${messageId}-${idx}`}
value={{
messageId,
isExpanded: true,
conversationId,
partIndex: idx,
nextType: content?.[idx + 1]?.type,
isSubmitting: effectiveIsSubmitting,
isLatestMessage,
}}
>
<Part
part={part}
attachments={partAttachments}
isSubmitting={effectiveIsSubmitting}
key={`part-${messageId}-${idx}`}
isCreatedByUser={isCreatedByUser}
isLast={isLastPart}
showCursor={isLastPart && isLast}
/>
</MessageContext.Provider>
);
}
},
[
attachmentMap,
content,
conversationId,
effectiveIsSubmitting,
isCreatedByUser,
isLast,
isLatestMessage,
messageId,
],
);
/** Show cursor placeholder when content is empty but actively submitting */
const showEmptyCursor = content.length === 0 && effectiveIsSubmitting;
// Early return: no content
if (!content) {
return null;
}
// Edit mode: render editable text parts
if (edit === true && enterEdit && setSiblingIdx) {
return (
<>
<SearchContext.Provider value={{ searchResults }}>
<MemoryArtifacts attachments={attachments} />
<Sources messageId={messageId} conversationId={conversationId || undefined} />
{showEmptyCursor && (
<Container>
<EmptyText />
</Container>
)}
{content.map((part, idx) => {
if (!part) {
return null;
}
{content.map((part, idx) => {
if (!part) {
return null;
}
const isTextPart =
part?.type === ContentTypes.TEXT ||
typeof (part as unknown as Agents.MessageContentText)?.text !== 'string';
const isThinkPart =
part?.type === ContentTypes.THINK ||
typeof (part as unknown as Agents.ReasoningDeltaUpdate)?.think !== 'string';
if (!isTextPart && !isThinkPart) {
return null;
}
const toolCallId =
(part?.[ContentTypes.TOOL_CALL] as Agents.ToolCall | undefined)?.id ?? '';
const partAttachments = attachmentMap[toolCallId];
const isToolCall = part.type === ContentTypes.TOOL_CALL || part['tool_call_ids'] != null;
if (isToolCall) {
return null;
}
return (
<MessageContext.Provider
key={`provider-${messageId}-${idx}`}
value={{
messageId,
isExpanded: true,
conversationId,
partIndex: idx,
nextType: content[idx + 1]?.type,
isSubmitting: effectiveIsSubmitting,
isLatestMessage,
}}
>
<Part
part={part}
attachments={partAttachments}
isSubmitting={effectiveIsSubmitting}
key={`part-${messageId}-${idx}`}
isCreatedByUser={isCreatedByUser}
isLast={idx === content.length - 1}
showCursor={idx === content.length - 1 && isLast}
/>
</MessageContext.Provider>
);
})}
</SearchContext.Provider>
return (
<EditTextPart
index={idx}
part={part as Agents.MessageContentText | Agents.ReasoningDeltaUpdate}
messageId={messageId}
isSubmitting={isSubmitting}
enterEdit={enterEdit}
siblingIdx={siblingIdx ?? null}
setSiblingIdx={setSiblingIdx}
key={`edit-${messageId}-${idx}`}
/>
);
})}
</>
);
},
);
}
const showEmptyCursor = content.length === 0 && effectiveIsSubmitting;
const lastContentIdx = content.length - 1;
// Parallel content: use dedicated renderer with columns (TMessageContentParts includes ContentMetadata)
const hasParallelContent = content.some((part) => part?.groupId != null);
if (hasParallelContent) {
return (
<ParallelContentRenderer
content={content}
messageId={messageId}
conversationId={conversationId}
attachments={attachments}
searchResults={searchResults}
isSubmitting={effectiveIsSubmitting}
renderPart={renderPart}
/>
);
}
// Sequential content: render parts in order (90% of cases)
const sequentialParts: PartWithIndex[] = [];
content.forEach((part, idx) => {
if (part) {
sequentialParts.push({ part, idx });
}
});
return (
<SearchContext.Provider value={{ searchResults }}>
<MemoryArtifacts attachments={attachments} />
<Sources messageId={messageId} conversationId={conversationId || undefined} />
{showEmptyCursor && (
<Container>
<EmptyText />
</Container>
)}
{sequentialParts.map(({ part, idx }) => renderPart(part, idx, idx === lastContentIdx))}
</SearchContext.Provider>
);
});
export default ContentParts;

View file

@ -1,10 +1,11 @@
import { useRef, useEffect, useCallback } from 'react';
import { useForm } from 'react-hook-form';
import { useRecoilState, useRecoilValue } from 'recoil';
import { useRecoilValue } from 'recoil';
import { TextareaAutosize, TooltipAnchor } from '@librechat/client';
import { useUpdateMessageMutation } from 'librechat-data-provider/react-query';
import type { TEditProps } from '~/common';
import { useMessagesOperations, useMessagesConversation, useAddedChatContext } from '~/Providers';
import { useMessagesOperations, useMessagesConversation } from '~/Providers';
import { useGetAddedConvo } from '~/hooks/Chat';
import { cn, removeFocusRings } from '~/utils';
import { useLocalize } from '~/hooks';
import Container from './Container';
@ -19,14 +20,10 @@ const EditMessage = ({
siblingIdx,
setSiblingIdx,
}: TEditProps) => {
const { addedIndex } = useAddedChatContext();
const saveButtonRef = useRef<HTMLButtonElement | null>(null);
const submitButtonRef = useRef<HTMLButtonElement | null>(null);
const { conversation } = useMessagesConversation();
const { getMessages, setMessages } = useMessagesOperations();
const [latestMultiMessage, setLatestMultiMessage] = useRecoilState(
store.latestMessageFamily(addedIndex),
);
const textAreaRef = useRef<HTMLTextAreaElement | null>(null);
@ -37,6 +34,8 @@ const EditMessage = ({
const chatDirection = useRecoilValue(store.chatDirection).toLowerCase();
const isRTL = chatDirection === 'rtl';
const getAddedConvo = useGetAddedConvo();
const { register, handleSubmit, setValue } = useForm({
defaultValues: {
text: text ?? '',
@ -62,6 +61,7 @@ const EditMessage = ({
},
{
overrideFiles: message.files,
addedConvo: getAddedConvo() || undefined,
},
);
@ -80,6 +80,7 @@ const EditMessage = ({
editedMessageId: messageId,
isRegenerate: true,
isEdited: true,
addedConvo: getAddedConvo() || undefined,
},
);
@ -101,10 +102,6 @@ const EditMessage = ({
messageId,
});
if (message.messageId === latestMultiMessage?.messageId) {
setLatestMultiMessage({ ...latestMultiMessage, text: data.text });
}
const isInMessages = messages.some((message) => message.messageId === messageId);
if (!isInMessages) {
message.text = data.text;

View file

@ -0,0 +1,269 @@
import { memo, useMemo } from 'react';
import type { TMessageContentParts, SearchResultData, TAttachment } from 'librechat-data-provider';
import { SearchContext } from '~/Providers';
import MemoryArtifacts from './MemoryArtifacts';
import Sources from '~/components/Web/Sources';
import { EmptyText } from './Parts';
import SiblingHeader from './SiblingHeader';
import Container from './Container';
import { cn } from '~/utils';
export type PartWithIndex = { part: TMessageContentParts; idx: number };
export type ParallelColumn = {
agentId: string;
parts: PartWithIndex[];
};
export type ParallelSection = {
groupId: number;
columns: ParallelColumn[];
};
/**
* Groups content parts by groupId for parallel rendering.
* Parts with same groupId are displayed in columns, grouped by agentId.
*
* @param content - Array of content parts
* @returns Object containing parallel sections and sequential parts
*/
export function groupParallelContent(
content: Array<TMessageContentParts | undefined> | undefined,
): { parallelSections: ParallelSection[]; sequentialParts: PartWithIndex[] } {
if (!content) {
return { parallelSections: [], sequentialParts: [] };
}
const groupMap = new Map<number, PartWithIndex[]>();
// Track placeholder agentIds per groupId (parts with empty type that establish columns)
const placeholderAgents = new Map<number, Set<string>>();
const noGroup: PartWithIndex[] = [];
content.forEach((part, idx) => {
if (!part) {
return;
}
// Read metadata directly from content part (TMessageContentParts includes ContentMetadata)
const { groupId } = part;
// Check for placeholder (empty type) before narrowing - access agentId via casting
const partAgentId = (part as { agentId?: string }).agentId;
if (groupId != null) {
// Track placeholder parts (empty type) to establish columns for pending agents
if (!part.type && partAgentId) {
if (!placeholderAgents.has(groupId)) {
placeholderAgents.set(groupId, new Set());
}
placeholderAgents.get(groupId)!.add(partAgentId);
return; // Don't add to groupMap - we'll handle these separately
}
if (!groupMap.has(groupId)) {
groupMap.set(groupId, []);
}
groupMap.get(groupId)!.push({ part, idx });
} else {
noGroup.push({ part, idx });
}
});
// Collect all groupIds (from both real content and placeholders)
const allGroupIds = new Set([...groupMap.keys(), ...placeholderAgents.keys()]);
// Build parallel sections with columns grouped by agentId
const sections: ParallelSection[] = [];
for (const groupId of allGroupIds) {
const columnMap = new Map<string, PartWithIndex[]>();
const parts = groupMap.get(groupId) ?? [];
for (const { part, idx } of parts) {
// Read agentId directly from content part (TMessageContentParts includes ContentMetadata)
const agentId = part.agentId ?? 'unknown';
if (!columnMap.has(agentId)) {
columnMap.set(agentId, []);
}
columnMap.get(agentId)!.push({ part, idx });
}
// Add empty columns for placeholder agents that don't have real content yet
const groupPlaceholders = placeholderAgents.get(groupId);
if (groupPlaceholders) {
for (const placeholderAgentId of groupPlaceholders) {
if (!columnMap.has(placeholderAgentId)) {
// Empty array signals this column should show loading state
columnMap.set(placeholderAgentId, []);
}
}
}
// Sort columns: primary agent (no ____N suffix) first, added agents (with suffix) second
// This ensures consistent column ordering regardless of which agent responds first
const sortedAgentIds = Array.from(columnMap.keys()).sort((a, b) => {
const aHasSuffix = a.includes('____');
const bHasSuffix = b.includes('____');
if (aHasSuffix && !bHasSuffix) {
return 1;
}
if (!aHasSuffix && bHasSuffix) {
return -1;
}
return 0;
});
const columns = sortedAgentIds.map((agentId) => ({
agentId,
parts: columnMap.get(agentId)!,
}));
sections.push({ groupId, columns });
}
// Sort sections by the minimum index in each section (sections with only placeholders go last)
sections.sort((a, b) => {
const aParts = a.columns.flatMap((c) => c.parts.map((p) => p.idx));
const bParts = b.columns.flatMap((c) => c.parts.map((p) => p.idx));
const aMin = aParts.length > 0 ? Math.min(...aParts) : Infinity;
const bMin = bParts.length > 0 ? Math.min(...bParts) : Infinity;
return aMin - bMin;
});
return { parallelSections: sections, sequentialParts: noGroup };
}
type ParallelColumnsProps = {
columns: ParallelColumn[];
groupId: number;
messageId: string;
isSubmitting: boolean;
lastContentIdx: number;
conversationId?: string | null;
renderPart: (part: TMessageContentParts, idx: number, isLastPart: boolean) => React.ReactNode;
};
/**
* Renders parallel content columns for a single groupId.
*/
export const ParallelColumns = memo(function ParallelColumns({
columns,
groupId,
messageId,
conversationId,
isSubmitting,
lastContentIdx,
renderPart,
}: ParallelColumnsProps) {
return (
<div className={cn('flex w-full flex-col gap-3 md:flex-row', 'sibling-content-group')}>
{columns.map(({ agentId, parts: columnParts }, colIdx) => {
// Show loading cursor if column has no content parts yet (empty array from placeholder)
const showLoadingCursor = isSubmitting && columnParts.length === 0;
return (
<div
key={`column-${messageId}-${groupId}-${agentId || colIdx}`}
className="min-w-0 flex-1 rounded-lg border border-border-light p-3"
>
<SiblingHeader
agentId={agentId}
messageId={messageId}
isSubmitting={isSubmitting}
conversationId={conversationId}
/>
{showLoadingCursor ? (
<Container>
<EmptyText />
</Container>
) : (
columnParts.map(({ part, idx }) => {
const isLastInColumn = idx === columnParts[columnParts.length - 1]?.idx;
const isLastContent = idx === lastContentIdx;
return renderPart(part, idx, isLastInColumn && isLastContent);
})
)}
</div>
);
})}
</div>
);
});
type ParallelContentRendererProps = {
content: Array<TMessageContentParts | undefined>;
messageId: string;
conversationId?: string | null;
attachments?: TAttachment[];
searchResults?: { [key: string]: SearchResultData };
isSubmitting: boolean;
renderPart: (part: TMessageContentParts, idx: number, isLastPart: boolean) => React.ReactNode;
};
/**
* Renders content with parallel sections (columns) and sequential parts.
* Handles the layout of before/parallel/after content sections.
*/
export const ParallelContentRenderer = memo(function ParallelContentRenderer({
content,
messageId,
conversationId,
attachments,
searchResults,
isSubmitting,
renderPart,
}: ParallelContentRendererProps) {
const { parallelSections, sequentialParts } = useMemo(
() => groupParallelContent(content),
[content],
);
const lastContentIdx = content.length - 1;
// Split sequential parts into before/after parallel sections
const { before, after } = useMemo(() => {
if (parallelSections.length === 0) {
return { before: sequentialParts, after: [] };
}
const allParallelIndices = parallelSections.flatMap((s) =>
s.columns.flatMap((c) => c.parts.map((p) => p.idx)),
);
const minParallelIdx = Math.min(...allParallelIndices);
const maxParallelIdx = Math.max(...allParallelIndices);
return {
before: sequentialParts.filter(({ idx }) => idx < minParallelIdx),
after: sequentialParts.filter(({ idx }) => idx > maxParallelIdx),
};
}, [parallelSections, sequentialParts]);
return (
<SearchContext.Provider value={{ searchResults }}>
<MemoryArtifacts attachments={attachments} />
<Sources messageId={messageId} conversationId={conversationId || undefined} />
{/* Sequential content BEFORE parallel sections */}
{before.map(({ part, idx }) => renderPart(part, idx, false))}
{/* Parallel sections - each group renders as columns */}
{parallelSections.map(({ groupId, columns }) => (
<ParallelColumns
key={`parallel-group-${messageId}-${groupId}`}
columns={columns}
groupId={groupId}
messageId={messageId}
renderPart={renderPart}
isSubmitting={isSubmitting}
conversationId={conversationId}
lastContentIdx={lastContentIdx}
/>
))}
{/* Sequential content AFTER parallel sections */}
{after.map(({ part, idx }) => renderPart(part, idx, idx === lastContentIdx))}
</SearchContext.Provider>
);
});
export default ParallelContentRenderer;

View file

@ -1,14 +1,15 @@
import { useRef, useEffect, useCallback, useMemo } from 'react';
import { useRecoilValue } from 'recoil';
import { useForm } from 'react-hook-form';
import { TextareaAutosize } from '@librechat/client';
import { ContentTypes } from 'librechat-data-provider';
import { useRecoilState, useRecoilValue } from 'recoil';
import { Lightbulb, MessageSquare } from 'lucide-react';
import { useUpdateMessageContentMutation } from 'librechat-data-provider/react-query';
import type { Agents } from 'librechat-data-provider';
import type { TEditProps } from '~/common';
import { useMessagesOperations, useMessagesConversation, useAddedChatContext } from '~/Providers';
import { useMessagesOperations, useMessagesConversation } from '~/Providers';
import Container from '~/components/Chat/Messages/Content/Container';
import { useGetAddedConvo } from '~/hooks/Chat';
import { cn, removeFocusRings } from '~/utils';
import { useLocalize } from '~/hooks';
import store from '~/store';
@ -25,12 +26,8 @@ const EditTextPart = ({
part: Agents.MessageContentText | Agents.ReasoningDeltaUpdate;
}) => {
const localize = useLocalize();
const { addedIndex } = useAddedChatContext();
const { conversation } = useMessagesConversation();
const { ask, getMessages, setMessages } = useMessagesOperations();
const [latestMultiMessage, setLatestMultiMessage] = useRecoilState(
store.latestMessageFamily(addedIndex),
);
const { conversationId = '' } = conversation ?? {};
const message = useMemo(
@ -40,6 +37,8 @@ const EditTextPart = ({
const chatDirection = useRecoilValue(store.chatDirection);
const getAddedConvo = useGetAddedConvo();
const textAreaRef = useRef<HTMLTextAreaElement | null>(null);
const updateMessageContentMutation = useUpdateMessageContentMutation(conversationId ?? '');
@ -87,6 +86,7 @@ const EditTextPart = ({
editedMessageId: messageId,
isRegenerate: true,
isEdited: true,
addedConvo: getAddedConvo() || undefined,
},
);
@ -105,10 +105,6 @@ const EditTextPart = ({
messageId,
});
if (messageId === latestMultiMessage?.messageId) {
setLatestMultiMessage({ ...latestMultiMessage, text: data.text });
}
const isInMessages = messages.some((msg) => msg.messageId === messageId);
if (!isInMessages) {
return enterEdit(true);

View file

@ -0,0 +1,140 @@
import { useMemo } from 'react';
import { GitBranchPlus } from 'lucide-react';
import { useToastContext } from '@librechat/client';
import { EModelEndpoint, parseEphemeralAgentId, stripAgentIdSuffix } from 'librechat-data-provider';
import type { TMessage, Agent } from 'librechat-data-provider';
import { useBranchMessageMutation } from '~/data-provider/Messages';
import MessageIcon from '~/components/Share/MessageIcon';
import { useAgentsMapContext } from '~/Providers';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
type SiblingHeaderProps = {
/** The agentId from the content part (could be real agent ID or endpoint__model format) */
agentId?: string;
/** The messageId of the parent message */
messageId?: string;
/** The conversationId */
conversationId?: string | null;
/** Whether a submission is in progress */
isSubmitting?: boolean;
};
/**
* Header component for sibling content parts in parallel agent responses.
* Displays the agent/model icon and name for each parallel response.
*/
export default function SiblingHeader({
agentId,
messageId,
conversationId,
isSubmitting,
}: SiblingHeaderProps) {
const agentsMap = useAgentsMapContext();
const localize = useLocalize();
const { showToast } = useToastContext();
const branchMessage = useBranchMessageMutation(conversationId ?? null, {
onSuccess: () => {
showToast({
message: localize('com_ui_branch_created'),
status: 'success',
});
},
onError: () => {
showToast({
message: localize('com_ui_branch_error'),
status: 'error',
});
},
});
const handleBranch = () => {
if (!messageId || !agentId || isSubmitting || branchMessage.isLoading) {
return;
}
branchMessage.mutate({ messageId, agentId });
};
const { displayName, displayEndpoint, displayModel, agent } = useMemo(() => {
// First, try to look up as a real agent
if (agentId) {
// Strip ____N suffix if present (used to distinguish parallel agents with same ID)
const baseAgentId = stripAgentIdSuffix(agentId);
const foundAgent = agentsMap?.[baseAgentId] as Agent | undefined;
if (foundAgent) {
return {
displayName: foundAgent.name,
displayEndpoint: EModelEndpoint.agents,
displayModel: foundAgent.model,
agent: foundAgent,
};
}
// Try to parse as ephemeral agent ID (endpoint__model___sender format)
const parsed = parseEphemeralAgentId(agentId);
if (parsed) {
return {
displayName: parsed.sender || parsed.model || 'AI',
displayEndpoint: parsed.endpoint,
displayModel: parsed.model,
agent: undefined,
};
}
// agentId exists but couldn't be parsed as ephemeral - use it as-is for display
return {
displayName: baseAgentId,
displayEndpoint: EModelEndpoint.agents,
displayModel: undefined,
agent: undefined,
};
}
// Use message model/endpoint as last resort
return {
displayName: 'Agent',
displayEndpoint: EModelEndpoint.agents,
displayModel: undefined,
agent: undefined,
};
}, [agentId, agentsMap]);
return (
<div className="mb-2 flex items-center justify-between gap-2 border-b border-border-light pb-2">
<div className="flex min-w-0 items-center gap-2">
<div className="flex h-5 w-5 flex-shrink-0 items-center justify-center overflow-hidden rounded-full">
<MessageIcon
message={
{
endpoint: displayEndpoint,
model: displayModel,
isCreatedByUser: false,
} as TMessage
}
agent={agent || undefined}
/>
</div>
<span className="truncate text-sm font-medium text-text-primary">{displayName}</span>
</div>
{messageId && agentId && !isSubmitting && (
<button
type="button"
onClick={handleBranch}
disabled={isSubmitting || branchMessage.isLoading}
className={cn(
'flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md',
'text-text-secondary transition-colors hover:bg-surface-hover hover:text-text-primary',
'focus:outline-none focus:ring-2 focus:ring-border-medium focus:ring-offset-1',
'disabled:cursor-not-allowed disabled:opacity-50',
)}
aria-label={localize('com_ui_branch_message')}
title={localize('com_ui_branch_message')}
>
<GitBranchPlus className="h-4 w-4" aria-hidden="true" />
</button>
)}
</div>
);
}