From 222a369c60b2e307af2ada476252fdf0d225b360 Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:11:03 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=BC=20refactor:=20Move=20the=20Subagen?= =?UTF-8?q?t=20Transcript=20Into=20@librechat/chat=20Behind=20a=20Subagent?= =?UTF-8?q?s=20Host=20(#17678)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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. --- client/src/App.jsx | 2 + .../src/Providers/MessagePartsHostContext.tsx | 6 +- client/src/Providers/SubagentsHostContext.tsx | 84 ++++ client/src/__tests__/hosts.test.tsx | 89 +++- .../Content/Parts/__tests__/host.test.tsx | 1 + .../Chat/Messages/Content/Parts/renderers.tsx | 9 +- .../Chat/Messages/Content/Parts/slots.ts | 19 + .../Chat/Messages/Content/register.tsx | 16 + .../components/Chat/Messages/ScrollButton.tsx | 2 +- .../Messages/__tests__/ScrollButton.spec.tsx | 3 +- .../SharedSubagentActivityDialog.test.tsx | 6 +- .../SharedSubagentActivityDialog.tsx | 2 +- .../Subagents/SubagentConversation.test.tsx | 40 +- .../Chat/Subagents/SubagentConversation.tsx | 4 +- .../Subagents/SubagentThreadPanel.test.tsx | 6 +- .../Chat/Subagents/SubagentThreadPanel.tsx | 2 +- .../src/data-provider/Subagents/content.tsx | 20 +- eslint-suppressions.json | 20 +- eslint.config.mjs | 1 + packages/chat/src/components.ts | 8 + .../src/components/__tests__/host.spec.tsx | 1 + .../components/messages}/ScrollToBottom.tsx | 76 +-- .../__tests__/ScrollToBottom.spec.tsx | 6 +- .../subagents/__tests__/activity.spec.tsx | 1 + .../subagents/__tests__/transcript.spec.tsx | 463 ++++++++---------- .../src/components/subagents/transcript.tsx | 204 ++++---- packages/chat/src/react.ts | 1 + .../chat/src/react/__tests__/host.spec.tsx | 1 + packages/chat/src/react/host.tsx | 38 +- packages/chat/src/react/subagents/host.tsx | 91 ++++ packages/chat/src/react/subagents/index.ts | 2 + packages/chat/src/react/subagents/scope.ts | 13 + packages/chat/test/consumer.spec.tsx | 1 + 33 files changed, 778 insertions(+), 460 deletions(-) create mode 100644 client/src/Providers/SubagentsHostContext.tsx create mode 100644 client/src/components/Chat/Messages/Content/register.tsx rename {client/src/components/Messages => packages/chat/src/components/messages}/ScrollToBottom.tsx (52%) rename {client/src/components/Messages => packages/chat/src/components/messages}/__tests__/ScrollToBottom.spec.tsx (97%) rename client/src/components/Chat/Subagents/SubagentActivity.test.tsx => packages/chat/src/components/subagents/__tests__/transcript.spec.tsx (77%) rename client/src/components/Chat/Subagents/SubagentActivity.tsx => packages/chat/src/components/subagents/transcript.tsx (80%) create mode 100644 packages/chat/src/react/subagents/host.tsx create mode 100644 packages/chat/src/react/subagents/scope.ts diff --git a/client/src/App.jsx b/client/src/App.jsx index a03ebdf904..6dd992080e 100644 --- a/client/src/App.jsx +++ b/client/src/App.jsx @@ -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(); diff --git a/client/src/Providers/MessagePartsHostContext.tsx b/client/src/Providers/MessagePartsHostContext.tsx index 4a3381e095..dd233e9248 100644 --- a/client/src/Providers/MessagePartsHostContext.tsx +++ b/client/src/Providers/MessagePartsHostContext.tsx @@ -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), diff --git a/client/src/Providers/SubagentsHostContext.tsx b/client/src/Providers/SubagentsHostContext.tsx new file mode 100644 index 0000000000..6f92b5e056 --- /dev/null +++ b/client/src/Providers/SubagentsHostContext.tsx @@ -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(null); + const [isSettled, setIsSettled] = useState(false); + return ( + setIsSettled(true)} + onExit={() => setIsSettled(false)} + > + + + ); +} + +/** 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) => , + renderJumpToLatest: (props) => , + useRetainedControl, +}; + +setDefaultSubagentsHost(appSubagentsHost); diff --git a/client/src/__tests__/hosts.test.tsx b/client/src/__tests__/hosts.test.tsx index 7c75b9b8fa..484121c328 100644 --- a/client/src/__tests__/hosts.test.tsx +++ b/client/src/__tests__/hosts.test.tsx @@ -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( + + + + + + + , + ); + + 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'); + }); + }); }); diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/host.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/host.test.tsx index 5f5e588068..85fa6d063f 100644 --- a/client/src/components/Chat/Messages/Content/Parts/__tests__/host.test.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/host.test.tsx @@ -58,6 +58,7 @@ function createHost(overrides: Partial = {}): MessagePartsHost usePaneConversationId: () => null, useLiveAppliedSteer: () => [false, jest.fn()], useShare: () => ({}), + renderContentParts: () => null, useMessagesEditing: () => ({ conversation: null, ask: jest.fn(), diff --git a/client/src/components/Chat/Messages/Content/Parts/renderers.tsx b/client/src/components/Chat/Messages/Content/Parts/renderers.tsx index 9671e69b55..17cb5b50be 100644 --- a/client/src/components/Chat/Messages/Content/Parts/renderers.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/renderers.tsx @@ -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' ? ( - + ) : ( ), diff --git a/client/src/components/Chat/Messages/Content/Parts/slots.ts b/client/src/components/Chat/Messages/Content/Parts/slots.ts index 955d42a1a0..313c765db2 100644 --- a/client/src/components/Chat/Messages/Content/Parts/slots.ts +++ b/client/src/components/Chat/Messages/Content/Parts/slots.ts @@ -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; +} diff --git a/client/src/components/Chat/Messages/Content/register.tsx b/client/src/components/Chat/Messages/Content/register.tsx new file mode 100644 index 0000000000..521cfab31a --- /dev/null +++ b/client/src/components/Chat/Messages/Content/register.tsx @@ -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 }) => ( + + ), +); diff --git a/client/src/components/Chat/Messages/ScrollButton.tsx b/client/src/components/Chat/Messages/ScrollButton.tsx index e852469d92..11086e3292 100644 --- a/client/src/components/Chat/Messages/ScrollButton.tsx +++ b/client/src/components/Chat/Messages/ScrollButton.tsx @@ -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; diff --git a/client/src/components/Chat/Messages/__tests__/ScrollButton.spec.tsx b/client/src/components/Chat/Messages/__tests__/ScrollButton.spec.tsx index 319bd58f09..c8379d1ac3 100644 --- a/client/src/components/Chat/Messages/__tests__/ScrollButton.spec.tsx +++ b/client/src/components/Chat/Messages/__tests__/ScrollButton.spec.tsx @@ -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, })); diff --git a/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.test.tsx b/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.test.tsx index 76928e1d9b..b47e8e7d68 100644 --- a/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.test.tsx +++ b/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.test.tsx @@ -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 }) => (
{children}
), - default: ({ + SubagentActivity: ({ activity, }: { activity: { title: string; items: Array<{ type: string; text?: string }> }; diff --git a/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.tsx b/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.tsx index 236308fbfc..93cb6b72f8 100644 --- a/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.tsx +++ b/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.tsx @@ -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'; diff --git a/client/src/components/Chat/Subagents/SubagentConversation.test.tsx b/client/src/components/Chat/Subagents/SubagentConversation.test.tsx index d9d9e3fa2e..2f867e14e2 100644 --- a/client/src/components/Chat/Subagents/SubagentConversation.test.tsx +++ b/client/src/components/Chat/Subagents/SubagentConversation.test.tsx @@ -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('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('@librechat/chat/react'); + chat.setDefaultMessagePartsHost({ useShowThinking: () => false, useAutoExpandTools: () => false, useMessagesAsk: () => mockParentAsk, - }); + renderMarkdown: ({ content }: { content: string }) => content, + renderContentParts: (props: Parameters>[0]) => + getAppContentParts()(props), + } as unknown as Parameters[0]); return { - MessagePartsHostProvider: ({ - host, - children, - }: { - host: React.ContextType; - children: React.ReactNode; - }) => {children}, - 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 }) =>
{children}
, })); -jest.mock('~/components/Chat/Messages/Content/Parts', () => ({ - EmptyText: ({ underHeaderIcon }: { underHeaderIcon?: boolean }) => ( -
- ), -})); - jest.mock('~/components/Chat/Messages/MessageIcon', () => ({ __esModule: true, default: () => , @@ -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); diff --git a/client/src/components/Chat/Subagents/SubagentConversation.tsx b/client/src/components/Chat/Subagents/SubagentConversation.tsx index b51b0e2b0d..c58735df4e 100644 --- a/client/src/components/Chat/Subagents/SubagentConversation.tsx +++ b/client/src/components/Chat/Subagents/SubagentConversation.tsx @@ -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'; diff --git a/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx b/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx index a00ee21bb5..b60135adbb 100644 --- a/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx +++ b/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx @@ -194,12 +194,12 @@ jest.mock('~/components/Chat/Messages/Content/MarkdownLite', () => ({ default: ({ content }: { content: string }) =>
{content}
, })); -jest.mock('./SubagentActivity', () => ({ - __esModule: true, +jest.mock('@librechat/chat/components', () => ({ + ...jest.requireActual('@librechat/chat/components'), SubagentActivityScrollSurface: ({ children }: { children: React.ReactNode }) => (
{children}
), - default: function MockActivity({ + SubagentActivity: function MockActivity({ activity, activityId, state, diff --git a/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx b/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx index cdb7c78710..b80c5b618d 100644 --- a/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx +++ b/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx @@ -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'; diff --git a/client/src/data-provider/Subagents/content.tsx b/client/src/data-provider/Subagents/content.tsx index 0495f23f2e..57d060f98b 100644 --- a/client/src/data-provider/Subagents/content.tsx +++ b/client/src/data-provider/Subagents/content.tsx @@ -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(null); +export { TaskContentScopeContext }; +export type { TaskContentScope }; export const subagentTaskContentKey = (scope: TaskContentScope) => [ QueryKeys.subagentTaskContent, diff --git a/eslint-suppressions.json b/eslint-suppressions.json index 357d9ce2a0..446303daa5 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -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 diff --git a/eslint.config.mjs b/eslint.config.mjs index bdf3f9ea02..a03470fc3f 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -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', diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts index 9ba7644eeb..ccd1d6105e 100644 --- a/packages/chat/src/components.ts +++ b/packages/chat/src/components.ts @@ -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'; diff --git a/packages/chat/src/components/__tests__/host.spec.tsx b/packages/chat/src/components/__tests__/host.spec.tsx index b392c0aeb7..74957b87a9 100644 --- a/packages/chat/src/components/__tests__/host.spec.tsx +++ b/packages/chat/src/components/__tests__/host.spec.tsx @@ -27,6 +27,7 @@ function createHost(enableUserMsgMarkdown = false): MessagePartsHost { useAgent: (agentId) => (agentId === agent.id ? agent : undefined), renderAgentIcon: (current) => {current?.id ?? 'unknown'}, renderAgentAvatar: () => null, + renderContentParts: () => null, useFontSize: () => 'text-base', useShowThinking: () => false, useAutoExpandTools: () => false, diff --git a/client/src/components/Messages/ScrollToBottom.tsx b/packages/chat/src/components/messages/ScrollToBottom.tsx similarity index 52% rename from client/src/components/Messages/ScrollToBottom.tsx rename to packages/chat/src/components/messages/ScrollToBottom.tsx index 1da1ca69c6..ff3b44a8ed 100644 --- a/client/src/components/Messages/ScrollToBottom.tsx +++ b/packages/chat/src/components/messages/ScrollToBottom.tsx @@ -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; @@ -25,49 +24,50 @@ type Props = { interactive?: boolean; }; -const ScrollToBottom = forwardRef( - ({ scrollHandler, maximizeChatSpace, overlayHeight = 0, interactive = false }, ref) => { - const localize = useLocalize(); +const ScrollToBottom: ForwardRefExoticComponent> = forwardRef< + HTMLDivElement, + Props +>(({ scrollHandler, maximizeChatSpace, overlayHeight = 0, interactive = false }, ref) => { + const localize = useLocalize(); - return ( -
- {/* The composer's own column, so the control stacks over the send + return ( +
+ {/* 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. */} -
+ -
+
- ); - }, -); +
+ ); +}); ScrollToBottom.displayName = 'ScrollToBottom'; diff --git a/client/src/components/Messages/__tests__/ScrollToBottom.spec.tsx b/packages/chat/src/components/messages/__tests__/ScrollToBottom.spec.tsx similarity index 97% rename from client/src/components/Messages/__tests__/ScrollToBottom.spec.tsx rename to packages/chat/src/components/messages/__tests__/ScrollToBottom.spec.tsx index cd7ea098d1..79d3573e8f 100644 --- a/client/src/components/Messages/__tests__/ScrollToBottom.spec.tsx +++ b/packages/chat/src/components/messages/__tests__/ScrollToBottom.spec.tsx @@ -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, })); diff --git a/packages/chat/src/components/subagents/__tests__/activity.spec.tsx b/packages/chat/src/components/subagents/__tests__/activity.spec.tsx index 994fc35820..53c8abe387 100644 --- a/packages/chat/src/components/subagents/__tests__/activity.spec.tsx +++ b/packages/chat/src/components/subagents/__tests__/activity.spec.tsx @@ -83,6 +83,7 @@ const host: MessagePartsHost = { useAgent: (agentId) => agents[agentId] as ReturnType, renderAgentIcon: () => null, renderAgentAvatar: () => , + renderContentParts: () => null, useFontSize: () => 'text-base', useShowThinking: () => false, useAutoExpandTools: () => false, diff --git a/client/src/components/Chat/Subagents/SubagentActivity.test.tsx b/packages/chat/src/components/subagents/__tests__/transcript.spec.tsx similarity index 77% rename from client/src/components/Chat/Subagents/SubagentActivity.test.tsx rename to packages/chat/src/components/subagents/__tests__/transcript.spec.tsx index 05cdfb6034..dfa854e5f5 100644 --- a/client/src/components/Chat/Subagents/SubagentActivity.test.tsx +++ b/packages/chat/src/components/subagents/__tests__/transcript.spec.tsx @@ -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 }) => ( - {children} -); -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; - }) => ( -
- {steer} - {hasMore && ( - - )} -
- ), -})); - -jest.mock('~/components/Chat/Messages/Content/Parts', () => ({ - EmptyText: () =>
, -})); - -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('react'); - const [expandedTool, setExpandedTool] = useState(null); - const tools = content.filter((part) => part?.type === 'tool_call'); - return ( -
- {content.map((part, index) => { - if (part == null) return null; - if (part.type === 'text') { - return ( -
- {part.text} -
- ); - } - if (part.type === 'think') { - if ((part as { reasoning_unavailable?: boolean }).reasoning_unavailable === true) { - return
{`reasoning-marker:${part.reasoning_label ?? ''}`}
; - } - return
{part.reasoning_label ?? part.think}
; - } - if (part.type === 'activity_label') { - return
{part.activity_label}
; - } - if (part.type !== 'tool_call' || part.tool_call == null) return null; - const tool = part.tool_call; - return ( -
- - {expandedTool === tool.id && ( -
- {JSON.stringify(tool.args)} {tool.output} -
- )} - {tool.approval != null &&
} -
- ); - })} - {/* eslint-disable-next-line i18next/no-literal-string */} - {tools.length > 1 &&
Used {tools.length} tools
} -
- ); - }, -})); - -jest.mock('~/components/Chat/Messages/Content/Parts/Reasoning', () => ({ - __esModule: true, - default: ({ reasoning }: { reasoning: string }) =>
{reasoning}
, -})); - -jest.mock('~/components/Chat/Messages/Content/MarkdownLite', () => ({ - __esModule: true, - default: ({ content }: { content: string }) =>
{content}
, -})); - -jest.mock('~/components/Chat/Messages/Content/Container', () => ({ - __esModule: true, - default: ({ children }: { children: React.ReactNode }) =>
{children}
, -})); - -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('react'); - const [open, setOpen] = useState(false); - return ( -
- - {open && ( -
- {JSON.stringify(args)} {output} -
- )} -
- ); - }, -})); - -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; - }) => ( -
- {/* eslint-disable-next-line i18next/no-literal-string */} -
Used {parts.length} tools
- {parts.map(({ part, idx }) => renderPart(part, idx, idx === lastContentIdx))} -
- ), -})); - -jest.mock('~/components/Chat/Messages/Content/ToolApproval', () => ({ - __esModule: true, - // eslint-disable-next-line i18next/no-literal-string - default: () =>
approval
, -})); - -jest.mock('@librechat/chat/components', () => ({ - ...jest.requireActual('@librechat/chat/components'), - SteerReceipt: ({ state }: { state: string }) => ( - - ), + default: () =>
, })); jest.mock('@librechat/client', () => ({ cn: jest.requireActual('@librechat/client').cn, useLanguage: () => 'en', + useLocalize: () => (key: string) => key, Alert: ({ children }: { children: React.ReactNode }) =>
{children}
, Button: ({ children, ...props }: React.ComponentProps<'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('react'); + const [expandedTool, setExpandedTool] = useState(null); + const tools = content.filter((part) => part?.type === 'tool_call'); + return ( +
+ {content.map((part, index) => { + if (part == null) return null; + if (part.type === 'text') { + return ( +
+ {part.text} +
+ ); + } + if (part.type === 'think') { + if ((part as { reasoning_unavailable?: boolean }).reasoning_unavailable === true) { + return
{`reasoning-marker:${part.reasoning_label ?? ''}`}
; + } + return
{part.reasoning_label ?? part.think}
; + } + if (part.type === 'activity_label') { + return
{part.activity_label}
; + } + if (part.type !== 'tool_call' || part.tool_call == null) return null; + const tool = part.tool_call; + return ( +
+ + {expandedTool === tool.id && ( +
+ {JSON.stringify(tool.args)} {tool.output} +
+ )} + {tool.approval != null &&
} +
+ ); + })} + {tools.length > 1 &&
Used {tools.length} tools
} +
+ ); +} + +const MockSteerPart = ({ + steer, + steerId, + receiptState, + hasMore, + onExpand, +}: { + steer: string; + steerId?: string; + receiptState?: string | null; + hasMore?: boolean; + onExpand?: () => void; +}) => ( +
+ {steer} + {hasMore && ( + + )} +
+); + +/** 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) => , + useRetainedControl, +}; + +const partsHost: Partial = { + renderContentParts: (props) => ( + [0])} /> + ), + useShowThinking: () => false, + useAutoExpandTools: () => mockAutoExpandTools, + renderMarkdown: ({ content }: { content: string }) =>
{content}
, +}; + +const surface: ChatSurface = { + enterToSend: true, + maximizeChatSpace: false, + showScrollButton: true, + composerBindings: { + shortcutsEnabled: true, + submitOverride: undefined, + yieldedChords: new Set(), + }, + claimForeground: () => undefined, + handOffComposerText: () => undefined, +}; + +function Wrapper({ children }: { children: React.ReactNode }) { + const [store] = useState(() => createStore()); + const [client] = useState( + () => new QueryClient({ defaultOptions: { queries: { retry: false } } }), + ); + return ( + + + + + {children} + + + + + ); +} +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( - {/* eslint-disable-next-line i18next/no-literal-string */}
Growing timeline
, ); @@ -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( - - - - - , + + + , ); 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.', diff --git a/client/src/components/Chat/Subagents/SubagentActivity.tsx b/packages/chat/src/components/subagents/transcript.tsx similarity index 80% rename from client/src/components/Chat/Subagents/SubagentActivity.tsx rename to packages/chat/src/components/subagents/transcript.tsx index aa0bd7cc00..3c5de5ed68 100644 --- a/client/src/components/Chat/Subagents/SubagentActivity.tsx +++ b/packages/chat/src/components/subagents/transcript.tsx @@ -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 ( <> - - {query.isFetching && {localize('com_ui_loading')}} - {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 && {localize('com_ui_loading')}} + {retained.isError && ( {localize('com_ui_conversation_load_error')} - @@ -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 ; - return ( - - ); + 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(null); const contentRef = useRef(null); - const scrollButtonRef = useRef(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) => { + const handleScroll = useCallback((event: UIEvent) => { 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 = ( + + ); + } + return (
- setIsSettled(true)} - onExit={() => setIsSettled(false)} - > - - + {jump}
); } @@ -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 }) { )} >
- + {renderMarkdown({ + content: prompt, + variant: 'lite', + isLatestMessage: false, + codeExecution: false, + })}
{!expanded && (
; 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({ ); - let body: React.ReactNode; + let body: ReactNode; if (state === 'loading' && parts.length === 0) { - body = ( - - - - ); + body = ; } else if (state === 'error' && parts.length === 0) { body = errorNotice; } else if (parts.length === 0) { - body = isSubmitting ? ( - - - - ) : null; + body = isSubmitting ? : null; } else { body = ( - + {host.renderContentParts({ + content: parts, + messageId: activity.messageId ?? activityId ?? 'subagent-activity-panel', + conversationId, + attachments: activity.attachments, + searchResults, + authorHeader, + isSubmitting, + showThinking, + })} ); } @@ -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) ? (
diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.ts index 7a2721687f..7bdc9c52ad 100644 --- a/packages/chat/src/react.ts +++ b/packages/chat/src/react.ts @@ -16,6 +16,7 @@ export type { MessagePartsUser, MessagePartsToast, MessagePartsShare, + ContentPartsSlotProps, MessagePartMessage, MessagePartsMarkdownProps, MessagePartsUserTextPreferences, diff --git a/packages/chat/src/react/__tests__/host.spec.tsx b/packages/chat/src/react/__tests__/host.spec.tsx index 18d8ee42dc..32f033b1f3 100644 --- a/packages/chat/src/react/__tests__/host.spec.tsx +++ b/packages/chat/src/react/__tests__/host.spec.tsx @@ -12,6 +12,7 @@ const createHost = (fontSize: string): MessagePartsHost => ({ useAgent: () => undefined, renderAgentIcon: () => null, renderAgentAvatar: () => null, + renderContentParts: () => null, useFontSize: () => fontSize, useShowThinking: () => false, useAutoExpandTools: () => false, diff --git a/packages/chat/src/react/host.tsx b/packages/chat/src/react/host.tsx index c7d1af8cbe..acc1da3ebc 100644 --- a/packages/chat/src/react/host.tsx +++ b/packages/chat/src/react/host.tsx @@ -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; + messageId: string; + conversationId: string | null; + attachments?: TAttachment[]; + searchResults?: Record; + 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. */ diff --git a/packages/chat/src/react/subagents/host.tsx b/packages/chat/src/react/subagents/host.tsx new file mode 100644 index 0000000000..202c113991 --- /dev/null +++ b/packages/chat/src/react/subagents/host.tsx @@ -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; + 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(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 {children}; +} + +/** The host of the nearest provider, else the registered default, else the fallback. */ +export function useSubagentsHost(): SubagentsHost { + return useContext(SubagentsHostContext) ?? defaultHost; +} diff --git a/packages/chat/src/react/subagents/index.ts b/packages/chat/src/react/subagents/index.ts index ef20dc9534..dd63921082 100644 --- a/packages/chat/src/react/subagents/index.ts +++ b/packages/chat/src/react/subagents/index.ts @@ -13,3 +13,5 @@ export * from './author'; export * from './surface'; export * from './provider'; export * from './task'; +export * from './scope'; +export * from './host'; diff --git a/packages/chat/src/react/subagents/scope.ts b/packages/chat/src/react/subagents/scope.ts new file mode 100644 index 0000000000..0f6e915a05 --- /dev/null +++ b/packages/chat/src/react/subagents/scope.ts @@ -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 = + createContext(null); diff --git a/packages/chat/test/consumer.spec.tsx b/packages/chat/test/consumer.spec.tsx index 40c9d43c66..d4bf615f8f 100644 --- a/packages/chat/test/consumer.spec.tsx +++ b/packages/chat/test/consumer.spec.tsx @@ -177,6 +177,7 @@ const host: MessagePartsHost = { useAgent: () => undefined, renderAgentIcon: () => null, renderAgentAvatar: () => null, + renderContentParts: () => null, useFontSize: () => 'text-base', useShowThinking: () => false, useAutoExpandTools: () => false,