mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-19 06:23:32 +00:00
🪪 feat: Name and Face Subagents Like Main Chat Turns (#16692)
* 🪪 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
This commit is contained in:
parent
9fe93939f5
commit
dc375a8e1c
36 changed files with 2990 additions and 247 deletions
|
|
@ -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}
|
||||
>
|
||||
<div className="text-text-primary flex items-center gap-2 text-sm font-medium">
|
||||
<div className="text-text-primary flex w-full min-w-0 items-center gap-2 text-sm font-medium">
|
||||
<div
|
||||
className={cn(
|
||||
FOLD_GLYPH_CLASS,
|
||||
|
|
@ -435,18 +443,47 @@ export default function SubagentCall({
|
|||
<Users size={14} />
|
||||
)}
|
||||
</div>
|
||||
<span className="min-w-0 truncate" title={headerText}>
|
||||
{headerText}
|
||||
</span>
|
||||
{subagentNameLabel ? (
|
||||
<span
|
||||
className="text-text-secondary min-w-0 flex-1 truncate font-normal"
|
||||
title={subagentNameLabel}
|
||||
>
|
||||
{subagentNameLabel}
|
||||
</span>
|
||||
<>
|
||||
<span
|
||||
className="max-w-[50%] min-w-0 shrink truncate font-semibold"
|
||||
title={subagentNameLabel}
|
||||
>
|
||||
{subagentNameLabel}
|
||||
</span>
|
||||
<span
|
||||
className="text-text-secondary min-w-0 flex-1 truncate font-normal"
|
||||
title={detachedStatusUnknown ? undefined : headerText}
|
||||
>
|
||||
{detachedStatusUnknown && backgroundHandle != null ? (
|
||||
<DetachedTaskStatus
|
||||
threadId={backgroundHandle.subagent_thread_id}
|
||||
taskId={backgroundHandle.background_task_id}
|
||||
fallback={headerText}
|
||||
/>
|
||||
) : (
|
||||
headerText
|
||||
)}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="flex-1" />
|
||||
<>
|
||||
<span
|
||||
className="min-w-0 truncate"
|
||||
title={detachedStatusUnknown ? undefined : headerText}
|
||||
>
|
||||
{detachedStatusUnknown && backgroundHandle != null ? (
|
||||
<DetachedTaskStatus
|
||||
threadId={backgroundHandle.subagent_thread_id}
|
||||
taskId={backgroundHandle.background_task_id}
|
||||
fallback={headerText}
|
||||
/>
|
||||
) : (
|
||||
headerText
|
||||
)}
|
||||
</span>
|
||||
<span className="flex-1" />
|
||||
</>
|
||||
)}
|
||||
{canOpenDetails && (
|
||||
<ChevronRight
|
||||
|
|
@ -474,6 +511,30 @@ export default function SubagentCall({
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A detached child's status as the parent's subagent index last reported it.
|
||||
* Its own leaf so an index refresh re-renders this text alone, never the card
|
||||
* or the message around it; with no indexed answer the card keeps its neutral
|
||||
* label rather than guessing.
|
||||
*/
|
||||
function DetachedTaskStatus({
|
||||
threadId,
|
||||
taskId,
|
||||
fallback,
|
||||
}: {
|
||||
threadId: string;
|
||||
taskId: string;
|
||||
fallback: string;
|
||||
}) {
|
||||
const localize = useLocalize();
|
||||
const { byThreadId } = useParentSubagents();
|
||||
const child = byThreadId.get(threadId);
|
||||
const status =
|
||||
child?.tasks.find((task) => 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 {
|
||||
|
|
|
|||
|
|
@ -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<string, ParentSubagentSummary>();
|
||||
|
||||
jest.mock('~/hooks', () => ({
|
||||
useLocalize:
|
||||
|
|
@ -59,16 +65,24 @@ jest.mock('../Attachment', () => ({
|
|||
|
||||
jest.mock('lucide-react', () => ({
|
||||
// eslint-disable-next-line i18next/no-literal-string
|
||||
ChevronRight: () => <span>chevron</span>,
|
||||
ChevronRight: () => <span aria-hidden="true">chevron</span>,
|
||||
// eslint-disable-next-line i18next/no-literal-string
|
||||
Users: () => <span>users</span>,
|
||||
Users: () => <span aria-hidden="true">users</span>,
|
||||
}));
|
||||
|
||||
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',
|
||||
|
|
|
|||
|
|
@ -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<TMessage, 'text' | 'isCreatedByUser' | 'isUserSubmitted'> | undefined,
|
||||
): WakeupDisplay | null {
|
||||
if (message?.isCreatedByUser !== true || message.isUserSubmitted === true) return null;
|
||||
return parseWakeupText(message.text);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<typeof threadStatus> }) {
|
||||
const StatusIcon = subagentStatusIcon(status);
|
||||
return (
|
||||
<SystemEventIcon>
|
||||
<StatusIcon size={14} className={cn(status === 'completed' && 'text-status-success')} />
|
||||
</SystemEventIcon>
|
||||
);
|
||||
}
|
||||
|
||||
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 !== '' && <span className="min-w-0 truncate font-medium">{title}</span>}
|
||||
<span className="shrink-0">{localize(subagentStatusLabelKey(status))}</span>
|
||||
{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<string>();
|
||||
const labels: string[] = [];
|
||||
|
|
@ -167,9 +177,7 @@ const Wakeup = memo(function Wakeup({
|
|||
live
|
||||
icon={
|
||||
display.kind === 'subagent' ? (
|
||||
<SystemEventIcon>
|
||||
<Users size={14} />
|
||||
</SystemEventIcon>
|
||||
<SubagentOutcomeIcon status={threadStatus(display.tasks[0]?.status ?? 'completed')} />
|
||||
) : (
|
||||
<StackedToolIcons toolNames={toolIconNames} mcpIconMap={mcpIconMap} maxIcons={4} />
|
||||
)
|
||||
|
|
|
|||
|
|
@ -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 ?? '';
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
|
|
|
|||
|
|
@ -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 | null | undefined>
|
||||
): 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),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<MessageRow
|
||||
<Row
|
||||
task={subagentWakeup}
|
||||
conversationId={msg.conversationId ?? conversation?.conversationId ?? ''}
|
||||
id={msg.messageId}
|
||||
icon={<MessageIcon iconData={iconData} assistant={assistant} agent={agent} />}
|
||||
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={
|
||||
<SubRow classes={cn(messageFooterClasses, msg.isCreatedByUser && 'justify-end')}>
|
||||
{/* The reading holds the column start: it takes over the slot the streaming
|
||||
|
|
@ -249,7 +256,7 @@ const MessageRender = memo(function MessageRender({
|
|||
/>
|
||||
))}
|
||||
</MessageContext.Provider>
|
||||
</MessageRow>
|
||||
</Row>
|
||||
);
|
||||
}, areMessageRenderPropsEqual);
|
||||
MessageRender.displayName = 'MessageRender';
|
||||
|
|
|
|||
|
|
@ -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<MessageRowProps, 'icon' | 'label' | 'hoverLabel' | 'headerPrefix' | 'timestamp'> & {
|
||||
align: 'start' | 'end';
|
||||
}) {
|
||||
return (
|
||||
<h2 className={authorHeaderClasses[align]}>
|
||||
{align === 'end' && (
|
||||
<MessageTimestamp value={timestamp} className="mr-auto shrink-0 font-normal" />
|
||||
)}
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="flex size-6 shrink-0 items-center justify-center overflow-hidden rounded-full"
|
||||
>
|
||||
{icon}
|
||||
</span>
|
||||
<span className="sr-only">{headerPrefix}</span>
|
||||
<HeaderLabel label={label} hoverLabel={hoverLabel} />
|
||||
{align === 'start' && (
|
||||
<MessageTimestamp value={timestamp} className="ml-auto shrink-0 font-normal" />
|
||||
)}
|
||||
</h2>
|
||||
);
|
||||
}
|
||||
|
||||
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({
|
|||
</span>
|
||||
</h2>
|
||||
)}
|
||||
{!hasParallelContent && !isSystem && isCreatedByUser && !showAuthor && (
|
||||
<h2 className="sr-only">
|
||||
{headerPrefix}
|
||||
{label}
|
||||
<MessageTimestamp value={timestamp} />
|
||||
</h2>
|
||||
)}
|
||||
{!hasParallelContent &&
|
||||
!isSystem &&
|
||||
(isCreatedByUser ? (
|
||||
<h2 className="sr-only">
|
||||
{headerPrefix}
|
||||
{label}
|
||||
<MessageTimestamp value={timestamp} />
|
||||
</h2>
|
||||
) : (
|
||||
/** `mb-1` keeps the name off its own first line of body text. */
|
||||
<h2 className="text-text-primary mb-1 flex min-h-7 w-full items-center gap-2 text-sm font-semibold select-none">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="flex size-6 shrink-0 items-center justify-center overflow-hidden rounded-full"
|
||||
>
|
||||
{icon}
|
||||
</span>
|
||||
<span className="sr-only">{headerPrefix}</span>
|
||||
<HeaderLabel label={label} hoverLabel={hoverLabel} />
|
||||
<MessageTimestamp value={timestamp} className="ml-auto shrink-0 font-normal" />
|
||||
</h2>
|
||||
))}
|
||||
(!isCreatedByUser || showAuthor) &&
|
||||
renderAuthorHeader({
|
||||
icon,
|
||||
label,
|
||||
hoverLabel,
|
||||
headerPrefix,
|
||||
timestamp,
|
||||
align: isCreatedByUser ? 'end' : 'start',
|
||||
})}
|
||||
|
||||
<div className={cn('flex w-full flex-col gap-1', isUserSide && 'items-end')}>
|
||||
<div
|
||||
|
|
@ -123,7 +170,9 @@ export default function MessageRow({
|
|||
isUserSide && !isEditing
|
||||
? cn(
|
||||
'rounded-theme-surface rounded-br-theme-control px-theme-normal w-fit',
|
||||
isSystem ? 'border-border-medium border py-1.5' : 'bg-surface-tertiary py-2.5',
|
||||
isSystem || outlined
|
||||
? 'border-border-medium border py-1.5'
|
||||
: 'bg-surface-tertiary py-2.5',
|
||||
)
|
||||
: 'w-full',
|
||||
)}
|
||||
|
|
|
|||
91
client/src/components/Chat/Messages/ui/WakeupRow.tsx
Normal file
91
client/src/components/Chat/Messages/ui/WakeupRow.tsx
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import { useMemo } from 'react';
|
||||
import type { ComponentProps } from 'react';
|
||||
import type { WakeupTask } from '../Content/Parts/wakeup';
|
||||
import {
|
||||
messageAuthor,
|
||||
resolveSubagentAuthor,
|
||||
findAgentAuthorMessage,
|
||||
useParentAuthor,
|
||||
} from '~/components/Chat/Subagents/author';
|
||||
import { useParentSubagents } from '~/components/Chat/Subagents/ParentSubagentsProvider';
|
||||
import { useOptionalMessagesOperations } from '~/Providers/MessagesViewContext';
|
||||
import { findSubagentDispatch } from '~/components/Chat/Subagents/dispatch';
|
||||
import { useShareContext } from '~/Providers/ShareContext';
|
||||
import { useAgentsMapContext } from '~/Providers';
|
||||
import MessageRow from './MessageRow';
|
||||
import { useLocalize } from '~/hooks';
|
||||
|
||||
/** Only wake-up rows observe the child index; ordinary rows keep their subscriptions. */
|
||||
export default function WakeupRow({
|
||||
task,
|
||||
conversationId,
|
||||
...props
|
||||
}: ComponentProps<typeof MessageRow> & { 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 (
|
||||
<MessageRow
|
||||
{...props}
|
||||
icon={author.icon}
|
||||
label={author.name}
|
||||
hoverLabel={undefined}
|
||||
headerPrefix={undefined}
|
||||
showAuthor
|
||||
outlined
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -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<string, ParentSubagentSummary>();
|
||||
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 } }) => (
|
||||
<span data-testid="author-face" data-agent={agent?.name ?? ''} data-icon={iconData.iconURL} />
|
||||
),
|
||||
}));
|
||||
jest.mock('~/components/Chat/Messages/Content/Wakeup', () => ({
|
||||
__esModule: true,
|
||||
default: () => <div data-testid="wakeup-card" />,
|
||||
}));
|
||||
jest.mock('~/components/Chat/Messages/Content/MessageContent', () => ({
|
||||
__esModule: true,
|
||||
default: () => <div data-testid="message-content" />,
|
||||
}));
|
||||
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 = <MessageRender message={message} chatContext={chatContext} currentEditId={null} />;
|
||||
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(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RecoilRoot>
|
||||
{shared ? (
|
||||
<ShareContext.Provider value={{ isSharedConvo: true, shareId: 'share-1' }}>
|
||||
<ShareMessagesProvider messages={[message, sharedReply]}>{row}</ShareMessagesProvider>
|
||||
</ShareContext.Provider>
|
||||
) : (
|
||||
<ShareMessagesProvider
|
||||
messages={
|
||||
queryClient.getQueryData<TMessage[]>([QueryKeys.messages, 'conversation-1']) ?? []
|
||||
}
|
||||
>
|
||||
{row}
|
||||
</ShareMessagesProvider>
|
||||
)}
|
||||
</RecoilRoot>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
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');
|
||||
});
|
||||
|
|
@ -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(
|
||||
<MessageRow
|
||||
|
|
@ -37,6 +41,8 @@ const renderRow = ({
|
|||
fullWidth={fullWidth}
|
||||
isEditing={isEditing}
|
||||
systemLabel={systemLabel}
|
||||
showAuthor={showAuthor}
|
||||
outlined={outlined}
|
||||
>
|
||||
<p>{MESSAGE_BODY}</p>
|
||||
</MessageRow>,
|
||||
|
|
@ -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 });
|
||||
|
||||
|
|
|
|||
|
|
@ -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<number, string>): 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 } }) => (
|
||||
<span data-testid="author-face" data-icon={iconData.iconURL} />
|
||||
),
|
||||
}));
|
||||
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 (
|
||||
<MessageSurfaceContext.Consumer>
|
||||
{(surface: string) => (
|
||||
<div data-testid="subagent-conversation" data-message-surface={surface}>
|
||||
<div
|
||||
data-testid="subagent-conversation"
|
||||
data-message-surface={surface}
|
||||
data-author={author.name}
|
||||
data-parent-author={parentAuthor.name}
|
||||
>
|
||||
{turns.map((turn) => (
|
||||
<div key={turn.taskId}>
|
||||
{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(
|
||||
<ChatSurfaceHarness>
|
||||
|
|
@ -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}
|
||||
/>
|
||||
<SharedSubagentActivityDialog shareId="share-1" />
|
||||
<SharedSubagentActivityDialog
|
||||
shareId="share-1"
|
||||
messages={input.messages ?? sharedMessages}
|
||||
/>
|
||||
</MessageContext.Provider>
|
||||
</ShareContext.Provider>
|
||||
</ChatSurfaceHarness>,
|
||||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
>
|
||||
<OGDialogHeader className="border-border-light shrink-0 border-b px-5 py-4 pr-14">
|
||||
<OGDialogTitle className="truncate text-left text-base" title={activity.title}>
|
||||
{activity.title}
|
||||
</OGDialogTitle>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="flex size-6 shrink-0 items-center justify-center overflow-hidden rounded-full"
|
||||
>
|
||||
{childAuthor.icon}
|
||||
</span>
|
||||
<OGDialogTitle className="truncate text-left text-base" title={title}>
|
||||
{title}
|
||||
</OGDialogTitle>
|
||||
</div>
|
||||
</OGDialogHeader>
|
||||
<MessageSurfaceContext.Provider value="bg-surface-dialog">
|
||||
<SubagentActivityScrollSurface padded={false}>
|
||||
<SubagentConversation
|
||||
author={childAuthor}
|
||||
parentAuthor={isSelfSpawn ? childAuthor : parentAuthor}
|
||||
turns={[
|
||||
{
|
||||
taskId:
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import React from 'react';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { fireEvent, render, screen, within } from '@testing-library/react';
|
||||
import type { ChildConversationTurn } from './adapters';
|
||||
import type { TurnAuthor } from './author';
|
||||
import SubagentConversation from './SubagentConversation';
|
||||
import { ChatSurfaceHarness } from 'test/harness';
|
||||
|
||||
|
|
@ -62,6 +63,9 @@ jest.mock('lucide-react', () => ({
|
|||
Zap: () => null,
|
||||
}));
|
||||
|
||||
const author: TurnAuthor = { name: 'Research child', icon: <span data-testid="child-face" /> };
|
||||
const parentAuthor: TurnAuthor = { name: 'Lia', icon: <span data-testid="parent-face" /> };
|
||||
|
||||
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(
|
||||
<ChatSurfaceHarness>
|
||||
<SubagentConversation turns={turns} />
|
||||
<SubagentConversation turns={turns} author={author} parentAuthor={parentAuthor} />
|
||||
</ChatSurfaceHarness>,
|
||||
);
|
||||
|
||||
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(
|
||||
<ChatSurfaceHarness>
|
||||
<SubagentConversation turns={[followUp]} author={author} parentAuthor={parentAuthor} />
|
||||
</ChatSurfaceHarness>,
|
||||
);
|
||||
|
||||
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(
|
||||
<ChatSurfaceHarness>
|
||||
<SubagentConversation turns={shortened} onLoadTurnDetails={loadDetails} />
|
||||
<SubagentConversation
|
||||
turns={shortened}
|
||||
author={author}
|
||||
parentAuthor={parentAuthor}
|
||||
onLoadTurnDetails={loadDetails}
|
||||
/>
|
||||
</ChatSurfaceHarness>,
|
||||
);
|
||||
|
||||
|
|
@ -182,7 +219,11 @@ describe('SubagentConversation', () => {
|
|||
|
||||
render(
|
||||
<ChatSurfaceHarness>
|
||||
<SubagentConversation turns={[turns[1], secondEvent]} />
|
||||
<SubagentConversation
|
||||
turns={[turns[1], secondEvent]}
|
||||
author={author}
|
||||
parentAuthor={parentAuthor}
|
||||
/>
|
||||
</ChatSurfaceHarness>,
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -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<ChildConversationTurn['trigger']['kind'], TranslationKeys>;
|
||||
|
||||
function TriggerIcon({ kind }: { kind: ChildConversationTurn['trigger']['kind'] }) {
|
||||
const Icon = kind === 'external_event' ? Radio : CornerDownRight;
|
||||
function ExternalEventIcon() {
|
||||
return (
|
||||
<SystemEventIcon>
|
||||
<Icon size={14} />
|
||||
<Radio size={14} />
|
||||
</SystemEventIcon>
|
||||
);
|
||||
}
|
||||
|
|
@ -54,7 +52,7 @@ function ExternalEventTrigger({
|
|||
if (details == null) {
|
||||
body = (
|
||||
<div className="text-text-secondary flex items-center gap-2 py-1 text-sm">
|
||||
<SystemEventHeader icon={<TriggerIcon kind="external_event" />} label={label} />
|
||||
<SystemEventHeader icon={<ExternalEventIcon />} label={label} />
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
|
|
@ -63,7 +61,7 @@ function ExternalEventTrigger({
|
|||
<CollapsibleTrigger asChild>
|
||||
<Button type="button" variant="ghost" className={systemEventHeaderClasses}>
|
||||
<SystemEventHeader
|
||||
icon={<TriggerIcon kind="external_event" />}
|
||||
icon={<ExternalEventIcon />}
|
||||
label={label}
|
||||
detail={`${details.eventType} · ${details.sourceType}`}
|
||||
expanded={expanded}
|
||||
|
|
@ -95,7 +93,7 @@ function ExternalEventTrigger({
|
|||
return (
|
||||
<MessageRow
|
||||
id={`${turn.taskId}:trigger`}
|
||||
icon={<TriggerIcon kind="external_event" />}
|
||||
icon={<ExternalEventIcon />}
|
||||
label={label}
|
||||
footer={null}
|
||||
timestamp={turn.trigger.createdAt ?? details?.occurredAt}
|
||||
|
|
@ -110,7 +108,19 @@ function ExternalEventTrigger({
|
|||
);
|
||||
}
|
||||
|
||||
function TriggerMessage({ turn, fullWidth }: { turn: ChildConversationTurn; fullWidth: boolean }) {
|
||||
/** A parent agent's briefing or follow-up is the user side of this conversation
|
||||
* with the parent as its author, so it is main chat's user turn under the
|
||||
* parent's name and face. Only an external event, which no agent wrote, stays
|
||||
* a system turn. */
|
||||
function TriggerMessage({
|
||||
turn,
|
||||
fullWidth,
|
||||
parentAuthor,
|
||||
}: {
|
||||
turn: ChildConversationTurn;
|
||||
fullWidth: boolean;
|
||||
parentAuthor: TurnAuthor;
|
||||
}) {
|
||||
const showThinking = useAtomValue(showThinkingAtom);
|
||||
const localize = useLocalize();
|
||||
const label = localize(TRIGGER_LABELS[turn.trigger.kind]);
|
||||
|
|
@ -132,20 +142,17 @@ function TriggerMessage({ turn, fullWidth }: { turn: ChildConversationTurn; full
|
|||
return (
|
||||
<MessageRow
|
||||
id={`${turn.taskId}:trigger`}
|
||||
icon={<TriggerIcon kind={turn.trigger.kind} />}
|
||||
label={label}
|
||||
icon={parentAuthor.icon}
|
||||
label={parentAuthor.name}
|
||||
footer={null}
|
||||
timestamp={turn.trigger.createdAt}
|
||||
ariaLabel={label}
|
||||
headerPrefix=""
|
||||
isCreatedByUser={true}
|
||||
systemLabel={localize('com_ui_system_event')}
|
||||
showAuthor
|
||||
fullWidth={fullWidth}
|
||||
>
|
||||
<div className="text-text-secondary flex items-center gap-2 py-1 text-sm">
|
||||
<SystemEventHeader icon={<TriggerIcon kind={turn.trigger.kind} />} label={label} />
|
||||
</div>
|
||||
{content.length > 0 && (
|
||||
{content.length > 0 ? (
|
||||
<ContentParts
|
||||
content={content}
|
||||
messageId={`${turn.taskId}:trigger`}
|
||||
|
|
@ -156,6 +163,8 @@ function TriggerMessage({ turn, fullWidth }: { turn: ChildConversationTurn; full
|
|||
isSubmitting={false}
|
||||
isLatestMessage={false}
|
||||
/>
|
||||
) : (
|
||||
<div className="text-text-secondary text-sm italic">{label}</div>
|
||||
)}
|
||||
{turn.trigger.summaryTruncated === true && (
|
||||
<div className="text-text-secondary mt-1 text-xs italic">
|
||||
|
|
@ -169,7 +178,7 @@ function TriggerMessage({ turn, fullWidth }: { turn: ChildConversationTurn; full
|
|||
function ChildMessage({
|
||||
turn,
|
||||
state,
|
||||
agentId,
|
||||
author,
|
||||
conversationId,
|
||||
fullWidth,
|
||||
onCancelControl,
|
||||
|
|
@ -178,7 +187,7 @@ function ChildMessage({
|
|||
}: {
|
||||
turn: ChildConversationTurn;
|
||||
state: 'ready' | 'loading' | 'error';
|
||||
agentId?: string;
|
||||
author: TurnAuthor;
|
||||
conversationId?: string | null;
|
||||
fullWidth: boolean;
|
||||
onCancelControl?: (controlId: string) => void;
|
||||
|
|
@ -186,9 +195,6 @@ function ChildMessage({
|
|||
onLoadDetails?: () => void;
|
||||
}) {
|
||||
const localize = useLocalize();
|
||||
const agentsMap = useAgentsMapContext();
|
||||
const agent = agentId == null ? undefined : agentsMap?.[agentId];
|
||||
const label = agent?.name ?? turn.activity.title;
|
||||
const detailsLimited = turn.activity.activityTruncated === true;
|
||||
let limitedNotice: ReactNode;
|
||||
if (detailsLimited && onLoadDetails != null && detailState !== 'unavailable') {
|
||||
|
|
@ -217,21 +223,13 @@ function ChildMessage({
|
|||
const footer = (
|
||||
<div className={cn('mt-1 flex justify-start gap-3', messageFooterClasses)}>{footerContent}</div>
|
||||
);
|
||||
const iconData = {
|
||||
endpoint: EModelEndpoint.agents,
|
||||
modelLabel: label,
|
||||
isCreatedByUser: false,
|
||||
};
|
||||
return (
|
||||
<MessageRow
|
||||
id={`${turn.taskId}:assistant`}
|
||||
/** The main chat author glyph, unconditionally: with no resolved agent it
|
||||
* falls back to the endpoint icon there too, so an unresolved child does
|
||||
* not get a differently-inset placeholder of its own. */
|
||||
icon={<MessageIcon iconData={iconData} agent={agent} />}
|
||||
label={label}
|
||||
icon={author.icon}
|
||||
label={author.name}
|
||||
footer={footer}
|
||||
ariaLabel={label}
|
||||
ariaLabel={author.name}
|
||||
headerPrefix=""
|
||||
isCreatedByUser={false}
|
||||
fullWidth={fullWidth}
|
||||
|
|
@ -259,7 +257,8 @@ function ChildMessage({
|
|||
|
||||
export default function SubagentConversation({
|
||||
turns,
|
||||
agentId,
|
||||
author,
|
||||
parentAuthor,
|
||||
conversationId,
|
||||
stateByTask,
|
||||
controllableTaskId,
|
||||
|
|
@ -268,7 +267,10 @@ export default function SubagentConversation({
|
|||
onLoadTurnDetails,
|
||||
}: {
|
||||
turns: ChildConversationTurn[];
|
||||
agentId?: string;
|
||||
/** The child agent: every assistant turn's header. */
|
||||
author: TurnAuthor;
|
||||
/** The agent that briefs the child: every parent-written turn's header. */
|
||||
parentAuthor: TurnAuthor;
|
||||
conversationId?: string | null;
|
||||
stateByTask?: ReadonlyMap<string, 'ready' | 'loading' | 'error'>;
|
||||
controllableTaskId?: string;
|
||||
|
|
@ -286,12 +288,12 @@ export default function SubagentConversation({
|
|||
data-subagent-thread-turn={turn.taskId}
|
||||
>
|
||||
<div className="px-4">
|
||||
<TriggerMessage turn={turn} fullWidth={fullWidth} />
|
||||
<TriggerMessage turn={turn} fullWidth={fullWidth} parentAuthor={parentAuthor} />
|
||||
</div>
|
||||
<div className="px-4">
|
||||
<ChildMessage
|
||||
turn={turn}
|
||||
agentId={agentId}
|
||||
author={author}
|
||||
conversationId={conversationId}
|
||||
fullWidth={fullWidth}
|
||||
state={stateByTask?.get(turn.taskId) ?? 'ready'}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
import React from 'react';
|
||||
import { useAtomValue, useSetAtom } from 'jotai';
|
||||
import { ContentTypes, ForkOptions } from 'librechat-data-provider';
|
||||
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
|
||||
import { ContentTypes, EModelEndpoint, ForkOptions, QueryKeys } from 'librechat-data-provider';
|
||||
import type {
|
||||
ParentSubagentSummary,
|
||||
TMessage,
|
||||
SubagentThreadView,
|
||||
TMessageContentParts,
|
||||
ParentSubagentSummary,
|
||||
} from 'librechat-data-provider';
|
||||
import type { ActiveSubagentPanel } from './state';
|
||||
import type { JotaiStore } from 'test/harness';
|
||||
|
|
@ -37,6 +39,9 @@ const mockRefreshParentChildren = jest.fn().mockResolvedValue(undefined);
|
|||
let mockEnterToSend = true;
|
||||
const mockClaimForeground = jest.fn();
|
||||
const mockHandOffComposerText = jest.fn();
|
||||
/** Real, per test: the panel reads the dispatching message from the parent
|
||||
* conversation's loaded thread, the cache main chat itself renders from. */
|
||||
let queryClient = new QueryClient();
|
||||
|
||||
function Root({
|
||||
seed,
|
||||
|
|
@ -46,16 +51,18 @@ function Root({
|
|||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<ChatSurfaceHarness
|
||||
seed={seed}
|
||||
surface={testChatSurface({
|
||||
enterToSend: mockEnterToSend,
|
||||
claimForeground: mockClaimForeground,
|
||||
handOffComposerText: mockHandOffComposerText,
|
||||
})}
|
||||
>
|
||||
{children}
|
||||
</ChatSurfaceHarness>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ChatSurfaceHarness
|
||||
seed={seed}
|
||||
surface={testChatSurface({
|
||||
enterToSend: mockEnterToSend,
|
||||
claimForeground: mockClaimForeground,
|
||||
handOffComposerText: mockHandOffComposerText,
|
||||
})}
|
||||
>
|
||||
{children}
|
||||
</ChatSurfaceHarness>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -123,6 +130,26 @@ jest.mock('~/Providers', () => ({
|
|||
}),
|
||||
}));
|
||||
|
||||
/** Main chat's author glyph, reduced to the face it draws: the agent's avatar
|
||||
* when it has one. */
|
||||
jest.mock('~/components/Chat/Messages/MessageIcon', () => ({
|
||||
__esModule: true,
|
||||
default: ({
|
||||
agent,
|
||||
iconData,
|
||||
}: {
|
||||
agent?: { avatar?: { filepath?: string } };
|
||||
iconData?: { iconURL?: string };
|
||||
}) => {
|
||||
const src = iconData?.iconURL ?? agent?.avatar?.filepath;
|
||||
return src != null ? (
|
||||
<img src={src} alt="" data-testid="author-face" />
|
||||
) : (
|
||||
<span data-testid="author-face" />
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock('./ParentSubagentsProvider', () => ({
|
||||
useParentSubagents: () => ({
|
||||
byMessageId: mockParentChildrenByMessage,
|
||||
|
|
@ -198,10 +225,14 @@ jest.mock('./SubagentConversation', () => ({
|
|||
__esModule: true,
|
||||
default: ({
|
||||
turns,
|
||||
author,
|
||||
parentAuthor,
|
||||
stateByTask,
|
||||
detailStateByTask,
|
||||
onLoadTurnDetails,
|
||||
}: {
|
||||
author: { name: string; icon: React.ReactNode };
|
||||
parentAuthor: { name: string };
|
||||
turns: Array<{
|
||||
taskId: string;
|
||||
trigger: { summary: string };
|
||||
|
|
@ -214,7 +245,10 @@ jest.mock('./SubagentConversation', () => ({
|
|||
<div
|
||||
data-testid="subagent-conversation"
|
||||
data-state={turns[0] == null ? undefined : stateByTask?.get(turns[0].taskId)}
|
||||
data-author={author.name}
|
||||
data-parent-author={parentAuthor.name}
|
||||
>
|
||||
{author.icon}
|
||||
{turns.map((turn) => (
|
||||
<div key={turn.taskId} data-testid="conversation-turn">
|
||||
{turn.trigger.summary}
|
||||
|
|
@ -455,8 +489,20 @@ const completedView: SubagentThreadView = {
|
|||
],
|
||||
};
|
||||
|
||||
const completedTurns: SubagentThreadView['turns'] = [
|
||||
{
|
||||
taskId: 'task',
|
||||
trigger: { kind: 'parent_dispatch', summary: 'Historical request.' },
|
||||
status: 'completed',
|
||||
activity: completedView.activity,
|
||||
activityTruncated: false,
|
||||
messages: completedView.messages,
|
||||
},
|
||||
];
|
||||
|
||||
describe('SubagentThreadPanel', () => {
|
||||
beforeEach(() => {
|
||||
queryClient = new QueryClient();
|
||||
window.sessionStorage.clear();
|
||||
mockIsMobile = false;
|
||||
mockCoarsePointer = false;
|
||||
|
|
@ -489,24 +535,648 @@ describe('SubagentThreadPanel', () => {
|
|||
...selection,
|
||||
durable: undefined,
|
||||
subagentType,
|
||||
subagentIdentity: { subagentKind: 'agent' as const, subagentAgentId: subagentType },
|
||||
subagentIdentity: {
|
||||
subagentKind: 'agent' as const,
|
||||
subagentAgentId: subagentType === 'self' ? 'agent-2' : subagentType,
|
||||
},
|
||||
};
|
||||
render(
|
||||
/** The dispatching agent, as main chat holds it: a self-spawn is that
|
||||
* agent working on its own behalf, so it takes the parent's name. */
|
||||
queryClient.setQueryData<TMessage[]>(
|
||||
[QueryKeys.messages, 'parent-conversation'],
|
||||
[
|
||||
{
|
||||
messageId: 'parent-message',
|
||||
parentMessageId: null,
|
||||
conversationId: 'parent-conversation',
|
||||
isCreatedByUser: false,
|
||||
endpoint: EModelEndpoint.agents,
|
||||
model: 'agent-2',
|
||||
sender: 'Analyst Two',
|
||||
text: '',
|
||||
} as unknown as TMessage,
|
||||
],
|
||||
);
|
||||
const { container } = render(
|
||||
<Root>
|
||||
<SubagentThreadPanel selection={foregroundSelection} />
|
||||
</Root>,
|
||||
);
|
||||
const title =
|
||||
subagentType === 'self'
|
||||
? 'com_ui_subagent_dialog_title_self'
|
||||
: `com_ui_subagent_dialog_title: ${subagentType === 'agent-1' ? 'Analyst One' : subagentType}`;
|
||||
expect(screen.getByRole('heading', { name: title })).toBeInTheDocument();
|
||||
const titles: Record<string, string> = {
|
||||
'agent-1': 'Analyst One',
|
||||
'missing-agent': 'com_ui_subagent_actor',
|
||||
self: 'Analyst Two',
|
||||
};
|
||||
expect(screen.getByRole('heading', { name: titles[subagentType] })).toBeInTheDocument();
|
||||
/** Never the id: an unresolvable agent is named generically. */
|
||||
expect(screen.queryByText(/missing-agent/)).not.toBeInTheDocument();
|
||||
if (subagentType === 'agent-1') {
|
||||
expect(screen.getByAltText('Analyst One avatar')).toHaveAttribute('src', '/analyst.png');
|
||||
expect(container.querySelector('header img[src="/analyst.png"]')).toBeInTheDocument();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('uses the durable title when the child agent is unavailable', () => {
|
||||
mockUseSubagentThreadQuery.mockReturnValue({
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
data: { ...completedView, agentId: 'agent_deleted', title: 'Historical Reviewer' },
|
||||
});
|
||||
render(
|
||||
<Root>
|
||||
<SubagentThreadPanel selection={selection} />
|
||||
</Root>,
|
||||
);
|
||||
expect(screen.getByRole('heading', { name: 'Historical Reviewer' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('textbox')).toHaveAttribute(
|
||||
'placeholder',
|
||||
'com_endpoint_message_new: Historical Reviewer',
|
||||
);
|
||||
});
|
||||
|
||||
it('restores a self-spawn with the complete historical parent author', () => {
|
||||
queryClient.setQueryData<TMessage[]>(
|
||||
[QueryKeys.messages, 'parent-conversation'],
|
||||
[
|
||||
{
|
||||
messageId: 'parent-message',
|
||||
parentMessageId: null,
|
||||
conversationId: 'parent-conversation',
|
||||
isCreatedByUser: false,
|
||||
endpoint: EModelEndpoint.agents,
|
||||
model: 'agent_deleted',
|
||||
sender: 'Historical Parent',
|
||||
iconURL: '/historical-parent.png',
|
||||
text: '',
|
||||
},
|
||||
],
|
||||
);
|
||||
mockUseSubagentThreadQuery.mockReturnValue({
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
data: {
|
||||
...completedView,
|
||||
subagentType: 'self',
|
||||
agentId: 'agent_deleted',
|
||||
turns: completedTurns,
|
||||
},
|
||||
});
|
||||
const { container } = render(
|
||||
<Root>
|
||||
<SubagentThreadPanel
|
||||
selection={{
|
||||
...selection,
|
||||
subagentType: 'self',
|
||||
}}
|
||||
/>
|
||||
</Root>,
|
||||
);
|
||||
expect(screen.getByRole('heading', { name: 'Historical Parent' })).toBeInTheDocument();
|
||||
expect(container.querySelector('header img[src="/historical-parent.png"]')).toBeInTheDocument();
|
||||
const conversation = screen.getByTestId('subagent-conversation');
|
||||
expect(conversation).toHaveAttribute('data-author', 'Historical Parent');
|
||||
expect(within(conversation).getByRole('img', { hidden: true })).toHaveAttribute(
|
||||
'src',
|
||||
'/historical-parent.png',
|
||||
);
|
||||
});
|
||||
|
||||
it.each(['selection', 'durable'])(
|
||||
'keeps a graph named self distinct from its parent (%s identity)',
|
||||
(source) => {
|
||||
queryClient.setQueryData<TMessage[]>(
|
||||
[QueryKeys.messages, 'parent-conversation'],
|
||||
[
|
||||
{
|
||||
messageId: 'parent-message',
|
||||
parentMessageId: null,
|
||||
conversationId: 'parent-conversation',
|
||||
isCreatedByUser: false,
|
||||
endpoint: EModelEndpoint.agents,
|
||||
model: 'agent_deleted',
|
||||
sender: 'Historical Parent',
|
||||
iconURL: '/historical-parent.png',
|
||||
text: '',
|
||||
},
|
||||
],
|
||||
);
|
||||
mockUseSubagentThreadQuery.mockReturnValue({
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
data: {
|
||||
...completedView,
|
||||
agentId: undefined,
|
||||
subagentType: 'self',
|
||||
title: 'self',
|
||||
subagentKind: source === 'durable' ? 'graph' : undefined,
|
||||
turns: completedTurns,
|
||||
},
|
||||
});
|
||||
const { container } = render(
|
||||
<Root>
|
||||
<SubagentThreadPanel
|
||||
selection={{
|
||||
...selection,
|
||||
subagentType: 'self',
|
||||
subagentIdentity:
|
||||
source === 'selection'
|
||||
? { subagentKind: 'graph', subagentAgentId: 'graph:self' }
|
||||
: undefined,
|
||||
}}
|
||||
/>
|
||||
</Root>,
|
||||
);
|
||||
expect(screen.getByRole('heading', { name: 'self' })).toBeInTheDocument();
|
||||
expect(screen.getByTestId('subagent-conversation')).toHaveAttribute('data-author', 'self');
|
||||
expect(container.querySelector('header img[src="/historical-parent.png"]')).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([false, true])(
|
||||
'preserves indexed graph identity before query success (failed: %s)',
|
||||
(failed) => {
|
||||
const child: ParentSubagentSummary = {
|
||||
threadId: 'child-thread',
|
||||
parentMessageId: 'parent-message',
|
||||
subagentType: 'self',
|
||||
subagentKind: 'graph',
|
||||
title: 'self',
|
||||
origin: 'tool',
|
||||
status: 'completed',
|
||||
latestTaskId: 'task',
|
||||
tasks: [{ taskId: 'task', status: 'completed' }],
|
||||
tasksTruncated: false,
|
||||
};
|
||||
mockParentChildrenByThread.set(child.threadId, child);
|
||||
queryClient.setQueryData<TMessage[]>(
|
||||
[QueryKeys.messages, 'parent-conversation'],
|
||||
[
|
||||
{
|
||||
messageId: 'parent-message',
|
||||
parentMessageId: null,
|
||||
conversationId: 'parent-conversation',
|
||||
isCreatedByUser: false,
|
||||
endpoint: EModelEndpoint.agents,
|
||||
model: 'agent_deleted',
|
||||
sender: 'Historical Parent',
|
||||
iconURL: '/historical-parent.png',
|
||||
text: '',
|
||||
},
|
||||
],
|
||||
);
|
||||
mockUseSubagentThreadQuery.mockReturnValue({ isLoading: !failed, isError: failed });
|
||||
const { container } = render(
|
||||
<Root>
|
||||
<SubagentThreadPanel selection={{ ...selection, subagentType: 'self' }} />
|
||||
</Root>,
|
||||
);
|
||||
expect(screen.getByRole('heading', { name: 'self' })).toBeInTheDocument();
|
||||
expect(container.querySelector('header img[src="/historical-parent.png"]')).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it('refreshes dispatch-lane attribution when switching streamed tool calls in one parent turn', async () => {
|
||||
const first: TMessage = {
|
||||
messageId: 'parent-message',
|
||||
parentMessageId: null,
|
||||
conversationId: 'parent-conversation',
|
||||
isCreatedByUser: false,
|
||||
text: '',
|
||||
endpoint: EModelEndpoint.agents,
|
||||
model: 'agent-2',
|
||||
sender: 'Analyst Two',
|
||||
content: [
|
||||
{
|
||||
type: ContentTypes.TOOL_CALL,
|
||||
agentId: 'agent-2',
|
||||
tool_call: { id: 'first-call', name: 'subagent', args: {} },
|
||||
},
|
||||
],
|
||||
};
|
||||
queryClient.setQueryData([QueryKeys.messages, 'parent-conversation'], [first]);
|
||||
mockUseSubagentThreadQuery.mockReturnValue({
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
data: { ...completedView, turns: completedTurns },
|
||||
});
|
||||
const { rerender } = render(
|
||||
<Root>
|
||||
<SubagentThreadPanel selection={{ ...selection, toolCallId: 'first-call' }} />
|
||||
</Root>,
|
||||
);
|
||||
expect(screen.getByTestId('subagent-conversation')).toHaveAttribute(
|
||||
'data-parent-author',
|
||||
'Analyst Two',
|
||||
);
|
||||
await act(async () => {
|
||||
queryClient.setQueryData(
|
||||
[QueryKeys.messages, 'parent-conversation'],
|
||||
[
|
||||
{
|
||||
...first,
|
||||
content: [
|
||||
...(first.content ?? []),
|
||||
{
|
||||
type: ContentTypes.TOOL_CALL,
|
||||
agentId: 'agent-1',
|
||||
tool_call: { id: 'second-call', name: 'subagent', args: {} },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
);
|
||||
});
|
||||
rerender(
|
||||
<Root>
|
||||
<SubagentThreadPanel selection={{ ...selection, toolCallId: 'second-call' }} />
|
||||
</Root>,
|
||||
);
|
||||
expect(screen.getByTestId('subagent-conversation')).toHaveAttribute(
|
||||
'data-parent-author',
|
||||
'Analyst One',
|
||||
);
|
||||
await act(async () => {
|
||||
queryClient.setQueryData(
|
||||
[QueryKeys.messages, 'parent-conversation'],
|
||||
[{ ...first, sender: 'Changed snapshot', text: 'Later chunk' }],
|
||||
);
|
||||
});
|
||||
expect(screen.getByTestId('subagent-conversation')).toHaveAttribute(
|
||||
'data-parent-author',
|
||||
'Analyst One',
|
||||
);
|
||||
});
|
||||
|
||||
it('switches repeated provider IDs between parallel dispatch occurrences', async () => {
|
||||
const first: TMessage = {
|
||||
messageId: 'parent-message',
|
||||
parentMessageId: null,
|
||||
conversationId: 'parent-conversation',
|
||||
isCreatedByUser: false,
|
||||
text: '',
|
||||
endpoint: EModelEndpoint.agents,
|
||||
model: 'agent-2',
|
||||
sender: 'Analyst Two',
|
||||
content: [
|
||||
{
|
||||
type: ContentTypes.TOOL_CALL,
|
||||
agentId: 'agent-2',
|
||||
tool_call: { id: 'repeat', name: 'subagent', args: {} },
|
||||
},
|
||||
],
|
||||
};
|
||||
queryClient.setQueryData([QueryKeys.messages, 'parent-conversation'], [first]);
|
||||
mockUseSubagentThreadQuery.mockReturnValue({
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
data: { ...completedView, turns: completedTurns },
|
||||
});
|
||||
const { rerender } = render(
|
||||
<Root>
|
||||
<SubagentThreadPanel
|
||||
selection={{ ...selection, durable: undefined, toolCallId: 'repeat', partIndex: 0 }}
|
||||
/>
|
||||
</Root>,
|
||||
);
|
||||
expect(screen.getByTestId('subagent-conversation')).toHaveAttribute(
|
||||
'data-parent-author',
|
||||
'Analyst Two',
|
||||
);
|
||||
await act(async () => {
|
||||
queryClient.setQueryData(
|
||||
[QueryKeys.messages, 'parent-conversation'],
|
||||
[
|
||||
{
|
||||
...first,
|
||||
content: [
|
||||
...(first.content ?? []),
|
||||
{
|
||||
type: ContentTypes.TOOL_CALL,
|
||||
agentId: 'agent-1',
|
||||
tool_call: { id: 'repeat', name: 'subagent', args: {} },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
);
|
||||
});
|
||||
rerender(
|
||||
<Root>
|
||||
<SubagentThreadPanel
|
||||
selection={{ ...selection, durable: undefined, toolCallId: 'repeat', partIndex: 1 }}
|
||||
/>
|
||||
</Root>,
|
||||
);
|
||||
expect(screen.getByTestId('subagent-conversation')).toHaveAttribute(
|
||||
'data-parent-author',
|
||||
'Analyst One',
|
||||
);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
'retains an indexed saved agent while durable details are unavailable (failed: %s)',
|
||||
(failed) => {
|
||||
const child: ParentSubagentSummary = {
|
||||
threadId: 'child-thread',
|
||||
parentMessageId: 'parent-message',
|
||||
subagentType: 'agent-2',
|
||||
subagentKind: 'agent',
|
||||
agentId: 'agent-2',
|
||||
title: 'Analyst Two',
|
||||
origin: 'tool',
|
||||
status: 'completed',
|
||||
latestTaskId: 'task',
|
||||
tasks: [{ taskId: 'task', status: 'completed' }],
|
||||
tasksTruncated: false,
|
||||
};
|
||||
mockParentChildrenByThread.set(child.threadId, child);
|
||||
mockUseSubagentThreadQuery.mockReturnValue({ isLoading: !failed, isError: failed });
|
||||
render(
|
||||
<Root>
|
||||
<SubagentThreadPanel
|
||||
selection={{ ...selection, subagentType: 'agent-2', subagentIdentity: undefined }}
|
||||
/>
|
||||
</Root>,
|
||||
);
|
||||
expect(screen.getByRole('heading', { name: 'Analyst Two' })).toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(
|
||||
['Historical Reviewer', 'Subagent: Reviewer', 'self', 'agent_research_team'].flatMap((title) =>
|
||||
[false, true].map((failed) => ({ title, failed })),
|
||||
),
|
||||
)('retains an unavailable indexed agent title $title (failed: $failed)', ({ title, failed }) => {
|
||||
const child: ParentSubagentSummary = {
|
||||
threadId: 'child-thread',
|
||||
parentMessageId: 'parent-message',
|
||||
subagentType: 'agent_deleted',
|
||||
subagentKind: 'agent',
|
||||
agentId: 'agent_deleted',
|
||||
title,
|
||||
origin: 'tool',
|
||||
status: 'completed',
|
||||
latestTaskId: 'task',
|
||||
tasks: [{ taskId: 'task', status: 'completed' }],
|
||||
tasksTruncated: false,
|
||||
};
|
||||
mockParentChildrenByThread.set(child.threadId, child);
|
||||
mockUseSubagentThreadQuery.mockReturnValue({ isLoading: !failed, isError: failed });
|
||||
const view = render(
|
||||
<Root>
|
||||
<SubagentThreadPanel
|
||||
selection={{ ...selection, subagentType: 'agent_deleted', subagentIdentity: undefined }}
|
||||
/>
|
||||
</Root>,
|
||||
);
|
||||
expect(screen.getByRole('heading', { name: title })).toBeInTheDocument();
|
||||
expect(screen.getByTestId('subagent-conversation')).toHaveAttribute('data-author', title);
|
||||
mockUseSubagentThreadQuery.mockReturnValue({
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
data: { ...completedView, agentId: 'agent_deleted', title },
|
||||
});
|
||||
view.rerender(
|
||||
<Root>
|
||||
<SubagentThreadPanel
|
||||
selection={{ ...selection, subagentType: 'agent_deleted', subagentIdentity: undefined }}
|
||||
/>
|
||||
</Root>,
|
||||
);
|
||||
expect(screen.getByRole('heading', { name: title })).toBeInTheDocument();
|
||||
expect(screen.getByRole('textbox')).toHaveAttribute(
|
||||
'placeholder',
|
||||
`com_endpoint_message_new: ${title}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves a literal graph display title beginning with Subagent:', () => {
|
||||
mockUseSubagentThreadQuery.mockReturnValue({
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
data: {
|
||||
...completedView,
|
||||
agentId: undefined,
|
||||
subagentKind: 'graph',
|
||||
subagentType: 'Subagent: research',
|
||||
title: 'Subagent: research',
|
||||
turns: completedTurns,
|
||||
},
|
||||
});
|
||||
render(
|
||||
<Root>
|
||||
<SubagentThreadPanel selection={{ ...selection, subagentType: 'Subagent: research' }} />
|
||||
</Root>,
|
||||
);
|
||||
expect(screen.getByRole('heading', { name: 'Subagent: research' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each(['self', 'researcher'])(
|
||||
'resolves a restored %s dispatch by thread handle rather than its placeholder index',
|
||||
(type) => {
|
||||
const handle = (threadId: string) =>
|
||||
JSON.stringify({
|
||||
background_task_id: 'task',
|
||||
subagent_thread_id: threadId,
|
||||
tool: 'subagent',
|
||||
subagent_type: type,
|
||||
status: 'running',
|
||||
message: 'Poll using background_task_id task.',
|
||||
});
|
||||
const dispatch: TMessage = {
|
||||
messageId: 'parent-message',
|
||||
parentMessageId: null,
|
||||
conversationId: 'parent-conversation',
|
||||
isCreatedByUser: false,
|
||||
text: '',
|
||||
endpoint: EModelEndpoint.agents,
|
||||
model: 'agent-2',
|
||||
sender: 'Analyst Two',
|
||||
content: [
|
||||
{
|
||||
type: ContentTypes.TOOL_CALL,
|
||||
agentId: 'agent-2',
|
||||
tool_call: {
|
||||
id: 'repeat',
|
||||
name: 'subagent',
|
||||
args: { run_in_background: true },
|
||||
output: handle('first-child'),
|
||||
},
|
||||
},
|
||||
{
|
||||
type: ContentTypes.TOOL_CALL,
|
||||
agentId: 'agent-1',
|
||||
tool_call: {
|
||||
id: 'repeat',
|
||||
name: 'subagent',
|
||||
args: { run_in_background: true },
|
||||
output: handle('child-thread'),
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
queryClient.setQueryData([QueryKeys.messages, 'parent-conversation'], [dispatch]);
|
||||
mockUseSubagentThreadQuery.mockReturnValue({
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
data: { ...completedView, subagentType: type, agentId: 'agent-1', turns: completedTurns },
|
||||
});
|
||||
render(
|
||||
<Root>
|
||||
<SubagentThreadPanel
|
||||
selection={{ ...selection, subagentType: type, toolCallId: 'repeat', partIndex: 0 }}
|
||||
/>
|
||||
</Root>,
|
||||
);
|
||||
expect(screen.getByTestId('subagent-conversation')).toHaveAttribute(
|
||||
'data-parent-author',
|
||||
'Analyst One',
|
||||
);
|
||||
expect(screen.getByTestId('subagent-conversation')).toHaveAttribute(
|
||||
'data-author',
|
||||
'Analyst One',
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('attributes restored parallel-lane self turns to the validated spawning agent', () => {
|
||||
queryClient.setQueryData<TMessage[]>(
|
||||
[QueryKeys.messages, 'parent-conversation'],
|
||||
[
|
||||
{
|
||||
messageId: 'parent-message',
|
||||
parentMessageId: null,
|
||||
conversationId: 'parent-conversation',
|
||||
isCreatedByUser: false,
|
||||
text: '',
|
||||
endpoint: EModelEndpoint.agents,
|
||||
model: 'agent-2',
|
||||
sender: 'Analyst Two',
|
||||
},
|
||||
],
|
||||
);
|
||||
mockUseSubagentThreadQuery.mockReturnValue({
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
data: { ...completedView, subagentType: 'self', agentId: 'agent-1', turns: completedTurns },
|
||||
});
|
||||
const { container } = render(
|
||||
<Root>
|
||||
<SubagentThreadPanel selection={{ ...selection, subagentType: 'self' }} />
|
||||
</Root>,
|
||||
);
|
||||
expect(screen.getByRole('heading', { name: 'Analyst One' })).toBeInTheDocument();
|
||||
expect(container.querySelector('header img[src="/analyst.png"]')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('subagent-conversation')).toHaveAttribute(
|
||||
'data-author',
|
||||
'Analyst One',
|
||||
);
|
||||
expect(screen.getByTestId('subagent-conversation')).toHaveAttribute(
|
||||
'data-parent-author',
|
||||
'Analyst One',
|
||||
);
|
||||
});
|
||||
|
||||
it('resolves a missing historical parent after its reply arrives and retains that author', async () => {
|
||||
queryClient.setQueryData<TMessage[]>([QueryKeys.messages, 'parent-conversation'], []);
|
||||
mockUseSubagentThreadQuery.mockReturnValue({
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
data: {
|
||||
...completedView,
|
||||
agentId: 'agent_deleted',
|
||||
subagentType: 'self',
|
||||
turns: completedTurns,
|
||||
},
|
||||
});
|
||||
const { container } = render(
|
||||
<Root>
|
||||
<SubagentThreadPanel selection={{ ...selection, subagentType: 'self' }} />
|
||||
</Root>,
|
||||
);
|
||||
expect(
|
||||
screen.getByRole('heading', { name: 'com_ui_subagent_parent_agent' }),
|
||||
).toBeInTheDocument();
|
||||
const reply: TMessage = {
|
||||
messageId: 'reply',
|
||||
parentMessageId: 'parent-message',
|
||||
conversationId: 'parent-conversation',
|
||||
isCreatedByUser: false,
|
||||
endpoint: EModelEndpoint.agents,
|
||||
model: 'agent_deleted',
|
||||
sender: 'Late Parent',
|
||||
iconURL: '/late.png',
|
||||
text: '',
|
||||
};
|
||||
await act(async () => {
|
||||
queryClient.setQueryData([QueryKeys.messages, 'parent-conversation'], [reply]);
|
||||
});
|
||||
expect(screen.getByRole('heading', { name: 'Late Parent' })).toBeInTheDocument();
|
||||
expect(container.querySelector('header img[src="/late.png"]')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('subagent-conversation')).toHaveAttribute(
|
||||
'data-author',
|
||||
'Late Parent',
|
||||
);
|
||||
await act(async () => {
|
||||
queryClient.setQueryData(
|
||||
[QueryKeys.messages, 'parent-conversation'],
|
||||
[{ ...reply, sender: 'Changed snapshot', iconURL: '/changed.png', text: 'Next chunk' }],
|
||||
);
|
||||
});
|
||||
expect(screen.getByRole('heading', { name: 'Late Parent' })).toBeInTheDocument();
|
||||
expect(container.querySelector('header img[src="/late.png"]')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([true, false])(
|
||||
'names an unavailable event actor by its projected label (indexed: %s)',
|
||||
(indexed) => {
|
||||
const child: ParentSubagentSummary = {
|
||||
threadId: 'child-thread',
|
||||
parentMessageId: 'parent-message',
|
||||
subagentType: 'agent_deleted',
|
||||
subagentKind: 'agent',
|
||||
agentId: 'agent_deleted',
|
||||
title: 'Agent actor: reviewer',
|
||||
origin: 'event',
|
||||
actorId: 'reviewer',
|
||||
status: 'completed',
|
||||
latestTaskId: 'task',
|
||||
tasks: [{ taskId: 'task', status: 'completed' }],
|
||||
tasksTruncated: false,
|
||||
};
|
||||
if (indexed) {
|
||||
mockParentChildrenByMessage = new Map([['parent-message', [child]]]);
|
||||
mockParentChildrenByThread = new Map([[child.threadId, child]]);
|
||||
}
|
||||
mockUseSubagentThreadQuery.mockReturnValue({
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
data: {
|
||||
...completedView,
|
||||
agentId: 'agent_deleted',
|
||||
title: child.title,
|
||||
turns: completedTurns,
|
||||
},
|
||||
});
|
||||
render(
|
||||
<Root>
|
||||
<SubagentThreadPanel
|
||||
selection={{
|
||||
...selection,
|
||||
event: { actorId: 'reviewer', progressKey: 'event-task:child-thread:task' },
|
||||
}}
|
||||
/>
|
||||
</Root>,
|
||||
);
|
||||
expect(screen.getByTestId('subagent-conversation')).toHaveAttribute(
|
||||
'data-author',
|
||||
'reviewer',
|
||||
);
|
||||
expect(screen.getByRole('heading', { name: 'reviewer' })).toBeInTheDocument();
|
||||
expect(screen.queryByText('Agent actor: reviewer')).not.toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([undefined, { subagentKind: 'graph' as const, subagentAgentId: 'graph:agent-1' }])(
|
||||
'does not resolve graph or legacy panel types as saved agents',
|
||||
(subagentIdentity) => {
|
||||
|
|
@ -523,10 +1193,9 @@ describe('SubagentThreadPanel', () => {
|
|||
/>
|
||||
</Root>,
|
||||
);
|
||||
expect(
|
||||
screen.getByRole('heading', { name: 'com_ui_subagent_dialog_title: agent-1' }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByAltText('Analyst One avatar')).not.toBeInTheDocument();
|
||||
/** A non-agent type is a readable name of its own, not an agent to look up. */
|
||||
expect(screen.getByRole('heading', { name: 'agent-1' })).toBeInTheDocument();
|
||||
expect(document.querySelector('img[src="/analyst.png"]')).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
|
|
@ -641,13 +1310,33 @@ describe('SubagentThreadPanel', () => {
|
|||
isReadinessPending: false,
|
||||
});
|
||||
|
||||
queryClient.setQueryData<TMessage[]>(
|
||||
[QueryKeys.messages, 'parent-conversation'],
|
||||
[
|
||||
{
|
||||
messageId: 'parent-message',
|
||||
parentMessageId: null,
|
||||
conversationId: 'parent-conversation',
|
||||
isCreatedByUser: false,
|
||||
endpoint: EModelEndpoint.agents,
|
||||
model: 'agent-2',
|
||||
sender: 'Analyst Two',
|
||||
text: '',
|
||||
} as unknown as TMessage,
|
||||
],
|
||||
);
|
||||
render(
|
||||
<Root>
|
||||
<SubagentThreadPanel selection={selection} />
|
||||
</Root>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('subagent-conversation')).toBeInTheDocument();
|
||||
/** One name for the child everywhere it appears, and the dispatching agent
|
||||
* as the author of every briefing — never an id or a role. */
|
||||
const conversation = screen.getByTestId('subagent-conversation');
|
||||
expect(conversation).toHaveAttribute('data-author', 'Analyst One');
|
||||
expect(conversation).toHaveAttribute('data-parent-author', 'Analyst Two');
|
||||
expect(screen.getByRole('heading', { name: 'Analyst One' })).toBeInTheDocument();
|
||||
expect(screen.getAllByTestId('conversation-turn')).toHaveLength(2);
|
||||
expect(screen.getByText(/Initial request/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Follow-up request/)).toBeInTheDocument();
|
||||
|
|
@ -703,6 +1392,8 @@ describe('SubagentThreadPanel', () => {
|
|||
);
|
||||
|
||||
const composer = screen.getByLabelText('com_ui_message_input');
|
||||
/** Addressed by name, as main chat's composer addresses its agent. */
|
||||
expect(composer).toHaveAttribute('placeholder', 'com_endpoint_message_new: Analyst One');
|
||||
fireEvent.change(composer, { target: { value: 'Check the primary source.' } });
|
||||
fireEvent.keyDown(composer, { key: 'Enter' });
|
||||
expect(mockControlMutate).not.toHaveBeenCalled();
|
||||
|
|
|
|||
|
|
@ -36,6 +36,14 @@ import {
|
|||
useSubagentControlMutation,
|
||||
useSubagentThreadQuery,
|
||||
} from '~/data-provider';
|
||||
import {
|
||||
agentAuthor,
|
||||
resolveSubagentAuthor,
|
||||
isSelfSpawn as isSelfSpawnType,
|
||||
resolveChildAgent,
|
||||
readableSubagentType,
|
||||
useParentAuthor,
|
||||
} from './author';
|
||||
import {
|
||||
activeSubagentPanel,
|
||||
subagentControlStateByTask,
|
||||
|
|
@ -151,14 +159,14 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
|
|||
selection.partIndex,
|
||||
),
|
||||
);
|
||||
const foregroundAgentId = resolveSubagentAgentId(progress, selection.subagentIdentity);
|
||||
const foregroundAgent = foregroundAgentId == null ? undefined : agentsMap?.[foregroundAgentId];
|
||||
const foregroundTitle =
|
||||
selection.subagentType === 'self'
|
||||
? localize('com_ui_subagent_dialog_title_self')
|
||||
: localize('com_ui_subagent_dialog_title', {
|
||||
0: foregroundAgent?.name || selection.subagentType,
|
||||
});
|
||||
const parentAuthor = useParentAuthor(
|
||||
selection.parentConversationId,
|
||||
selection.parentMessageId,
|
||||
localize('com_ui_subagent_parent_agent'),
|
||||
selection.toolCallId,
|
||||
selection.partIndex,
|
||||
selection.durable?.threadId,
|
||||
);
|
||||
const threadId = selection.durable?.threadId ?? '';
|
||||
const taskId = selection.durable?.taskId ?? '';
|
||||
const controlIdentity = subagentControlStateKey(selection.parentConversationId, threadId, taskId);
|
||||
|
|
@ -213,13 +221,6 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
|
|||
});
|
||||
}, [byMessageId, selection.event, selection.parentMessageId]);
|
||||
const selectedEventActor = eventSiblings.find((child) => child.threadId === threadId);
|
||||
const selectedEventActorName =
|
||||
(selectedEventActor?.agentId == null
|
||||
? undefined
|
||||
: agentsMap?.[selectedEventActor.agentId]?.name) ??
|
||||
selectedEventActor?.actorId ??
|
||||
eventSummary?.actorId ??
|
||||
foregroundTitle;
|
||||
const { data, isLoading, isError, isPreviousData, isReadinessPending, refetch } =
|
||||
useSubagentThreadQuery(selection.parentConversationId, threadId, taskId, {
|
||||
/** A new delivery re-keys this query to its task. Keeping the previous
|
||||
|
|
@ -234,6 +235,34 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
|
|||
* task-scoped fields (selected activity, status, control receipts) must not
|
||||
* be attributed to the newly selected task. */
|
||||
const threadView = data?.threadId === threadId ? data : undefined;
|
||||
const childKind =
|
||||
threadView?.subagentKind ??
|
||||
progress?.subagentKind ??
|
||||
selection.subagentIdentity?.subagentKind ??
|
||||
byThreadId.get(threadId)?.subagentKind;
|
||||
const isSelfSpawn = isSelfSpawnType(selection.subagentType, childKind);
|
||||
const foregroundAgentId =
|
||||
childKind === 'graph'
|
||||
? undefined
|
||||
: (resolveSubagentAgentId(progress, selection.subagentIdentity) ??
|
||||
byThreadId.get(threadId)?.agentId);
|
||||
const foregroundAgent = foregroundAgentId == null ? undefined : agentsMap?.[foregroundAgentId];
|
||||
/** Named the way main chat names an agent turn — never by its id. A
|
||||
* self-spawn is the parent agent working on its own behalf. */
|
||||
const foregroundTitle =
|
||||
foregroundAgent?.name ||
|
||||
(isSelfSpawn
|
||||
? parentAuthor.name
|
||||
: readableSubagentType(selection.subagentType, foregroundAgentId, childKind)) ||
|
||||
localize('com_ui_subagent_actor');
|
||||
const selectedEventActorName =
|
||||
(selectedEventActor?.agentId == null
|
||||
? undefined
|
||||
: agentsMap?.[selectedEventActor.agentId]?.name) ??
|
||||
selectedEventActor?.actorId ??
|
||||
eventSummary?.actorId ??
|
||||
selection.event?.actorId ??
|
||||
foregroundTitle;
|
||||
const taskView = isPreviousData ? undefined : threadView;
|
||||
const latestHistoryGeneration = JSON.stringify([
|
||||
threadView?.nextCursor ?? null,
|
||||
|
|
@ -826,9 +855,48 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
|
|||
}
|
||||
return { ...merged, controls: [...(merged.controls ?? []), transientControl] };
|
||||
}, [liveActivity, progress, selection.durable, taskView, transientControl]);
|
||||
const panelAgent = threadView?.agentId == null ? undefined : agentsMap?.[threadView.agentId];
|
||||
const panelTitle =
|
||||
selection.event == null ? panelAgent?.name || activity.title : selectedEventActorName;
|
||||
const selectedActorAgentId =
|
||||
selectedEventActor?.agentId ?? threadView?.agentId ?? foregroundAgentId;
|
||||
const selectedActorAgent = resolveChildAgent(
|
||||
selectedActorAgentId,
|
||||
selection.subagentType,
|
||||
parentAuthor.agent,
|
||||
agentsMap,
|
||||
childKind,
|
||||
);
|
||||
/** One author for the header, the composer and every child turn, so the three
|
||||
* can never name the child differently. */
|
||||
const childAuthor = useMemo(
|
||||
() =>
|
||||
selection.event != null
|
||||
? agentAuthor(selectedActorAgent, selectedEventActorName)
|
||||
: resolveSubagentAuthor(
|
||||
{
|
||||
agentId: selectedActorAgentId,
|
||||
subagentType: selection.subagentType,
|
||||
subagentKind: childKind,
|
||||
title: threadView?.title ?? byThreadId.get(threadId)?.title,
|
||||
},
|
||||
parentAuthor,
|
||||
agentsMap,
|
||||
localize('com_ui_subagent_actor'),
|
||||
),
|
||||
[
|
||||
agentsMap,
|
||||
byThreadId,
|
||||
childKind,
|
||||
localize,
|
||||
parentAuthor,
|
||||
selectedActorAgent,
|
||||
selectedActorAgentId,
|
||||
selectedEventActorName,
|
||||
selection.event,
|
||||
selection.subagentType,
|
||||
threadId,
|
||||
threadView?.title,
|
||||
],
|
||||
);
|
||||
const panelTitle = childAuthor.name;
|
||||
const actorOptions = useMemo<OptionWithIcon[]>(() => {
|
||||
if (selection.event == null) return [];
|
||||
return (
|
||||
|
|
@ -839,7 +907,11 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
|
|||
.filter((child) => child.latestTaskId != null || child.threadId === threadId)
|
||||
.map((child) => {
|
||||
const agent = child.agentId == null ? undefined : agentsMap?.[child.agentId];
|
||||
const name = agent?.name || child.actorId || child.title;
|
||||
const name =
|
||||
agent?.name ||
|
||||
child.actorId ||
|
||||
readableSubagentType(child.subagentType, child.agentId, child.subagentKind) ||
|
||||
localize('com_ui_subagent_actor');
|
||||
return {
|
||||
value: child.threadId,
|
||||
label:
|
||||
|
|
@ -848,15 +920,14 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
|
|||
};
|
||||
})
|
||||
);
|
||||
}, [agentsMap, eventSiblings, selection.event, threadId]);
|
||||
}, [agentsMap, eventSiblings, localize, selection.event, threadId]);
|
||||
const selectedActorLabel =
|
||||
actorOptions.find((option) => option.value === threadId)?.label ?? panelTitle;
|
||||
const selectedActorAgentId =
|
||||
selectedEventActor?.agentId ?? threadView?.agentId ?? foregroundAgentId;
|
||||
const selectedActorIcon = renderAgentAvatar(
|
||||
selectedActorAgentId == null ? undefined : agentsMap?.[selectedActorAgentId],
|
||||
{ size: 'icon', showBorder: false },
|
||||
);
|
||||
/** The picker's own glyph, matching the rows it lists. */
|
||||
const selectedActorIcon = renderAgentAvatar(selectedActorAgent, {
|
||||
size: 'icon',
|
||||
showBorder: false,
|
||||
});
|
||||
const latestConversationTurns = useMemo(
|
||||
() => (threadView == null ? [] : adaptDurableThreadConversation(threadView)),
|
||||
[threadView],
|
||||
|
|
@ -1353,7 +1424,8 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
|
|||
)}
|
||||
<SubagentConversation
|
||||
turns={conversationTurns}
|
||||
agentId={threadView?.agentId}
|
||||
author={childAuthor}
|
||||
parentAuthor={isSelfSpawn && selection.event == null ? childAuthor : parentAuthor}
|
||||
conversationId={threadId || selection.parentConversationId}
|
||||
stateByTask={conversationStateByTask}
|
||||
controllableTaskId={
|
||||
|
|
@ -1451,10 +1523,10 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
|
|||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* The `MessageRow` author-glyph slot, one size up: no plate
|
||||
behind it, so an agent avatar reads as the avatar it is. */}
|
||||
{/* The `MessageRow` author glyph, one size up: the same face the
|
||||
child's turns below carry. */}
|
||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center overflow-hidden rounded-full">
|
||||
{selectedActorIcon}
|
||||
{childAuthor.icon}
|
||||
</div>
|
||||
<h2 className="min-w-0 flex-1 truncate text-sm font-semibold" title={panelTitle}>
|
||||
{panelTitle}
|
||||
|
|
|
|||
56
client/src/components/Chat/Subagents/author.public.test.tsx
Normal file
56
client/src/components/Chat/Subagents/author.public.test.tsx
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import { RecoilRoot } from 'recoil';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { dataService, EModelEndpoint } from 'librechat-data-provider';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import type { TMessage } from 'librechat-data-provider';
|
||||
import { ShareContext } from '~/Providers/ShareContext';
|
||||
import { agentAuthor, messageAuthor } from './author';
|
||||
|
||||
jest.mock('librechat-data-provider', () => {
|
||||
const actual = jest.requireActual('librechat-data-provider');
|
||||
return {
|
||||
...actual,
|
||||
dataService: { ...actual.dataService, getAIEndpoints: jest.fn().mockResolvedValue({}) },
|
||||
};
|
||||
});
|
||||
|
||||
const historicalMessage: TMessage = {
|
||||
messageId: 'parent',
|
||||
parentMessageId: null,
|
||||
conversationId: 'shared',
|
||||
isCreatedByUser: false,
|
||||
text: '',
|
||||
sender: 'Historical Parent',
|
||||
model: 'agent_deleted',
|
||||
endpoint: EModelEndpoint.agents,
|
||||
iconURL: '/historical.png',
|
||||
};
|
||||
|
||||
it('draws public-share authors without private requests and enables them again in chat', async () => {
|
||||
const getEndpoints = jest.mocked(dataService.getAIEndpoints);
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const child = agentAuthor(undefined, 'Agent');
|
||||
const parent = messageAuthor(historicalMessage, undefined, 'Parent agent');
|
||||
const tree = (isSharedConvo: boolean) => (
|
||||
<RecoilRoot>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ShareContext.Provider value={{ isSharedConvo }}>
|
||||
{child.icon}
|
||||
{parent.icon}
|
||||
</ShareContext.Provider>
|
||||
</QueryClientProvider>
|
||||
</RecoilRoot>
|
||||
);
|
||||
const { rerender } = render(tree(true));
|
||||
|
||||
expect(screen.getByRole('img', { name: 'Historical Parent' })).toHaveAttribute(
|
||||
'src',
|
||||
'/historical.png',
|
||||
);
|
||||
expect(queryClient.isFetching()).toBe(0);
|
||||
expect(getEndpoints).not.toHaveBeenCalled();
|
||||
|
||||
rerender(tree(false));
|
||||
await waitFor(() => expect(getEndpoints).toHaveBeenCalledTimes(1));
|
||||
queryClient.clear();
|
||||
});
|
||||
141
client/src/components/Chat/Subagents/author.test.ts
Normal file
141
client/src/components/Chat/Subagents/author.test.ts
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
import { ContentTypes, EModelEndpoint } from 'librechat-data-provider';
|
||||
import type { TMessage } from 'librechat-data-provider';
|
||||
import {
|
||||
isSelfSpawn,
|
||||
messageAuthor,
|
||||
resolveSelfAuthor,
|
||||
resolveSubagentAuthor,
|
||||
findAgentLaneId,
|
||||
resolveChildAgent,
|
||||
readableSubagentType,
|
||||
readableSubagentTitle,
|
||||
findAgentAuthorMessage,
|
||||
} from './author';
|
||||
|
||||
function message(
|
||||
messageId: string,
|
||||
parentMessageId: string | null,
|
||||
isCreatedByUser = false,
|
||||
): TMessage {
|
||||
return {
|
||||
messageId,
|
||||
parentMessageId,
|
||||
isCreatedByUser,
|
||||
conversationId: 'parent',
|
||||
text: '',
|
||||
sender: messageId,
|
||||
endpoint: EModelEndpoint.agents,
|
||||
};
|
||||
}
|
||||
|
||||
it('prefers the dispatch itself over an earlier reply and preserves the first agent reply', () => {
|
||||
const firstReply = message('first', 'dispatch');
|
||||
const dispatch = message('dispatch', null);
|
||||
const messages = [
|
||||
message('user', null, true),
|
||||
firstReply,
|
||||
dispatch,
|
||||
message('second', 'dispatch'),
|
||||
];
|
||||
expect(findAgentAuthorMessage(messages, 'dispatch')).toBe(dispatch);
|
||||
expect(findAgentAuthorMessage(messages, 'missing')).toBeUndefined();
|
||||
expect(findAgentAuthorMessage([firstReply, message('second', 'dispatch')], 'dispatch')).toBe(
|
||||
firstReply,
|
||||
);
|
||||
});
|
||||
|
||||
it('shares one history traversal across multiple wake-up authors and indexes a new snapshot', () => {
|
||||
const messages = Array.from({ length: 1000 }, (_, i) => message(`reply-${i}`, `wake-${i}`));
|
||||
const traversal = jest.spyOn(messages, Symbol.iterator);
|
||||
for (let i = 0; i < messages.length; i++) {
|
||||
expect(findAgentAuthorMessage(messages, `wake-${i}`)).toBe(messages[i]);
|
||||
}
|
||||
expect(traversal).toHaveBeenCalledTimes(1);
|
||||
const added = message('added', 'new-wake');
|
||||
expect(findAgentAuthorMessage([...messages, added], 'new-wake')).toBe(added);
|
||||
expect(findAgentAuthorMessage(messages, 'new-wake')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('preserves self as an explicit graph alias across author resolution', () => {
|
||||
expect(isSelfSpawn('self', 'graph')).toBe(false);
|
||||
expect(isSelfSpawn('self', 'agent')).toBe(true);
|
||||
expect(isSelfSpawn('self')).toBe(true);
|
||||
expect(readableSubagentType('self', undefined, 'graph')).toBe('self');
|
||||
expect(readableSubagentType('self')).toBeUndefined();
|
||||
expect(resolveChildAgent('agent-1', 'self', undefined, {}, 'graph')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('retains matching historical snapshots and never borrows an enclosing avatar for a missing lane', () => {
|
||||
const snapshot = message('dispatch', null);
|
||||
snapshot.model = 'agent_deleted';
|
||||
snapshot.sender = 'Historical Parent';
|
||||
snapshot.iconURL = '/historical.png';
|
||||
const parent = messageAuthor(snapshot, undefined, 'Agent');
|
||||
expect(resolveSelfAuthor(parent, 'agent_deleted', undefined, 'Agent')).toBe(parent);
|
||||
expect(resolveSelfAuthor(parent, undefined, undefined, 'Agent')).toBe(parent);
|
||||
expect(resolveSelfAuthor(parent, 'agent_missing_lane', undefined, 'Agent').name).toBe('Agent');
|
||||
expect(messageAuthor(snapshot, undefined, 'Agent', 'agent_missing_lane').name).toBe('Agent');
|
||||
expect(findAgentLaneId(snapshot, 'missing')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('retains legacy graph aliases while suppressing identities known to be agent IDs', () => {
|
||||
expect(readableSubagentType('agent_research_team')).toBe('agent_research_team');
|
||||
expect(readableSubagentType('agent_research_team', undefined, 'graph')).toBe(
|
||||
'agent_research_team',
|
||||
);
|
||||
expect(readableSubagentType('agent_deleted', 'agent_deleted')).toBeUndefined();
|
||||
expect(readableSubagentType('agent_deleted', undefined, 'agent')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('resolves repeated tool IDs by their content-part occurrence and rejects ambiguous legacy matches', () => {
|
||||
const dispatch = message('dispatch', null);
|
||||
dispatch.content = [
|
||||
{
|
||||
type: ContentTypes.TOOL_CALL,
|
||||
agentId: 'first',
|
||||
tool_call: { id: 'repeat', name: 'subagent', args: {} },
|
||||
},
|
||||
{
|
||||
type: ContentTypes.TOOL_CALL,
|
||||
agentId: 'second',
|
||||
tool_call: { id: 'repeat', name: 'subagent', args: {} },
|
||||
},
|
||||
];
|
||||
expect(findAgentLaneId(dispatch, 'repeat', 0)).toBe('first');
|
||||
expect(findAgentLaneId(dispatch, 'repeat', 1)).toBe('second');
|
||||
expect(findAgentLaneId(dispatch, 'repeat')).toBeUndefined();
|
||||
expect(findAgentLaneId(dispatch, 'repeat', 9)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('preserves literal display titles while suppressing legacy storage keys', () => {
|
||||
expect(readableSubagentTitle('Subagent: research', undefined, 'graph')).toBe(
|
||||
'Subagent: research',
|
||||
);
|
||||
expect(readableSubagentTitle('Subagent: Historical Agent', 'agent_deleted', 'agent')).toBe(
|
||||
'Subagent: Historical Agent',
|
||||
);
|
||||
expect(readableSubagentTitle('self', 'agent_deleted', 'agent')).toBe('self');
|
||||
expect(readableSubagentTitle('agent_research_team', 'agent_deleted', 'agent')).toBe(
|
||||
'agent_research_team',
|
||||
);
|
||||
expect(
|
||||
readableSubagentTitle('Subagent: agent_deleted', 'agent_deleted', 'agent'),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ subagentType: 'self' }, 'Historical Parent'],
|
||||
[{ subagentType: 'self', agentId: 'agent_parent' }, 'Historical Parent'],
|
||||
[{ subagentType: 'self', agentId: 'agent_missing_lane' }, 'Agent'],
|
||||
[{ subagentType: 'self', subagentKind: 'graph' as const }, 'self'],
|
||||
[{ subagentType: 'Subagent: research', subagentKind: 'graph' as const }, 'Subagent: research'],
|
||||
[{ subagentType: 'agent_research_team' }, 'agent_research_team'],
|
||||
[{ subagentType: 'agent_deleted', subagentKind: 'agent' as const }, 'Agent'],
|
||||
[{ subagentType: 'agent_deleted', agentId: 'agent_deleted' }, 'Agent'],
|
||||
])('resolves child identity %j consistently across surfaces', (child, expectedName) => {
|
||||
const snapshot = message('dispatch', null);
|
||||
snapshot.model = 'agent_parent';
|
||||
snapshot.sender = 'Historical Parent';
|
||||
const parent = messageAuthor(snapshot, undefined, 'Agent');
|
||||
expect(resolveSubagentAuthor(child, parent, undefined, 'Agent').name).toBe(expectedName);
|
||||
});
|
||||
270
client/src/components/Chat/Subagents/author.tsx
Normal file
270
client/src/components/Chat/Subagents/author.tsx
Normal file
|
|
@ -0,0 +1,270 @@
|
|||
import { useMemo, useSyncExternalStore } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { EModelEndpoint, QueryKeys, ContentTypes } from 'librechat-data-provider';
|
||||
import type { Agent, TMessage } from 'librechat-data-provider';
|
||||
import type { ReactNode } from 'react';
|
||||
import { isDocumentId } from '~/components/Chat/Messages/ui/HeaderLabel';
|
||||
import MessageIcon from '~/components/Chat/Messages/MessageIcon';
|
||||
import { useAgentsMapContext } from '~/Providers';
|
||||
import { findSubagentDispatch } from './dispatch';
|
||||
|
||||
/** Who wrote a turn, in the form main chat's message header shows an author. */
|
||||
export type TurnAuthor = { name: string; icon: ReactNode; agent?: Agent; agentId?: string };
|
||||
|
||||
/** Keep graph and legacy aliases readable. A prefix alone cannot prove a
|
||||
* stored agent identity; suppress known agent IDs and the non-graph self alias. */
|
||||
export function readableSubagentType(
|
||||
subagentType?: string | null,
|
||||
agentId?: string,
|
||||
kind?: 'agent' | 'graph',
|
||||
): string | undefined {
|
||||
if (subagentType == null || subagentType === '') return undefined;
|
||||
if (kind === 'graph') return subagentType;
|
||||
if (subagentType === 'self') return undefined;
|
||||
return subagentType === agentId || (kind === 'agent' && isDocumentId(subagentType))
|
||||
? undefined
|
||||
: subagentType;
|
||||
}
|
||||
|
||||
/** Stored display title, excluding legacy titles that contain storage keys. */
|
||||
export function readableSubagentTitle(
|
||||
title: string | undefined,
|
||||
agentId?: string,
|
||||
kind?: 'agent' | 'graph',
|
||||
): string | undefined {
|
||||
if (!title) return undefined;
|
||||
if (kind === 'graph') return title;
|
||||
const candidate = title.startsWith('Subagent: ') ? title.slice('Subagent: '.length) : title;
|
||||
if (candidate === agentId) return undefined;
|
||||
return title;
|
||||
}
|
||||
|
||||
/** Explicit graph identity takes precedence over the legacy self alias. */
|
||||
export function isSelfSpawn(subagentType?: string | null, kind?: 'agent' | 'graph'): boolean {
|
||||
return kind !== 'graph' && subagentType === 'self';
|
||||
}
|
||||
|
||||
/** The agent a child runs as: its own saved agent, or — for a self-spawn,
|
||||
* which records none — the agent that spawned it. */
|
||||
export function resolveChildAgent(
|
||||
agentId: string | undefined,
|
||||
subagentType: string | null | undefined,
|
||||
spawningAgent: Agent | undefined,
|
||||
agentsMap: Record<string, Agent | undefined> | undefined,
|
||||
kind?: 'agent' | 'graph',
|
||||
): Agent | undefined {
|
||||
if (kind === 'graph') return undefined;
|
||||
if (agentId != null) return agentsMap?.[agentId];
|
||||
return isSelfSpawn(subagentType, kind) ? spawningAgent : undefined;
|
||||
}
|
||||
|
||||
/** Match the parallel lane that wrote the dispatch rather than its enclosing
|
||||
* message's default author. */
|
||||
export function findAgentLaneId(
|
||||
message: TMessage | undefined,
|
||||
toolCallId?: string,
|
||||
partIndex?: number,
|
||||
): string | undefined {
|
||||
if (!toolCallId) return undefined;
|
||||
const indexed = partIndex == null ? undefined : message?.content?.[partIndex];
|
||||
if (indexed?.type === ContentTypes.TOOL_CALL && indexed.tool_call.id === toolCallId) {
|
||||
return indexed.agentId;
|
||||
}
|
||||
/** Durable legacy selections may have no usable index. Only a unique call
|
||||
* can identify their lane; repeated provider IDs are ambiguous. */
|
||||
let laneId: string | undefined;
|
||||
let found = false;
|
||||
for (const part of message?.content ?? []) {
|
||||
if (part?.type !== ContentTypes.TOOL_CALL || part.tool_call.id !== toolCallId) continue;
|
||||
if (found) return undefined;
|
||||
found = true;
|
||||
laneId = part.agentId;
|
||||
}
|
||||
return laneId;
|
||||
}
|
||||
|
||||
/** A validated self-child identity wins when it belongs to another lane;
|
||||
* matching identities retain the historical name/avatar snapshot. */
|
||||
export function resolveSelfAuthor(
|
||||
parent: TurnAuthor,
|
||||
agentId: string | undefined,
|
||||
agentsMap: Record<string, Agent | undefined> | undefined,
|
||||
fallbackName: string,
|
||||
): TurnAuthor {
|
||||
if (agentId == null || agentId === parent.agentId) return parent;
|
||||
const agent = agentsMap?.[agentId];
|
||||
if (parent.agentId == null && agent == null) return parent;
|
||||
return agentAuthor(agent, fallbackName);
|
||||
}
|
||||
|
||||
/** One display rule for live, restored and shared child tasks. Explicit graph
|
||||
* aliases stay literal; self tasks retain the matching parent-turn snapshot. */
|
||||
export function resolveSubagentAuthor(
|
||||
child: {
|
||||
subagentType?: string | null;
|
||||
subagentKind?: 'agent' | 'graph';
|
||||
agentId?: string;
|
||||
title?: string;
|
||||
},
|
||||
parent: TurnAuthor,
|
||||
agentsMap: Record<string, Agent | undefined> | undefined,
|
||||
fallbackName: string,
|
||||
): TurnAuthor {
|
||||
if (isSelfSpawn(child.subagentType, child.subagentKind)) {
|
||||
return resolveSelfAuthor(parent, child.agentId, agentsMap, fallbackName);
|
||||
}
|
||||
return agentAuthor(
|
||||
resolveChildAgent(
|
||||
child.agentId,
|
||||
child.subagentType,
|
||||
parent.agent,
|
||||
agentsMap,
|
||||
child.subagentKind,
|
||||
),
|
||||
readableSubagentTitle(child.title, child.agentId, child.subagentKind) ??
|
||||
readableSubagentType(child.subagentType, child.agentId, child.subagentKind) ??
|
||||
fallbackName,
|
||||
);
|
||||
}
|
||||
|
||||
/** The author main chat draws for an agent turn: the agent's name and avatar,
|
||||
* or the agents endpoint icon when it has none or is not resolvable. */
|
||||
export function agentAuthor(agent: Agent | undefined, fallbackName: string): TurnAuthor {
|
||||
const name = agent?.name || fallbackName;
|
||||
return {
|
||||
agent,
|
||||
agentId: agent?.id,
|
||||
name,
|
||||
icon: (
|
||||
<MessageIcon
|
||||
iconData={{ endpoint: EModelEndpoint.agents, modelLabel: name, isCreatedByUser: false }}
|
||||
agent={agent}
|
||||
/>
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
type AuthorIndex = {
|
||||
byId: Map<string, TMessage>;
|
||||
byParentId: Map<string, TMessage>;
|
||||
};
|
||||
|
||||
/** React Query replaces loaded message arrays. Weak keys let streamed snapshots
|
||||
* be collected, while every wake-up in one snapshot shares a single pass. */
|
||||
const authorIndexes = new WeakMap<TMessage[], AuthorIndex>();
|
||||
|
||||
/** The dispatching agent message, or the first agent reply to a user turn. */
|
||||
export function findAgentAuthorMessage(
|
||||
messages: TMessage[] | undefined,
|
||||
messageId: string,
|
||||
): TMessage | undefined {
|
||||
if (messages == null || messageId === '') return undefined;
|
||||
let index = authorIndexes.get(messages);
|
||||
if (index == null) {
|
||||
index = { byId: new Map(), byParentId: new Map() };
|
||||
for (const message of messages) {
|
||||
if (message.isCreatedByUser === true) continue;
|
||||
if (!index.byId.has(message.messageId)) index.byId.set(message.messageId, message);
|
||||
if (message.parentMessageId != null && !index.byParentId.has(message.parentMessageId)) {
|
||||
index.byParentId.set(message.parentMessageId, message);
|
||||
}
|
||||
}
|
||||
authorIndexes.set(messages, index);
|
||||
}
|
||||
return index.byId.get(messageId) ?? index.byParentId.get(messageId);
|
||||
}
|
||||
|
||||
/** The author main chat's own header shows for `message`. */
|
||||
export function messageAuthor(
|
||||
message: TMessage | undefined,
|
||||
agentsMap: Record<string, Agent | undefined> | undefined,
|
||||
fallbackName: string,
|
||||
laneId?: string,
|
||||
): TurnAuthor {
|
||||
if (message == null) return agentAuthor(undefined, fallbackName);
|
||||
const agentId = laneId ?? message.model ?? undefined;
|
||||
const differentLane = laneId != null && laneId !== message.model;
|
||||
const agent = agentId == null ? undefined : agentsMap?.[agentId];
|
||||
const name = agent?.name || (differentLane ? undefined : message.sender) || fallbackName;
|
||||
return {
|
||||
agent,
|
||||
agentId,
|
||||
name,
|
||||
icon: (
|
||||
<MessageIcon
|
||||
iconData={{
|
||||
endpoint: message.endpoint,
|
||||
model: agentId,
|
||||
iconURL: differentLane ? undefined : message.iconURL,
|
||||
modelLabel: name,
|
||||
isCreatedByUser: false,
|
||||
}}
|
||||
agent={agent}
|
||||
/>
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/** Wait for a missing historical author, then retain its snapshot so streamed
|
||||
* content updates do not rerender every wake-up or open activity panel. */
|
||||
export function useParentAuthor(
|
||||
conversationId: string,
|
||||
messageId: string,
|
||||
fallbackName: string,
|
||||
toolCallId?: string,
|
||||
partIndex?: number,
|
||||
threadId?: string,
|
||||
): TurnAuthor {
|
||||
const queryClient = useQueryClient();
|
||||
const agentsMap = useAgentsMapContext();
|
||||
/** A different dispatch must read the latest message snapshot, even when
|
||||
* both children belong to the same streamed parent turn. */
|
||||
const source = useMemo(
|
||||
() => ({ conversationId, messageId, toolCallId, partIndex, threadId }),
|
||||
[conversationId, messageId, toolCallId, partIndex, threadId],
|
||||
);
|
||||
const store = useMemo(() => {
|
||||
let snapshot: { message: TMessage; laneId?: string } | undefined;
|
||||
const getSnapshot = () => {
|
||||
if (snapshot != null) return snapshot;
|
||||
const messages = queryClient.getQueryData<TMessage[]>([
|
||||
QueryKeys.messages,
|
||||
source.conversationId,
|
||||
]);
|
||||
const dispatch = findSubagentDispatch(messages, source.threadId);
|
||||
const message = dispatch?.message ?? findAgentAuthorMessage(messages, source.messageId);
|
||||
if (message == null) return undefined;
|
||||
/** Durable selections use a placeholder part index. A host-issued thread
|
||||
* handle identifies the real occurrence; without it, accept only a unique ID. */
|
||||
const laneId =
|
||||
dispatch != null
|
||||
? dispatch.agentId
|
||||
: findAgentLaneId(
|
||||
message,
|
||||
source.toolCallId,
|
||||
source.threadId ? undefined : source.partIndex,
|
||||
);
|
||||
snapshot = { message, laneId };
|
||||
return snapshot;
|
||||
};
|
||||
return {
|
||||
getSnapshot,
|
||||
subscribe: (onChange: () => void) => {
|
||||
if (source.messageId === '' || getSnapshot() != null) return () => {};
|
||||
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
|
||||
const key = event.query.queryKey;
|
||||
if (key[0] !== QueryKeys.messages || key[1] !== source.conversationId) return;
|
||||
if (getSnapshot() == null) return;
|
||||
unsubscribe();
|
||||
onChange();
|
||||
});
|
||||
return unsubscribe;
|
||||
},
|
||||
};
|
||||
}, [queryClient, source]);
|
||||
const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
|
||||
return useMemo(
|
||||
() => messageAuthor(snapshot?.message, agentsMap, fallbackName, snapshot?.laneId),
|
||||
[agentsMap, fallbackName, snapshot],
|
||||
);
|
||||
}
|
||||
68
client/src/components/Chat/Subagents/dispatch.test.ts
Normal file
68
client/src/components/Chat/Subagents/dispatch.test.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import { ContentTypes } from 'librechat-data-provider';
|
||||
import type { TMessage } from 'librechat-data-provider';
|
||||
import { findSubagentDispatch } from './dispatch';
|
||||
|
||||
const output = JSON.stringify({
|
||||
background_task_id: 'task',
|
||||
subagent_thread_id: 'thread',
|
||||
tool: 'subagent',
|
||||
subagent_type: 'self',
|
||||
status: 'running',
|
||||
message: 'Poll using background_task_id task.',
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
'resolves historical dispatch metadata (function format: %s)',
|
||||
(functional) => {
|
||||
const identity = { subagentKind: 'graph' as const, subagentAgentId: 'graph:self' };
|
||||
const message: TMessage = {
|
||||
messageId: 'dispatch',
|
||||
parentMessageId: null,
|
||||
conversationId: 'parent',
|
||||
isCreatedByUser: false,
|
||||
text: '',
|
||||
content: [
|
||||
{
|
||||
type: ContentTypes.TOOL_CALL,
|
||||
tool_call: functional
|
||||
? {
|
||||
id: 'call',
|
||||
type: 'function',
|
||||
function: { name: 'subagent', arguments: { run_in_background: true }, output },
|
||||
subagentIdentity: identity,
|
||||
}
|
||||
: {
|
||||
name: 'subagent',
|
||||
args: { run_in_background: true },
|
||||
output,
|
||||
subagentIdentity: identity,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
const messages = [message];
|
||||
const scan = jest.spyOn(messages, Symbol.iterator);
|
||||
expect(findSubagentDispatch(messages, 'thread')).toEqual({
|
||||
message,
|
||||
identity,
|
||||
subagentType: 'self',
|
||||
});
|
||||
expect(findSubagentDispatch(messages, 'thread')?.message).toBe(message);
|
||||
expect(findSubagentDispatch(messages, 'absent')).toBeUndefined();
|
||||
expect(scan).toHaveBeenCalledTimes(1);
|
||||
expect(findSubagentDispatch([{ ...message, isCreatedByUser: true }], 'thread')).toBeUndefined();
|
||||
expect(
|
||||
findSubagentDispatch(
|
||||
[
|
||||
{
|
||||
...message,
|
||||
content: [
|
||||
{ type: ContentTypes.TOOL_CALL, tool_call: { name: 'subagent', args: {}, output } },
|
||||
],
|
||||
},
|
||||
],
|
||||
'thread',
|
||||
),
|
||||
).toBeUndefined();
|
||||
},
|
||||
);
|
||||
55
client/src/components/Chat/Subagents/dispatch.ts
Normal file
55
client/src/components/Chat/Subagents/dispatch.ts
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import { Constants, ContentTypes } from 'librechat-data-provider';
|
||||
import type { SubagentIdentity, TMessage } from 'librechat-data-provider';
|
||||
import { parseSubagentBackgroundHandle } from '~/components/Chat/Messages/Content/Parts/handle';
|
||||
|
||||
type Dispatch = {
|
||||
message: TMessage;
|
||||
subagentType: string;
|
||||
identity?: SubagentIdentity;
|
||||
agentId?: string;
|
||||
};
|
||||
|
||||
const indexes = new WeakMap<TMessage[], Map<string, Dispatch>>();
|
||||
|
||||
/** Public transcripts carry dispatch metadata instead of an authenticated child
|
||||
* index. Match the host-issued handle, sharing one scan per transcript snapshot. */
|
||||
export function findSubagentDispatch(
|
||||
messages: TMessage[] | undefined,
|
||||
threadId: string | undefined,
|
||||
): Dispatch | undefined {
|
||||
if (messages == null || !threadId) return undefined;
|
||||
let index = indexes.get(messages);
|
||||
if (index == null) {
|
||||
index = new Map();
|
||||
for (const message of messages) {
|
||||
if (message.isCreatedByUser === true) continue;
|
||||
for (const part of message.content ?? []) {
|
||||
if (part?.type !== ContentTypes.TOOL_CALL) continue;
|
||||
const call = part.tool_call;
|
||||
if (!('name' in call) && !('function' in call)) continue;
|
||||
const name = 'function' in call ? call.function.name : call.name;
|
||||
if (name !== Constants.SUBAGENT) continue;
|
||||
const output = 'function' in call ? call.function.output : call.output;
|
||||
let args: Parameters<typeof parseSubagentBackgroundHandle>[1];
|
||||
if ('function' in call) {
|
||||
args =
|
||||
typeof call.function.arguments === 'string'
|
||||
? call.function.arguments
|
||||
: JSON.stringify(call.function.arguments);
|
||||
} else {
|
||||
args = call.args;
|
||||
}
|
||||
const handle = parseSubagentBackgroundHandle(output, args);
|
||||
if (handle == null || index.has(handle.subagent_thread_id)) continue;
|
||||
index.set(handle.subagent_thread_id, {
|
||||
message,
|
||||
subagentType: handle.subagent_type,
|
||||
identity: call.subagentIdentity,
|
||||
agentId: part.agentId,
|
||||
});
|
||||
}
|
||||
}
|
||||
indexes.set(messages, index);
|
||||
}
|
||||
return index.get(threadId);
|
||||
}
|
||||
|
|
@ -12,4 +12,8 @@ describe('resolveSubagentAgentId', () => {
|
|||
expect(resolveSubagentAgentId(graph, agent)).toBeUndefined();
|
||||
expect(resolveSubagentAgentId(null, graph)).toBeUndefined();
|
||||
});
|
||||
it('does not infer a saved agent when identity is absent', () => {
|
||||
expect(resolveSubagentAgentId(null, undefined)).toBeUndefined();
|
||||
expect(resolveSubagentAgentId({ subagentKind: 'graph' }, undefined)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,10 +1,17 @@
|
|||
import type { SubagentIdentity } from 'librechat-data-provider';
|
||||
|
||||
/**
|
||||
* The saved agent behind a child, from live progress, then its persisted
|
||||
* identity. Types are aliases, not proof of a saved-agent identity.
|
||||
*/
|
||||
export function resolveSubagentAgentId(
|
||||
progress: Partial<SubagentIdentity> | null | undefined,
|
||||
persisted: SubagentIdentity | undefined,
|
||||
): string | undefined {
|
||||
if (progress?.subagentKind === 'graph') return undefined;
|
||||
if (progress?.subagentAgentId) return progress.subagentAgentId;
|
||||
return persisted?.subagentKind === 'agent' ? persisted.subagentAgentId : undefined;
|
||||
if (persisted != null) {
|
||||
return persisted.subagentKind === 'agent' ? persisted.subagentAgentId : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import { useMemo } from 'react';
|
||||
import type { TMessageProps } from '~/common';
|
||||
import SearchContent, {
|
||||
rendersMarkdownLite,
|
||||
} from '~/components/Chat/Messages/Content/SearchContent';
|
||||
import { parseWakeupMessage } from '~/components/Chat/Messages/Content/Parts/wakeup';
|
||||
import AuthorHeader from '~/components/Chat/Messages/Content/Parts/AuthorHeader';
|
||||
import MinimalHoverButtons from '~/components/Chat/Messages/MinimalHoverButtons';
|
||||
import { getHeaderHoverLabel } from '~/components/Chat/Messages/ui/HeaderLabel';
|
||||
|
|
@ -9,6 +11,8 @@ import MessageContent from '~/components/Chat/Messages/Content/MessageContent';
|
|||
import { getHeaderPrefixForScreenReader, getMessageAriaLabel } from '~/utils';
|
||||
import SiblingSwitch from '~/components/Chat/Messages/SiblingSwitch';
|
||||
import MessageRow from '~/components/Chat/Messages/ui/MessageRow';
|
||||
import WakeupRow from '~/components/Chat/Messages/ui/WakeupRow';
|
||||
import Wakeup from '~/components/Chat/Messages/Content/Wakeup';
|
||||
import { MessageContext, useShareContext } from '~/Providers';
|
||||
import SubRow from '~/components/Chat/Messages/SubRow';
|
||||
import { useAttachments, useLocalize } from '~/hooks';
|
||||
|
|
@ -32,6 +36,7 @@ export default function Message(props: TMessageProps) {
|
|||
messageId: message?.messageId,
|
||||
attachments: message?.attachments,
|
||||
});
|
||||
const wakeupDisplay = useMemo(() => parseWakeupMessage(message), [message]);
|
||||
|
||||
if (!message) {
|
||||
return null;
|
||||
|
|
@ -51,12 +56,16 @@ export default function Message(props: TMessageProps) {
|
|||
* view and wrong here: it is the screen-reader heading for the user turn, and it
|
||||
* would credit every prompt the sharer wrote to the person reading the transcript. */
|
||||
const messageLabel = isCreatedByUser ? localize('com_ui_user') : (message.sender ?? '');
|
||||
const subagentWakeup = wakeupDisplay?.kind === 'subagent' ? wakeupDisplay.tasks[0] : undefined;
|
||||
const Row = subagentWakeup == null ? MessageRow : WakeupRow;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="w-full border-0 bg-transparent text-text-primary">
|
||||
<div className="text-text-primary w-full border-0 bg-transparent">
|
||||
<div className="m-auto justify-center px-4 py-3 sm:px-0">
|
||||
<MessageRow
|
||||
<Row
|
||||
task={subagentWakeup}
|
||||
conversationId={message.conversationId ?? conversation?.conversationId ?? ''}
|
||||
id={messageId}
|
||||
icon={<Icon message={message} conversation={conversation} />}
|
||||
label={messageLabel}
|
||||
|
|
@ -65,6 +74,11 @@ export default function Message(props: TMessageProps) {
|
|||
ariaLabel={getMessageAriaLabel(message, localize)}
|
||||
headerPrefix={getHeaderPrefixForScreenReader(message, localize)}
|
||||
isCreatedByUser={isCreatedByUser}
|
||||
systemLabel={
|
||||
wakeupDisplay != null && subagentWakeup == null
|
||||
? localize('com_ui_system_event')
|
||||
: undefined
|
||||
}
|
||||
className="final-completion"
|
||||
footer={
|
||||
<SubRow classes={isCreatedByUser ? 'justify-end text-xs' : 'text-xs'}>
|
||||
|
|
@ -90,38 +104,42 @@ export default function Message(props: TMessageProps) {
|
|||
isLatestMessage: false,
|
||||
}}
|
||||
>
|
||||
{message.content ? (
|
||||
<SearchContent
|
||||
message={message}
|
||||
attachments={attachments}
|
||||
searchResults={searchResults}
|
||||
authorHeader={
|
||||
isCreatedByUser ? undefined : (
|
||||
<AuthorHeader
|
||||
icon={<Icon message={message} conversation={conversation} />}
|
||||
label={messageLabel}
|
||||
/>
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<MessageContent
|
||||
edit={false}
|
||||
error={error}
|
||||
isLast={false}
|
||||
ask={() => {}}
|
||||
text={text || ''}
|
||||
message={message}
|
||||
isSubmitting={false}
|
||||
enterEdit={() => ({})}
|
||||
unfinished={unfinished}
|
||||
siblingIdx={siblingIdx ?? 0}
|
||||
isCreatedByUser={isCreatedByUser}
|
||||
setSiblingIdx={setSiblingIdx ?? (() => ({}))}
|
||||
/>
|
||||
{wakeupDisplay != null && (
|
||||
<Wakeup display={wakeupDisplay} conversationId={message.conversationId} />
|
||||
)}
|
||||
{wakeupDisplay == null &&
|
||||
(message.content ? (
|
||||
<SearchContent
|
||||
message={message}
|
||||
attachments={attachments}
|
||||
searchResults={searchResults}
|
||||
authorHeader={
|
||||
isCreatedByUser ? undefined : (
|
||||
<AuthorHeader
|
||||
icon={<Icon message={message} conversation={conversation} />}
|
||||
label={messageLabel}
|
||||
/>
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<MessageContent
|
||||
edit={false}
|
||||
error={error}
|
||||
isLast={false}
|
||||
ask={() => {}}
|
||||
text={text || ''}
|
||||
message={message}
|
||||
isSubmitting={false}
|
||||
enterEdit={() => ({})}
|
||||
unfinished={unfinished}
|
||||
siblingIdx={siblingIdx ?? 0}
|
||||
isCreatedByUser={isCreatedByUser}
|
||||
setSiblingIdx={setSiblingIdx ?? (() => ({}))}
|
||||
/>
|
||||
))}
|
||||
</MessageContext.Provider>
|
||||
</MessageRow>
|
||||
</Row>
|
||||
</div>
|
||||
</div>
|
||||
<MultiMessage
|
||||
|
|
|
|||
306
client/src/components/Share/Message.wakeup.spec.tsx
Normal file
306
client/src/components/Share/Message.wakeup.spec.tsx
Normal file
|
|
@ -0,0 +1,306 @@
|
|||
import { Provider } from 'jotai';
|
||||
import { RecoilRoot } from 'recoil';
|
||||
import copy from 'copy-to-clipboard';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { ContentTypes, dataService, EModelEndpoint } from 'librechat-data-provider';
|
||||
import type { TMessage, TAgentsMap } from 'librechat-data-provider';
|
||||
import { ShareMessagesProvider } from './ShareMessagesProvider';
|
||||
import { AgentsMapContext } from '~/Providers/AgentsMapContext';
|
||||
import { ShareContext } from '~/Providers/ShareContext';
|
||||
import MessagesView from './MessagesView';
|
||||
|
||||
jest.mock('librechat-data-provider', () => {
|
||||
const actual = jest.requireActual('librechat-data-provider');
|
||||
return {
|
||||
...actual,
|
||||
dataService: { ...actual.dataService, getAIEndpoints: jest.fn().mockResolvedValue({}) },
|
||||
};
|
||||
});
|
||||
|
||||
jest.mock('~/hooks', () => ({
|
||||
useLocalize: () => (key: string) => key,
|
||||
useAttachments: () => ({ attachments: [], searchResults: [] }),
|
||||
useExpandCollapse: jest.requireActual('~/hooks/Messages/useExpandCollapse').default,
|
||||
useLazyCollapseBody: jest.requireActual('~/hooks/Messages/useLazyCollapseBody').default,
|
||||
...jest.requireActual('~/hooks/Messages/useCopyToClipboard'),
|
||||
}));
|
||||
jest.mock('~/hooks/MCP', () => ({
|
||||
useMCPIconMap: () => new Map(),
|
||||
useMCPServerNames: () => [],
|
||||
}));
|
||||
jest.mock('copy-to-clipboard');
|
||||
jest.mock('~/components/Chat/Messages/Content/SearchContent', () => ({
|
||||
__esModule: true,
|
||||
default: ({ message }: { message: TMessage }) => <div>{message.text}</div>,
|
||||
rendersMarkdownLite: () => false,
|
||||
}));
|
||||
jest.mock('~/components/Chat/Messages/Content/MessageContent', () => ({
|
||||
__esModule: true,
|
||||
default: ({ text }: { text: string }) => <div>{text}</div>,
|
||||
}));
|
||||
jest.mock('~/components/Chat/Messages/Content/MarkdownLite', () => ({
|
||||
__esModule: true,
|
||||
default: ({ content }: { content: string }) => <div>{content}</div>,
|
||||
}));
|
||||
jest.mock('~/components/Chat/Messages/Content/ToolOutput', () => ({
|
||||
StackedToolIcons: () => null,
|
||||
ToolIcon: () => null,
|
||||
getToolIconType: () => '',
|
||||
getMCPServerName: () => '',
|
||||
OutputRenderer: ({ text }: { text: string }) => <div>{text}</div>,
|
||||
}));
|
||||
|
||||
const prompt = (status = 'completed', subagentType = 'self') =>
|
||||
`A detached subagent task has ${status}. Continue the parent task using its durable result below.\n${JSON.stringify(
|
||||
{
|
||||
background_task_id: 'task',
|
||||
subagent_thread_id: 'thread',
|
||||
subagent_type: subagentType,
|
||||
status,
|
||||
result: 'Shared durable result.',
|
||||
},
|
||||
)}`;
|
||||
|
||||
function renderShared(
|
||||
text: string,
|
||||
content = false,
|
||||
dispatch?: TMessage,
|
||||
submitted = false,
|
||||
agentsMap?: TAgentsMap,
|
||||
) {
|
||||
const wake: TMessage = {
|
||||
messageId: 'wake',
|
||||
parentMessageId: null,
|
||||
conversationId: 'original',
|
||||
isCreatedByUser: true,
|
||||
isUserSubmitted: submitted,
|
||||
text,
|
||||
...(content ? { content: [{ type: ContentTypes.TEXT, text }] } : {}),
|
||||
};
|
||||
const reply: TMessage = {
|
||||
messageId: 'reply',
|
||||
parentMessageId: 'wake',
|
||||
conversationId: 'original',
|
||||
isCreatedByUser: false,
|
||||
text: 'Parent continuation.',
|
||||
sender: 'Historical Parent',
|
||||
endpoint: EModelEndpoint.agents,
|
||||
model: 'agent_deleted',
|
||||
iconURL: '/historical.png',
|
||||
};
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<Provider>
|
||||
<RecoilRoot>
|
||||
<ShareContext.Provider value={{ isSharedConvo: true, shareId: 'share' }}>
|
||||
<AgentsMapContext.Provider value={agentsMap}>
|
||||
<ShareMessagesProvider
|
||||
messages={[...(dispatch == null ? [] : [dispatch]), wake, reply]}
|
||||
>
|
||||
<MessagesView messagesTree={[wake]} conversationId="shared-view" />
|
||||
</ShareMessagesProvider>
|
||||
</AgentsMapContext.Provider>
|
||||
</ShareContext.Provider>
|
||||
</RecoilRoot>
|
||||
</Provider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
return queryClient;
|
||||
}
|
||||
|
||||
beforeEach(() => jest.mocked(dataService.getAIEndpoints).mockClear());
|
||||
|
||||
it.each([false, true])(
|
||||
'renders the actual public self wake-up author and task card (content: %s)',
|
||||
(content) => {
|
||||
const text = prompt();
|
||||
const queryClient = renderShared(text, content);
|
||||
expect(screen.getByRole('heading', { name: 'Historical Parent' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('img', { hidden: true })).toHaveAttribute('src', '/historical.png');
|
||||
expect(screen.getByTestId('message-body')).toHaveClass('border', 'border-border-medium');
|
||||
expect(screen.queryByText(text)).not.toBeInTheDocument();
|
||||
const toggle = screen.getByRole('button', { name: 'com_ui_wakeup_subagent_completed' });
|
||||
expect(toggle).toHaveAttribute('aria-expanded', 'false');
|
||||
fireEvent.click(toggle);
|
||||
expect(toggle).toHaveAttribute('aria-expanded', 'true');
|
||||
expect(screen.getByText('Shared durable result.')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'com_ui_wakeup_view_activity' }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(dataService.getAIEndpoints).not.toHaveBeenCalled();
|
||||
expect(queryClient.isFetching()).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(['error', 'cancelled'])('renders a public subagent %s outcome', (status) => {
|
||||
renderShared(prompt(status, 'reviewer'));
|
||||
expect(screen.getByRole('heading', { name: 'reviewer' })).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('button', {
|
||||
name:
|
||||
status === 'error' ? 'com_ui_wakeup_subagent_errored' : 'com_ui_wakeup_subagent_cancelled',
|
||||
}),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders background-tool wake-ups as system task cards', () => {
|
||||
const text = `A background tool task has finished. Continue using its durable result below.\n${JSON.stringify(
|
||||
[
|
||||
{
|
||||
background_task_id: 'task',
|
||||
tool_call_id: 'call',
|
||||
tool: 'bash',
|
||||
status: 'completed',
|
||||
result: 'Tool result.',
|
||||
},
|
||||
],
|
||||
)}`;
|
||||
renderShared(text);
|
||||
expect(screen.getByRole('heading', { name: 'com_ui_system_event' })).toBeInTheDocument();
|
||||
expect(screen.queryByText(text)).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'com_ui_wakeup_task_finished' }));
|
||||
expect(screen.getByText('Tool result.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([false, true])('keeps an ordinary public user message (content: %s)', (content) => {
|
||||
renderShared('Ordinary shared prompt.', content);
|
||||
expect(screen.getByText('Ordinary shared prompt.')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('wakeup-panel')).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('heading', { name: 'com_ui_prompt: com_ui_user', hidden: true }),
|
||||
).toHaveClass('sr-only');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['self', 'graph', 'self'],
|
||||
['agent_research_team', 'graph', 'agent_research_team'],
|
||||
['agent_research_team', undefined, 'agent_research_team'],
|
||||
['self', 'agent', 'Dispatch Parent'],
|
||||
] as const)('retains persisted shared alias %s with kind %s', (alias, kind, label) => {
|
||||
const dispatch: TMessage = {
|
||||
messageId: 'dispatch',
|
||||
parentMessageId: null,
|
||||
conversationId: 'original',
|
||||
isCreatedByUser: false,
|
||||
text: '',
|
||||
sender: 'Dispatch Parent',
|
||||
endpoint: EModelEndpoint.agents,
|
||||
model: 'agent_deleted',
|
||||
iconURL: '/dispatch.png',
|
||||
content: [
|
||||
{
|
||||
type: ContentTypes.TOOL_CALL,
|
||||
tool_call: {
|
||||
name: 'subagent',
|
||||
args: { run_in_background: true },
|
||||
output: JSON.stringify({
|
||||
background_task_id: 'task',
|
||||
subagent_thread_id: 'thread',
|
||||
tool: 'subagent',
|
||||
subagent_type: alias,
|
||||
status: 'running',
|
||||
message: 'Poll with background_task_id task.',
|
||||
}),
|
||||
...(kind == null
|
||||
? {}
|
||||
: {
|
||||
subagentIdentity: {
|
||||
subagentKind: kind,
|
||||
subagentAgentId: kind === 'graph' ? `graph:${alias}` : 'agent_deleted',
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
renderShared(prompt('completed', alias), false, dispatch);
|
||||
expect(screen.getByRole('heading', { name: label })).toBeInTheDocument();
|
||||
if (kind !== 'agent') {
|
||||
expect(screen.queryByRole('heading', { name: 'Dispatch Parent' })).not.toBeInTheDocument();
|
||||
} else {
|
||||
expect(screen.getByRole('img', { hidden: true })).toHaveAttribute('src', '/dispatch.png');
|
||||
}
|
||||
expect(screen.queryByRole('heading', { name: 'Historical Parent' })).not.toBeInTheDocument();
|
||||
expect(dataService.getAIEndpoints).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(['self', 'reviewer'])(
|
||||
'keeps a user-submitted %s wake-up lookalike as a prompt',
|
||||
(alias) => {
|
||||
const text = prompt('completed', alias);
|
||||
renderShared(text, false, undefined, true);
|
||||
expect(screen.getByTestId('message-body')).toHaveTextContent(text.replace(/\s+/g, ' '));
|
||||
expect(screen.queryByTestId('wakeup-panel')).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('heading', { name: 'com_ui_prompt: com_ui_user', hidden: true }),
|
||||
).toHaveClass('sr-only');
|
||||
},
|
||||
);
|
||||
|
||||
it('attributes a public parallel-lane self-spawn to its validated lane', () => {
|
||||
const dispatch: TMessage = {
|
||||
messageId: 'dispatch',
|
||||
parentMessageId: null,
|
||||
conversationId: 'original',
|
||||
isCreatedByUser: false,
|
||||
text: '',
|
||||
sender: 'Outer Parent',
|
||||
model: 'agent_outer',
|
||||
endpoint: EModelEndpoint.agents,
|
||||
iconURL: '/outer.png',
|
||||
content: [
|
||||
{
|
||||
type: ContentTypes.TOOL_CALL,
|
||||
agentId: 'agent_lane',
|
||||
tool_call: {
|
||||
id: 'call',
|
||||
name: 'subagent',
|
||||
args: { run_in_background: true },
|
||||
output: JSON.stringify({
|
||||
background_task_id: 'task',
|
||||
subagent_thread_id: 'thread',
|
||||
tool: 'subagent',
|
||||
subagent_type: 'self',
|
||||
status: 'running',
|
||||
message: 'Poll with background_task_id task.',
|
||||
}),
|
||||
subagentIdentity: { subagentKind: 'agent', subagentAgentId: 'agent_lane' },
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
renderShared(prompt(), false, dispatch, false, {
|
||||
agent_lane: {
|
||||
id: 'agent_lane',
|
||||
name: 'Lane Parent',
|
||||
description: null,
|
||||
created_at: 0,
|
||||
avatar: { filepath: '/lane.png', source: 'local' },
|
||||
provider: EModelEndpoint.openAI,
|
||||
model: 'test',
|
||||
model_parameters: {
|
||||
temperature: 1,
|
||||
maxContextTokens: 4096,
|
||||
max_context_tokens: 4096,
|
||||
max_output_tokens: 1024,
|
||||
top_p: 1,
|
||||
frequency_penalty: 0,
|
||||
presence_penalty: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(screen.getByRole('heading', { name: 'Lane Parent' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('heading', { name: 'Outer Parent' })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('img', { hidden: true })).toHaveAttribute('src', '/lane.png');
|
||||
expect(dataService.getAIEndpoints).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('copies only the visible public wake-up result through its real footer', () => {
|
||||
const clipboard = jest.mocked(copy);
|
||||
clipboard.mockReturnValue(true);
|
||||
renderShared(prompt(), true);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'com_ui_copy_to_clipboard' }));
|
||||
expect(clipboard).toHaveBeenCalledWith('Shared durable result.', expect.anything());
|
||||
});
|
||||
|
|
@ -264,7 +264,7 @@ function SharedView() {
|
|||
{artifactsContainer}
|
||||
</main>
|
||||
</div>
|
||||
<SharedSubagentActivityDialog shareId={shareId} />
|
||||
<SharedSubagentActivityDialog shareId={shareId} messages={data?.messages} />
|
||||
</AppChatSurface>
|
||||
</ShareContext.Provider>
|
||||
</CodeHighlightThrottleContext.Provider>
|
||||
|
|
|
|||
|
|
@ -27,7 +27,11 @@ export { default as useMemoizedChatContext } from './useMemoizedChatContext';
|
|||
export { default as useMessageProcess } from './useMessageProcess';
|
||||
export { default as useMessageHelpers } from './useMessageHelpers';
|
||||
export { default as useCopyToClipboard } from './useCopyToClipboard';
|
||||
export { hasCopyableText, useCopyMessageToClipboard } from './useCopyToClipboard';
|
||||
export {
|
||||
hasCopyableText,
|
||||
getMessageClipboardSource,
|
||||
useCopyMessageToClipboard,
|
||||
} from './useCopyToClipboard';
|
||||
export { default as useContentMetadata } from './useContentMetadata';
|
||||
export { default as useMessageScrolling } from './useMessageScrolling';
|
||||
export { default as useScrollbarGutter, useScrollbarGutterSeed } from './useScrollbarGutter';
|
||||
|
|
|
|||
|
|
@ -1,10 +1,15 @@
|
|||
import { RecoilRoot } from 'recoil';
|
||||
import copy from 'copy-to-clipboard';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import type { TMessage } from 'librechat-data-provider';
|
||||
import type { MutableSnapshot } from 'recoil';
|
||||
import type { ReactNode } from 'react';
|
||||
import type { MarkdownVariant } from '~/utils/richtext';
|
||||
import { useCopyMessageToClipboard } from '~/hooks/Messages/useCopyToClipboard';
|
||||
import {
|
||||
useCopyMessageToClipboard,
|
||||
getMessageClipboardSource,
|
||||
hasCopyableText,
|
||||
} from '~/hooks/Messages/useCopyToClipboard';
|
||||
import store from '~/store';
|
||||
|
||||
jest.mock('copy-to-clipboard');
|
||||
|
|
@ -53,6 +58,77 @@ describe('useCopyMessageToClipboard', () => {
|
|||
return (clipboardData.setData.mock.calls[0]?.[1] ?? '') as string;
|
||||
};
|
||||
|
||||
it.each([false, true])('copies rendered wake-up results with rich text %s', (rich) => {
|
||||
const text = `A detached subagent task has completed. Continue the parent task using its durable result below.\n${JSON.stringify({ background_task_id: 'task', subagent_thread_id: 'thread', subagent_type: 'reviewer', status: 'completed', result: '**Visible result**', snapshot: 'private orchestration' })}`;
|
||||
const message: TMessage = {
|
||||
messageId: 'wake',
|
||||
parentMessageId: null,
|
||||
conversationId: 'parent',
|
||||
isCreatedByUser: true,
|
||||
isUserSubmitted: false,
|
||||
text,
|
||||
content: [],
|
||||
};
|
||||
const { result } = renderHook(
|
||||
() => useCopyMessageToClipboard(getMessageClipboardSource(message)),
|
||||
{
|
||||
wrapper: ({ children }: { children: ReactNode }) => (
|
||||
<RecoilRoot
|
||||
initializeState={({ set }) => {
|
||||
set(store.copyRichText, rich);
|
||||
set(store.enableUserMsgMarkdown, false);
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</RecoilRoot>
|
||||
),
|
||||
},
|
||||
);
|
||||
act(() => {
|
||||
result.current(mockSetIsCopied);
|
||||
});
|
||||
expect(mockCopy.mock.calls[0][0]).toBe('**Visible result**');
|
||||
if (rich) expect(copiedHtml()).toBe('<p><strong>Visible result</strong></p>');
|
||||
expect(getMessageClipboardSource({ ...message, isUserSubmitted: true }).text).toBe(text);
|
||||
const empty = { ...message, text: text.replace('**Visible result**', '') };
|
||||
expect(hasCopyableText(getMessageClipboardSource(empty))).toBe(false);
|
||||
});
|
||||
|
||||
it('copies all displayed background results without host metadata', () => {
|
||||
const text = `2 background tool tasks have finished. Continue using their durable results below.\n${JSON.stringify(
|
||||
[
|
||||
{
|
||||
background_task_id: 'first',
|
||||
tool_call_id: 'call-1',
|
||||
tool: 'tool',
|
||||
status: 'completed',
|
||||
result: 'First result',
|
||||
},
|
||||
{
|
||||
background_task_id: 'second',
|
||||
tool_call_id: 'call-2',
|
||||
tool: 'tool',
|
||||
status: 'error',
|
||||
result: 'Second result',
|
||||
},
|
||||
],
|
||||
)}`;
|
||||
const source = getMessageClipboardSource({
|
||||
messageId: 'wake',
|
||||
parentMessageId: null,
|
||||
conversationId: 'parent',
|
||||
isCreatedByUser: true,
|
||||
text,
|
||||
});
|
||||
const { result } = renderHook(() => useCopyMessageToClipboard(source), {
|
||||
wrapper: ({ children }: { children: ReactNode }) => <RecoilRoot>{children}</RecoilRoot>,
|
||||
});
|
||||
act(() => {
|
||||
result.current(mockSetIsCopied);
|
||||
});
|
||||
expect(mockCopy.mock.calls[0][0]).toBe('First result\n\nSecond result');
|
||||
});
|
||||
|
||||
it('copies an assistant message as html when the preference is on', () => {
|
||||
const { result } = renderWithSettings(
|
||||
{ copyRichText: true, enableUserMsgMarkdown: false },
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import {
|
|||
STANDALONE_PATTERN,
|
||||
INVALID_CITATION_REGEX,
|
||||
} from '~/utils/citations';
|
||||
import { parseWakeupMessage } from '~/components/Chat/Messages/Content/Parts/wakeup';
|
||||
import { markdownToHtml } from '~/utils/richtext';
|
||||
import store from '~/store';
|
||||
|
||||
|
|
@ -221,6 +222,25 @@ type MessageClipboardSource = ClipboardSource &
|
|||
variant?: MarkdownVariant;
|
||||
};
|
||||
|
||||
/** Mirror the rendered task results, never the hidden host prompt, when
|
||||
* copying a wake-up. User-submitted lookalikes retain their original content. */
|
||||
export function getMessageClipboardSource(message?: TMessage | null): MessageClipboardSource {
|
||||
const display = parseWakeupMessage(message ?? undefined);
|
||||
if (display != null) {
|
||||
return {
|
||||
text: display.tasks.map((task) => task.result).join('\n\n'),
|
||||
isCreatedByUser: false,
|
||||
variant: 'lite',
|
||||
};
|
||||
}
|
||||
return {
|
||||
text: message?.text,
|
||||
content: message?.content,
|
||||
isCreatedByUser: message?.isCreatedByUser,
|
||||
error: message?.error,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies a message honoring the user's rich text preference. Kept apart from
|
||||
* `useCopyToClipboard` so the plain copies (share links, API keys, callback
|
||||
|
|
|
|||
|
|
@ -13,7 +13,11 @@ import {
|
|||
} from 'librechat-data-provider';
|
||||
import type { TMessageChatContext } from '~/common/types';
|
||||
import type { TMessageProps } from '~/common';
|
||||
import { useCopyMessageToClipboard, hasCopyableText } from './useCopyToClipboard';
|
||||
import {
|
||||
useCopyMessageToClipboard,
|
||||
getMessageClipboardSource,
|
||||
hasCopyableText,
|
||||
} from './useCopyToClipboard';
|
||||
import { useAssistantsMapContext, useAgentsMapContext } from '~/Providers';
|
||||
import { useAuthContext } from '~/hooks/AuthContext';
|
||||
import { useGetAddedConvo } from '~/hooks/Chat';
|
||||
|
|
@ -57,7 +61,7 @@ export default function useMessageActions(props: TMessageActions) {
|
|||
const agentsMap = useAgentsMapContext();
|
||||
const assistantMap = useAssistantsMapContext();
|
||||
|
||||
const { text, content, messageId = null, isCreatedByUser } = message ?? {};
|
||||
const { messageId = null, isCreatedByUser } = message ?? {};
|
||||
const edit = useMemo(() => messageId === currentEditId, [messageId, currentEditId]);
|
||||
|
||||
const [feedback, setFeedback] = useState<TFeedback | undefined>(() => {
|
||||
|
|
@ -121,17 +125,15 @@ export default function useMessageActions(props: TMessageActions) {
|
|||
regenerate(message, { addedConvo: getAddedConvo() });
|
||||
}, [chatContext, isCreatedByUser, message, regenerate, getAddedConvo]);
|
||||
|
||||
const clipboardSource = useMemo(() => getMessageClipboardSource(message), [message]);
|
||||
const copyToClipboard = useCopyMessageToClipboard({
|
||||
text,
|
||||
content,
|
||||
...clipboardSource,
|
||||
searchResults,
|
||||
isCreatedByUser,
|
||||
error: message?.error,
|
||||
});
|
||||
|
||||
const getCanCopy = useCallback(
|
||||
() => hasCopyableText({ text, content, searchResults }),
|
||||
[text, content, searchResults],
|
||||
() => hasCopyableText({ ...clipboardSource, searchResults }),
|
||||
[clipboardSource, searchResults],
|
||||
);
|
||||
|
||||
const messageLabel = useMemo(() => {
|
||||
|
|
|
|||
|
|
@ -7,8 +7,12 @@ import {
|
|||
} from 'librechat-data-provider';
|
||||
import type { SearchResultData } from 'librechat-data-provider';
|
||||
import type { TMessageProps } from '~/common';
|
||||
import {
|
||||
useCopyMessageToClipboard,
|
||||
getMessageClipboardSource,
|
||||
hasCopyableText,
|
||||
} from './useCopyToClipboard';
|
||||
import { useMessagesViewContext, useAssistantsMapContext, useAgentsMapContext } from '~/Providers';
|
||||
import { useCopyMessageToClipboard, hasCopyableText } from './useCopyToClipboard';
|
||||
import { useGetAddedConvo } from '~/hooks/Chat';
|
||||
import { logger } from '~/utils';
|
||||
|
||||
|
|
@ -33,7 +37,7 @@ export default function useMessageHelpers(
|
|||
|
||||
const getAddedConvo = useGetAddedConvo();
|
||||
|
||||
const { text, content, children, messageId = null, isCreatedByUser } = message ?? {};
|
||||
const { children, messageId = null, isCreatedByUser } = message ?? {};
|
||||
const edit = messageId === currentEditId;
|
||||
const isLast = children?.length === 0 || children?.length === undefined;
|
||||
|
||||
|
|
@ -89,17 +93,15 @@ export default function useMessageHelpers(
|
|||
regenerate(message, { addedConvo: getAddedConvo() });
|
||||
};
|
||||
|
||||
const clipboardSource = useMemo(() => getMessageClipboardSource(message), [message]);
|
||||
const copyToClipboard = useCopyMessageToClipboard({
|
||||
text,
|
||||
content,
|
||||
...clipboardSource,
|
||||
searchResults,
|
||||
isCreatedByUser,
|
||||
error: message?.error,
|
||||
});
|
||||
|
||||
const getCanCopy = useCallback(
|
||||
() => hasCopyableText({ text, content, searchResults }),
|
||||
[text, content, searchResults],
|
||||
() => hasCopyableText({ ...clipboardSource, searchResults }),
|
||||
[clipboardSource, searchResults],
|
||||
);
|
||||
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -2896,10 +2896,9 @@
|
|||
"com_ui_subagent_count_cancelled_one": "{{0}} cancelled",
|
||||
"com_ui_subagent_count_cancelled_other": "{{0}} cancelled",
|
||||
"com_ui_subagent_actor": "Agent",
|
||||
"com_ui_subagent_parent_agent": "Parent agent",
|
||||
"com_ui_subagent_cancelled": "Agent stopped",
|
||||
"com_ui_subagent_complete": "Ran agent",
|
||||
"com_ui_subagent_dialog_title": "\"{{0}}\" agent",
|
||||
"com_ui_subagent_dialog_title_self": "Agent",
|
||||
"com_ui_subagent_cancel_task": "Cancel task",
|
||||
"com_ui_subagent_control_cancel": "Cancel task",
|
||||
"com_ui_subagent_control_cancel_message": "Withdraw message",
|
||||
|
|
@ -2950,8 +2949,8 @@
|
|||
"com_ui_subagent_thread_status_interrupted": "Interrupted",
|
||||
"com_ui_subagent_thread_status_running": "Running",
|
||||
"com_ui_subagent_trigger_external_event": "External event",
|
||||
"com_ui_subagent_trigger_parent_continuation": "Parent agent continuation",
|
||||
"com_ui_subagent_trigger_parent_dispatch": "Parent agent dispatch",
|
||||
"com_ui_subagent_trigger_parent_continuation": "Followed up on the task",
|
||||
"com_ui_subagent_trigger_parent_dispatch": "Assigned a task",
|
||||
"com_ui_subagent_trigger_truncated": "Trigger summary shortened for display.",
|
||||
"com_ui_subagent_turn": "Turn",
|
||||
"com_ui_subagent_running": "Running agent",
|
||||
|
|
@ -3245,9 +3244,9 @@
|
|||
"com_ui_via_server": "in {{0}}",
|
||||
"com_ui_view_memory": "View Memory",
|
||||
"com_ui_wakeup_explainer": "The agent continued with this result.",
|
||||
"com_ui_wakeup_subagent_cancelled": "Subagent task cancelled",
|
||||
"com_ui_wakeup_subagent_completed": "Subagent task completed",
|
||||
"com_ui_wakeup_subagent_errored": "Subagent task failed",
|
||||
"com_ui_wakeup_subagent_cancelled": "Task cancelled",
|
||||
"com_ui_wakeup_subagent_completed": "Task completed",
|
||||
"com_ui_wakeup_subagent_errored": "Task failed",
|
||||
"com_ui_wakeup_task_cancelled": "Background task cancelled",
|
||||
"com_ui_wakeup_task_errored": "Background task failed",
|
||||
"com_ui_wakeup_task_finished": "Background task finished",
|
||||
|
|
|
|||
|
|
@ -376,6 +376,7 @@ const FIELD_MUTATIONS: Array<[string, Partial<TMessage>]> = [
|
|||
['createdAt', { createdAt: '2026-07-02T00:00:00.000Z' }],
|
||||
['depth', { depth: 3 }],
|
||||
['isCreatedByUser', { isCreatedByUser: true }],
|
||||
['isUserSubmitted', { isUserSubmitted: true }],
|
||||
['children length', { children: [makeFieldsMsg(), makeFieldsMsg()] }],
|
||||
['content reference', { content: [] as TMessage['content'] }],
|
||||
['model', { model: 'gpt-5' }],
|
||||
|
|
|
|||
|
|
@ -905,6 +905,7 @@ export function areMessageFieldsEqual(
|
|||
prevMsg.createdAt === nextMsg.createdAt &&
|
||||
prevMsg.depth === nextMsg.depth &&
|
||||
prevMsg.isCreatedByUser === nextMsg.isCreatedByUser &&
|
||||
prevMsg.isUserSubmitted === nextMsg.isUserSubmitted &&
|
||||
(prevMsg.children?.length ?? 0) === (nextMsg.children?.length ?? 0) &&
|
||||
prevMsg.content === nextMsg.content &&
|
||||
prevMsg.model === nextMsg.model &&
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue