From dc375a8e1cc79eae700da7667e17015c29810e2e Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Mon, 5 Oct 2026 07:15:04 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=AA=AA=20feat:=20Name=20and=20Face=20Suba?= =?UTF-8?q?gents=20Like=20Main=20Chat=20Turns=20(#16692)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🪪 feat: Name and Face Subagents Like Main Chat Turns The subagent panel and its main chat entry points named children by agent id ("Subagent: agent_…") and framed a parent agent's briefing as a "System" turn under "Parent agent dispatch". They now use main chat's own author treatment: - MessageRow gains `showAuthor` (a user-side turn written by someone other than the reader carries the agent header, mirrored) and `outlined` (host-delivered body without a system heading). The agent header is a shared render helper with static classes, so main chat rows render the same tree as before. - Panel: the parent's briefing and follow-ups are filled user turns under the parent agent's name and avatar; the header, composer placeholder and child turns share one resolved author. External events stay system turns. - Main chat: a subagent wake-up is headed by the subagent's name and face, outlined, with an outcome icon; background-tool wake-ups stay "System". The subagent card leads with the agent's name, and a detached card shows the indexed task status from a leaf component. - Shared conversations resolve the same authors from the shared thread. - `resolveSubagentAgentId` reads an `agent_` type only when no identity was recorded, never for a graph child. Ids never reach visible text; an unresolvable agent is named generically. * fix: Preserve Subagent Identity and Accessible Status * fix: Skip Private Avatar Queries on Public Shares * fix: Preserve Restored Authors and Reuse History Lookups * fix: Respect Graph Identity and Await Historical Authors * fix: Retain Indexed Identity and Shared Wakeup Authors * fix: Render Wakeup Authors in Public Shares * fix: Resolve Shared Wakeups from Persisted Dispatch Identity * fix: Preserve Wakeup Provenance and Parallel Self Identity * fix: Refresh Author Snapshots Between Subagent Dispatches * fix: Align Wakeup Copy and Dispatch Identity * fix: Resolve Restored Subagent Authors Consistently * fix: Preserve Indexed Subagent Display Names --- .../Messages/Content/Parts/SubagentCall.tsx | 95 ++- .../Parts/__tests__/SubagentCall.test.tsx | 115 ++- .../Chat/Messages/Content/Parts/wakeup.ts | 11 + .../Chat/Messages/Content/Wakeup.tsx | 22 +- .../components/Chat/Messages/MessageIcon.tsx | 4 +- .../Chat/Messages/MinimalHoverButtons.tsx | 19 +- .../Chat/Messages/ui/HeaderLabel.tsx | 9 +- .../Chat/Messages/ui/MessageRender.tsx | 23 +- .../Chat/Messages/ui/MessageRow.tsx | 97 ++- .../components/Chat/Messages/ui/WakeupRow.tsx | 91 +++ .../__tests__/MessageRender.wakeup.spec.tsx | 365 +++++++++ .../Messages/ui/__tests__/MessageRow.spec.tsx | 35 + .../SharedSubagentActivityDialog.test.tsx | 112 ++- .../SharedSubagentActivityDialog.tsx | 81 +- .../Subagents/SubagentConversation.test.tsx | 57 +- .../Chat/Subagents/SubagentConversation.tsx | 78 +- .../Subagents/SubagentThreadPanel.test.tsx | 743 +++++++++++++++++- .../Chat/Subagents/SubagentThreadPanel.tsx | 132 +++- .../Chat/Subagents/author.public.test.tsx | 56 ++ .../components/Chat/Subagents/author.test.ts | 141 ++++ .../src/components/Chat/Subagents/author.tsx | 270 +++++++ .../Chat/Subagents/dispatch.test.ts | 68 ++ .../src/components/Chat/Subagents/dispatch.ts | 55 ++ .../Chat/Subagents/identity.test.ts | 4 + .../src/components/Chat/Subagents/identity.ts | 9 +- client/src/components/Share/Message.tsx | 82 +- .../components/Share/Message.wakeup.spec.tsx | 306 ++++++++ client/src/components/Share/ShareView.tsx | 2 +- client/src/hooks/Messages/index.ts | 6 +- .../useCopyMessageToClipboard.spec.tsx | 78 +- .../src/hooks/Messages/useCopyToClipboard.ts | 20 + .../src/hooks/Messages/useMessageActions.tsx | 18 +- .../src/hooks/Messages/useMessageHelpers.tsx | 18 +- client/src/locales/en/translation.json | 13 +- client/src/utils/__tests__/messages.test.ts | 1 + client/src/utils/messages.ts | 1 + 36 files changed, 2990 insertions(+), 247 deletions(-) create mode 100644 client/src/components/Chat/Messages/ui/WakeupRow.tsx create mode 100644 client/src/components/Chat/Messages/ui/__tests__/MessageRender.wakeup.spec.tsx create mode 100644 client/src/components/Chat/Subagents/author.public.test.tsx create mode 100644 client/src/components/Chat/Subagents/author.test.ts create mode 100644 client/src/components/Chat/Subagents/author.tsx create mode 100644 client/src/components/Chat/Subagents/dispatch.test.ts create mode 100644 client/src/components/Chat/Subagents/dispatch.ts create mode 100644 client/src/components/Share/Message.wakeup.spec.tsx diff --git a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx index c5bef1a9c7..f7a38cb4c2 100644 --- a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx @@ -14,8 +14,11 @@ import { subagentProgressKey, useSubagentProgress, } from '~/components/Chat/Subagents/state'; +import { useParentSubagents } from '~/components/Chat/Subagents/ParentSubagentsProvider'; +import { isSelfSpawn as isSelfSpawnType } from '~/components/Chat/Subagents/author'; import { adaptLivePersistedActivity } from '~/components/Chat/Subagents/adapters'; import { resolveSubagentAgentId } from '~/components/Chat/Subagents/identity'; +import { subagentStatusLabelKey } from '~/components/Chat/Subagents/status'; import { useOpenSubagentPanel } from '~/components/Chat/Subagents/surface'; import { MessageContext } from '~/Providers/MessageContext'; import { useShareContext } from '~/Providers/ShareContext'; @@ -193,7 +196,10 @@ export default function SubagentCall({ isSharedConvo !== true && backgroundHandle != null && parentConversationId !== ''; const subagentType = progress?.subagentType ?? extractSubagentType(args); - const isSelfSpawn = subagentType === 'self'; + const isSelfSpawn = isSelfSpawnType( + subagentType, + progress?.subagentKind ?? subagentIdentity?.subagentKind, + ); const subagentAgentId = resolveSubagentAgentId(progress, subagentIdentity); const subagentAgent = subagentAgentId ? agentsMap?.[subagentAgentId] : undefined; /** @@ -280,12 +286,14 @@ export default function SubagentCall({ return localize('com_ui_subagent_complete'); }; const headerText = getHeaderText(); - /** Muted sub-label shown to the right of the base label: the - * configured agent name for named subagents. Self-spawns omit it - * (redundant — the header already says "agent") as do cases where - * the name isn't resolvable (agent map miss). */ + /** A named subagent leads with its own name and face, the way its turns read + * in main chat, and the verb or status follows it muted. Self-spawns keep + * the verb alone — the name would be the agent this card already sits + * under — as do agents the map cannot resolve. */ const subagentNameLabel = !isSelfSpawn && subagentAgent?.name ? subagentAgent.name : ''; + const cardLabel = subagentNameLabel ? `${subagentNameLabel}: ${headerText}` : headerText; + const canOpenDetails = useMemo(() => { const fallbackActivity = adaptLivePersistedActivity({ title: '', @@ -410,9 +418,9 @@ export default function SubagentCall({ canOpenDetails ? 'group' : 'cursor-default opacity-80', running && !detachedStatusUnknown && 'animate-pulse-slow', )} - aria-label={headerText} + aria-label={detachedStatusUnknown ? undefined : cardLabel} > -
+
)}
- - {headerText} - {subagentNameLabel ? ( - - {subagentNameLabel} - + <> + + {subagentNameLabel} + + + {detachedStatusUnknown && backgroundHandle != null ? ( + + ) : ( + headerText + )} + + ) : ( - + <> + + {detachedStatusUnknown && backgroundHandle != null ? ( + + ) : ( + headerText + )} + + + )} {canOpenDetails && ( task.taskId === taskId)?.status ?? + (child?.latestTaskId === taskId ? child.status : undefined); + return <>{status == null ? fallback : localize(subagentStatusLabelKey(status))}; +} + function extractSubagentType(args: SubagentCallProps['args']): string { if (typeof args === 'string') { try { diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx index 9ab4124e92..f1c981b3dd 100644 --- a/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx @@ -3,7 +3,12 @@ import { RecoilRoot } from 'recoil'; import { useAtomValue, useStore } from 'jotai'; import { MemoryRouter } from 'react-router-dom'; import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import type { SubagentUpdateEvent, SubagentIdentity, PartMetadata } from 'librechat-data-provider'; +import type { + PartMetadata, + SubagentIdentity, + SubagentUpdateEvent, + ParentSubagentSummary, +} from 'librechat-data-provider'; import type { SubagentAggregatorState, SubagentContentPart, @@ -29,6 +34,7 @@ import { FOLD_GLYPH_SELECTOR } from '../../rows'; import { litFoldPath } from '../../rail'; const mockMCPServerNames: string[] = []; +let mockIndexedChildren = new Map(); jest.mock('~/hooks', () => ({ useLocalize: @@ -59,16 +65,24 @@ jest.mock('../Attachment', () => ({ jest.mock('lucide-react', () => ({ // eslint-disable-next-line i18next/no-literal-string - ChevronRight: () => chevron, + ChevronRight: () => , // eslint-disable-next-line i18next/no-literal-string - Users: () => users, + Users: () => , })); jest.mock('~/Providers', () => ({ useAgentsMapContext: () => ({ 'agent-1': { id: 'agent-1', name: 'Analyst One', avatar: { filepath: '/analyst.png' } }, + agent_reviewer: { + id: 'agent_reviewer', + name: 'Code Reviewer', + avatar: { filepath: '/reviewer.png' }, + }, }), })); +jest.mock('~/components/Chat/Subagents/ParentSubagentsProvider', () => ({ + useParentSubagents: () => ({ byThreadId: mockIndexedChildren }), +})); jest.mock('~/components/Share/MessageIcon', () => ({ __esModule: true, default: ({ agent }: { agent: { name: string; avatar: { filepath: string } } }) => ( @@ -85,6 +99,7 @@ jest.mock('~/utils', () => ({ afterEach(() => { jest.useRealTimers(); mockMCPServerNames.length = 0; + mockIndexedChildren = new Map(); }); function foldEvents(events: SubagentUpdateEvent[]): { @@ -505,6 +520,100 @@ describe('SubagentCall', () => { expect(rendered.getSelection()?.legacyOutput).toBeUndefined(); }); + it('leads a detached agent card with its name, face and the indexed task status', () => { + const output = JSON.stringify({ + background_task_id: 'task-1', + subagent_thread_id: 'child-thread-1', + tool: 'subagent', + subagent_type: 'agent_reviewer', + status: 'running', + message: + 'Started subagent "agent_reviewer" background task. Poll the host background-task tool with background_task_id "task-1".', + }); + mockIndexedChildren = new Map([ + [ + 'child-thread-1', + { + threadId: 'child-thread-1', + status: 'completed', + latestTaskId: 'task-1', + tasks: [{ taskId: 'task-1', status: 'completed' }], + } as ParentSubagentSummary, + ], + ]); + /** Saved identity disambiguates agent ids from graph aliases. */ + renderWithState({ + toolCallId: 'named-detached', + initialProgress: 1, + subagentIdentity: { subagentKind: 'agent', subagentAgentId: 'agent_reviewer' }, + output, + toolArgs: { subagent_type: 'agent_reviewer', run_in_background: true }, + }); + + const card = screen.getByRole('button', { + name: 'Code Reviewer com_ui_subagent_thread_status_completed', + }); + expect(within(card).getByText('Code Reviewer')).toBeInTheDocument(); + expect(within(card).getByRole('img', { hidden: true })).toHaveAttribute('src', '/reviewer.png'); + expect(within(card).getByText('com_ui_subagent_thread_status_completed')).toBeInTheDocument(); + expect(within(card).queryByText(/agent_reviewer/)).not.toBeInTheDocument(); + }); + + it.each(['self', 'researcher', 'agent_missing'])( + 'exposes the indexed outcome for an unnamed detached %s child', + (subagentType) => { + mockIndexedChildren = new Map([ + [ + 'child-thread-1', + { + threadId: 'child-thread-1', + latestTaskId: 'task-1', + status: 'failed', + tasks: [{ taskId: 'task-1', status: 'failed' }], + } as ParentSubagentSummary, + ], + ]); + renderWithState({ + toolCallId: 'unnamed-detached', + initialProgress: 1, + toolArgs: { subagent_type: subagentType, run_in_background: true }, + output: JSON.stringify({ + background_task_id: 'task-1', + subagent_thread_id: 'child-thread-1', + tool: 'subagent', + subagent_type: subagentType, + status: 'running', + message: 'Started subagent background task. Poll with background_task_id task-1.', + }), + }); + expect( + screen.getByRole('button', { name: 'com_ui_subagent_thread_status_failed' }), + ).not.toHaveAttribute('aria-label'); + }, + ); + + it('keeps the neutral label for a detached child the index has not reported', () => { + const output = JSON.stringify({ + background_task_id: 'task-1', + subagent_thread_id: 'child-thread-1', + tool: 'subagent', + subagent_type: 'agent_reviewer', + status: 'running', + message: + 'Started subagent "agent_reviewer" background task. Poll the host background-task tool with background_task_id "task-1".', + }); + renderWithState({ + toolCallId: 'unindexed-detached', + initialProgress: 1, + subagentIdentity: { subagentKind: 'agent', subagentAgentId: 'agent_reviewer' }, + output, + toolArgs: { subagent_type: 'agent_reviewer', run_in_background: true }, + }); + + const card = screen.getByRole('button', { name: 'Code Reviewer Agent activity' }); + expect(within(card).getByText('Agent activity')).toBeInTheDocument(); + }); + it('disables an inaccessible nested detached drilldown without renderable activity', () => { const output = JSON.stringify({ background_task_id: 'task-1', diff --git a/client/src/components/Chat/Messages/Content/Parts/wakeup.ts b/client/src/components/Chat/Messages/Content/Parts/wakeup.ts index 1b90e90ee6..b91106fce8 100644 --- a/client/src/components/Chat/Messages/Content/Parts/wakeup.ts +++ b/client/src/components/Chat/Messages/Content/Parts/wakeup.ts @@ -1,3 +1,5 @@ +import type { TMessage } from 'librechat-data-provider'; + export type WakeupTaskStatus = 'completed' | 'error' | 'cancelled'; export type WakeupTask = { @@ -123,3 +125,12 @@ export function parseWakeupText(text?: string | null): WakeupDisplay | null { } return { kind: 'background_tool', tasks: tasks as WakeupTask[] }; } + +/** User-submitted lookalikes are ordinary prompts. Older host wake-ups may omit + * provenance, so retain their existing strict header/payload compatibility. */ +export function parseWakeupMessage( + message: Pick | undefined, +): WakeupDisplay | null { + if (message?.isCreatedByUser !== true || message.isUserSubmitted === true) return null; + return parseWakeupText(message.text); +} diff --git a/client/src/components/Chat/Messages/Content/Wakeup.tsx b/client/src/components/Chat/Messages/Content/Wakeup.tsx index b6345cd244..a918d656d8 100644 --- a/client/src/components/Chat/Messages/Content/Wakeup.tsx +++ b/client/src/components/Chat/Messages/Content/Wakeup.tsx @@ -1,5 +1,4 @@ import { memo, useCallback, useMemo, useState } from 'react'; -import { Users } from 'lucide-react'; import { useRecoilValue } from 'recoil'; import { Button } from '@librechat/client'; import type { WakeupDisplay, WakeupTask } from './Parts/wakeup'; @@ -27,6 +26,17 @@ const SUBAGENT_HEADER_KEYS = { const threadStatus = (status: WakeupTask['status']) => status === 'error' ? ('failed' as const) : status; +/** The outcome glyph, colored for success only: a failure already paints the + * header label with the warning role. */ +function SubagentOutcomeIcon({ status }: { status: ReturnType }) { + const StatusIcon = subagentStatusIcon(status); + return ( + + + + ); +} + function WakeupTaskCard({ task, conversationId, @@ -47,7 +57,6 @@ function WakeupTaskCard({ const { selection, open: openActivity } = useSubagentTaskPanel(durableTask, conversationId); const status = threadStatus(task.status); const StatusIcon = subagentStatusIcon(status); - const title = task.subagentType ?? ''; const hasResult = task.result.trim() !== ''; return ( @@ -58,7 +67,6 @@ function WakeupTaskCard({ aria-hidden className={cn('shrink-0', status === 'failed' && 'text-status-error')} /> - {title !== '' && {title}} {localize(subagentStatusLabelKey(status))} {selection != null && openActivity != null && ( /** The trigger identity attributes let the panel's close handler @@ -129,9 +137,11 @@ const Wakeup = memo(function Wakeup({ return localize('com_ui_wakeup_task_finished'); }, [display.kind, display.tasks, localize]); + /** A subagent's report is headed by the agent's own name and face on its row, + * so its header line carries only the outcome. */ const nameSummary = useMemo(() => { if (display.kind === 'subagent') { - return display.tasks[0]?.subagentType ?? ''; + return ''; } const seen = new Set(); const labels: string[] = []; @@ -167,9 +177,7 @@ const Wakeup = memo(function Wakeup({ live icon={ display.kind === 'subagent' ? ( - - - + ) : ( ) diff --git a/client/src/components/Chat/Messages/MessageIcon.tsx b/client/src/components/Chat/Messages/MessageIcon.tsx index a5a395473f..83f2bc1dfe 100644 --- a/client/src/components/Chat/Messages/MessageIcon.tsx +++ b/client/src/components/Chat/Messages/MessageIcon.tsx @@ -3,6 +3,7 @@ import { getEndpointField } from 'librechat-data-provider'; import type { Assistant, Agent } from 'librechat-data-provider'; import type { TMessageIcon } from '~/common'; import ConvoIconURL from '~/components/Endpoints/ConvoIconURL'; +import { useShareContext } from '~/Providers/ShareContext'; import { useGetEndpointsQuery } from '~/data-provider'; import Icon from '~/components/Endpoints/Icon'; import { isImageURL } from '~/utils/icons'; @@ -41,7 +42,8 @@ export function arePropsEqual(prev: MessageIconProps, next: MessageIconProps): b } const MessageIcon = memo(({ iconData, assistant, agent }: MessageIconProps) => { - const { data: endpointsConfig } = useGetEndpointsQuery(); + const { isSharedConvo } = useShareContext(); + const { data: endpointsConfig } = useGetEndpointsQuery({ enabled: isSharedConvo !== true }); const agentName = agent?.name ?? ''; const agentAvatar = agent?.avatar?.filepath ?? ''; diff --git a/client/src/components/Chat/Messages/MinimalHoverButtons.tsx b/client/src/components/Chat/Messages/MinimalHoverButtons.tsx index ef5e6a73f9..6754727f48 100644 --- a/client/src/components/Chat/Messages/MinimalHoverButtons.tsx +++ b/client/src/components/Chat/Messages/MinimalHoverButtons.tsx @@ -3,7 +3,12 @@ import { Copy, Check } from 'lucide'; import { Button, MorphIcon, TooltipAnchor } from '@librechat/client'; import type { TMessage, SearchResultData } from 'librechat-data-provider'; import type { MarkdownVariant } from '~/utils/richtext'; -import { useLocalize, useCopyMessageToClipboard, hasCopyableText } from '~/hooks'; +import { + useLocalize, + useCopyMessageToClipboard, + getMessageClipboardSource, + hasCopyableText, +} from '~/hooks'; import { revealOnRowHoverClasses } from './styles'; import { cn } from '~/utils'; @@ -17,17 +22,15 @@ type THoverButtons = { export default function MinimalHoverButtons({ message, searchResults, variant }: THoverButtons) { const localize = useLocalize(); const [isCopied, setIsCopied] = useState(false); + const clipboardSource = useMemo(() => getMessageClipboardSource(message), [message]); const copyToClipboard = useCopyMessageToClipboard({ - text: message.text, - content: message.content, + ...clipboardSource, searchResults, - isCreatedByUser: message.isCreatedByUser, - error: message.error, - variant, + variant: clipboardSource.variant ?? variant, }); const canCopy = useMemo( - () => hasCopyableText({ text: message.text, content: message.content, searchResults }), - [message.text, message.content, searchResults], + () => hasCopyableText({ ...clipboardSource, searchResults }), + [clipboardSource, searchResults], ); return ( diff --git a/client/src/components/Chat/Messages/ui/HeaderLabel.tsx b/client/src/components/Chat/Messages/ui/HeaderLabel.tsx index 83167b40df..9eaa2d12f3 100644 --- a/client/src/components/Chat/Messages/ui/HeaderLabel.tsx +++ b/client/src/components/Chat/Messages/ui/HeaderLabel.tsx @@ -11,15 +11,16 @@ type HeaderLabelProps = { * header. */ const DOCUMENT_ID_PREFIXES = ['agent_', 'asst_']; +/** An agent or assistant document id: a storage key, never a name to show. */ +export const isDocumentId = (value: string): boolean => + DOCUMENT_ID_PREFIXES.some((prefix) => value.startsWith(prefix)); + /** Skip document ids so the hover label is a real model name. */ export function getHeaderModelName( ...candidates: Array ): string | undefined { return candidates.find( - (value): value is string => - value != null && - value !== '' && - !DOCUMENT_ID_PREFIXES.some((prefix) => value.startsWith(prefix)), + (value): value is string => value != null && value !== '' && !isDocumentId(value), ); } diff --git a/client/src/components/Chat/Messages/ui/MessageRender.tsx b/client/src/components/Chat/Messages/ui/MessageRender.tsx index 63f9dcf2ff..945a4d6c6c 100644 --- a/client/src/components/Chat/Messages/ui/MessageRender.tsx +++ b/client/src/components/Chat/Messages/ui/MessageRender.tsx @@ -10,7 +10,7 @@ import { getHeaderPrefixForScreenReader, } from '~/utils'; import { revealOnRowHoverClasses, messageFooterClasses } from '~/components/Chat/Messages/styles'; -import { parseWakeupText } from '~/components/Chat/Messages/Content/Parts/wakeup'; +import { parseWakeupMessage } from '~/components/Chat/Messages/Content/Parts/wakeup'; import Elapsed, { shouldShowElapsed } from '~/components/Chat/Messages/Elapsed'; import { getHeaderHoverLabel } from '~/components/Chat/Messages/ui/HeaderLabel'; import MessageContent from '~/components/Chat/Messages/Content/MessageContent'; @@ -23,6 +23,7 @@ import MessageIcon from '~/components/Chat/Messages/MessageIcon'; import Wakeup from '~/components/Chat/Messages/Content/Wakeup'; import SubRow from '~/components/Chat/Messages/SubRow'; import { MessageContext } from '~/Providers'; +import WakeupRow from './WakeupRow'; import store from '~/store'; type MessageRenderProps = { @@ -139,10 +140,7 @@ const MessageRender = memo(function MessageRender({ ); const { hasParallelContent } = useContentMetadata(msg); - const wakeupDisplay = useMemo( - () => (msg?.isCreatedByUser === true ? parseWakeupText(msg.text) : null), - [msg?.isCreatedByUser, msg?.text], - ); + const wakeupDisplay = useMemo(() => parseWakeupMessage(msg), [msg]); const messageId = msg?.messageId ?? ''; const messageContextValue = useMemo( () => ({ @@ -160,9 +158,14 @@ const MessageRender = memo(function MessageRender({ } const showOwnerText = !edit && msg.isCreatedByUser && Boolean(msg.privacyRevision); + const subagentWakeup = + !edit && wakeupDisplay?.kind === 'subagent' ? wakeupDisplay.tasks[0] : undefined; + const Row = subagentWakeup == null ? MessageRow : WakeupRow; return ( - } label={messageLabel ?? ''} @@ -180,7 +183,11 @@ const MessageRender = memo(function MessageRender({ hasParallelContent={hasParallelContent} fullWidth={maximizeChatSpace} isEditing={edit} - systemLabel={wakeupDisplay != null && !edit ? localize('com_ui_system_event') : undefined} + systemLabel={ + wakeupDisplay != null && subagentWakeup == null && !edit + ? localize('com_ui_system_event') + : undefined + } footer={ {/* The reading holds the column start: it takes over the slot the streaming @@ -249,7 +256,7 @@ const MessageRender = memo(function MessageRender({ /> ))} - + ); }, areMessageRenderPropsEqual); MessageRender.displayName = 'MessageRender'; diff --git a/client/src/components/Chat/Messages/ui/MessageRow.tsx b/client/src/components/Chat/Messages/ui/MessageRow.tsx index 3ea142bf43..4971419f5e 100644 --- a/client/src/components/Chat/Messages/ui/MessageRow.tsx +++ b/client/src/components/Chat/Messages/ui/MessageRow.tsx @@ -18,13 +18,62 @@ type MessageRowProps = { hasParallelContent?: boolean; fullWidth?: boolean; isEditing?: boolean; - /** Marks a host-authored turn (wake-up results, subagent triggers): it keeps - * the user's position and bubble shape, outlined instead of filled, under - * this visible heading in place of the author's name. */ + /** Marks a host-authored turn with no author to name (background-tool + * wake-ups, external events): it keeps the user's position and bubble shape, + * outlined instead of filled, under this visible heading. */ systemLabel?: string; + /** A user-side turn written by someone other than the reader — a parent agent + * briefing its subagent, a subagent reporting back. It keeps the user's + * position and bubble, under the same avatar-and-name header an agent turn + * carries. */ + showAuthor?: boolean; + /** Outline the user-side bubble instead of filling it: content the host + * delivered rather than words someone typed. Implied by `systemLabel`. */ + outlined?: boolean; className?: string; }; +/** `mb-1` keeps the name off its own first line of body text. Static per side: + * every agent row in a thread renders one, so it is never merged at runtime. */ +const authorHeaderClasses = { + start: + 'text-text-primary mb-1 flex min-h-7 w-full items-center gap-2 text-sm font-semibold select-none', + end: 'text-text-primary mb-1 flex min-h-7 items-center justify-end gap-2 text-sm font-semibold select-none', +} as const; + +/** The author line every visible-author turn shares, so an agent's turn and an + * agent-written user-side turn cannot drift apart. A render helper rather than + * a component, so a main chat row's tree stays exactly as deep as before. */ +function renderAuthorHeader({ + icon, + label, + hoverLabel, + headerPrefix, + timestamp, + align, +}: Pick & { + align: 'start' | 'end'; +}) { + return ( +

+ {align === 'end' && ( + + )} + + {headerPrefix} + + {align === 'start' && ( + + )} +

+ ); +} + export function getMessageRowWidthClass({ fullWidth = false, hasParallelContent = false, @@ -53,6 +102,8 @@ export default function MessageRow({ fullWidth = false, isEditing = false, systemLabel, + showAuthor = false, + outlined = false, }: MessageRowProps) { // Same column as ChatForm: max-width plus `sm:px-2`, so the body lines // up with the composer surface rather than the form's outer box. @@ -93,28 +144,24 @@ export default function MessageRow({
)} + {!hasParallelContent && !isSystem && isCreatedByUser && !showAuthor && ( +

+ {headerPrefix} + {label} + +

+ )} {!hasParallelContent && !isSystem && - (isCreatedByUser ? ( -

- {headerPrefix} - {label} - -

- ) : ( - /** `mb-1` keeps the name off its own first line of body text. */ -

- - {headerPrefix} - - -

- ))} + (!isCreatedByUser || showAuthor) && + renderAuthorHeader({ + icon, + label, + hoverLabel, + headerPrefix, + timestamp, + align: isCreatedByUser ? 'end' : 'start', + })}
& { task?: WakeupTask; conversationId: string }) { + const localize = useLocalize(); + const agentsMap = useAgentsMapContext(); + const { isSharedConvo } = useShareContext(); + const { getMessages } = useOptionalMessagesOperations(); + const { byThreadId } = useParentSubagents(); + const child = task?.threadId == null ? undefined : byThreadId.get(task.threadId); + const dispatch = useMemo( + () => + child == null ? findSubagentDispatch(getMessages(conversationId), task?.threadId) : undefined, + [child, conversationId, getMessages, task?.threadId], + ); + const parentMessageId = child?.parentMessageId ?? dispatch?.message.messageId ?? props.id ?? ''; + const fallbackName = localize('com_ui_subagent_actor'); + const privateParentAuthor = useParentAuthor( + conversationId, + isSharedConvo === true ? '' : parentMessageId, + fallbackName, + child?.parentToolCallId, + undefined, + isSharedConvo === true ? undefined : task?.threadId, + ); + const parentAuthor = useMemo( + () => + isSharedConvo === true + ? messageAuthor( + dispatch?.message ?? findAgentAuthorMessage(getMessages(), parentMessageId), + agentsMap, + fallbackName, + dispatch?.agentId, + ) + : privateParentAuthor, + [ + agentsMap, + fallbackName, + getMessages, + isSharedConvo, + parentMessageId, + privateParentAuthor, + dispatch, + ], + ); + const author = useMemo( + () => + resolveSubagentAuthor( + { + subagentType: child?.subagentType ?? dispatch?.subagentType ?? task?.subagentType, + subagentKind: child?.subagentKind ?? dispatch?.identity?.subagentKind, + agentId: child?.agentId ?? dispatch?.identity?.subagentAgentId, + title: child?.title, + }, + parentAuthor, + agentsMap, + fallbackName, + ), + [agentsMap, child, dispatch, fallbackName, parentAuthor, task?.subagentType], + ); + return ( + + ); +} diff --git a/client/src/components/Chat/Messages/ui/__tests__/MessageRender.wakeup.spec.tsx b/client/src/components/Chat/Messages/ui/__tests__/MessageRender.wakeup.spec.tsx new file mode 100644 index 0000000000..18a2163fd5 --- /dev/null +++ b/client/src/components/Chat/Messages/ui/__tests__/MessageRender.wakeup.spec.tsx @@ -0,0 +1,365 @@ +import { RecoilRoot } from 'recoil'; +import { render, screen } from '@testing-library/react'; +import { ContentTypes, QueryKeys } from 'librechat-data-provider'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import type { ParentSubagentSummary, TMessage } from 'librechat-data-provider'; +import type { TMessageChatContext } from '~/common'; +import { ShareMessagesProvider } from '~/components/Share/ShareMessagesProvider'; +import { ShareContext } from '~/Providers/ShareContext'; +import MessageRender from '../MessageRender'; + +const mockAgentsMap = { + agent_reviewer: { id: 'agent_reviewer', name: 'Code Reviewer' }, + agent_lia: { id: 'agent_lia', name: 'Lia' }, +}; + +let mockChildren = new Map(); +jest.mock('~/components/Chat/Subagents/ParentSubagentsProvider', () => ({ + useParentSubagents: () => ({ byThreadId: mockChildren }), +})); + +jest.mock('~/Providers', () => ({ + ...jest.requireActual('~/Providers/MessageContext'), + useAgentsMapContext: () => mockAgentsMap, +})); + +jest.mock('~/hooks', () => ({ + useLocalize: () => (key: string) => key, + useContentMetadata: () => ({ hasParallelContent: false }), + useMessageActions: ({ message }: { message: TMessage }) => ({ + ask: jest.fn(), + edit: false, + index: 0, + agent: mockAgentsMap.agent_lia, + assistant: undefined, + enterEdit: jest.fn(), + conversation: { conversationId: 'conversation-1', endpoint: 'agents' }, + messageLabel: message.isCreatedByUser ? 'Danny' : 'Lia', + handleFeedback: jest.fn(), + handleContinue: jest.fn(), + copyToClipboard: jest.fn(), + getCanCopy: () => true, + regenerateMessage: jest.fn(), + hasConfiguredSender: false, + }), +})); + +/** The author glyph reduced to whose face it is. */ +jest.mock('~/components/Chat/Messages/MessageIcon', () => ({ + __esModule: true, + default: ({ agent, iconData }: { agent?: { name?: string }; iconData: { iconURL?: string } }) => ( + + ), +})); +jest.mock('~/components/Chat/Messages/Content/Wakeup', () => ({ + __esModule: true, + default: () =>
, +})); +jest.mock('~/components/Chat/Messages/Content/MessageContent', () => ({ + __esModule: true, + default: () =>
, +})); +jest.mock('~/components/Chat/Messages/HoverButtons', () => ({ + __esModule: true, + default: () => null, +})); +jest.mock('~/components/Chat/Messages/SiblingSwitch', () => ({ + __esModule: true, + default: () => null, +})); +jest.mock('~/components/Chat/Messages/ui/MessageTimestamp', () => ({ + __esModule: true, + default: () => null, +})); + +const chatContext = { latestMessageId: 'wake' } as unknown as TMessageChatContext; + +const subagentWakeup = (subagentType: string) => + [ + 'A detached subagent task has completed. Continue the parent task using its durable result below.', + JSON.stringify({ + background_task_id: 'task-1', + subagent_thread_id: 'thread-1', + subagent_type: subagentType, + status: 'completed', + result: 'One finding.', + }), + ].join('\n'); + +const backgroundWakeup = [ + 'A background tool task has finished. Continue using its durable result below.', + JSON.stringify([ + { + background_task_id: 'task-2', + tool_call_id: 'call-1', + tool: 'bash', + status: 'completed', + result: 'ok', + }, + ]), +].join('\n'); + +function renderMessage( + text: string, + parentModel = 'agent_lia', + shared = false, + submitted = false, + dispatch?: TMessage, +) { + const queryClient = new QueryClient(); + queryClient.setQueryData( + [QueryKeys.messages, 'conversation-1'], + [ + dispatch ?? { + messageId: 'dispatch', + isCreatedByUser: false, + endpoint: 'agents', + model: parentModel, + sender: 'Historical Parent', + iconURL: '/historical.png', + }, + ], + ); + const message = { + messageId: 'wake', + parentMessageId: 'parent', + conversationId: 'conversation-1', + isCreatedByUser: true, + isUserSubmitted: submitted, + text, + } as unknown as TMessage; + const row = ; + const sharedReply: TMessage = { + messageId: 'shared-reply', + parentMessageId: 'wake', + conversationId: 'original-shared-conversation', + text: 'Parent continuation', + isCreatedByUser: false, + endpoint: 'agents', + model: parentModel, + sender: 'Shared Historical Parent', + iconURL: '/shared-historical.png', + }; + return render( + + + {shared ? ( + + {row} + + ) : ( + ([QueryKeys.messages, 'conversation-1']) ?? [] + } + > + {row} + + )} + + , + ); +} + +describe('MessageRender wake-up rows', () => { + beforeEach(() => { + mockChildren = new Map([ + [ + 'thread-1', + { + threadId: 'thread-1', + parentMessageId: 'dispatch', + subagentType: 'agent_reviewer', + subagentKind: 'agent', + agentId: 'agent_reviewer', + title: 'Stored Reviewer', + } as ParentSubagentSummary, + ], + ]); + }); + it('heads a subagent report with the subagent name and face instead of a system label', () => { + renderMessage(subagentWakeup('agent_reviewer')); + + const heading = screen.getByRole('heading', { name: 'Code Reviewer' }); + expect(heading).not.toHaveClass('sr-only'); + expect(screen.getByTestId('author-face')).toHaveAttribute('data-agent', 'Code Reviewer'); + expect(screen.queryByText('com_ui_system_event')).not.toBeInTheDocument(); + expect(screen.queryByText(/agent_reviewer/)).not.toBeInTheDocument(); + /** Delivered by the host, not typed: outlined, on the user's side. */ + expect(screen.getByTestId('message-body')).toHaveClass('border', 'border-border-medium'); + expect(screen.getByTestId('message-body')).not.toHaveClass('bg-surface-tertiary'); + expect(screen.getByTestId('wakeup-card')).toBeInTheDocument(); + }); + + it('names a self-spawned report after the agent it woke', () => { + mockChildren.set('thread-1', { + ...mockChildren.get('thread-1')!, + subagentType: 'self', + agentId: 'agent_lia', + }); + renderMessage(subagentWakeup('self')); + + expect(screen.getByRole('heading', { name: /Lia$/ })).toBeInTheDocument(); + expect(screen.getByTestId('author-face')).toHaveAttribute('data-agent', 'Lia'); + }); + + it('keeps historical self-spawn identity after switching the current agent', () => { + mockChildren.set('thread-1', { ...mockChildren.get('thread-1')!, subagentType: 'self' }); + renderMessage(subagentWakeup('self'), 'agent_reviewer'); + expect(screen.getByRole('heading', { name: 'Code Reviewer' })).toBeInTheDocument(); + expect(screen.getByTestId('author-face')).toHaveAttribute('data-agent', 'Code Reviewer'); + }); + + it('retains the historical avatar when the self-spawning agent is unavailable', () => { + mockChildren.set('thread-1', { + ...mockChildren.get('thread-1')!, + subagentType: 'self', + agentId: 'agent_deleted', + }); + renderMessage(subagentWakeup('self'), 'agent_deleted'); + expect(screen.getByRole('heading', { name: 'Historical Parent' })).toBeInTheDocument(); + expect(screen.getByTestId('author-face')).toHaveAttribute('data-icon', '/historical.png'); + }); + + it.each(['agent_reviewer', 'agent_deleted'])( + 'reads an unindexed public self wake-up author from the shared transcript (%s)', + (parentModel) => { + mockChildren.clear(); + renderMessage(subagentWakeup('self'), parentModel, true); + const name = parentModel === 'agent_reviewer' ? 'Code Reviewer' : 'Shared Historical Parent'; + expect(screen.getByRole('heading', { name })).toBeInTheDocument(); + expect(screen.getByTestId('author-face')).toHaveAttribute( + 'data-icon', + '/shared-historical.png', + ); + expect(screen.queryByRole('heading', { name: 'Lia' })).not.toBeInTheDocument(); + }, + ); + + it.each(['agent_reviewer', 'agent_research_team'])( + 'preserves the explicit graph alias %s without resolving a saved agent', + (subagentType) => { + mockChildren.set('thread-1', { + ...mockChildren.get('thread-1')!, + subagentType, + subagentKind: 'graph', + title: subagentType, + }); + renderMessage(subagentWakeup(subagentType)); + expect(screen.getByRole('heading', { name: subagentType })).toBeInTheDocument(); + expect(screen.getByTestId('author-face')).toHaveAttribute('data-agent', ''); + }, + ); + + it('preserves an unindexed legacy alias without resolving a saved agent', () => { + mockChildren.clear(); + renderMessage(subagentWakeup('agent_reviewer')); + expect(screen.getByRole('heading', { name: 'agent_reviewer' })).toBeInTheDocument(); + expect(screen.getByTestId('author-face')).toHaveAttribute('data-agent', ''); + }); + + it('names an unresolvable known agent generically, never by its id', () => { + mockChildren.set('thread-1', { + ...mockChildren.get('thread-1')!, + subagentKind: 'agent', + agentId: 'agent_unknown', + subagentType: 'agent_unknown', + title: 'agent_unknown', + }); + renderMessage(subagentWakeup('agent_unknown')); + + expect(screen.getByRole('heading', { name: /com_ui_subagent_actor$/ })).toBeInTheDocument(); + expect(screen.queryByText(/agent_unknown/)).not.toBeInTheDocument(); + }); + + it('keeps a background tool report a system turn, since no agent wrote it', () => { + renderMessage(backgroundWakeup); + + expect(screen.getByRole('heading', { name: 'com_ui_system_event' })).toBeInTheDocument(); + expect(screen.queryByTestId('author-face')).not.toBeInTheDocument(); + }); + + it.each([ + ['self', 'graph', 'self'], + ['agent_reviewer', 'agent', 'Code Reviewer'], + ['self', 'agent', 'Code Reviewer'], + ] as const)( + 'recovers a private child omitted from the bounded index (%s/%s)', + (alias, kind, label) => { + mockChildren.clear(); + const dispatch: TMessage = { + messageId: 'old-dispatch', + parentMessageId: null, + conversationId: 'conversation-1', + isCreatedByUser: false, + text: '', + endpoint: 'agents', + model: 'agent_lia', + sender: 'Lia', + content: [ + { + type: ContentTypes.TOOL_CALL, + tool_call: { + id: 'old-call', + name: 'subagent', + args: { run_in_background: true }, + output: JSON.stringify({ + background_task_id: 'task-1', + subagent_thread_id: 'thread-1', + tool: 'subagent', + subagent_type: alias, + status: 'running', + message: 'Poll using background_task_id task-1.', + }), + subagentIdentity: { + subagentKind: kind, + subagentAgentId: kind === 'graph' ? 'graph:self' : 'agent_reviewer', + }, + }, + }, + ], + }; + renderMessage(subagentWakeup(alias), 'agent_lia', false, false, dispatch); + expect(screen.getByRole('heading', { name: label })).toBeInTheDocument(); + expect(screen.queryByRole('heading', { name: 'Lia' })).not.toBeInTheDocument(); + }, + ); + + it('preserves a graph title whose prefix resembles a legacy label', () => { + mockChildren.set('thread-1', { + ...mockChildren.get('thread-1')!, + subagentType: 'Subagent: research', + title: 'Subagent: research', + subagentKind: 'graph', + agentId: undefined, + }); + renderMessage(subagentWakeup('Subagent: research')); + expect(screen.getByRole('heading', { name: 'Subagent: research' })).toBeInTheDocument(); + }); + + it('leaves an ordinary user turn without a visible author', () => { + renderMessage('Hello there'); + + expect(screen.getByRole('heading', { hidden: true })).toHaveClass('sr-only'); + expect(screen.getByTestId('message-body')).toHaveClass('bg-surface-tertiary'); + }); +}); + +it('keeps user-submitted wake-up lookalikes as ordinary chat prompts', () => { + const text = subagentWakeup('self'); + renderMessage(text, 'agent_lia', false, true); + expect(screen.getByTestId('message-content')).toBeInTheDocument(); + expect(screen.queryByTestId('wakeup-card')).not.toBeInTheDocument(); + expect(screen.getByRole('heading', { hidden: true })).toHaveClass('sr-only'); +}); + +it('uses the validated spawning lane for a private self wake-up', () => { + mockChildren.set('thread-1', { + ...mockChildren.get('thread-1')!, + subagentType: 'self', + agentId: 'agent_reviewer', + }); + renderMessage(subagentWakeup('self'), 'agent_lia'); + expect(screen.getByRole('heading', { name: 'Code Reviewer' })).toBeInTheDocument(); + expect(screen.getByTestId('author-face')).toHaveAttribute('data-agent', 'Code Reviewer'); +}); diff --git a/client/src/components/Chat/Messages/ui/__tests__/MessageRow.spec.tsx b/client/src/components/Chat/Messages/ui/__tests__/MessageRow.spec.tsx index b2f95dc25b..e6f5da2f12 100644 --- a/client/src/components/Chat/Messages/ui/__tests__/MessageRow.spec.tsx +++ b/client/src/components/Chat/Messages/ui/__tests__/MessageRow.spec.tsx @@ -16,12 +16,16 @@ const renderRow = ({ fullWidth = false, isEditing = false, systemLabel, + showAuthor, + outlined, }: { isCreatedByUser: boolean; hasParallelContent?: boolean; fullWidth?: boolean; isEditing?: boolean; systemLabel?: string; + showAuthor?: boolean; + outlined?: boolean; }) => render(

{MESSAGE_BODY}

, @@ -59,6 +65,35 @@ describe('MessageRow', () => { expect(screen.getByTestId('message-actions')).toBeInTheDocument(); }); + it('names another author of a user-side turn with the agent header, mirrored', () => { + renderRow({ isCreatedByUser: true, showAuthor: true }); + + const row = screen.getByLabelText('User message'); + const heading = screen.getByRole('heading', { name: 'Message from You' }); + const messageSurface = screen.getByText(MESSAGE_BODY).parentElement; + + /** The user's position and filled bubble, under the same visible + * avatar-and-name line an agent turn carries — closed toward the bubble. */ + expect(row).toHaveClass('justify-end'); + expect(heading).not.toHaveClass('sr-only'); + expect(heading).toHaveClass('justify-end', 'text-sm', 'font-semibold'); + expect(heading).toContainElement(screen.getByTestId('message-icon')); + expect(screen.getByTestId('message-icon').parentElement).toHaveClass('size-6'); + expect(heading.lastElementChild).toHaveTextContent('You'); + expect(messageSurface).toHaveClass('bg-surface-tertiary'); + expect(messageSurface).not.toHaveClass('border'); + }); + + it('outlines a delivered user-side turn without a system heading', () => { + renderRow({ isCreatedByUser: true, showAuthor: true, outlined: true }); + + const messageSurface = screen.getByText(MESSAGE_BODY).parentElement; + + expect(messageSurface).toHaveClass('border', 'border-border-medium'); + expect(messageSurface).not.toHaveClass('bg-surface-tertiary'); + expect(screen.getByRole('heading', { name: 'Message from You' })).toBeVisible(); + }); + it('renders user content as a right-aligned semantic surface without a visible avatar', () => { renderRow({ isCreatedByUser: true }); diff --git a/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.test.tsx b/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.test.tsx index db5310177b..de2a25e5e7 100644 --- a/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.test.tsx +++ b/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.test.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { ContentTypes } from 'librechat-data-provider'; import { fireEvent, render, screen, waitFor } from '@testing-library/react'; -import type { TMessageContentParts } from 'librechat-data-provider'; +import type { TMessage, TMessageContentParts } from 'librechat-data-provider'; import SubagentCall from '~/components/Chat/Messages/Content/Parts/SubagentCall'; import SharedSubagentActivityDialog from './SharedSubagentActivityDialog'; import { MessageContext } from '~/Providers/MessageContext'; @@ -17,8 +17,7 @@ jest.mock('~/data-provider', () => ({ jest.mock('~/hooks', () => ({ useLocalize: () => - (key: string, values?: Record): string => { - if (key === 'com_ui_subagent_dialog_title') return `Agent ${values?.[0] ?? ''}`; + (key: string): string => { if (key === 'com_ui_subagent_complete') return 'Ran agent'; if (key === 'com_ui_subagent_activity') return 'Agent activity'; return key; @@ -27,6 +26,12 @@ jest.mock('~/hooks', () => ({ jest.mock('~/Providers', () => ({ useAgentsMapContext: () => ({}) })); jest.mock('~/components/Share/MessageIcon', () => ({ __esModule: true, default: () => null })); +jest.mock('~/components/Chat/Messages/MessageIcon', () => ({ + __esModule: true, + default: ({ iconData }: { iconData: { iconURL?: string } }) => ( + + ), +})); jest.mock('~/hooks/MCP', () => ({ useMCPServerNames: () => [] })); jest.mock('./SubagentActivity', () => ({ @@ -52,7 +57,11 @@ jest.mock('./SubagentConversation', () => ({ __esModule: true, default: ({ turns, + author, + parentAuthor, }: { + author: { name: string }; + parentAuthor: { name: string }; turns: Array<{ taskId: string; trigger: { summary: string }; @@ -63,7 +72,12 @@ jest.mock('./SubagentConversation', () => ({ return ( {(surface: string) => ( -
+
{turns.map((turn) => (
{turn.trigger.summary} @@ -93,10 +107,29 @@ const detachedOutput = JSON.stringify({ 'Started subagent "researcher" background task. Poll the host background-task tool with background_task_id "task-1".', }); +/** The shared thread as ShareView holds it: the agent that dispatched the child. */ +const sharedMessages = [ + { + messageId: 'shared-parent', + parentMessageId: null, + conversationId: 'shared-conversation', + isCreatedByUser: false, + endpoint: 'agents', + model: 'agent_parent', + sender: 'Lia', + iconURL: '/lia.png', + text: '', + } as unknown as TMessage, +]; + function renderSharedCall(input: { output?: string; persistedContent?: TMessageContentParts[]; detached?: boolean; + partIndex?: number; + messages?: TMessage[]; + subagentType?: string; + subagentIdentity?: { subagentKind: 'graph'; subagentAgentId: 'graph:self' }; }) { return render( @@ -105,6 +138,7 @@ function renderSharedCall(input: { value={{ conversationId: 'shared-conversation', messageId: 'shared-parent', + partIndex: input.partIndex, isExpanded: false, }} > @@ -112,14 +146,18 @@ function renderSharedCall(input: { toolCallId="shared-call" initialProgress={1} args={{ - subagent_type: 'researcher', + subagent_type: input.subagentType ?? 'researcher', description: 'Review the release.', run_in_background: input.detached === true, }} output={input.output} + subagentIdentity={input.subagentIdentity} persistedContent={input.persistedContent} /> - + , @@ -144,10 +182,72 @@ describe('SharedSubagentActivityDialog', () => { 'bg-surface-dialog', ); expect(screen.getByText('Shared review complete.')).toBeInTheDocument(); + /** Named as main chat names them: the child by its readable type, the + * briefing by the shared agent that sent it. */ + expect(screen.getByRole('heading', { name: 'researcher' })).toBeInTheDocument(); + expect(screen.getByTestId('subagent-conversation')).toHaveAttribute( + 'data-author', + 'researcher', + ); + expect(screen.getByTestId('subagent-conversation')).toHaveAttribute( + 'data-parent-author', + 'Lia', + ); fireEvent.click(screen.getByRole('button', { name: 'Close' })); await waitFor(() => expect(trigger).toHaveFocus()); }); + it('reuses the historical parent avatar for a shared self-spawn', () => { + renderSharedCall({ subagentType: 'self', persistedContent: persistedContent('Self work.') }); + fireEvent.click(screen.getByRole('button', { name: 'Ran agent' })); + expect(screen.getByRole('heading', { name: 'Lia' })).toBeInTheDocument(); + expect(screen.getByTestId('author-face')).toHaveAttribute('data-icon', '/lia.png'); + expect(screen.getByTestId('subagent-conversation')).toHaveAttribute('data-author', 'Lia'); + }); + + it('uses the exact shared part when provider tool IDs repeat', () => { + renderSharedCall({ + subagentType: 'self', + partIndex: 1, + persistedContent: persistedContent('Lane work.'), + messages: [ + { + ...sharedMessages[0], + content: [ + { + type: ContentTypes.TOOL_CALL, + agentId: 'agent_parent', + tool_call: { id: 'shared-call', name: 'subagent', args: {} }, + }, + { + type: ContentTypes.TOOL_CALL, + agentId: 'agent_missing_lane', + tool_call: { id: 'shared-call', name: 'subagent', args: {} }, + }, + ], + }, + ], + }); + fireEvent.click(screen.getByRole('button', { name: 'Ran agent' })); + expect(screen.getByTestId('subagent-conversation')).toHaveAttribute( + 'data-parent-author', + 'com_ui_subagent_parent_agent', + ); + expect(screen.queryByRole('heading', { name: 'Lia' })).not.toBeInTheDocument(); + }); + + it('preserves a shared graph alias named self instead of the parent author', () => { + renderSharedCall({ + subagentType: 'self', + subagentIdentity: { subagentKind: 'graph', subagentAgentId: 'graph:self' }, + persistedContent: persistedContent('Graph work.'), + }); + fireEvent.click(screen.getByRole('button', { name: 'Ran agent' })); + expect(screen.getByRole('heading', { name: 'self' })).toBeInTheDocument(); + expect(screen.getByTestId('subagent-conversation')).toHaveAttribute('data-author', 'self'); + expect(screen.getByTestId('author-face')).not.toHaveAttribute('data-icon', '/lia.png'); + }); + it('renders detached persisted activity without performing the private durable query', () => { renderSharedCall({ output: detachedOutput, diff --git a/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.tsx b/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.tsx index 823df45cd6..01c26a7ff4 100644 --- a/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.tsx +++ b/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.tsx @@ -1,25 +1,80 @@ import { useCallback, useEffect, useMemo, useRef } from 'react'; import { useAtom } from 'jotai'; import { OGDialog, OGDialogContent, OGDialogHeader, OGDialogTitle } from '@librechat/client'; +import type { TMessage } from 'librechat-data-provider'; +import { + isSelfSpawn as isSelfSpawnType, + messageAuthor, + findAgentLaneId, + resolveSubagentAuthor, + findAgentAuthorMessage, +} from './author'; import { MessageSurfaceContext } from '~/components/Chat/Messages/ui/surface'; import { SubagentActivityScrollSurface } from './SubagentActivity'; import SubagentConversation from './SubagentConversation'; import { adaptLivePersistedActivity } from './adapters'; +import { resolveSubagentAgentId } from './identity'; +import { useAgentsMapContext } from '~/Providers'; import { activeSubagentPanel } from './state'; import { useLocalize } from '~/hooks'; /** Public-share fallback for subagent activity already embedded in the shared message payload. */ -export default function SharedSubagentActivityDialog({ shareId }: { shareId?: string }) { +export default function SharedSubagentActivityDialog({ + shareId, + messages, +}: { + shareId?: string; + /** The shared thread, which names the agent that dispatched the child. */ + messages?: TMessage[]; +}) { const localize = useLocalize(); + const agentsMap = useAgentsMapContext(); const [selected, setSelected] = useAtom(activeSubagentPanel); const resetSelection = useCallback(() => setSelected(null), [setSelected]); const selection = selected?.host === 'share' && selected.shareId === shareId ? selected : null; const restoreSelectionRef = useRef(selection); if (selection != null) restoreSelectionRef.current = selection; - const title = - selection?.subagentType === 'self' - ? localize('com_ui_subagent_dialog_title_self') - : localize('com_ui_subagent_dialog_title', { 0: selection?.subagentType ?? '' }); + const parentMessageId = selection?.parentMessageId ?? ''; + const parentFallback = localize('com_ui_subagent_parent_agent'); + /** Resolved only while a child is open: the shared thread is never scanned for + * a dialog nobody is looking at. */ + const parentAuthor = useMemo(() => { + const message = + parentMessageId === '' ? undefined : findAgentAuthorMessage(messages, parentMessageId); + return messageAuthor( + message, + agentsMap, + parentFallback, + findAgentLaneId(message, selection?.toolCallId, selection?.partIndex), + ); + }, [ + agentsMap, + messages, + parentFallback, + parentMessageId, + selection?.toolCallId, + selection?.partIndex, + ]); + const childAgentId = resolveSubagentAgentId(null, selection?.subagentIdentity); + const isSelfSpawn = isSelfSpawnType( + selection?.subagentType, + selection?.subagentIdentity?.subagentKind, + ); + const childAuthor = useMemo( + () => + resolveSubagentAuthor( + { + agentId: childAgentId, + subagentType: selection?.subagentType, + subagentKind: selection?.subagentIdentity?.subagentKind, + }, + parentAuthor, + agentsMap, + localize('com_ui_subagent_actor'), + ), + [agentsMap, childAgentId, localize, parentAuthor, selection], + ); + const title = childAuthor.name; const activity = useMemo( () => adaptLivePersistedActivity({ @@ -65,13 +120,23 @@ export default function SharedSubagentActivityDialog({ shareId }: { shareId?: st onCloseAutoFocus={restoreTriggerFocus} > - - {activity.title} - +
+ + + {title} + +
({ Zap: () => null, })); +const author: TurnAuthor = { name: 'Research child', icon: }; +const parentAuthor: TurnAuthor = { name: 'Lia', icon: }; + const turns: ChildConversationTurn[] = [ { taskId: 'task-1', @@ -107,16 +111,24 @@ const turns: ChildConversationTurn[] = [ ]; describe('SubagentConversation', () => { - it('renders host triggers and child activity through the main chat row and content modules', () => { + it('renders parent turns and child activity through the main chat row and content modules', () => { const { container } = render( - + , ); - expect(screen.getByText('com_ui_subagent_trigger_parent_dispatch')).toBeInTheDocument(); + /** The parent's briefing is a user turn in the parent's name, filled like + * one; only the external event, which no agent wrote, is a system turn. */ + const briefing = screen.getByRole('group', { name: 'com_ui_subagent_trigger_parent_dispatch' }); + expect(briefing).toHaveClass('justify-end'); + expect(within(briefing).getByRole('heading', { name: /Lia$/ })).toBeInTheDocument(); + expect(within(briefing).getByTestId('parent-face')).toBeInTheDocument(); + expect(within(briefing).getByTestId('message-body')).toHaveClass('bg-surface-tertiary'); + expect(screen.queryByText('com_ui_subagent_trigger_parent_dispatch')).not.toBeInTheDocument(); expect(screen.getByText('com_ui_subagent_trigger_external_event')).toBeInTheDocument(); - expect(screen.getAllByRole('heading', { name: /^com_ui_system_event/ })).toHaveLength(2); + expect(screen.getAllByRole('heading', { name: /^com_ui_system_event/ })).toHaveLength(1); + expect(screen.getAllByRole('heading', { name: 'Research child' })).toHaveLength(2); expect(screen.getByText('Investigate the release.')).toBeInTheDocument(); expect(screen.getByText('Checked the constraints.')).toBeInTheDocument(); expect(screen.getByText('search')).toBeInTheDocument(); @@ -125,7 +137,7 @@ describe('SubagentConversation', () => { expect(screen.queryByText('com_ui_subagent_thread_status_running')).not.toBeInTheDocument(); /** Both halves of the main chat author column: the shared glyph, and the * streaming dot inset onto that glyph's axis the way main chat insets it. */ - expect(screen.getAllByTestId('message-icon')).toHaveLength(2); + expect(screen.getAllByTestId('child-face')).toHaveLength(2); expect(screen.getByTestId('thinking-cursor')).toHaveAttribute('data-under-header-icon', 'true'); expect(container.querySelectorAll('.message-render')).toHaveLength(4); expect(container.querySelectorAll('.user-turn')).toHaveLength(2); @@ -150,6 +162,26 @@ describe('SubagentConversation', () => { expect(screen.getByText('submit_move')).toBeInTheDocument(); }); + it('names an empty parent follow-up instead of rendering a blank bubble', () => { + const followUp: ChildConversationTurn = { + ...turns[0], + taskId: 'task-4', + trigger: { kind: 'parent_continuation', summary: '' }, + }; + render( + + + , + ); + + const row = screen.getByRole('group', { name: 'com_ui_subagent_trigger_parent_continuation' }); + expect(within(row).getByRole('heading', { name: /Lia$/ })).toBeInTheDocument(); + expect( + within(row).getByText('com_ui_subagent_trigger_parent_continuation'), + ).toBeInTheDocument(); + expect(within(row).queryByTestId('shared-content-parts')).not.toBeInTheDocument(); + }); + it('requests an exact bounded projection only when shortened turn activity is opened', () => { const loadDetails = jest.fn(); const shortened = [ @@ -157,7 +189,12 @@ describe('SubagentConversation', () => { ]; render( - + , ); @@ -182,7 +219,11 @@ describe('SubagentConversation', () => { render( - + , ); diff --git a/client/src/components/Chat/Subagents/SubagentConversation.tsx b/client/src/components/Chat/Subagents/SubagentConversation.tsx index 9ba061760f..76d56b31f0 100644 --- a/client/src/components/Chat/Subagents/SubagentConversation.tsx +++ b/client/src/components/Chat/Subagents/SubagentConversation.tsx @@ -1,12 +1,13 @@ import { useMemo, useState } from 'react'; import { useAtomValue } from 'jotai'; -import { CornerDownRight, Radio } from 'lucide-react'; -import { ContentTypes, EModelEndpoint } from 'librechat-data-provider'; +import { Radio } from 'lucide-react'; +import { ContentTypes } from 'librechat-data-provider'; import { Button, Collapsible, CollapsibleContent, CollapsibleTrigger } from '@librechat/client'; import type { TMessageContentParts } from 'librechat-data-provider'; import type { ReactNode } from 'react'; import type { ChildConversationTurn } from './adapters'; import type { TranslationKeys } from '~/hooks'; +import type { TurnAuthor } from './author'; import SystemEventHeader, { SystemEventIcon, systemEventHeaderClasses, @@ -17,9 +18,7 @@ import { isAbnormalTerminalStatus, isLiveSubagentStatus } from './status'; import { messageFooterClasses } from '~/components/Chat/Messages/styles'; import MessageRow from '~/components/Chat/Messages/ui/MessageRow'; import { ElapsedTimer } from '~/components/Chat/Messages/Elapsed'; -import MessageIcon from '~/components/Chat/Messages/MessageIcon'; import { showThinkingAtom } from '~/store/showThinking'; -import { useAgentsMapContext } from '~/Providers'; import { useChatSurface } from './surface'; import { useLocalize } from '~/hooks'; import { cn } from '~/utils'; @@ -30,11 +29,10 @@ const TRIGGER_LABELS = { external_event: 'com_ui_subagent_trigger_external_event', } as const satisfies Record; -function TriggerIcon({ kind }: { kind: ChildConversationTurn['trigger']['kind'] }) { - const Icon = kind === 'external_event' ? Radio : CornerDownRight; +function ExternalEventIcon() { return ( - + ); } @@ -54,7 +52,7 @@ function ExternalEventTrigger({ if (details == null) { body = (
- } label={label} /> + } label={label} />
); } else { @@ -63,7 +61,7 @@ function ExternalEventTrigger({