📼 refactor: Move the Subagent Transcript Into @librechat/chat Behind a Subagents Host (#17678)

* refactor: Move the Subagent Transcript Into @librechat/chat Behind a Subagents Host

SubagentActivity, its scroll surface, content, status and guidance history
move into @librechat/chat/components, and ScrollToBottom moves into the
package with them. A new SubagentsHost carries what still lives in the app:
the content-parts and steer renderers, the animated jump-to-latest control,
and the read of a shortened guidance receipt, which stays an app query. The
prompt preview reuses renderMarkdown with a new codeExecution flag, and the
task content scope becomes a plain package context.

* refactor: Draw Content Parts Through the Message Parts Host

renderContentParts moves from SubagentsHost onto MessagePartsHost as the one
content slot, typed as ContentPartsSlotProps: the transcript fields plus the
optional row fields message rows pass. The app fills it through a registered
renderer, so the host module does not import the content stack, and omitted
row fields keep an assistant reply's defaults.

* refactor: Let the Content Parts Slot Carry Sparse Content

Main message rows keep holes at streaming and parallel indexes, and part indexes depend on those positions, so the slot's content keeps undefined entries as ContentParts already accepts them.

* test: Exercise the Real App Renderers in the Host Registration Spec

The transcript host test now renders the app's ContentParts and SteerPart under the providers they read, so the registered content renderer and steer slot are proven against the real components; only the receipt request stays mocked.
This commit is contained in:
Marco Beretta 2026-10-31 22:11:03 +01:00 • committed by GitHub
parent b03c9432c5
commit 222a369c60
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
33 changed files with 778 additions and 460 deletions

View file

@ -19,6 +19,8 @@ import { LiveAnnouncer } from '~/a11y';
import { router } from './routes';
import '~/Providers/MessagePartsHostContext';
import '~/Providers/MessagesHostContext';
import '~/Providers/SubagentsHostContext';
import '~/components/Chat/Messages/Content/register';
const App = () => {
const { setError } = useApiErrorBoundary();

View file

@ -32,7 +32,10 @@ import {
useMessagesConversation,
useOptionalMessagesOperations,
} from '~/Providers';
import { getAppPartRenderers } from '~/components/Chat/Messages/Content/Parts/slots';
import {
getAppContentParts,
getAppPartRenderers,
} from '~/components/Chat/Messages/Content/Parts/slots';
import useSmoothStreaming from '~/hooks/Messages/useSmoothStreaming';
import { ptcTraceByToolCallId, ptcTraceKey } from '~/hooks/SSE/ptc';
import { sandboxStartingByToolCallId } from '~/hooks/SSE/sandbox';
@ -131,6 +134,7 @@ export const appMessagePartsHost: MessagePartsHost = {
useSmoothStreaming,
useAgent: useAppAgent,
renderAgentIcon: (agent) => getAppPartRenderers().renderAgentIcon(agent),
renderContentParts: (props) => getAppContentParts()(props),
renderAgentAvatar: (agent) => renderAgentAvatar(agent, { size: 'icon', showBorder: false }),
useFontSize: () => useAtomValue(fontSizeAtom),
useShowThinking: () => useAtomValue(showThinkingAtom),

View file

@ -0,0 +1,84 @@
import { useRef, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { CSSTransition } from 'react-transition-group';
import { ScrollToBottom } from '@librechat/chat/components';
import { setDefaultSubagentsHost } from '@librechat/chat/react';
import { QueryKeys, dataService } from 'librechat-data-provider';
import type {
SubagentsHost,
TaskContentScope,
SubagentRetainedControl,
SubagentJumpToLatestProps,
} from '@librechat/chat/react';
import SteerPart from '~/components/Chat/Messages/Content/Parts/SteerPart';
/** Reads a shortened guidance message's full receipt, once the reader asks for it. */
function useRetainedControl(
scope: TaskContentScope,
invocationId: string,
enabled: boolean,
): SubagentRetainedControl {
const query = useQuery(
[
QueryKeys.subagentControlReceipt,
scope.parentConversationId,
scope.threadId,
scope.taskId,
invocationId,
],
async () => {
const response = await dataService.getSubagentControlReceipt(
scope.parentConversationId,
scope.threadId,
scope.taskId,
invocationId,
);
if (response.receipt.invocationId !== invocationId)
throw new Error('subagent_control_identity_mismatch');
return response;
},
{ enabled, retry: 1, staleTime: Infinity, refetchOnWindowFocus: false },
);
return {
message: query.data?.receipt.message,
isFetching: query.isFetching,
isError: query.isError,
refetch: () => void query.refetch(),
};
}
/** The transcript's jump-to-latest control with the app's fade: the button takes pointers and
* focus only once the enter transition has settled. */
function JumpToLatest({ visible, onClick, maximizeChatSpace }: SubagentJumpToLatestProps) {
const ref = useRef<HTMLDivElement>(null);
const [isSettled, setIsSettled] = useState(false);
return (
<CSSTransition
in={visible}
timeout={{ enter: 300, exit: 180 }}
classNames="scroll-animation"
unmountOnExit={true}
appear={true}
nodeRef={ref}
onEntered={() => setIsSettled(true)}
onExit={() => setIsSettled(false)}
>
<ScrollToBottom
ref={ref}
scrollHandler={onClick}
maximizeChatSpace={maximizeChatSpace}
interactive={isSettled}
/>
</CSSTransition>
);
}
/** What subagent transcripts read from the app: the steer renderer and the jump-to-latest fade
* that still live here, and the receipt read. Registered as the default when this module loads. */
export const appSubagentsHost: SubagentsHost = {
renderSteer: (props) => <SteerPart {...props} />,
renderJumpToLatest: (props) => <JumpToLatest {...props} />,
useRetainedControl,
};
setDefaultSubagentsHost(appSubagentsHost);

View file

@ -1,9 +1,12 @@
import React from 'react';
import { join } from 'path';
import { readFileSync } from 'fs';
import { render, screen } from '@testing-library/react';
import { agentAuthor, useParentAuthor } from '@librechat/chat/react';
import { RecoilRoot } from 'recoil';
import { SubagentActivity } from '@librechat/chat/components';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { agentAuthor, useParentAuthor, TaskContentScopeContext } from '@librechat/chat/react';
import type { ChildActivity } from '@librechat/chat/react';
jest.mock('~/components/Chat/Messages/MessageIcon', () => ({
__esModule: true,
@ -12,9 +15,26 @@ jest.mock('~/components/Chat/Messages/MessageIcon', () => ({
),
}));
const mockReadControl = jest.fn();
jest.mock('librechat-data-provider', () => {
const actual = jest.requireActual('librechat-data-provider');
return {
...actual,
dataService: {
...actual.dataService,
getSubagentControlReceipt: (...args: unknown[]) => mockReadControl(...args),
},
};
});
/** The registrations the app entry performs, loaded the way `App.jsx` loads them. Nothing here
* imports a message component, so the hosts cannot arrive as a side effect of one. */
const ENTRY_HOSTS = ['~/Providers/MessagePartsHostContext', '~/Providers/MessagesHostContext'];
const ENTRY_HOSTS = [
'~/Providers/MessagePartsHostContext',
'~/Providers/MessagesHostContext',
'~/Providers/SubagentsHostContext',
'~/components/Chat/Messages/Content/register',
];
ENTRY_HOSTS.forEach((path) => jest.requireActual(path));
function ParentAuthor() {
@ -28,7 +48,7 @@ function ParentAuthor() {
}
describe('app host registration', () => {
it('registers both default hosts from the app entry', () => {
it('registers every default host from the app entry', () => {
const entry = readFileSync(join(__dirname, '..', 'App.jsx'), 'utf8');
for (const path of ENTRY_HOSTS) {
expect(entry).toContain(`import '${path}';`);
@ -49,4 +69,65 @@ describe('app host registration', () => {
'Child agent',
]);
});
describe('subagent transcripts', () => {
const control = {
invocationId: 'budgeted',
controlId: 'pending-control',
action: 'queue' as const,
status: 'accepted' as const,
createdAt: '2026-10-23T00:00:00Z',
updatedAt: '2026-10-23T00:00:01Z',
message: 'Budgeted prefix',
messageTruncated: true,
};
const activity: ChildActivity = {
title: 'Child',
status: 'running',
items: [{ type: 'writing', text: 'Working.' }],
controls: [control],
};
const renderTranscript = () =>
render(
<RecoilRoot>
<QueryClientProvider
client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}
>
<TaskContentScopeContext.Provider
value={{ parentConversationId: 'parent', threadId: 'child', taskId: 'task' }}
>
<SubagentActivity activity={activity} embedded />
</TaskContentScopeContext.Provider>
</QueryClientProvider>
</RecoilRoot>,
);
beforeEach(() => mockReadControl.mockReset());
it('draws content and guidance with the real app renderers and reads a receipt only on request', async () => {
mockReadControl.mockResolvedValueOnce({
receipt: { ...control, message: 'Full guidance.', messageTruncated: false },
});
renderTranscript();
expect(screen.getByText('Working.').closest('[data-message-text]')).not.toBeNull();
expect(screen.getByTestId('steer-part')).toHaveTextContent('Budgeted prefix');
expect(mockReadControl).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: /show more/i }));
await waitFor(() =>
expect(screen.getByTestId('steer-part')).toHaveTextContent('Full guidance.'),
);
expect(mockReadControl).toHaveBeenCalledWith('parent', 'child', 'task', 'budgeted');
});
it('reports a receipt for another control as a load error', async () => {
mockReadControl.mockResolvedValue({ receipt: { ...control, invocationId: 'other' } });
renderTranscript();
fireEvent.click(screen.getByRole('button', { name: /show more/i }));
/** The receipt query retries once, as the transcript always has, before it reports. */
expect(await screen.findByRole('alert', {}, { timeout: 5000 })).toBeInTheDocument();
expect(mockReadControl).toHaveBeenCalledTimes(2);
expect(screen.getByTestId('steer-part')).toHaveTextContent('Budgeted prefix');
});
});
});

View file

@ -58,6 +58,7 @@ function createHost(overrides: Partial<MessagePartsHost> = {}): MessagePartsHost
usePaneConversationId: () => null,
useLiveAppliedSteer: () => [false, jest.fn()],
useShare: () => ({}),
renderContentParts: () => null,
useMessagesEditing: () => ({
conversation: null,
ask: jest.fn(),

View file

@ -9,9 +9,14 @@ import Markdown from '../Markdown';
const agentMessage = { endpoint: EModelEndpoint.agents, isCreatedByUser: false } as TMessage;
setAppPartRenderers({
renderMarkdown: ({ content, variant, isLatestMessage }: MessagePartsMarkdownProps) =>
renderMarkdown: ({
content,
variant,
isLatestMessage,
codeExecution,
}: MessagePartsMarkdownProps) =>
variant === 'lite' ? (
<MarkdownLite content={content} />
<MarkdownLite content={content} codeExecution={codeExecution} />
) : (
<Markdown content={content} isLatestMessage={isLatestMessage} />
),

View file

@ -1,3 +1,5 @@
import type { ContentPartsSlotProps } from '@librechat/chat/react';
import type { ReactNode } from 'react';
import type { MessagePartsHost } from '~/hooks/Chat/contract';
/** The host slots drawn with app components that import the markdown stack. */
@ -21,3 +23,20 @@ export function getAppPartRenderers(): AppPartRenderers {
}
return appPartRenderers;
}
let appContentParts: ((props: ContentPartsSlotProps) => ReactNode) | null = null;
/** Registers the app's content-parts renderer, which `~/components/Chat/Messages/Content/register`
* does when the app entry loads it, so the host never imports the content stack itself. */
export function setAppContentParts(render: (props: ContentPartsSlotProps) => ReactNode): void {
appContentParts = render;
}
export function getAppContentParts(): (props: ContentPartsSlotProps) => ReactNode {
if (appContentParts == null) {
throw new Error(
'The content-parts renderer is registered by ~/components/Chat/Messages/Content/register.',
);
}
return appContentParts;
}

View file

@ -0,0 +1,16 @@
import { setAppContentParts } from './Parts/slots';
import ContentParts from './ContentParts';
/** Fills the parts host's content slot with the app's renderer. Omitted row fields take an
* assistant reply's defaults: not the user's, the last row, latest while it is submitting. */
setAppContentParts(
({ isCreatedByUser = false, isLast = true, isLatestMessage, isSubmitting, ...props }) => (
<ContentParts
{...props}
isCreatedByUser={isCreatedByUser}
isLast={isLast}
isSubmitting={isSubmitting}
isLatestMessage={isLatestMessage ?? isSubmitting}
/>
),
);

View file

@ -1,8 +1,8 @@
import { memo, useState, useRef, useEffect } from 'react';
import { useAtomValue } from 'jotai';
import { CSSTransition } from 'react-transition-group';
import { ScrollToBottom } from '@librechat/chat/components';
import { composerOverlayCountFamily } from '@librechat/chat/react';
import ScrollToBottom from '~/components/Messages/ScrollToBottom';
const intersectionThreshold = 0.85;
const visibilityDebounceRate = 150;

View file

@ -4,7 +4,8 @@ import { act, render, screen } from '@testing-library/react';
import { composerOverlayCountFamily } from '@librechat/chat/react';
import ScrollButton from '../ScrollButton';
jest.mock('~/hooks', () => ({
jest.mock('@librechat/client', () => ({
...jest.requireActual('@librechat/client'),
useLocalize: () => (key: string) => key,
}));

View file

@ -36,12 +36,12 @@ jest.mock('~/components/Chat/Messages/MessageIcon', () => ({
}));
jest.mock('~/hooks/MCP', () => ({ useMCPServerNames: () => [] }));
jest.mock('./SubagentActivity', () => ({
__esModule: true,
jest.mock('@librechat/chat/components', () => ({
...jest.requireActual('@librechat/chat/components'),
SubagentActivityScrollSurface: ({ children }: { children: React.ReactNode }) => (
<div data-testid="shared-scroll-surface">{children}</div>
),
default: ({
SubagentActivity: ({
activity,
}: {
activity: { title: string; items: Array<{ type: string; text?: string }> };

View file

@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useAtom } from 'jotai';
import { SubagentActivityScrollSurface } from '@librechat/chat/components';
import { OGDialog, OGDialogContent, OGDialogHeader, OGDialogTitle } from '@librechat/client';
import {
activeSubagentPanel,
@ -13,7 +14,6 @@ import {
} from '@librechat/chat/react';
import type { TMessage } from 'librechat-data-provider';
import { MessageSurfaceContext } from '~/components/Chat/Messages/ui/surface';
import { SubagentActivityScrollSurface } from './SubagentActivity';
import SubagentConversation from './SubagentConversation';
import { useAgentsMapContext } from '~/Providers';
import { useLocalize } from '~/hooks';

View file

@ -13,6 +13,8 @@ import type { ChatContract } from '~/hooks/Chat/contract';
import SubagentConversation from './SubagentConversation';
import { ChatContext } from '~/Providers/ChatContext';
import { ChatSurfaceHarness } from 'test/harness';
import '~/Providers/SubagentsHostContext';
import '~/components/Chat/Messages/Content/register';
const mockRecoveredQuery = jest.fn();
jest.mock('~/data-provider/Subagents/content', () => ({
@ -25,22 +27,24 @@ const mockRenderedContent = jest.fn();
const mockPartScope = jest.fn();
const mockParentAsk = jest.fn();
/** The package's own provider, so the transcript, which reads the package host, sees the same
* host as the conversation around it. Registered as the default, as the app entry does. */
jest.mock('~/Providers/MessagePartsHostContext', () => {
const React = jest.requireActual<typeof import('react')>('react');
const Context = React.createContext({
const { getAppContentParts } = jest.requireActual<
typeof import('~/components/Chat/Messages/Content/Parts/slots')
>('~/components/Chat/Messages/Content/Parts/slots');
const chat = jest.requireActual<typeof import('@librechat/chat/react')>('@librechat/chat/react');
chat.setDefaultMessagePartsHost({
useShowThinking: () => false,
useAutoExpandTools: () => false,
useMessagesAsk: () => mockParentAsk,
});
renderMarkdown: ({ content }: { content: string }) => content,
renderContentParts: (props: Parameters<ReturnType<typeof getAppContentParts>>[0]) =>
getAppContentParts()(props),
} as unknown as Parameters<typeof chat.setDefaultMessagePartsHost>[0]);
return {
MessagePartsHostProvider: ({
host,
children,
}: {
host: React.ContextType<typeof Context>;
children: React.ReactNode;
}) => <Context.Provider value={host}>{children}</Context.Provider>,
useMessagePartsHost: () => React.useContext(Context),
MessagePartsHostProvider: chat.MessagePartsHostProvider,
useMessagePartsHost: chat.useMessagePartsHost,
};
});
@ -56,6 +60,11 @@ jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
}));
jest.mock('@librechat/client', () => ({
...jest.requireActual('@librechat/client'),
useLocalize: () => (key: string) => key,
}));
jest.mock('~/Providers', () => ({
useAgentsMapContext: () => undefined,
}));
@ -94,12 +103,6 @@ jest.mock('~/components/Chat/Messages/Content/Container', () => ({
default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));
jest.mock('~/components/Chat/Messages/Content/Parts', () => ({
EmptyText: ({ underHeaderIcon }: { underHeaderIcon?: boolean }) => (
<div data-testid="thinking-cursor" data-under-header-icon={String(underHeaderIcon === true)} />
),
}));
jest.mock('~/components/Chat/Messages/MessageIcon', () => ({
__esModule: true,
default: () => <span data-testid="message-icon" />,
@ -192,7 +195,8 @@ describe('SubagentConversation', () => {
/** 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('child-face')).toHaveLength(2);
expect(screen.getByTestId('thinking-cursor')).toHaveAttribute('data-under-header-icon', 'true');
const dot = container.querySelector('.result-thinking');
expect(dot?.parentElement?.parentElement).toHaveClass('ps-1.5');
expect(container.querySelectorAll('.message-render')).toHaveLength(4);
expect(container.querySelectorAll('.user-turn')).toHaveLength(1);
expect(container.querySelectorAll('.agent-turn')).toHaveLength(2);

View file

@ -22,6 +22,9 @@ import {
messageFooterClasses,
ElapsedTimer,
MessageRow,
SubagentActivityContent,
SubagentStatus,
getActivityContent,
} from '@librechat/chat/components';
import type { ChildConversationTurn, ToolContentQuery, TurnAuthor } from '@librechat/chat/react';
import type { TMessage, TMessageContentParts } from 'librechat-data-provider';
@ -35,7 +38,6 @@ import {
useSubagentToolContentQuery,
} from '~/data-provider/Subagents/content';
import { MessagePartsHostProvider, useMessagePartsHost } from '~/Providers/MessagePartsHostContext';
import { SubagentActivityContent, SubagentStatus, getActivityContent } from './SubagentActivity';
import ResumeAuthorHeader from '~/components/Chat/Messages/Content/Parts/ResumeAuthorHeader';
import { useSearchResultsByTurn } from '~/hooks/Messages/useSearchResultsByTurn';
import { ErrorSourceProvider } from '~/components/Messages/Content/Error/source';

View file

@ -194,12 +194,12 @@ jest.mock('~/components/Chat/Messages/Content/MarkdownLite', () => ({
default: ({ content }: { content: string }) => <div>{content}</div>,
}));
jest.mock('./SubagentActivity', () => ({
__esModule: true,
jest.mock('@librechat/chat/components', () => ({
...jest.requireActual('@librechat/chat/components'),
SubagentActivityScrollSurface: ({ children }: { children: React.ReactNode }) => (
<div data-testid="shared-scroll-surface">{children}</div>
),
default: function MockActivity({
SubagentActivity: function MockActivity({
activity,
activityId,
state,

View file

@ -5,6 +5,7 @@ import { dataService, ForkOptions } from 'librechat-data-provider';
import { useAtom, useAtomValue, useSetAtom, useStore } from 'jotai';
import { isMacPlatform, resolveComposerKeyDown } from '@librechat/chat';
import { ArrowUpRight, Clock, OctagonPause, X, Zap } from 'lucide-react';
import { SubagentActivity, SubagentActivityScrollSurface } from '@librechat/chat/components';
import {
Alert,
Button,
@ -58,7 +59,6 @@ import {
useSubagentControlMutation,
useSubagentThreadQuery,
} from '~/data-provider';
import SubagentActivity, { SubagentActivityScrollSurface } from './SubagentActivity';
import ApprovalProvider from '~/components/Chat/Messages/Content/ApprovalContext';
import { TaskContentScopeContext } from '~/data-provider/Subagents/content';
import { useFocusTrap, useLocalize, useNavigateToConvo } from '~/hooks';

View file

@ -1,20 +1,20 @@
import { createContext, useContext } from 'react';
import { useContext } from 'react';
import { atom, createStore } from 'jotai';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { QueryKeys, dataService, hasToolCallPreview } from 'librechat-data-provider';
import { recoverTaskContent, recoveredToolPart, isLiveSubagentStatus } from '@librechat/chat/react';
import {
recoverTaskContent,
recoveredToolPart,
isLiveSubagentStatus,
TaskContentScopeContext,
} from '@librechat/chat/react';
import type { RecoveredContent, TaskContentScope, ToolContentQuery } from '@librechat/chat/react';
import type { SubagentTaskContentSnapshot, ToolCallPartResponse } from 'librechat-data-provider';
import type { RecoveredContent, ToolContentQuery } from '@librechat/chat/react';
import type { QueryClient, UseQueryOptions } from '@tanstack/react-query';
import { ACTIVE_THREAD_REFRESH_MS } from './queries';
export type TaskContentScope = {
parentConversationId: string;
threadId: string;
taskId: string;
};
export const TaskContentScopeContext = createContext<TaskContentScope | null>(null);
export { TaskContentScopeContext };
export type { TaskContentScope };
export const subagentTaskContentKey = (scope: TaskContentScope) =>
[
QueryKeys.subagentTaskContent,

View file

@ -436,11 +436,6 @@
"count": 2
}
},
"client/src/components/Chat/Subagents/SubagentActivity.tsx": {
"shadcn/no-restyle": {
"count": 12
}
},
"client/src/components/Chat/Subagents/SubagentConversation.tsx": {
"shadcn/require-static-classes": {
"count": 1
@ -657,11 +652,6 @@
"count": 4
}
},
"client/src/components/Messages/ScrollToBottom.tsx": {
"shadcn/no-restyle": {
"count": 1
}
},
"client/src/components/Nav/AccountSettings.tsx": {
"shadcn/no-inline-styles": {
"count": 1
@ -1398,6 +1388,11 @@
"count": 1
}
},
"packages/chat/src/components/messages/ScrollToBottom.tsx": {
"shadcn/no-restyle": {
"count": 1
}
},
"packages/chat/src/components/messages/SiblingSwitch.tsx": {
"shadcn/no-restyle": {
"count": 2
@ -1419,6 +1414,11 @@
"count": 4
}
},
"packages/chat/src/components/subagents/transcript.tsx": {
"shadcn/no-restyle": {
"count": 12
}
},
"packages/client/src/components/Badge.tsx": {
"design/disabled-recipe": {
"count": 1

View file

@ -352,6 +352,7 @@ export default [
// that stylesheet, so its lint has no Tailwind entry that declares them.
'markdown',
'prose',
'prose-sm',
'message-content',
'submitting',
'result-streaming',

View file

@ -138,3 +138,11 @@ export type {
} from './components/messages/MessagesView';
export { EventSubagentActivityGroup } from './components/subagents/activity';
export { default as ScrollToBottom } from './components/messages/ScrollToBottom';
export {
SubagentStatus,
SubagentActivity,
getActivityContent,
SubagentActivityContent,
SubagentActivityScrollSurface,
} from './components/subagents/transcript';

View file

@ -27,6 +27,7 @@ function createHost(enableUserMsgMarkdown = false): MessagePartsHost {
useAgent: (agentId) => (agentId === agent.id ? agent : undefined),
renderAgentIcon: (current) => <span data-testid="agent-icon">{current?.id ?? 'unknown'}</span>,
renderAgentAvatar: () => null,
renderContentParts: () => null,
useFontSize: () => 'text-base',
useShowThinking: () => false,
useAutoExpandTools: () => false,

View file

@ -1,8 +1,7 @@
import { forwardRef } from 'react';
import { ChevronDown } from 'lucide-react';
import { Button } from '@librechat/client';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
import { Button, cn, useLocalize } from '@librechat/client';
import type { ForwardRefExoticComponent, RefAttributes } from 'react';
type Props = {
scrollHandler: React.MouseEventHandler<HTMLButtonElement>;
@ -25,49 +24,50 @@ type Props = {
interactive?: boolean;
};
const ScrollToBottom = forwardRef<HTMLDivElement, Props>(
({ scrollHandler, maximizeChatSpace, overlayHeight = 0, interactive = false }, ref) => {
const localize = useLocalize();
const ScrollToBottom: ForwardRefExoticComponent<Props & RefAttributes<HTMLDivElement>> = forwardRef<
HTMLDivElement,
Props
>(({ scrollHandler, maximizeChatSpace, overlayHeight = 0, interactive = false }, ref) => {
const localize = useLocalize();
return (
<div
ref={ref}
className="scrollbar-gutter-spacer pointer-events-none absolute inset-x-0 z-10"
style={{ bottom: `calc(1.25rem + ${overlayHeight}px)` }}
>
{/* The composer's own column, so the control stacks over the send
return (
<div
ref={ref}
className="scrollbar-gutter-spacer pointer-events-none absolute inset-x-0 z-10"
style={{ bottom: `calc(1.25rem + ${overlayHeight}px)` }}
>
{/* The composer's own column, so the control stacks over the send
button one row down: the same end inset (`me-2`, mirroring Send's
`me-2`) and, through `icon-theme` + `round`, the same control
geometry as every button in the composer's action row. */}
<div
<div
className={cn(
'mx-auto flex justify-end sm:px-2',
maximizeChatSpace ? 'max-w-full' : 'md:max-w-3xl xl:max-w-4xl',
)}
>
<Button
type="button"
variant="floating"
size="icon-theme"
shape="round"
onClick={scrollHandler}
disabled={!interactive}
aria-label={localize('com_ui_scroll_to_bottom')}
className={cn(
'mx-auto flex justify-end sm:px-2',
maximizeChatSpace ? 'max-w-full' : 'md:max-w-3xl xl:max-w-4xl',
'me-2 active:scale-[0.96] motion-reduce:active:scale-100',
/* The wrapper owns the fade, so being briefly unreachable must not
dim the control on its way in on top of it. */
'disabled:opacity-100',
interactive ? 'pointer-events-auto' : 'pointer-events-none',
)}
>
<Button
type="button"
variant="floating"
size="icon-theme"
shape="round"
onClick={scrollHandler}
disabled={!interactive}
aria-label={localize('com_ui_scroll_to_bottom')}
className={cn(
'me-2 active:scale-[0.96] motion-reduce:active:scale-100',
/* The wrapper owns the fade, so being briefly unreachable must not
dim the control on its way in on top of it. */
'disabled:opacity-100',
interactive ? 'pointer-events-auto' : 'pointer-events-none',
)}
>
<ChevronDown className="size-4" aria-hidden="true" />
</Button>
</div>
<ChevronDown className="size-4" aria-hidden="true" />
</Button>
</div>
);
},
);
</div>
);
});
ScrollToBottom.displayName = 'ScrollToBottom';

View file

@ -1,7 +1,11 @@
/**
* @jest-environment jsdom
*/
import { render, screen } from '@testing-library/react';
import ScrollToBottom from '../ScrollToBottom';
jest.mock('~/hooks', () => ({
jest.mock('@librechat/client', () => ({
...jest.requireActual('@librechat/client'),
useLocalize: () => (key: string) => key,
}));

View file

@ -83,6 +83,7 @@ const host: MessagePartsHost = {
useAgent: (agentId) => agents[agentId] as ReturnType<MessagePartsHost['useAgent']>,
renderAgentIcon: () => null,
renderAgentAvatar: () => <span data-testid="agent-avatar" />,
renderContentParts: () => null,
useFontSize: () => 'text-base',
useShowThinking: () => false,
useAutoExpandTools: () => false,

View file

@ -1,239 +1,39 @@
import React from 'react';
/**
* @jest-environment jsdom
*/
import React, { useState } from 'react';
import { ContentTypes } from 'librechat-data-provider';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Provider as JotaiProvider, createStore } from 'jotai';
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';
import { act, fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react';
import type { TMessageContentParts, Agents } from 'librechat-data-provider';
import type { ChildActivity } from '@librechat/chat/react';
import SubagentActivity, { SubagentActivityScrollSurface } from './SubagentActivity';
import { TaskContentScopeContext } from '~/data-provider/Subagents/content';
import { ChatSurfaceHarness } from 'test/harness';
const Wrapper = ({ children }: { children: React.ReactNode }) => (
<ChatSurfaceHarness>{children}</ChatSurfaceHarness>
);
const render = (ui: React.ReactElement) => rtlRender(ui, { wrapper: Wrapper });
import type { ChildActivity } from '../../../react/subagents/adapters';
import type { ChatSurface } from '../../../react/subagents/surface';
import type { SubagentsHost } from '../../../react/subagents/host';
import type { MessagePartsHost } from '../../../react/host';
import { SubagentActivity, SubagentActivityScrollSurface } from '../transcript';
import { TaskContentScopeContext } from '../../../react/subagents/scope';
import { ChatSurfaceProvider } from '../../../react/subagents/provider';
import { SubagentsHostProvider } from '../../../react/subagents/host';
import { MessagePartsHostProvider } from '../../../react/host';
const mockShowMore = 'com_ui_show_more';
const mockReadControl = jest.fn();
jest.mock('librechat-data-provider', () => {
const actual = jest.requireActual('librechat-data-provider');
return {
...actual,
dataService: {
...actual.dataService,
getSubagentControlReceipt: (...args: unknown[]) => mockReadControl(...args),
},
};
});
const mockContentParts = jest.fn();
let mockAutoExpandTools = false;
jest.mock('~/Providers/MessagePartsHostContext', () => ({
useMessagePartsHost: () => ({
useShowThinking: () => false,
useAutoExpandTools: () => mockAutoExpandTools,
}),
}));
const lastContentParts = () =>
mockContentParts.mock.calls[mockContentParts.mock.calls.length - 1]?.[0];
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
}));
jest.mock('~/components/Chat/Messages/Content/Parts/SteerPart', () => ({
jest.mock('../../EmptyText', () => ({
__esModule: true,
default: ({
steer,
steerId,
receiptState,
hasMore,
onExpand,
}: {
steer: string;
steerId?: string;
receiptState?: string | null;
hasMore?: boolean;
onExpand?: () => void;
}) => (
<div data-testid="shared-steer-part" data-receipt={receiptState} data-steer-id={steerId}>
{steer}
{hasMore && (
<button type="button" onClick={onExpand}>
{mockShowMore}
</button>
)}
</div>
),
}));
jest.mock('~/components/Chat/Messages/Content/Parts', () => ({
EmptyText: () => <div data-testid="thinking-cursor" />,
}));
jest.mock('~/components/Chat/Messages/Content/ContentParts', () => ({
__esModule: true,
default: function MockContentParts({
content,
messageId,
...props
}: {
content: Array<{
type: string;
text?: string;
phase?: string;
think?: string;
reasoning_label?: string;
activity_label?: string;
tool_call?: {
id: string;
name: string;
args?: unknown;
output?: string;
inputValidationError?: true;
approval?: unknown;
runStepStatus?: string;
};
}>;
messageId: string;
foldLiveActivity?: boolean;
}) {
mockContentParts({ content, messageId, ...props });
const { useState } = jest.requireActual<typeof import('react')>('react');
const [expandedTool, setExpandedTool] = useState<string | null>(null);
const tools = content.filter((part) => part?.type === 'tool_call');
return (
<div data-testid="regular-content-parts" data-message-id={messageId}>
{content.map((part, index) => {
if (part == null) return null;
if (part.type === 'text') {
return (
<div key={index} data-phase={part.phase}>
{part.text}
</div>
);
}
if (part.type === 'think') {
if ((part as { reasoning_unavailable?: boolean }).reasoning_unavailable === true) {
return <div key={index}>{`reasoning-marker:${part.reasoning_label ?? ''}`}</div>;
}
return <div key={index}>{part.reasoning_label ?? part.think}</div>;
}
if (part.type === 'activity_label') {
return <div key={index}>{part.activity_label}</div>;
}
if (part.type !== 'tool_call' || part.tool_call == null) return null;
const tool = part.tool_call;
return (
<div key={tool.id}>
<button
type="button"
aria-expanded={expandedTool === tool.id}
data-run-step-status={tool.runStepStatus}
data-input-validation-error={tool.inputValidationError}
onClick={() => setExpandedTool(expandedTool === tool.id ? null : tool.id)}
>
{tool.name}
</button>
{expandedTool === tool.id && (
<div>
{JSON.stringify(tool.args)} {tool.output}
</div>
)}
{tool.approval != null && <div data-testid="tool-approval" />}
</div>
);
})}
{/* eslint-disable-next-line i18next/no-literal-string */}
{tools.length > 1 && <div>Used {tools.length} tools</div>}
</div>
);
},
}));
jest.mock('~/components/Chat/Messages/Content/Parts/Reasoning', () => ({
__esModule: true,
default: ({ reasoning }: { reasoning: string }) => <div>{reasoning}</div>,
}));
jest.mock('~/components/Chat/Messages/Content/MarkdownLite', () => ({
__esModule: true,
default: ({ content }: { content: string }) => <div>{content}</div>,
}));
jest.mock('~/components/Chat/Messages/Content/Container', () => ({
__esModule: true,
default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));
jest.mock('~/components/Chat/Messages/Content/ToolCall', () => ({
__esModule: true,
default: function MockToolCall({
name,
args,
output,
runStepStatus,
}: {
name: string;
args: unknown;
output: string;
runStepStatus?: string;
}) {
const { useState } = jest.requireActual<typeof import('react')>('react');
const [open, setOpen] = useState(false);
return (
<div>
<button
type="button"
aria-expanded={open}
data-run-step-status={runStepStatus}
onClick={() => setOpen((value) => !value)}
>
{name}
</button>
{open && (
<div>
{JSON.stringify(args)} {output}
</div>
)}
</div>
);
},
}));
jest.mock('~/components/Chat/Messages/Content/ToolCallGroup', () => ({
__esModule: true,
default: ({
parts,
renderPart,
lastContentIdx,
}: {
parts: Array<{ part: unknown; idx: number }>;
renderPart: (part: unknown, idx: number, isLast: boolean) => React.ReactNode;
lastContentIdx: number;
}) => (
<div>
{/* eslint-disable-next-line i18next/no-literal-string */}
<div>Used {parts.length} tools</div>
{parts.map(({ part, idx }) => renderPart(part, idx, idx === lastContentIdx))}
</div>
),
}));
jest.mock('~/components/Chat/Messages/Content/ToolApproval', () => ({
__esModule: true,
// eslint-disable-next-line i18next/no-literal-string
default: () => <div data-testid="tool-approval">approval</div>,
}));
jest.mock('@librechat/chat/components', () => ({
...jest.requireActual('@librechat/chat/components'),
SteerReceipt: ({ state }: { state: string }) => (
<span data-testid="steer-receipt" data-receipt-state={state} />
),
default: () => <div data-testid="thinking-cursor" />,
}));
jest.mock('@librechat/client', () => ({
cn: jest.requireActual('@librechat/client').cn,
useLanguage: () => 'en',
useLocalize: () => (key: string) => key,
Alert: ({ children }: { children: React.ReactNode }) => <div role="alert">{children}</div>,
Button: ({ children, ...props }: React.ComponentProps<'button'>) => (
<button {...props}>{children}</button>
@ -250,6 +50,187 @@ jest.mock('lucide-react', () => ({
XCircle: () => null,
}));
function MockContentParts({
content,
messageId,
...props
}: {
content: Array<{
type: string;
text?: string;
phase?: string;
think?: string;
reasoning_label?: string;
activity_label?: string;
tool_call?: {
id: string;
name: string;
args?: unknown;
output?: string;
inputValidationError?: true;
approval?: unknown;
runStepStatus?: string;
};
}>;
messageId: string;
foldLiveActivity?: boolean;
}) {
mockContentParts({ content, messageId, ...props });
const { useState } = jest.requireActual<typeof import('react')>('react');
const [expandedTool, setExpandedTool] = useState<string | null>(null);
const tools = content.filter((part) => part?.type === 'tool_call');
return (
<div data-testid="regular-content-parts" data-message-id={messageId}>
{content.map((part, index) => {
if (part == null) return null;
if (part.type === 'text') {
return (
<div key={index} data-phase={part.phase}>
{part.text}
</div>
);
}
if (part.type === 'think') {
if ((part as { reasoning_unavailable?: boolean }).reasoning_unavailable === true) {
return <div key={index}>{`reasoning-marker:${part.reasoning_label ?? ''}`}</div>;
}
return <div key={index}>{part.reasoning_label ?? part.think}</div>;
}
if (part.type === 'activity_label') {
return <div key={index}>{part.activity_label}</div>;
}
if (part.type !== 'tool_call' || part.tool_call == null) return null;
const tool = part.tool_call;
return (
<div key={tool.id}>
<button
type="button"
aria-expanded={expandedTool === tool.id}
data-run-step-status={tool.runStepStatus}
data-input-validation-error={tool.inputValidationError}
onClick={() => setExpandedTool(expandedTool === tool.id ? null : tool.id)}
>
{tool.name}
</button>
{expandedTool === tool.id && (
<div>
{JSON.stringify(tool.args)} {tool.output}
</div>
)}
{tool.approval != null && <div data-testid="tool-approval" />}
</div>
);
})}
{tools.length > 1 && <div>Used {tools.length} tools</div>}
</div>
);
}
const MockSteerPart = ({
steer,
steerId,
receiptState,
hasMore,
onExpand,
}: {
steer: string;
steerId?: string;
receiptState?: string | null;
hasMore?: boolean;
onExpand?: () => void;
}) => (
<div data-testid="shared-steer-part" data-receipt={receiptState} data-steer-id={steerId}>
{steer}
{hasMore && (
<button type="button" onClick={onExpand}>
{mockShowMore}
</button>
)}
</div>
);
/** The receipt read the app supplies, over the same query and identity check. */
const useRetainedControl: SubagentsHost['useRetainedControl'] = (scope, invocationId, enabled) => {
const query = useQuery(
[
'subagentControlReceipt',
scope.parentConversationId,
scope.threadId,
scope.taskId,
invocationId,
],
async () => {
const response = await mockReadControl(
scope.parentConversationId,
scope.threadId,
scope.taskId,
invocationId,
);
if (response.receipt.invocationId !== invocationId)
throw new Error('subagent_control_identity_mismatch');
return response;
},
{ enabled, retry: 1, staleTime: Infinity, refetchOnWindowFocus: false },
);
return {
message: query.data?.receipt.message,
isFetching: query.isFetching,
isError: query.isError,
refetch: () => void query.refetch(),
};
};
const subagentsHost: SubagentsHost = {
renderSteer: (props) => <MockSteerPart {...props} />,
useRetainedControl,
};
const partsHost: Partial<MessagePartsHost> = {
renderContentParts: (props) => (
<MockContentParts {...(props as Parameters<typeof MockContentParts>[0])} />
),
useShowThinking: () => false,
useAutoExpandTools: () => mockAutoExpandTools,
renderMarkdown: ({ content }: { content: string }) => <div>{content}</div>,
};
const surface: ChatSurface = {
enterToSend: true,
maximizeChatSpace: false,
showScrollButton: true,
composerBindings: {
shortcutsEnabled: true,
submitOverride: undefined,
yieldedChords: new Set<string>(),
},
claimForeground: () => undefined,
handOffComposerText: () => undefined,
};
function Wrapper({ children }: { children: React.ReactNode }) {
const [store] = useState(() => createStore());
const [client] = useState(
() => new QueryClient({ defaultOptions: { queries: { retry: false } } }),
);
return (
<JotaiProvider store={store}>
<QueryClientProvider client={client}>
<MessagePartsHostProvider host={partsHost as MessagePartsHost}>
<SubagentsHostProvider host={subagentsHost}>
<ChatSurfaceProvider value={surface}>{children}</ChatSurfaceProvider>
</SubagentsHostProvider>
</MessagePartsHostProvider>
</QueryClientProvider>
</JotaiProvider>
);
}
const render = (ui: React.ReactElement) => rtlRender(ui, { wrapper: Wrapper });
beforeEach(() => {
mockContentParts.mockClear();
mockReadControl.mockReset();
});
const base: ChildActivity = {
title: 'Research child',
prompt: 'Investigate.',
@ -332,7 +313,7 @@ describe('SubagentActivity', () => {
expect(mockContentParts).toHaveBeenLastCalledWith(
expect.objectContaining({ content, messageId: 'stable-response' }),
);
expect(mockContentParts.mock.calls.at(-1)?.[0].content).toBe(content);
expect(lastContentParts().content).toBe(content);
});
it.each([false, true])(
@ -343,7 +324,7 @@ describe('SubagentActivity', () => {
expect(mockContentParts).toHaveBeenLastCalledWith(
expect.objectContaining({ isSubmitting: true }),
);
expect(mockContentParts.mock.calls.at(-1)?.[0].foldLiveActivity).toBeUndefined();
expect(lastContentParts().foldLiveActivity).toBeUndefined();
},
);
it.each(['failed', 'cancelled'] as const)(
@ -604,16 +585,14 @@ describe('SubagentActivity', () => {
it('keeps the shared scroll surface pinned when activity grows at the bottom', () => {
let resize!: ResizeObserverCallback;
const resizeObserver = window.ResizeObserver as unknown as jest.Mock;
const originalImplementation = resizeObserver.getMockImplementation();
resizeObserver.mockImplementation((callback: ResizeObserverCallback) => {
const original = window.ResizeObserver;
window.ResizeObserver = jest.fn((callback: ResizeObserverCallback) => {
resize = callback;
return { observe: jest.fn(), disconnect: jest.fn(), unobserve: jest.fn() };
});
}) as unknown as typeof ResizeObserver;
const { container, unmount } = render(
<SubagentActivityScrollSurface padded={false}>
{/* eslint-disable-next-line i18next/no-literal-string */}
<div>Growing timeline</div>
</SubagentActivityScrollSurface>,
);
@ -625,11 +604,7 @@ describe('SubagentActivity', () => {
expect(surface?.scrollTop).toBe(640);
unmount();
if (originalImplementation == null) {
resizeObserver.mockReset();
} else {
resizeObserver.mockImplementation(originalImplementation);
}
window.ResizeObserver = original;
});
it('renders a sanitized reasoning marker through regular ContentParts', () => {
@ -731,7 +706,7 @@ it('does not repeat an applied control already rendered at its standard content
/>,
);
expect(screen.queryByText('com_ui_subagent_control_status_applied')).not.toBeInTheDocument();
expect(mockContentParts.mock.calls.at(-1)?.[0].content[0]).toMatchObject({
expect(lastContentParts().content[0]).toMatchObject({
type: ContentTypes.STEER,
steerId: 'control-1',
});
@ -816,7 +791,7 @@ it('renders applied controls inline once instead of repeating them below all cur
/>,
);
expect(screen.queryByTestId('shared-steer-part')).not.toBeInTheDocument();
expect(mockContentParts.mock.calls.at(-1)?.[0].content).toEqual([
expect(lastContentParts().content).toEqual([
part,
{ type: ContentTypes.TEXT, text: 'Work after guidance.' },
]);
@ -875,13 +850,12 @@ it('suppresses only the corresponding number of legacy guidance bodies and does
expect(screen.getAllByTestId('shared-steer-part')).toHaveLength(1);
expect(screen.getByTestId('shared-steer-part')).toHaveTextContent('Repeated guidance.');
expect(screen.getByTestId('shared-steer-part')).toHaveAttribute('data-steer-id', 'one');
expect(mockContentParts.mock.calls.at(-1)?.[0].content).toEqual([
expect(lastContentParts().content).toEqual([
{ type: ContentTypes.STEER, steer: 'Repeated guidance.' },
]);
});
it('loads a budgeted retained body only after expansion while keeping Withdraw actionable', async () => {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const full = 'Full retained guidance. '.repeat(80);
const control = {
invocationId: 'budgeted',
@ -898,13 +872,11 @@ it('loads a budgeted retained body only after expansion while keeping Withdraw a
});
const withdraw = jest.fn();
const { unmount } = render(
<QueryClientProvider client={client}>
<TaskContentScopeContext.Provider
value={{ parentConversationId: 'parent', threadId: 'child', taskId: 'task' }}
>
<SubagentActivity activity={{ ...base, controls: [control] }} onCancelControl={withdraw} />
</TaskContentScopeContext.Provider>
</QueryClientProvider>,
<TaskContentScopeContext.Provider
value={{ parentConversationId: 'parent', threadId: 'child', taskId: 'task' }}
>
<SubagentActivity activity={{ ...base, controls: [control] }} onCancelControl={withdraw} />
</TaskContentScopeContext.Provider>,
);
expect(mockReadControl).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: mockShowMore }));
@ -917,7 +889,6 @@ it('loads a budgeted retained body only after expansion while keeping Withdraw a
expect(withdraw).toHaveBeenCalledWith('pending-control');
expect(screen.queryByText('Message shortened for display.')).not.toBeInTheDocument();
unmount();
client.clear();
});
it.each(['submitted', 'accepted', 'failed'] as const)(
@ -948,7 +919,7 @@ it.each(['submitted', 'accepted', 'failed'] as const)(
/>,
);
expect(screen.queryByTestId('shared-steer-part')).not.toBeInTheDocument();
expect(mockContentParts.mock.calls.at(-1)?.[0].content).toContainEqual(applied);
expect(lastContentParts().content).toContainEqual(applied);
},
);
@ -1037,7 +1008,7 @@ it.each(['submitted', 'failed'] as const)(
/>,
);
expect(screen.queryByTestId('shared-steer-part')).not.toBeInTheDocument();
expect(mockContentParts.mock.calls.at(-1)?.[0].content).toEqual([
expect(lastContentParts().content).toEqual([
{
type: ContentTypes.STEER,
steer: 'Durably applied guidance.',

View file

@ -1,33 +1,28 @@
import { useCallback, useEffect, useId, useMemo, useContext, useRef, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Alert, Button } from '@librechat/client';
import { Maximize2, Minimize2 } from 'lucide-react';
import { CSSTransition } from 'react-transition-group';
import { MessageTimestamp } from '@librechat/chat/components';
import { ContentTypes, QueryKeys, dataService } from 'librechat-data-provider';
import { ContentTypes } from 'librechat-data-provider';
import { Alert, Button, cn, useLocalize } from '@librechat/client';
import type { SearchResultData, TMessageContentParts } from 'librechat-data-provider';
import type { TranslationKeys } from '@librechat/client';
import type { ReactNode, UIEvent } from 'react';
import type { ChildActivity, ChildActivityItem } from '../../react/subagents/adapters';
import type { SteerReceiptState } from '../composer/steering/Receipt';
import type { ToolContentQuery } from '../../react/parts/disclosure';
import type { TaskContentScope } from '../../react/subagents/scope';
import {
isAbnormalTerminalStatus,
isLiveSubagentStatus,
subagentStatusIcon,
subagentStatusLabelKey,
ToolContentQueryContext,
useChatSurface,
} from '@librechat/chat/react';
import type { ChildActivity, ChildActivityItem, ToolContentQuery } from '@librechat/chat/react';
import type { SearchResultData, TMessageContentParts } from 'librechat-data-provider';
import type { SteerReceiptState } from '@librechat/chat/components';
import type { TaskContentScope } from '~/data-provider/Subagents/content';
import type { TranslationKeys } from '~/hooks';
import { TaskContentScopeContext } from '~/data-provider/Subagents/content';
import MarkdownLite from '~/components/Chat/Messages/Content/MarkdownLite';
import ContentParts from '~/components/Chat/Messages/Content/ContentParts';
import SteerPart from '~/components/Chat/Messages/Content/Parts/SteerPart';
import { useMessagePartsHost } from '~/Providers/MessagePartsHostContext';
import Container from '~/components/Chat/Messages/Content/Container';
import { EmptyText } from '~/components/Chat/Messages/Content/Parts';
import ScrollToBottom from '~/components/Messages/ScrollToBottom';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
} from '../../react/subagents/status';
import { ToolContentQueryContext } from '../../react/parts/disclosure';
import { TaskContentScopeContext } from '../../react/subagents/scope';
import { useChatSurface } from '../../react/subagents/surface';
import { useSubagentsHost } from '../../react/subagents/host';
import MessageTimestamp from '../messages/MessageTimestamp';
import ScrollToBottom from '../messages/ScrollToBottom';
import { useMessagePartsHost } from '../../react/host';
import EmptyText from '../EmptyText';
const AT_BOTTOM_THRESHOLD_PX = 120;
const CONTROL_ACTION_LABELS = {
@ -69,45 +64,26 @@ function RetainedControlMessage({
scope,
}: ControlMessageProps & { scope: TaskContentScope }) {
const localize = useLocalize();
const { renderSteer } = useSubagentsHost();
const [expanded, setExpanded] = useState(false);
const reveal = useCallback(() => setExpanded(true), []);
const query = useQuery(
[
QueryKeys.subagentControlReceipt,
scope.parentConversationId,
scope.threadId,
scope.taskId,
control.invocationId,
],
async () => {
const response = await dataService.getSubagentControlReceipt(
scope.parentConversationId,
scope.threadId,
scope.taskId,
control.invocationId,
);
if (response.receipt.invocationId !== control.invocationId)
throw new Error('subagent_control_identity_mismatch');
return response;
},
{ enabled: expanded, retry: 1, staleTime: Infinity, refetchOnWindowFocus: false },
);
const retained = useSubagentsHost().useRetainedControl(scope, control.invocationId, expanded);
return (
<>
<SteerPart
steer={query.data?.receipt.message ?? control.message ?? ''}
steerId={control.controlId ?? control.invocationId}
createdAt={Date.parse(control.createdAt)}
receiptState={receiptState}
isSubmitting={pending}
hasMore={query.data == null}
onExpand={reveal}
/>
{query.isFetching && <span role="status">{localize('com_ui_loading')}</span>}
{query.isError && (
{renderSteer({
steer: retained.message ?? control.message ?? '',
steerId: control.controlId ?? control.invocationId,
createdAt: Date.parse(control.createdAt),
receiptState,
isSubmitting: pending,
hasMore: retained.message == null,
onExpand: reveal,
})}
{retained.isFetching && <span role="status">{localize('com_ui_loading')}</span>}
{retained.isError && (
<Alert variant="error">
<span>{localize('com_ui_conversation_load_error')}</span>
<Button variant="ghost" size="sm" onClick={() => void query.refetch()}>
<Button variant="ghost" size="sm" onClick={retained.refetch}>
{localize('com_ui_retry')}
</Button>
</Alert>
@ -118,17 +94,16 @@ function RetainedControlMessage({
function ControlMessage(props: ControlMessageProps) {
const scope = useContext(TaskContentScopeContext);
const { renderSteer } = useSubagentsHost();
if (props.control.messageTruncated === true && scope != null)
return <RetainedControlMessage {...props} scope={scope} />;
return (
<SteerPart
steer={props.control.message ?? ''}
steerId={props.control.controlId ?? props.control.invocationId}
createdAt={Date.parse(props.control.createdAt)}
receiptState={props.receiptState}
isSubmitting={props.pending}
/>
);
return renderSteer({
steer: props.control.message ?? '',
steerId: props.control.controlId ?? props.control.invocationId,
createdAt: Date.parse(props.control.createdAt),
receiptState: props.receiptState,
isSubmitting: props.pending,
});
}
function SubagentControlHistory({
@ -255,18 +230,17 @@ export function SubagentActivityScrollSurface({
padded = true,
headerInset = false,
}: {
children: React.ReactNode;
children: ReactNode;
padded?: boolean;
/** Clears the panel's overlay header, which floats above this surface so the
* thread scrolls under it rather than starting below a solid bar. */
headerInset?: boolean;
}) {
}): ReactNode {
const scrollRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const scrollButtonRef = useRef<HTMLDivElement>(null);
const [isAtBottom, setIsAtBottom] = useState(true);
const [isSettled, setIsSettled] = useState(false);
const { showScrollButton: scrollButtonPreference, maximizeChatSpace } = useChatSurface();
const { renderJumpToLatest } = useSubagentsHost();
useEffect(() => {
const scroll = scrollRef.current;
@ -279,7 +253,7 @@ export function SubagentActivityScrollSurface({
return () => observer.disconnect();
}, [isAtBottom]);
const handleScroll = useCallback((event: React.UIEvent<HTMLDivElement>) => {
const handleScroll = useCallback((event: UIEvent<HTMLDivElement>) => {
const element = event.currentTarget;
setIsAtBottom(
element.scrollHeight - element.scrollTop - element.clientHeight <= AT_BOTTOM_THRESHOLD_PX,
@ -294,6 +268,20 @@ export function SubagentActivityScrollSurface({
setIsAtBottom(true);
}, []);
const jumpVisible = !isAtBottom && scrollButtonPreference;
let jump: ReactNode = null;
if (renderJumpToLatest != null) {
jump = renderJumpToLatest({ visible: jumpVisible, onClick: scrollToBottom, maximizeChatSpace });
} else if (jumpVisible) {
jump = (
<ScrollToBottom
scrollHandler={scrollToBottom}
maximizeChatSpace={maximizeChatSpace}
interactive
/>
);
}
return (
<div className="relative flex min-h-0 flex-1 flex-col">
<div
@ -306,23 +294,7 @@ export function SubagentActivityScrollSurface({
{children}
</div>
</div>
<CSSTransition
in={!isAtBottom && scrollButtonPreference}
timeout={{ enter: 300, exit: 180 }}
classNames="scroll-animation"
unmountOnExit={true}
appear={true}
nodeRef={scrollButtonRef}
onEntered={() => setIsSettled(true)}
onExit={() => setIsSettled(false)}
>
<ScrollToBottom
ref={scrollButtonRef}
scrollHandler={scrollToBottom}
maximizeChatSpace={maximizeChatSpace}
interactive={isSettled}
/>
</CSSTransition>
{jump}
</div>
);
}
@ -403,6 +375,7 @@ export const getActivityContent = (activity: ChildActivity): TMessageContentPart
function SubagentPrompt({ prompt }: { prompt: string }) {
const localize = useLocalize();
const { renderMarkdown } = useMessagePartsHost();
const [expanded, setExpanded] = useState(false);
const headingId = useId();
const contentId = useId();
@ -438,7 +411,12 @@ function SubagentPrompt({ prompt }: { prompt: string }) {
)}
>
<div className="markdown prose prose-sm message-content light text-text-primary w-full max-w-none break-words">
<MarkdownLite content={prompt} codeExecution={false} />
{renderMarkdown({
content: prompt,
variant: 'lite',
isLatestMessage: false,
codeExecution: false,
})}
</div>
{!expanded && (
<div
@ -465,7 +443,7 @@ export function SubagentActivityContent({
toolContentQuery,
}: {
toolContentQuery?: ToolContentQuery;
authorHeader?: React.ReactNode;
authorHeader?: ReactNode;
searchResults?: Record<string, SearchResultData>;
content?: TMessageContentParts[];
activity: ChildActivity;
@ -478,7 +456,7 @@ export function SubagentActivityContent({
* chat (see `EmptyTextPart`). */
underHeaderIcon?: boolean;
onCancelControl?: (controlId: string) => void;
}) {
}): ReactNode {
const localize = useLocalize();
const host = useMessagePartsHost();
const showThinking = host.useShowThinking();
@ -490,37 +468,26 @@ export function SubagentActivityContent({
</Alert>
);
let body: React.ReactNode;
let body: ReactNode;
if (state === 'loading' && parts.length === 0) {
body = (
<Container>
<EmptyText underHeaderIcon={underHeaderIcon} />
</Container>
);
body = <EmptyText underHeaderIcon={underHeaderIcon} />;
} else if (state === 'error' && parts.length === 0) {
body = errorNotice;
} else if (parts.length === 0) {
body = isSubmitting ? (
<Container>
<EmptyText underHeaderIcon={underHeaderIcon} />
</Container>
) : null;
body = isSubmitting ? <EmptyText underHeaderIcon={underHeaderIcon} /> : null;
} else {
body = (
<ToolContentQueryContext.Provider value={toolContentQuery ?? null}>
<ContentParts
content={parts}
messageId={activity.messageId ?? activityId ?? 'subagent-activity-panel'}
conversationId={conversationId}
attachments={activity.attachments}
searchResults={searchResults}
authorHeader={authorHeader}
isCreatedByUser={false}
isLast
isSubmitting={isSubmitting}
showThinking={showThinking}
isLatestMessage={isSubmitting}
/>
{host.renderContentParts({
content: parts,
messageId: activity.messageId ?? activityId ?? 'subagent-activity-panel',
conversationId,
attachments: activity.attachments,
searchResults,
authorHeader,
isSubmitting,
showThinking,
})}
</ToolContentQueryContext.Provider>
);
}
@ -556,7 +523,7 @@ export function SubagentActivityContent({
);
}
export function SubagentStatus({ activity }: { activity: ChildActivity }) {
export function SubagentStatus({ activity }: { activity: ChildActivity }): ReactNode {
const localize = useLocalize();
const StatusIcon = subagentStatusIcon(activity.status);
return (
@ -575,7 +542,8 @@ export function SubagentStatus({ activity }: { activity: ChildActivity }) {
);
}
export default function SubagentActivity({
/** One child run's transcript: its prompt, content and guidance history, scrollable or embedded. */
export function SubagentActivity({
activity,
activityId,
state = 'ready',
@ -591,9 +559,9 @@ export default function SubagentActivity({
embedded?: boolean;
showPrompt?: boolean;
headerInset?: boolean;
notice?: React.ReactNode;
notice?: ReactNode;
onCancelControl?: (controlId: string) => void;
}) {
}): ReactNode {
const statusHeader = isAbnormalTerminalStatus(activity.status) ? (
<div className="border-border-light shrink-0 border-b px-4 py-2">
<SubagentStatus activity={activity} />

View file

@ -16,6 +16,7 @@ export type {
MessagePartsUser,
MessagePartsToast,
MessagePartsShare,
ContentPartsSlotProps,
MessagePartMessage,
MessagePartsMarkdownProps,
MessagePartsUserTextPreferences,

View file

@ -12,6 +12,7 @@ const createHost = (fontSize: string): MessagePartsHost => ({
useAgent: () => undefined,
renderAgentIcon: () => null,
renderAgentAvatar: () => null,
renderContentParts: () => null,
useFontSize: () => fontSize,
useShowThinking: () => false,
useAutoExpandTools: () => false,

View file

@ -1,6 +1,12 @@
import { createContext, useContext } from 'react';
import type {
Agent,
TFile,
TAttachment,
SearchResultData,
TMessageContentParts,
} from 'librechat-data-provider';
import type { Dispatch, ReactNode, SetStateAction } from 'react';
import type { Agent, TFile } from 'librechat-data-provider';
import type { TShowToast } from '@librechat/client';
/** The message a part renders in, as its host reports it. */
@ -35,6 +41,32 @@ export type MessagePartsUser = { id?: string; name?: string; username?: string }
/** Shows a transient notification. */
export type MessagePartsToast = (toast: TShowToast) => void;
/** What a caller asks the host's content-parts renderer to draw: a message's parts, and the row
* state around them. Omitted row fields take an assistant reply's defaults: not the user's,
* the last row, and latest while it is submitting. */
export type ContentPartsSlotProps = {
/** Holes stay where a streaming or parallel index has no part yet; positions are part indexes. */
content: Array<TMessageContentParts | undefined>;
messageId: string;
conversationId: string | null;
attachments?: TAttachment[];
searchResults?: Record<string, SearchResultData>;
authorHeader?: ReactNode;
isSubmitting: boolean;
showThinking: boolean;
edit?: boolean;
enterEdit?: (cancel?: boolean) => void | null | undefined;
siblingIdx?: number;
setSiblingIdx?: ((value: number) => void) | null;
isCreatedByUser?: boolean;
isLast?: boolean;
isLatestMessage?: boolean;
manualSkills?: string[];
renderOwnerId?: string;
createdAt?: string | null;
foldLiveActivity?: boolean;
};
/** Where the calling message is rendered: a public share link, or the reader's own chat. */
export type MessagePartsShare = {
isSharedConvo?: boolean;
@ -49,6 +81,8 @@ export type MessagePartsMarkdownProps = {
variant: 'full' | 'lite';
/** Whether the text belongs to the tail of the active branch. */
isLatestMessage: boolean;
/** `false` draws code blocks without run controls, for text that is shown and never run. */
codeExecution?: boolean;
};
/**
@ -72,6 +106,8 @@ export interface MessagePartsHost {
useSmoothStreaming: () => boolean;
/** An agent the viewer can see, by id. */
useAgent: (agentId: string) => Agent | undefined;
/** Draws a message's content parts with the app's renderer. */
renderContentParts: (props: ContentPartsSlotProps) => ReactNode;
/** Renders an agent's avatar; `undefined` when the agent is unknown. */
renderAgentIcon: (agent: Agent | undefined) => ReactNode;
/** Renders an agent's bare inline avatar, without the message icon around it. */

View file

@ -0,0 +1,91 @@
import { createContext, useContext } from 'react';
import type { MouseEventHandler, ReactNode } from 'react';
import type { SteerReceiptState } from '../../components/composer/steering/Receipt';
import type { TaskContentScope } from './scope';
/** One guidance message sent to a child, drawn as the main chat draws a steer. */
export type SubagentSteerProps = {
steer: string;
steerId: string;
createdAt: number;
receiptState: SteerReceiptState | null;
isSubmitting: boolean;
hasMore?: boolean;
onExpand?: () => void;
};
/** The transcript's jump-to-latest control, and whether the reader has scrolled away from it. */
export type SubagentJumpToLatestProps = {
visible: boolean;
onClick: MouseEventHandler<HTMLButtonElement>;
maximizeChatSpace: boolean;
};
/** A guidance message the transcript was handed shortened, read in full on request. */
export type SubagentRetainedControl = {
message?: string;
isFetching: boolean;
isError: boolean;
refetch: () => void;
};
/**
* What a subagent transcript reads from the app: render slots for the parts it shares with the
* main chat and has not received yet, and the one read it makes. Members are hooks or slots,
* called unconditionally, and a host stays the same object for the life of the tree it wraps.
*/
export interface SubagentsHost {
/** Draws one guidance message with the app's steer renderer. */
renderSteer: (props: SubagentSteerProps) => ReactNode;
/**
* Draws the jump-to-latest control with the app's enter and exit animation. Without it the
* package's `ScrollToBottom` shows while `visible`, unanimated.
*/
renderJumpToLatest?: (props: SubagentJumpToLatestProps) => ReactNode;
/** The full text of a shortened guidance message, fetched only while `enabled`. */
useRetainedControl: (
scope: TaskContentScope,
invocationId: string,
enabled: boolean,
) => SubagentRetainedControl;
}
const idleControl: SubagentRetainedControl = {
isFetching: false,
isError: false,
refetch: () => undefined,
};
/** The host a transcript reads before an app registers one: no slots and no reads. */
const fallbackHost: SubagentsHost = {
renderSteer: () => null,
useRetainedControl: () => idleControl,
};
const SubagentsHostContext = createContext<SubagentsHost | null>(null);
let defaultHost: SubagentsHost = fallbackHost;
/**
* Registers the host that transcripts rendered outside any `SubagentsHostProvider` read. An app
* registers its own once, when the module that builds it loads; a provider always wins over it.
*/
export function setDefaultSubagentsHost(host: SubagentsHost): void {
defaultHost = host;
}
/** Supplies the host subagent transcripts read from. */
export function SubagentsHostProvider({
host,
children,
}: {
host: SubagentsHost;
children: ReactNode;
}): ReactNode {
return <SubagentsHostContext.Provider value={host}>{children}</SubagentsHostContext.Provider>;
}
/** The host of the nearest provider, else the registered default, else the fallback. */
export function useSubagentsHost(): SubagentsHost {
return useContext(SubagentsHostContext) ?? defaultHost;
}

View file

@ -13,3 +13,5 @@ export * from './author';
export * from './surface';
export * from './provider';
export * from './task';
export * from './scope';
export * from './host';

View file

@ -0,0 +1,13 @@
import { createContext } from 'react';
import type { Context } from 'react';
/** One durable child task's identity, which retained content and receipts are read under. */
export type TaskContentScope = {
parentConversationId: string;
threadId: string;
taskId: string;
};
/** The task a transcript renders for; `null` where it is not a durable task. */
export const TaskContentScopeContext: Context<TaskContentScope | null> =
createContext<TaskContentScope | null>(null);

View file

@ -177,6 +177,7 @@ const host: MessagePartsHost = {
useAgent: () => undefined,
renderAgentIcon: () => null,
renderAgentAvatar: () => null,
renderContentParts: () => null,
useFontSize: () => 'text-base',
useShowThinking: () => false,
useAutoExpandTools: () => false,